tmux-context.spec.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. import { afterEach, describe, expect, it, vi } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { Session, SessionId } from '@deepseek-ai/dsh-session'
  4. import AgentRegistry, { agentEvents, Inbox, type Agent } from '@deepseek-ai/dsh-agent'
  5. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  6. import { BashExecutor } from '@deepseek-ai/dsh-bash'
  7. import type { BashExecRequest, BashExecSpec, BashProcess, BashRunResult } from '@deepseek-ai/dsh-bash'
  8. import * as tmuxContext from '@deepseek-ai/dsh-tmux-context'
  9. import type { Config } from '@deepseek-ai/dsh-tmux-context'
  10. const SIGNAL = new AbortController().signal
  11. /** One `#{...}`-joined tmux reading line for the eight queried fields. */
  12. function tmuxLine(fields: {
  13. sessionName?: string
  14. windowIndex?: string
  15. windowName?: string
  16. paneIndex?: string
  17. paneId?: string
  18. windowActive?: string
  19. paneActive?: string
  20. windowLayout?: string
  21. } = {}): string {
  22. return [
  23. fields.sessionName ?? '0',
  24. fields.windowIndex ?? '1',
  25. fields.windowName ?? 'node',
  26. fields.paneIndex ?? '2',
  27. fields.paneId ?? '%90',
  28. fields.windowActive ?? '1',
  29. fields.paneActive ?? '0',
  30. fields.windowLayout ?? 'd517,270x71,0,0{135x71,0,0,87,134x71,136,0[134x35,136,0,90,134x35,136,36,93]}',
  31. ].join('\\t')
  32. }
  33. function runResult(stdout: string, overrides: Partial<BashRunResult> = {}): BashRunResult {
  34. return {
  35. exitCode: 0,
  36. signal: null,
  37. timedOut: false,
  38. aborted: false,
  39. timeoutMs: 60_000,
  40. stdout: { text: stdout, truncated: false },
  41. stderr: { text: '', truncated: false },
  42. ...overrides,
  43. }
  44. }
  45. /** A scriptable fake `ctx.bash` recording the command it was asked to run. */
  46. class FakeBash extends BashExecutor {
  47. commands: string[] = []
  48. result: BashRunResult = runResult(`${tmuxLine()}\n`)
  49. runError?: Error
  50. resolveError?: Error
  51. override resolve(request: BashExecRequest): BashExecSpec {
  52. if (this.resolveError) throw this.resolveError
  53. return {
  54. command: request.command,
  55. workdir: request.workdir ?? '/work',
  56. timeoutMs: request.timeoutMs ?? 60_000,
  57. stdoutMaxBytes: request.stdoutMaxBytes ?? 64_000,
  58. signal: request.signal,
  59. sandboxPolicy: request.sandboxPolicy,
  60. }
  61. }
  62. override async run(spec: BashExecSpec): Promise<BashRunResult> {
  63. this.commands.push(spec.command)
  64. if (this.runError) throw this.runError
  65. return this.result
  66. }
  67. override start(): BashProcess {
  68. throw new Error('tmux-context must never start a background task')
  69. }
  70. }
  71. async function mount(config: Config, withBash: true): Promise<{ ctx: Context; bash: FakeBash }>
  72. async function mount(config?: Config, withBash?: boolean): Promise<{ ctx: Context; bash: FakeBash | undefined }>
  73. async function mount(
  74. config: Config = {},
  75. withBash = false,
  76. ): Promise<{ ctx: Context; bash: FakeBash | undefined }> {
  77. const ctx = new Context()
  78. await ctx.plugin(AgentRegistry)
  79. let bash: FakeBash | undefined
  80. if (withBash) {
  81. await ctx.plugin(FakeBash)
  82. bash = ctx.bash as FakeBash
  83. }
  84. await ctx.plugin(tmuxContext, config)
  85. return { ctx, bash }
  86. }
  87. function sessionAgent(session: Session, id = 'agent'): Agent {
  88. return {
  89. id: SessionId(id),
  90. options: {},
  91. session,
  92. inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }),
  93. status: 'running',
  94. ctx: new Context(),
  95. send: () => {},
  96. followup: () => {},
  97. steer: () => {},
  98. inject: () => { throw new Error('tmux-context must append directly to the open step') },
  99. cancel() {},
  100. runMaintenance: task => task(new AbortController().signal),
  101. whenIdle: () => Promise.resolve(),
  102. }
  103. }
  104. function openMessageTurn(session: Session, turn: number): void {
  105. session.append('turn/start', { turn })
  106. session.append('user/message', createUserMessage({
  107. content: [{ type: 'text', text: `turn ${turn}` }],
  108. source: { kind: 'user' },
  109. }), { surfaceOp: 'append' })
  110. }
  111. function contextTexts(session: Session): string[] {
  112. const texts: string[] = []
  113. for (const event of session.events) {
  114. if (event.type === 'user/message'
  115. && event.data.source.kind === 'plugin'
  116. && event.data.source.plugin === 'tmux-context') {
  117. texts.push(event.data.content.find(block => block.type === 'text')?.text ?? '')
  118. }
  119. }
  120. return texts
  121. }
  122. async function fire(
  123. ctx: Context,
  124. agent: Agent,
  125. turn: number,
  126. step: number,
  127. signal: AbortSignal = SIGNAL,
  128. ): Promise<void> {
  129. const decision = await agentEvents(ctx, agent).waterfall(
  130. 'agent/pre-step',
  131. { messages: [], turn, step, signal },
  132. () => Promise.resolve({ kind: 'enter' as const, messages: [] }),
  133. )
  134. if (decision.kind === 'enter') {
  135. for (const message of decision.messages) {
  136. agent.session.append('user/message', message, { surfaceOp: 'append' })
  137. }
  138. }
  139. }
  140. afterEach(() => {
  141. vi.restoreAllMocks()
  142. vi.useRealTimers()
  143. })
  144. describe('tmux-context injection', () => {
  145. it('injects the tmux location on the first step of a turn', async () => {
  146. const { ctx } = await mount({}, true)
  147. const session = Session.create(SessionId('first'))
  148. openMessageTurn(session, 1)
  149. await fire(ctx, sessionAgent(session), 1, 1)
  150. expect(contextTexts(session)).toEqual([
  151. 'tmux location (turn 1):\n'
  152. + 'session 0, window 1 "node", pane 2 %90\n'
  153. + 'window active=1, pane active=0, '
  154. + 'layout d517,270x71,0,0{135x71,0,0,87,134x71,136,0[134x35,136,0,90,134x35,136,36,93]}',
  155. ])
  156. const event = session.events.at(-1)
  157. if (event?.type !== 'user/message') throw new Error('missing tmux context')
  158. // `snapshot` form: one named contribution carrying exactly the reading the
  159. // model saw, so a consumer attributes it without re-splitting prose.
  160. expect(event.data.source).toMatchObject({
  161. kind: 'plugin',
  162. plugin: 'tmux-context',
  163. form: 'snapshot',
  164. sections: [{ name: 'tmux-context' }],
  165. })
  166. expect(event.surfaceOp).toBe('append')
  167. })
  168. it('queries the pane this process runs in and matches its controlling tty', async () => {
  169. const { ctx, bash } = await mount({}, true)
  170. const session = Session.create(SessionId('command'))
  171. openMessageTurn(session, 1)
  172. await fire(ctx, sessionAgent(session), 1, 1)
  173. expect(bash.commands).toHaveLength(1)
  174. const command = bash.commands[0]!
  175. expect(command).toContain('[ -n "$TMUX_PANE" ]')
  176. expect(command).toContain('tmux display-message -t "$TMUX_PANE" -p')
  177. // Guards against an inherited $TMUX_PANE: the pane's tty must equal this
  178. // process's controlling tty (resolved for this exact pid).
  179. expect(command).toContain(`ps -o tty= -p ${process.pid}`)
  180. expect(command).toContain('#{pane_tty}')
  181. expect(command).toContain('[ "$pane_tty" = "/dev/$self_tty" ]')
  182. })
  183. it('does not run on later steps of a turn', async () => {
  184. const { ctx, bash } = await mount({}, true)
  185. const session = Session.create(SessionId('later-step'))
  186. openMessageTurn(session, 1)
  187. await fire(ctx, sessionAgent(session), 1, 2)
  188. expect(bash.commands).toHaveLength(0)
  189. expect(contextTexts(session)).toHaveLength(0)
  190. })
  191. it('re-injects a new turn only when tmux state changed', async () => {
  192. const { ctx, bash } = await mount({}, true)
  193. const session = Session.create(SessionId('change'))
  194. const agent = sessionAgent(session)
  195. openMessageTurn(session, 1)
  196. await fire(ctx, agent, 1, 1)
  197. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  198. // Same state on turn 2: suppressed.
  199. openMessageTurn(session, 2)
  200. await fire(ctx, agent, 2, 1)
  201. session.append('turn/end', { turn: 2, reason: { kind: 'completed' } })
  202. expect(contextTexts(session)).toHaveLength(1)
  203. // Moved pane on turn 3: re-injected.
  204. bash.result = runResult(`${tmuxLine({ windowName: 'shell', paneId: '%12' })}\n`)
  205. openMessageTurn(session, 3)
  206. await fire(ctx, agent, 3, 1)
  207. const texts = contextTexts(session)
  208. expect(texts).toHaveLength(2)
  209. expect(texts[1]).toContain('tmux location (turn 3):')
  210. expect(texts[1]).toContain('window 1 "shell", pane 2 %12')
  211. })
  212. it('honors a positive refresh interval between injections', async () => {
  213. vi.useFakeTimers()
  214. vi.setSystemTime(1_000)
  215. const { ctx, bash } = await mount({ refreshIntervalMs: 10_000 }, true)
  216. const session = Session.create(SessionId('interval'))
  217. const agent = sessionAgent(session)
  218. openMessageTurn(session, 1)
  219. await fire(ctx, agent, 1, 1)
  220. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  221. // Changed state but inside the interval: suppressed, and never queried.
  222. bash.result = runResult(`${tmuxLine({ paneId: '%99' })}\n`)
  223. vi.setSystemTime(5_000)
  224. openMessageTurn(session, 2)
  225. await fire(ctx, agent, 2, 1)
  226. expect(contextTexts(session)).toHaveLength(1)
  227. expect(bash.commands).toHaveLength(1)
  228. // Past the interval: queried and re-injected.
  229. vi.setSystemTime(12_000)
  230. openMessageTurn(session, 3)
  231. await fire(ctx, agent, 3, 1)
  232. expect(contextTexts(session)).toHaveLength(2)
  233. expect(bash.commands).toHaveLength(2)
  234. })
  235. })
  236. describe('tmux-context prior-reading resilience', () => {
  237. it('treats a prior non-text plugin reading as absent and injects afresh', async () => {
  238. const { ctx, bash } = await mount({}, true)
  239. const session = Session.create(SessionId('prior-non-text'))
  240. const agent = sessionAgent(session)
  241. openMessageTurn(session, 1)
  242. session.append('user/message', createUserMessage({
  243. content: [{ type: 'reasoning', text: 'not a location' }],
  244. source: { kind: 'plugin', plugin: 'tmux-context' },
  245. }), { surfaceOp: 'append' })
  246. await fire(ctx, agent, 1, 1)
  247. expect(bash.commands).toHaveLength(1)
  248. expect(contextTexts(session).at(-1)).toContain('tmux location (turn 1):')
  249. })
  250. it('treats a prior single-line plugin reading (no newline) as empty state', async () => {
  251. const { ctx, bash } = await mount({}, true)
  252. const session = Session.create(SessionId('prior-single-line'))
  253. const agent = sessionAgent(session)
  254. openMessageTurn(session, 1)
  255. session.append('user/message', createUserMessage({
  256. content: [{ type: 'text', text: 'single line, no newline' }],
  257. source: { kind: 'plugin', plugin: 'tmux-context' },
  258. }), { surfaceOp: 'append' })
  259. await fire(ctx, agent, 1, 1)
  260. // Empty prior state never equals the multi-line reading, so it re-injects.
  261. expect(bash.commands).toHaveLength(1)
  262. expect(contextTexts(session).at(-1)).toContain('tmux location (turn 1):')
  263. })
  264. })
  265. describe('tmux-context no-op paths', () => {
  266. it('is a no-op when no bash executor is mounted', async () => {
  267. const { ctx } = await mount()
  268. const session = Session.create(SessionId('no-bash'))
  269. openMessageTurn(session, 1)
  270. await fire(ctx, sessionAgent(session), 1, 1)
  271. expect(contextTexts(session)).toHaveLength(0)
  272. })
  273. it('is a no-op when the tmux query exits nonzero (outside tmux, or an inherited env whose tty does not match the pane)', async () => {
  274. const { ctx, bash } = await mount({}, true)
  275. bash.result = runResult('', { exitCode: 1 })
  276. const session = Session.create(SessionId('outside-tmux'))
  277. openMessageTurn(session, 1)
  278. await fire(ctx, sessionAgent(session), 1, 1)
  279. expect(contextTexts(session)).toHaveLength(0)
  280. })
  281. it('is a no-op when the reading has the wrong field count', async () => {
  282. const { ctx, bash } = await mount({}, true)
  283. bash.result = runResult('0\\t1\\tnode\n')
  284. const session = Session.create(SessionId('malformed'))
  285. openMessageTurn(session, 1)
  286. await fire(ctx, sessionAgent(session), 1, 1)
  287. expect(contextTexts(session)).toHaveLength(0)
  288. })
  289. it('is a no-op when the pane id is empty', async () => {
  290. const { ctx, bash } = await mount({}, true)
  291. bash.result = runResult(`${tmuxLine({ paneId: '' })}\n`)
  292. const session = Session.create(SessionId('empty-pane'))
  293. openMessageTurn(session, 1)
  294. await fire(ctx, sessionAgent(session), 1, 1)
  295. expect(contextTexts(session)).toHaveLength(0)
  296. })
  297. it('warns and injects nothing when the executor rejects the run', async () => {
  298. const { ctx, bash } = await mount({}, true)
  299. bash.runError = new Error('bash executor unavailable')
  300. const warn = vi.spyOn(ctx.logger, 'warn')
  301. const session = Session.create(SessionId('run-rejected'))
  302. openMessageTurn(session, 1)
  303. await fire(ctx, sessionAgent(session), 1, 1)
  304. expect(contextTexts(session)).toHaveLength(0)
  305. expect(warn).toHaveBeenCalledWith(expect.stringContaining('bash executor unavailable'))
  306. })
  307. it('warns and injects nothing when the executor rejects the command at resolve', async () => {
  308. const { ctx, bash } = await mount({}, true)
  309. bash.resolveError = new Error('command denied by policy')
  310. const warn = vi.spyOn(ctx.logger, 'warn')
  311. const session = Session.create(SessionId('resolve-rejected'))
  312. openMessageTurn(session, 1)
  313. await fire(ctx, sessionAgent(session), 1, 1)
  314. expect(contextTexts(session)).toHaveLength(0)
  315. expect(warn).toHaveBeenCalledWith(expect.stringContaining('command denied by policy'))
  316. })
  317. it('reports a non-Error rejection in the warning', async () => {
  318. const { ctx, bash } = await mount({}, true)
  319. // Non-Error throw: the executor seam is typed, but a bad impl can reject with anything.
  320. bash.runError = 'spawn refused' as unknown as Error
  321. const warn = vi.spyOn(ctx.logger, 'warn')
  322. const session = Session.create(SessionId('non-error-rejection'))
  323. openMessageTurn(session, 1)
  324. await fire(ctx, sessionAgent(session), 1, 1)
  325. expect(contextTexts(session)).toHaveLength(0)
  326. expect(warn).toHaveBeenCalledWith(expect.stringContaining('spawn refused'))
  327. })
  328. it('skips an already-aborted prompt submission', async () => {
  329. const { ctx } = await mount({}, true)
  330. const session = Session.create(SessionId('ordering'))
  331. const agent = sessionAgent(session)
  332. openMessageTurn(session, 1)
  333. const abort = new AbortController()
  334. abort.abort()
  335. await fire(ctx, agent, 1, 1, abort.signal)
  336. expect(contextTexts(session)).toHaveLength(0)
  337. await fire(ctx, agent, 1, 1)
  338. expect(contextTexts(session)).toHaveLength(1)
  339. })
  340. })
  341. describe('tmux-context configuration', () => {
  342. it('rejects a negative refresh interval at plugin load', async () => {
  343. await expect(mount({ refreshIntervalMs: -1 })).rejects.toThrow(
  344. /refreshIntervalMs must be a non-negative safe integer/,
  345. )
  346. })
  347. it('rejects a non-integer refresh interval at plugin load', async () => {
  348. await expect(mount({ refreshIntervalMs: 1.5 })).rejects.toThrow(
  349. /refreshIntervalMs must be a non-negative safe integer/,
  350. )
  351. })
  352. })