tmux-context.spec.ts 14 KB

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