tmux-context.spec.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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. [],
  132. { turn, step, signal },
  133. () => Promise.resolve({ kind: 'enter' as const, messages: [] }),
  134. )
  135. if (decision.kind === 'enter') {
  136. for (const message of decision.messages) {
  137. agent.session.append('user/message', message, { surfaceOp: 'append' })
  138. }
  139. }
  140. }
  141. afterEach(() => {
  142. vi.restoreAllMocks()
  143. vi.useRealTimers()
  144. })
  145. describe('tmux-context injection', () => {
  146. it('injects the tmux location on the first step of a turn', async () => {
  147. const { ctx } = await mount({}, true)
  148. const session = Session.create(SessionId('first'))
  149. openMessageTurn(session, 1)
  150. await fire(ctx, sessionAgent(session), 1, 1)
  151. expect(contextTexts(session)).toEqual([
  152. 'tmux location (turn 1):\n'
  153. + 'session 0, window 1 "node", pane 2 %90\n'
  154. + 'window active=1, pane active=0, '
  155. + 'layout d517,270x71,0,0{135x71,0,0,87,134x71,136,0[134x35,136,0,90,134x35,136,36,93]}',
  156. ])
  157. const event = session.events.at(-1)
  158. if (event?.type !== 'user/message') throw new Error('missing tmux context')
  159. expect(event.data.source).toEqual({ kind: 'plugin', plugin: 'tmux-context' })
  160. expect(event.surfaceOp).toBe('append')
  161. })
  162. it('queries the pane this process runs in and matches its controlling tty', async () => {
  163. const { ctx, bash } = await mount({}, true)
  164. const session = Session.create(SessionId('command'))
  165. openMessageTurn(session, 1)
  166. await fire(ctx, sessionAgent(session), 1, 1)
  167. expect(bash.commands).toHaveLength(1)
  168. const command = bash.commands[0]!
  169. expect(command).toContain('[ -n "$TMUX_PANE" ]')
  170. expect(command).toContain('tmux display-message -t "$TMUX_PANE" -p')
  171. // Guards against an inherited $TMUX_PANE: the pane's tty must equal this
  172. // process's controlling tty (resolved for this exact pid).
  173. expect(command).toContain(`ps -o tty= -p ${process.pid}`)
  174. expect(command).toContain('#{pane_tty}')
  175. expect(command).toContain('[ "$pane_tty" = "/dev/$self_tty" ]')
  176. })
  177. it('does not run on later steps of a turn', async () => {
  178. const { ctx, bash } = await mount({}, true)
  179. const session = Session.create(SessionId('later-step'))
  180. openMessageTurn(session, 1)
  181. await fire(ctx, sessionAgent(session), 1, 2)
  182. expect(bash.commands).toHaveLength(0)
  183. expect(contextTexts(session)).toHaveLength(0)
  184. })
  185. it('re-injects a new turn only when tmux state changed', async () => {
  186. const { ctx, bash } = await mount({}, true)
  187. const session = Session.create(SessionId('change'))
  188. const agent = sessionAgent(session)
  189. openMessageTurn(session, 1)
  190. await fire(ctx, agent, 1, 1)
  191. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  192. // Same state on turn 2: suppressed.
  193. openMessageTurn(session, 2)
  194. await fire(ctx, agent, 2, 1)
  195. session.append('turn/end', { turn: 2, reason: { kind: 'completed' } })
  196. expect(contextTexts(session)).toHaveLength(1)
  197. // Moved pane on turn 3: re-injected.
  198. bash.result = runResult(`${tmuxLine({ windowName: 'shell', paneId: '%12' })}\n`)
  199. openMessageTurn(session, 3)
  200. await fire(ctx, agent, 3, 1)
  201. const texts = contextTexts(session)
  202. expect(texts).toHaveLength(2)
  203. expect(texts[1]).toContain('tmux location (turn 3):')
  204. expect(texts[1]).toContain('window 1 "shell", pane 2 %12')
  205. })
  206. it('honors a positive refresh interval between injections', async () => {
  207. vi.useFakeTimers()
  208. vi.setSystemTime(1_000)
  209. const { ctx, bash } = await mount({ refreshIntervalMs: 10_000 }, true)
  210. const session = Session.create(SessionId('interval'))
  211. const agent = sessionAgent(session)
  212. openMessageTurn(session, 1)
  213. await fire(ctx, agent, 1, 1)
  214. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  215. // Changed state but inside the interval: suppressed, and never queried.
  216. bash.result = runResult(`${tmuxLine({ paneId: '%99' })}\n`)
  217. vi.setSystemTime(5_000)
  218. openMessageTurn(session, 2)
  219. await fire(ctx, agent, 2, 1)
  220. expect(contextTexts(session)).toHaveLength(1)
  221. expect(bash.commands).toHaveLength(1)
  222. // Past the interval: queried and re-injected.
  223. vi.setSystemTime(12_000)
  224. openMessageTurn(session, 3)
  225. await fire(ctx, agent, 3, 1)
  226. expect(contextTexts(session)).toHaveLength(2)
  227. expect(bash.commands).toHaveLength(2)
  228. })
  229. })
  230. describe('tmux-context prior-reading resilience', () => {
  231. it('treats a prior non-text plugin reading as absent and injects afresh', async () => {
  232. const { ctx, bash } = await mount({}, true)
  233. const session = Session.create(SessionId('prior-non-text'))
  234. const agent = sessionAgent(session)
  235. openMessageTurn(session, 1)
  236. session.append('user/message', createUserMessage({
  237. content: [{ type: 'reasoning', text: 'not a location' }],
  238. source: { kind: 'plugin', plugin: 'tmux-context' },
  239. }), { surfaceOp: 'append' })
  240. await fire(ctx, agent, 1, 1)
  241. expect(bash.commands).toHaveLength(1)
  242. expect(contextTexts(session).at(-1)).toContain('tmux location (turn 1):')
  243. })
  244. it('treats a prior single-line plugin reading (no newline) as empty state', async () => {
  245. const { ctx, bash } = await mount({}, true)
  246. const session = Session.create(SessionId('prior-single-line'))
  247. const agent = sessionAgent(session)
  248. openMessageTurn(session, 1)
  249. session.append('user/message', createUserMessage({
  250. content: [{ type: 'text', text: 'single line, no newline' }],
  251. source: { kind: 'plugin', plugin: 'tmux-context' },
  252. }), { surfaceOp: 'append' })
  253. await fire(ctx, agent, 1, 1)
  254. // Empty prior state never equals the multi-line reading, so it re-injects.
  255. expect(bash.commands).toHaveLength(1)
  256. expect(contextTexts(session).at(-1)).toContain('tmux location (turn 1):')
  257. })
  258. })
  259. describe('tmux-context no-op paths', () => {
  260. it('is a no-op when no bash executor is mounted', async () => {
  261. const { ctx } = await mount()
  262. const session = Session.create(SessionId('no-bash'))
  263. openMessageTurn(session, 1)
  264. await fire(ctx, sessionAgent(session), 1, 1)
  265. expect(contextTexts(session)).toHaveLength(0)
  266. })
  267. 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 () => {
  268. const { ctx, bash } = await mount({}, true)
  269. bash.result = runResult('', { exitCode: 1 })
  270. const session = Session.create(SessionId('outside-tmux'))
  271. openMessageTurn(session, 1)
  272. await fire(ctx, sessionAgent(session), 1, 1)
  273. expect(contextTexts(session)).toHaveLength(0)
  274. })
  275. it('is a no-op when the reading has the wrong field count', async () => {
  276. const { ctx, bash } = await mount({}, true)
  277. bash.result = runResult('0\\t1\\tnode\n')
  278. const session = Session.create(SessionId('malformed'))
  279. openMessageTurn(session, 1)
  280. await fire(ctx, sessionAgent(session), 1, 1)
  281. expect(contextTexts(session)).toHaveLength(0)
  282. })
  283. it('is a no-op when the pane id is empty', async () => {
  284. const { ctx, bash } = await mount({}, true)
  285. bash.result = runResult(`${tmuxLine({ paneId: '' })}\n`)
  286. const session = Session.create(SessionId('empty-pane'))
  287. openMessageTurn(session, 1)
  288. await fire(ctx, sessionAgent(session), 1, 1)
  289. expect(contextTexts(session)).toHaveLength(0)
  290. })
  291. it('warns and injects nothing when the executor rejects the run', async () => {
  292. const { ctx, bash } = await mount({}, true)
  293. bash.runError = new Error('bash executor unavailable')
  294. const warn = vi.spyOn(ctx.logger, 'warn')
  295. const session = Session.create(SessionId('run-rejected'))
  296. openMessageTurn(session, 1)
  297. await fire(ctx, sessionAgent(session), 1, 1)
  298. expect(contextTexts(session)).toHaveLength(0)
  299. expect(warn).toHaveBeenCalledWith(expect.stringContaining('bash executor unavailable'))
  300. })
  301. it('warns and injects nothing when the executor rejects the command at resolve', async () => {
  302. const { ctx, bash } = await mount({}, true)
  303. bash.resolveError = new Error('command denied by policy')
  304. const warn = vi.spyOn(ctx.logger, 'warn')
  305. const session = Session.create(SessionId('resolve-rejected'))
  306. openMessageTurn(session, 1)
  307. await fire(ctx, sessionAgent(session), 1, 1)
  308. expect(contextTexts(session)).toHaveLength(0)
  309. expect(warn).toHaveBeenCalledWith(expect.stringContaining('command denied by policy'))
  310. })
  311. it('reports a non-Error rejection in the warning', async () => {
  312. const { ctx, bash } = await mount({}, true)
  313. // Non-Error throw: the executor seam is typed, but a bad impl can reject with anything.
  314. bash.runError = 'spawn refused' as unknown as Error
  315. const warn = vi.spyOn(ctx.logger, 'warn')
  316. const session = Session.create(SessionId('non-error-rejection'))
  317. openMessageTurn(session, 1)
  318. await fire(ctx, sessionAgent(session), 1, 1)
  319. expect(contextTexts(session)).toHaveLength(0)
  320. expect(warn).toHaveBeenCalledWith(expect.stringContaining('spawn refused'))
  321. })
  322. it('skips an already-aborted prompt submission', async () => {
  323. const { ctx } = await mount({}, true)
  324. const session = Session.create(SessionId('ordering'))
  325. const agent = sessionAgent(session)
  326. openMessageTurn(session, 1)
  327. const abort = new AbortController()
  328. abort.abort()
  329. await fire(ctx, agent, 1, 1, abort.signal)
  330. expect(contextTexts(session)).toHaveLength(0)
  331. await fire(ctx, agent, 1, 1)
  332. expect(contextTexts(session)).toHaveLength(1)
  333. })
  334. })
  335. describe('tmux-context configuration', () => {
  336. it('rejects a negative refresh interval at plugin load', async () => {
  337. await expect(mount({ refreshIntervalMs: -1 })).rejects.toThrow(
  338. /refreshIntervalMs must be a non-negative safe integer/,
  339. )
  340. })
  341. it('rejects a non-integer refresh interval at plugin load', async () => {
  342. await expect(mount({ refreshIntervalMs: 1.5 })).rejects.toThrow(
  343. /refreshIntervalMs must be a non-negative safe integer/,
  344. )
  345. })
  346. })