@fish-under-sea/dsh-agent-teams-fish 1.0.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (179) hide show
  1. package/NOTICE.md +13 -7
  2. package/README.en.md +20 -12
  3. package/README.md +20 -12
  4. package/compatibility.json +82 -46
  5. package/icon.png +0 -0
  6. package/lib/artifacts.js +148 -25
  7. package/lib/client/ActivityPanel.js +26 -5
  8. package/lib/client/WorkspaceActivity.js +6 -4
  9. package/lib/client/activity-monitor.js +113 -41
  10. package/lib/client/locales.js +14 -0
  11. package/lib/client.js +433 -199
  12. package/lib/client.js.map +1 -1
  13. package/lib/command.js +7 -4
  14. package/lib/git-artifact-stamp.json +2 -2
  15. package/lib/harness-compat.js +120 -62
  16. package/lib/index.js +7 -10
  17. package/lib/mailbox.js +15 -5
  18. package/lib/members.js +221 -154
  19. package/lib/snapshot.js +15 -10
  20. package/lib/state.js +41 -8
  21. package/lib/tools.js +123 -64
  22. package/lib/types/artifacts.d.ts +6 -3
  23. package/lib/types/client/activity-monitor.d.ts +13 -4
  24. package/lib/types/client/locales.d.ts +14 -0
  25. package/lib/types/harness-compat.d.ts +63 -16
  26. package/lib/types/mailbox.d.ts +2 -0
  27. package/lib/types/members.d.ts +5 -17
  28. package/lib/types/snapshot.d.ts +12 -7
  29. package/lib/types/state.d.ts +10 -3
  30. package/lib/types/types.d.ts +5 -0
  31. package/lib/types/web-routes.d.ts +2 -0
  32. package/lib/types/workspace-audit-service.d.ts +35 -0
  33. package/lib/types/workspace-audit-worker.d.ts +1 -0
  34. package/lib/web-routes.js +31 -0
  35. package/lib/workspace-audit-service.js +165 -0
  36. package/lib/workspace-audit-worker.js +11 -0
  37. package/lib/workspace-audit.js +6 -5
  38. package/locale/en.json +6 -0
  39. package/locale/zh.json +6 -0
  40. package/package.json +69 -64
  41. package/pnpm-workspace.yaml +306 -273
  42. package/release-notes/v0.1.25.md +16 -0
  43. package/release-notes/v0.1.26.md +19 -0
  44. package/release-notes/v0.1.27.md +42 -0
  45. package/release-notes/v0.1.28.md +45 -0
  46. package/release-notes/v0.1.29.md +23 -0
  47. package/release-notes/v1.1.0.md +42 -0
  48. package/release-notes/v2.0.0.md +17 -0
  49. package/scripts/artwork-role-match.test.mjs +517 -0
  50. package/scripts/capabilities.test.mjs +301 -0
  51. package/scripts/check-install-channel.mjs +55 -0
  52. package/scripts/check-install-channel.test.mjs +39 -0
  53. package/scripts/clean-build.mjs +14 -0
  54. package/scripts/client-harness-migration.test.mjs +46 -0
  55. package/scripts/compatibility.mjs +20 -0
  56. package/scripts/compatibility.test.mjs +187 -0
  57. package/scripts/corrupt-teamjson.test.mjs +180 -0
  58. package/scripts/custom-artwork.test.mjs +273 -0
  59. package/scripts/fallback-tdd.mjs +61 -0
  60. package/scripts/fixtures/harness-benchmark-scope.mjs +16 -0
  61. package/scripts/fixtures/harness-benchmark-scope.test.mjs +18 -0
  62. package/scripts/fixtures/harness-complex-case.mjs +201 -0
  63. package/scripts/fixtures/harness-complex-case.test.mjs +21 -0
  64. package/scripts/fixtures/harness-complex-oracle.mjs +63 -0
  65. package/scripts/fixtures/harness-issue-case.mjs +51 -0
  66. package/scripts/fixtures/harness-issue159-case.mjs +28 -0
  67. package/scripts/fixtures/harness-model-case.mjs +127 -0
  68. package/scripts/fixtures/harness-model-case.test.mjs +37 -0
  69. package/scripts/fixtures/harness-model-driver.mjs +100 -0
  70. package/scripts/fixtures/harness-runtime-credentials.mjs +23 -0
  71. package/scripts/fixtures/harness-runtime-entry.mjs +171 -0
  72. package/scripts/fixtures/harness-runtime-idle.mjs +42 -0
  73. package/scripts/fixtures/harness-runtime-llm.mjs +193 -0
  74. package/scripts/fixtures/harness-runtime-protocol.mjs +187 -0
  75. package/scripts/fixtures/harness-runtime-resume.mjs +24 -0
  76. package/scripts/fixtures/harness-runtime-stability.mjs +282 -0
  77. package/scripts/fixtures/harness-runtime-tools.mjs +13 -0
  78. package/scripts/fixtures/harness-runtime-web-approval.mjs +341 -0
  79. package/scripts/fixtures/issue-336-audit-worker.mjs +18 -0
  80. package/scripts/git-artifacts.mjs +64 -0
  81. package/scripts/git-artifacts.test.mjs +32 -0
  82. package/scripts/harness-compat-tdd.mjs +492 -0
  83. package/scripts/harness-issue-verify.mjs +26 -0
  84. package/scripts/harness-model-benchmark.mjs +163 -0
  85. package/scripts/harness-runtime-platform.test.mjs +31 -0
  86. package/scripts/harness-runtime-scenarios.mjs +297 -0
  87. package/scripts/harness-runtime-verify.mjs +169 -0
  88. package/scripts/harness-source-verify.mjs +211 -0
  89. package/scripts/harness-source-verify.test.mjs +97 -0
  90. package/scripts/harness-validation.mjs +68 -0
  91. package/scripts/harness-validation.test.mjs +95 -0
  92. package/scripts/http-body.test.mjs +72 -0
  93. package/scripts/import-vendor-artwork.mjs +78 -0
  94. package/scripts/inline-plan-blank-optional-tdd.mjs +121 -0
  95. package/scripts/issue-159.test.mjs +78 -0
  96. package/scripts/issue-188.test.mjs +148 -0
  97. package/scripts/issue-189.test.mjs +100 -0
  98. package/scripts/issue-203-card.test.mjs +181 -0
  99. package/scripts/issue-205.test.mjs +163 -0
  100. package/scripts/issue-234.test.mjs +424 -0
  101. package/scripts/issue-236-stale-module.test.mjs +63 -0
  102. package/scripts/issue-236.test.mjs +59 -0
  103. package/scripts/issue-262.test.mjs +98 -0
  104. package/scripts/issue-336.test.mjs +404 -0
  105. package/scripts/legacy-session-source-repair.test.mjs +201 -0
  106. package/scripts/lifecycle-verify.mjs +1573 -0
  107. package/scripts/lineage-identity.test.mjs +77 -0
  108. package/scripts/member-failure-tdd.mjs +451 -0
  109. package/scripts/member-spawn-recovery.test.mjs +92 -0
  110. package/scripts/quality-gates-amend.test.mjs +161 -0
  111. package/scripts/quality-gates-content-bound.test.mjs +572 -0
  112. package/scripts/quality-gates-cross-binding.test.mjs +184 -0
  113. package/scripts/quality-gates-excluded-scope.test.mjs +163 -0
  114. package/scripts/quality-gates-repair-scope.test.mjs +143 -0
  115. package/scripts/quality-gates-repair-wiring.test.mjs +189 -0
  116. package/scripts/quality-gates-tdd.mjs +1238 -0
  117. package/scripts/quality-gates-work-order.test.mjs +494 -0
  118. package/scripts/readme-version.mjs +89 -0
  119. package/scripts/readme-version.test.mjs +77 -0
  120. package/scripts/release-metadata.mjs +45 -0
  121. package/scripts/release-metadata.test.mjs +66 -0
  122. package/scripts/scoped-release.test.mjs +52 -0
  123. package/scripts/stability-tdd.mjs +144 -0
  124. package/scripts/stress-verify.mjs +548 -0
  125. package/scripts/symlink-support.mjs +46 -0
  126. package/scripts/sync-skill.mjs +103 -0
  127. package/scripts/tool-policies.test.mjs +280 -0
  128. package/scripts/update-skills.mjs +105 -0
  129. package/scripts/update-skills.test.mjs +79 -0
  130. package/scripts/upgrade-status.mjs +66 -0
  131. package/scripts/upgrade-status.test.mjs +83 -0
  132. package/scripts/verify-package.mjs +73 -0
  133. package/scripts/verify.mjs +2199 -0
  134. package/scripts/web-routes-verify.mjs +142 -0
  135. package/scripts/workspace-activity.test.mjs +346 -0
  136. package/scripts/workspace-summary.test.mjs +49 -0
  137. package/src/artifacts.ts +487 -0
  138. package/src/artwork-source.ts +262 -0
  139. package/src/capabilities.ts +113 -0
  140. package/src/client/ActivityPanel.module.css +2390 -0
  141. package/src/client/ActivityPanel.tsx +1507 -0
  142. package/src/client/AgentTeamsCard.module.css +148 -0
  143. package/src/client/AgentTeamsCard.tsx +155 -0
  144. package/src/client/StagingPlanEditor.tsx +829 -0
  145. package/src/client/TeamChatEntry.tsx +27 -0
  146. package/src/client/WorkspaceActivity.module.css +41 -0
  147. package/src/client/WorkspaceActivity.tsx +137 -0
  148. package/src/client/activity-model.ts +372 -0
  149. package/src/client/activity-monitor.ts +440 -0
  150. package/src/client/agent-teams-card-definition.ts +250 -0
  151. package/src/client/artwork.ts +374 -0
  152. package/src/client/icons.tsx +17 -0
  153. package/src/client/index.tsx +140 -0
  154. package/src/client/locales.ts +481 -0
  155. package/src/client/panel-geometry.ts +194 -0
  156. package/src/client/session-navigation.ts +73 -0
  157. package/src/client/workspace-state.ts +52 -0
  158. package/src/command.ts +145 -0
  159. package/src/css-modules.d.ts +4 -0
  160. package/src/event-types.ts +177 -0
  161. package/src/events.ts +78 -0
  162. package/src/harness-compat.ts +570 -0
  163. package/src/index.ts +599 -0
  164. package/src/lineage.ts +248 -0
  165. package/src/mailbox.ts +185 -0
  166. package/src/members.ts +1230 -0
  167. package/src/profiles.ts +765 -0
  168. package/src/quality-gates.ts +2124 -0
  169. package/src/scheduler.ts +554 -0
  170. package/src/snapshot.ts +333 -0
  171. package/src/state.ts +1317 -0
  172. package/src/tool-names.ts +14 -0
  173. package/src/tool-policies.ts +219 -0
  174. package/src/tools.ts +2939 -0
  175. package/src/types.ts +414 -0
  176. package/src/web-routes.ts +128 -0
  177. package/src/workspace-audit-service.ts +182 -0
  178. package/src/workspace-audit-worker.ts +12 -0
  179. package/src/workspace-audit.ts +57 -0
@@ -0,0 +1,142 @@
1
+ #!/usr/bin/env node
2
+ /** Exercise raw plugin routes through the installed host's browser-auth service. */
3
+ import assert from 'node:assert/strict'
4
+ import { createServer, request } from 'node:http'
5
+ import { once } from 'node:events'
6
+ import { Context } from '@deepseek-ai/cordis'
7
+ import { apply as installConnection } from '@deepseek-ai/dsh-client-connection'
8
+ import { authenticatedWebRoutes, readJsonRequest, RequestBodyError } from '../lib/web-routes.js'
9
+
10
+ const ctx = new Context()
11
+ const routes = new Map()
12
+ const server = createServer((req, res) => {
13
+ if (req.url.startsWith('/?token=')) {
14
+ ctx.connection.authorizeIndex(req, res)
15
+ return
16
+ }
17
+ const route = routes.get(req.url)
18
+ if (!route) { res.writeHead(404); res.end(); return }
19
+ Promise.resolve(route.handler(req, res)).catch(() => {
20
+ res.writeHead(500); res.end()
21
+ })
22
+ })
23
+ const webServer = {
24
+ register(route) {
25
+ assert(!routes.has(route.path), `duplicate route: ${route.path}`)
26
+ routes.set(route.path, route)
27
+ return () => routes.delete(route.path)
28
+ },
29
+ }
30
+ // Only persistence is replaced: actual token exchange, signed cookies,
31
+ // Host/Origin validation, and HTTP requests all use the target implementation.
32
+ let credentialRecord
33
+ ctx.provide('credentials', {
34
+ async modifyRecord(_key, update) {
35
+ credentialRecord = await update(credentialRecord) ?? credentialRecord
36
+ return credentialRecord
37
+ },
38
+ })
39
+ ctx.provide('webServer', webServer)
40
+ let gate
41
+ let calls = 0
42
+ const paths = ['/plugins/dsh-agent-teams/state', '/plugins/dsh-agent-teams/plan']
43
+ const routePlugin = {
44
+ name: 'agent-teams-auth-test',
45
+ apply(owner) {
46
+ const protectedRoutes = authenticatedWebRoutes(webServer, () => gate)
47
+ for (const path of paths) {
48
+ owner.effect(() => protectedRoutes.register({
49
+ kind: 'exact', path,
50
+ async handler(req, res) {
51
+ if (req.method === 'POST') {
52
+ try {
53
+ await readJsonRequest(req, 64)
54
+ } catch (error) {
55
+ res.writeHead(error instanceof RequestBodyError ? error.status : 500)
56
+ res.end()
57
+ return
58
+ }
59
+ }
60
+ calls += 1
61
+ res.writeHead(200, { 'content-type': 'application/json' })
62
+ res.end(JSON.stringify({ ok: true }))
63
+ },
64
+ }))
65
+ }
66
+ },
67
+ }
68
+
69
+ try {
70
+ await installConnection(ctx, {})
71
+ gate = ctx.connection
72
+ server.listen(0, '127.0.0.1')
73
+ await once(server, 'listening')
74
+ const base = `http://127.0.0.1:${server.address().port}`
75
+ const fiber = ctx.plugin(routePlugin)
76
+ await fiber.inertia
77
+ for (const path of paths) {
78
+ const response = await fetch(base + path, { method: path.endsWith('/plan') ? 'POST' : 'GET' })
79
+ assert.equal(response.status, 401)
80
+ assert.equal(response.headers.get('cache-control'), 'no-store')
81
+ assert.deepEqual(await response.json(), { error: 'unauthorized' })
82
+ }
83
+ assert.equal(calls, 0, 'unauthenticated requests must not read or mutate team state')
84
+
85
+ const exchange = await fetch(gate.authenticatedUrl(base), { redirect: 'manual' })
86
+ assert.equal(exchange.status, 303)
87
+ const cookie = exchange.headers.getSetCookie().map(value => value.split(';')[0]).join('; ')
88
+ assert(cookie, 'real Connection must issue a browser cookie')
89
+ for (const path of paths) {
90
+ const response = await fetch(base + path, {
91
+ method: path.endsWith('/plan') ? 'POST' : 'GET', headers: { cookie, origin: base },
92
+ })
93
+ assert.equal(response.status, 200)
94
+ assert.deepEqual(await response.json(), { ok: true })
95
+ }
96
+ assert.equal(calls, 2)
97
+ const unauthenticatedUpload = await fetch(base + paths[1], { method: 'POST', body: 'x'.repeat(65) })
98
+ assert.equal(unauthenticatedUpload.status, 401, 'authentication runs before parsing request bodies')
99
+ await unauthenticatedUpload.arrayBuffer()
100
+ const oversized = await fetch(base + paths[1], {
101
+ method: 'POST', headers: { cookie, origin: base }, body: 'x'.repeat(65),
102
+ })
103
+ assert.equal(oversized.status, 413, 'authorized oversized requests fail before mutating team state')
104
+ await oversized.arrayBuffer()
105
+ assert.equal(calls, 2)
106
+ for (const headers of [
107
+ { cookie, origin: 'https://untrusted.invalid' },
108
+ { cookie, 'sec-fetch-site': 'cross-site' },
109
+ { cookie, host: 'untrusted.invalid' },
110
+ ]) {
111
+ // node:http preserves an explicitly hostile Host; Fetch may replace it.
112
+ const status = await new Promise((resolve, reject) => {
113
+ const req = request(base + paths[1], { method: 'POST', headers }, response => {
114
+ response.resume()
115
+ response.on('end', () => resolve(response.statusCode))
116
+ })
117
+ req.on('error', reject)
118
+ req.end()
119
+ })
120
+ assert.equal(status, 403, `reject ${Object.keys(headers).filter(key => key !== 'cookie').join(', ')}`)
121
+ }
122
+ assert.equal(calls, 2, 'rejected origins must not enter the mutation handler')
123
+
124
+ gate = undefined
125
+ const unavailable = await fetch(base + paths[0], { headers: { cookie } })
126
+ assert.equal(unavailable.status, 503)
127
+ await unavailable.arrayBuffer()
128
+ assert.equal(calls, 2, 'missing Connection must fail closed')
129
+
130
+ await fiber.dispose()
131
+ assert(paths.every(path => !routes.has(path)), 'unload removes every owned route')
132
+ gate = ctx.connection
133
+ const reloaded = ctx.plugin(routePlugin)
134
+ await reloaded.inertia
135
+ assert(paths.every(path => routes.has(path)), 'reload restores exactly one registration')
136
+ await reloaded.dispose()
137
+ console.log('PASS Web routes: real host authentication, bounded bodies, trusted origins, fail-closed startup, disposal and reload')
138
+ } finally {
139
+ await ctx.fiber.dispose()
140
+ server.closeAllConnections()
141
+ if (server.listening) await new Promise(resolve => server.close(resolve))
142
+ }
@@ -0,0 +1,346 @@
1
+ import assert from 'node:assert/strict'
2
+ import test from 'node:test'
3
+ import {createWorkspaceState,createTeamDiscovery} from '../lib/client/workspace-state.js'
4
+ import {getActivitySnapshotsSnapshot, getPublishedActivityRows, startActivityPolling, updateActivitySnapshots} from '../lib/client/activity-monitor.js'
5
+
6
+ test('restored, closed, updated and newly created teams have distinct discovery semantics',()=>{
7
+ const discover=createTeamDiscovery()
8
+ const a={teamId:'a'},b={teamId:'b'}
9
+ assert.equal(discover([a]),undefined)
10
+ assert.equal(discover([{...a,phase:'running'}]),undefined)
11
+ assert.equal(discover([a,b]),'b')
12
+ assert.equal(discover([a,b]),undefined)
13
+ assert.equal(discover([]),undefined)
14
+ })
15
+ test('historical cards and selected teams remain bound to their owner',()=>{
16
+ const state=createWorkspaceState();let count=0;const off=state.subscribe(()=>count++)
17
+ const old={teamId:'old',captainSessionId:'',teamName:'Old',members:[]}
18
+ state.remember('a',old)
19
+ state.select('b','new')
20
+ state.remember('a',{...old,teamId:'foreign',captainSessionId:'b'})
21
+ assert.equal(state.getSnapshot().history.size,1)
22
+ assert.equal(state.getSnapshot().history.get('a:old').captainSessionId,'a')
23
+ assert.equal(state.getSnapshot().selected.get('a'),'old')
24
+ assert.equal(state.getSnapshot().selected.get('b'),'new')
25
+ state.status('a','ready');state.status('a','ready')
26
+ assert.equal(count,3)
27
+ off();state.status('a','error');assert.equal(count,3)
28
+ })
29
+ test('offline, invalid data and recovery report health without erasing the last snapshot',async()=>{
30
+ let tick;let response={ok:false};const statuses=[],snapshots=[]
31
+ const poll=startActivityPolling([],{discoverySessionId:'a',fetchState:async()=>response,
32
+ schedule:fn=>{tick=fn;return 1},cancel:()=>{},onStatus:s=>statuses.push(s),publishSnapshots:s=>snapshots.push(s)})
33
+ await poll.firstTick;assert.deepEqual(statuses,['error']);assert.equal(snapshots.length,0)
34
+ response={ok:true,json:async()=>({invalid:true})};tick();await new Promise(resolve=>setImmediate(resolve));assert.equal(statuses.at(-1),'error')
35
+ response={ok:true,json:async()=>({teams:[]})};tick();await new Promise(resolve=>setImmediate(resolve));assert.equal(statuses.at(-1),'ready');assert.equal(snapshots.length,2)
36
+ poll.stop()
37
+ })
38
+ test('disposal prevents a late failed request from updating a different session',async()=>{
39
+ let reject;const statuses=[]
40
+ const poll=startActivityPolling([],{discoverySessionId:'a',fetchState:()=>new Promise((_,no)=>reject=no),schedule:()=>1,cancel:()=>{},onStatus:s=>statuses.push(s)})
41
+ poll.stop();reject(new Error('offline'));await poll.firstTick;assert.deepEqual(statuses,[])
42
+ })
43
+
44
+ test('workspace DAG keeps real dependency endpoints aligned with enlarged nodes',async()=>{
45
+ const {compactDagLayout}=await import('../lib/client/activity-model.js')
46
+ const tasks=[{id:'implement',depth:0,dependencies:[]},{id:'review',depth:1,dependencies:['implement']}]
47
+ const layout=compactDagLayout(tasks,{nodeWidth:164,nodeHeight:76,columnGap:36,rowGap:16})
48
+ assert.equal(layout.width,364)
49
+ assert.equal(layout.nodes[1].x,200)
50
+ assert.equal(layout.edges[0].path,'M164 38C178 38,186 38,200 38')
51
+ })
52
+
53
+ function scriptedPoller(targets, discoverySessionId, responses, runtime = {}) {
54
+ let tick
55
+ const requests = [], snapshots = [], statuses = [], settled = []
56
+ const poll = startActivityPolling(targets, {
57
+ discoverySessionId,
58
+ async fetchState(url, init) {
59
+ const request = { url, tag: init.headers?.['if-none-match'] }
60
+ requests.push(request)
61
+ const response = responses.shift()
62
+ return typeof response === 'function' ? response(request) : response
63
+ },
64
+ schedule(callback) { tick = callback; return 1 },
65
+ cancel() {},
66
+ publishSnapshots(update) { snapshots.push(update) },
67
+ onStatus(status) { statuses.push(status) },
68
+ settleTargets(keys) { settled.push([...keys]) },
69
+ ...runtime,
70
+ })
71
+ return {
72
+ poll, requests, snapshots, statuses, settled,
73
+ async advance() { tick(); await new Promise(resolve => setImmediate(resolve)) },
74
+ }
75
+ }
76
+
77
+ function stateResponse(teams, tag) {
78
+ return Response.json({ teams }, { headers: tag === undefined ? {} : { etag: tag } })
79
+ }
80
+
81
+ test('a poll is scoped only when every discovery and card target has one owner', async () => {
82
+ const sessionId = 'captain+A/&'
83
+ const team = { teamId: 'team', captainSessionId: sessionId }
84
+ const target = { teamId: team.teamId, sessionId, key: 'card' }
85
+ const scoped = scriptedPoller([target], sessionId, [stateResponse([team]), stateResponse([])])
86
+ const mixed = scriptedPoller([target], 'another-captain', [stateResponse([team]), stateResponse([])])
87
+ try {
88
+ await Promise.all([scoped.poll.firstTick, mixed.poll.firstTick])
89
+ const [live, archived] = scoped.requests.map(({ url }) => new URL(url, 'http://fixture').searchParams)
90
+ assert.equal(live.get('session'), sessionId)
91
+ assert.equal(live.get('summary'), '1')
92
+ assert.equal(archived.get('session'), sessionId)
93
+ assert.equal(archived.get('archived'), '1')
94
+ assert.equal(archived.has('summary'), false)
95
+ assert.deepEqual(mixed.requests.map(({ url }) => url), [
96
+ '/plugins/dsh-agent-teams/state', '/plugins/dsh-agent-teams/state?archived=1',
97
+ ])
98
+ } finally {
99
+ scoped.poll.stop()
100
+ mixed.poll.stop()
101
+ }
102
+ })
103
+
104
+ test('a truncated or invalid body never becomes the held validator', async () => {
105
+ const tag = 'W/"live"'
106
+ const lab = scriptedPoller([], 'captain', [
107
+ new Response('{"teams":', { headers: { etag: tag } }),
108
+ stateResponse([null], tag),
109
+ stateResponse([], tag), stateResponse([], 'W/"archive"'),
110
+ new Response(null, { status: 304 }),
111
+ ])
112
+ try {
113
+ await lab.poll.firstTick
114
+ await lab.advance()
115
+ await lab.advance()
116
+ await lab.advance()
117
+ assert.deepEqual(lab.requests.map(({ tag }) => tag), [undefined, undefined, undefined, undefined, tag])
118
+ assert.deepEqual(lab.snapshots, [{ teams: [] }, { archivedTeams: [] }])
119
+ assert.deepEqual(lab.statuses, ['error', 'error', 'ready', 'ready'])
120
+ } finally { lab.poll.stop() }
121
+ })
122
+
123
+ test('304 still retries initial archive discovery and settles the missing card', async () => {
124
+ const history = { teamId: 'finished', captainSessionId: 'captain' }
125
+ const target = { teamId: history.teamId, sessionId: history.captainSessionId, key: 'card' }
126
+ const lab = scriptedPoller([target], 'captain', [
127
+ stateResponse([], 'W/"live"'), new Response(null, { status: 503 }),
128
+ new Response(null, { status: 304 }), stateResponse([history], 'W/"archive"'),
129
+ new Response(null, { status: 304 }),
130
+ ])
131
+ try {
132
+ await lab.poll.firstTick
133
+ await lab.advance()
134
+ await lab.advance()
135
+ assert.deepEqual(lab.requests.map(({ tag }) => tag), [undefined, undefined, 'W/"live"', undefined, 'W/"live"'])
136
+ assert.deepEqual(lab.snapshots, [{ teams: [] }, { archivedTeams: [history] }])
137
+ assert.deepEqual(lab.settled, [['card']])
138
+ } finally { lab.poll.stop() }
139
+ })
140
+
141
+ test('304 retries an archive refresh after a previously live team disappears', async () => {
142
+ const team = { teamId: 'running', captainSessionId: 'captain' }
143
+ const lab = scriptedPoller([], 'captain', [
144
+ stateResponse([team], 'W/"running"'), stateResponse([], 'W/"empty-archive"'),
145
+ stateResponse([], 'W/"finished"'), new Response(null, { status: 503 }),
146
+ new Response(null, { status: 304 }), stateResponse([team], 'W/"archived"'),
147
+ new Response(null, { status: 304 }),
148
+ ])
149
+ try {
150
+ await lab.poll.firstTick
151
+ await lab.advance()
152
+ await lab.advance()
153
+ await lab.advance()
154
+ assert.deepEqual(lab.requests.map(({ tag }) => tag), [
155
+ undefined, undefined, 'W/"running"', 'W/"empty-archive"', 'W/"finished"', 'W/"empty-archive"', 'W/"finished"',
156
+ ])
157
+ assert.deepEqual(lab.snapshots, [{ teams: [team] }, { archivedTeams: [] }, { teams: [] }, { archivedTeams: [team] }])
158
+ } finally { lab.poll.stop() }
159
+ })
160
+
161
+ for (const pauseAt of ['live', 'archive']) {
162
+ test(`a delayed Retry ${pauseAt} response cannot pin an outdated shared snapshot`, async () => {
163
+ const initial = getActivitySnapshotsSnapshot()
164
+ const moved = { teamId: 'moving', captainSessionId: 'captain' }
165
+ const oldLive = [moved]
166
+ const newLive = [{ teamId: 'new', captainSessionId: 'captain' }]
167
+ const liveTag = 'W/"new-live"', archiveTag = 'W/"new-archive"'
168
+ const revalidate = (teams, tag) => request => request.tag === tag
169
+ ? new Response(null, { status: 304 }) : stateResponse(teams, tag)
170
+ const resident = scriptedPoller([], 'captain', [
171
+ stateResponse(oldLive, 'W/"old-live"'), stateResponse([], 'W/"old-archive"'),
172
+ stateResponse(newLive, liveTag), stateResponse([moved], archiveTag),
173
+ revalidate(newLive, liveTag), revalidate([moved], archiveTag), revalidate(newLive, liveTag),
174
+ ], pauseAt === 'live' ? { publishSnapshots: undefined } : {
175
+ publishSnapshots: (update, scope) => updateActivitySnapshots(update, scope),
176
+ getPublishedRows: getPublishedActivityRows,
177
+ })
178
+ let retry
179
+ try {
180
+ await resident.poll.firstTick
181
+ const delayed = Promise.withResolvers()
182
+ const requestedArchive = Promise.withResolvers()
183
+ retry = scriptedPoller([], 'captain', [
184
+ pauseAt === 'live' ? delayed.promise : stateResponse(oldLive, 'W/"old-live"'),
185
+ () => {
186
+ requestedArchive.resolve()
187
+ return pauseAt === 'archive' ? delayed.promise : stateResponse([], 'W/"old-archive"')
188
+ },
189
+ ], { publishSnapshots: undefined })
190
+ if (pauseAt === 'archive') await requestedArchive.promise
191
+ await resident.advance()
192
+ assert.deepEqual(getActivitySnapshotsSnapshot(), { teams: newLive, archivedTeams: [moved] })
193
+ delayed.resolve(pauseAt === 'live'
194
+ ? stateResponse(oldLive, 'W/"old-live"') : stateResponse([], 'W/"old-archive"'))
195
+ await retry.poll.firstTick
196
+ retry.poll.stop()
197
+ assert.deepEqual(getActivitySnapshotsSnapshot(), { teams: pauseAt === 'live' ? oldLive : newLive, archivedTeams: [] })
198
+
199
+ await resident.advance()
200
+ const recovered = getActivitySnapshotsSnapshot()
201
+ assert.deepEqual(recovered, { teams: newLive, archivedTeams: [moved] })
202
+ await resident.advance()
203
+ assert.equal(getActivitySnapshotsSnapshot(), recovered, 'an unchanged tick publishes nothing')
204
+ assert.deepEqual(resident.requests.slice(4).map(({ tag }) => tag), [
205
+ pauseAt === 'live' ? undefined : liveTag, undefined, liveTag,
206
+ ])
207
+ } finally {
208
+ retry?.poll.stop()
209
+ resident.poll.stop()
210
+ updateActivitySnapshots(initial)
211
+ }
212
+ })
213
+ }
214
+
215
+ test('a stopped controller cannot publish its delayed archive response', async () => {
216
+ const initial = getActivitySnapshotsSnapshot()
217
+ const delayed = Promise.withResolvers()
218
+ const requested = Promise.withResolvers()
219
+ const lab = scriptedPoller([], 'captain', [
220
+ stateResponse([], 'W/"live"'),
221
+ () => { requested.resolve(); return delayed.promise },
222
+ ], { publishSnapshots: undefined })
223
+ try {
224
+ await requested.promise
225
+ lab.poll.stop()
226
+ const shown = getActivitySnapshotsSnapshot()
227
+ delayed.resolve(stateResponse([{ teamId: 'history', captainSessionId: 'captain' }], 'W/"archive"'))
228
+ await lab.poll.firstTick
229
+ assert.equal(getActivitySnapshotsSnapshot(), shown)
230
+ } finally {
231
+ lab.poll.stop()
232
+ updateActivitySnapshots(initial)
233
+ }
234
+ })
235
+
236
+ test('switching back during a restart keeps the last successful live and archived rows', async () => {
237
+ const initial = getActivitySnapshotsSnapshot()
238
+ const a = { captainSessionId: 'captain-a', teamId: 'live-a' }
239
+ const b = { captainSessionId: 'captain-b', teamId: 'live-b' }
240
+ const archivedA = { ...a, teamId: 'history-a' }
241
+ const archivedB = { ...b, teamId: 'history-b' }
242
+ const controllers = []
243
+ async function visit(owner, responses) {
244
+ const lab = scriptedPoller([], owner, responses, { publishSnapshots: undefined })
245
+ controllers.push(lab.poll)
246
+ await lab.poll.firstTick
247
+ return lab
248
+ }
249
+ try {
250
+ updateActivitySnapshots({ teams: [], archivedTeams: [] })
251
+ const firstA = await visit(a.captainSessionId, [stateResponse([a]), stateResponse([archivedA])])
252
+ firstA.poll.stop()
253
+ const firstB = await visit(b.captainSessionId, [stateResponse([b]), stateResponse([archivedB])])
254
+ firstB.poll.stop()
255
+ const returned = await visit(a.captainSessionId, [
256
+ () => { throw new Error('host restarting') }, stateResponse([]), stateResponse([]),
257
+ ])
258
+ assert.deepEqual(returned.statuses, ['error'])
259
+ assert.deepEqual(getActivitySnapshotsSnapshot(), { teams: [a, b], archivedTeams: [archivedA, archivedB] })
260
+ await returned.advance()
261
+ assert.deepEqual(getActivitySnapshotsSnapshot(), { teams: [b], archivedTeams: [archivedB] })
262
+ } finally {
263
+ for (const controller of controllers) controller.stop()
264
+ updateActivitySnapshots(initial)
265
+ }
266
+ })
267
+
268
+ test('an older full-table response updates only the requested scope and preserves another validator', async () => {
269
+ const initial = getActivitySnapshotsSnapshot()
270
+ updateActivitySnapshots({ teams: [], archivedTeams: [] })
271
+ const a = { captainSessionId: 'captain-a', teamId: 'live-a' }
272
+ const b = { captainSessionId: 'captain-b', teamId: 'live-b' }
273
+ const archivedA = { ...a, teamId: 'history-a' }
274
+ const archivedB = { ...b, teamId: 'history-b' }
275
+ const tag = 'W/"scope-a"'
276
+ const activeA = scriptedPoller([], a.captainSessionId, [
277
+ stateResponse([a], tag), stateResponse([archivedA], 'W/"archive-a"'), new Response(null, { status: 304 }),
278
+ ], { publishSnapshots: undefined })
279
+ let activeB
280
+ try {
281
+ await activeA.poll.firstTick
282
+ activeB = scriptedPoller([], b.captainSessionId, [
283
+ stateResponse([{ ...a, name: 'stale' }, b]), stateResponse([{ ...archivedA, name: 'stale' }, archivedB]),
284
+ ], { publishSnapshots: undefined })
285
+ await activeB.poll.firstTick
286
+ const shown = getActivitySnapshotsSnapshot()
287
+ assert.deepEqual(shown, { teams: [a, b], archivedTeams: [archivedA, archivedB] })
288
+ await activeA.advance()
289
+ assert.deepEqual(activeA.requests.map(({ tag }) => tag), [undefined, undefined, tag])
290
+ assert.equal(getActivitySnapshotsSnapshot(), shown, 'another session must not invalidate a held snapshot')
291
+ } finally {
292
+ activeA.poll.stop()
293
+ activeB?.poll.stop()
294
+ updateActivitySnapshots(initial)
295
+ }
296
+ })
297
+
298
+ test('an unscoped poll still replaces the full result and invalidates superseded scoped tags', async () => {
299
+ const initial = getActivitySnapshotsSnapshot()
300
+ updateActivitySnapshots({ teams: [], archivedTeams: [] })
301
+ const a = { captainSessionId: 'captain-a', teamId: 'live-a' }
302
+ const c = { captainSessionId: 'captain-c', teamId: 'live-c' }
303
+ const archivedA = { ...a, teamId: 'history-a' }
304
+ const archivedC = { ...c, teamId: 'history-c' }
305
+ const tag = 'W/"scope-a"'
306
+ const activeA = scriptedPoller([], a.captainSessionId, [
307
+ stateResponse([a], tag), stateResponse([archivedA], 'W/"archive-a"'),
308
+ stateResponse([a], tag), stateResponse([archivedA], 'W/"archive-a"'),
309
+ ], { publishSnapshots: undefined })
310
+ let unscoped
311
+ try {
312
+ await activeA.poll.firstTick
313
+ unscoped = scriptedPoller([
314
+ { key: 'a', sessionId: 'captain-a', teamId: 'missing' },
315
+ { key: 'b', sessionId: 'captain-b', teamId: 'missing' },
316
+ ], undefined, [stateResponse([c]), stateResponse([archivedC])], { publishSnapshots: undefined })
317
+ await unscoped.poll.firstTick
318
+ assert.deepEqual(getActivitySnapshotsSnapshot(), { teams: [c], archivedTeams: [archivedC] })
319
+ await activeA.advance()
320
+ assert.deepEqual(activeA.requests.map(({ tag }) => tag), [undefined, undefined, undefined, undefined])
321
+ assert.deepEqual(getActivitySnapshotsSnapshot(), { teams: [c, a], archivedTeams: [archivedC, archivedA] })
322
+ } finally {
323
+ activeA.poll.stop()
324
+ unscoped?.poll.stop()
325
+ updateActivitySnapshots(initial)
326
+ }
327
+ })
328
+
329
+ test('scoped live and archived rows retain only the eight most recently published sessions', () => {
330
+ const initial = getActivitySnapshotsSnapshot()
331
+ function publish(index) {
332
+ const owner = `captain-${index}`
333
+ const row = { captainSessionId: owner, teamId: `team-${index}` }
334
+ updateActivitySnapshots({ teams: [row], archivedTeams: [{ ...row, teamId: `history-${index}` }] }, owner)
335
+ }
336
+ try {
337
+ updateActivitySnapshots({ teams: [], archivedTeams: [] })
338
+ for (let index = 0; index < 8; index++) publish(index)
339
+ publish(0)
340
+ publish(8)
341
+ const shown = getActivitySnapshotsSnapshot()
342
+ for (const rows of [shown.teams, shown.archivedTeams]) {
343
+ assert.deepEqual(rows.map(({ captainSessionId }) => captainSessionId), [2, 3, 4, 5, 6, 7, 0, 8].map(index => `captain-${index}`))
344
+ }
345
+ } finally { updateActivitySnapshots(initial) }
346
+ })
@@ -0,0 +1,49 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import { registerHooks } from 'node:module'
4
+ import React from 'react'
5
+ import { renderToStaticMarkup } from 'react-dom/server'
6
+ import { en, zh } from '../lib/client/locales.js'
7
+
8
+ // Render the production component; only unrelated host UI and CSS imports are stubbed.
9
+ const hook = registerHooks({ resolve(specifier, context, next) {
10
+ let source
11
+ if (specifier.endsWith('.module.css')) source = 'export default new Proxy({}, {get: (_, key) => key})'
12
+ if (context.parentURL?.endsWith('/client/ActivityPanel.js')) {
13
+ if (specifier === '@deepseek-ai/dsh-client-ui-primitives') source = 'export const Modal = () => null'
14
+ if (specifier === './AgentTeamsCard.js') source = 'export const OPEN_PANEL_EVENT = "test-open"'
15
+ if (specifier === './StagingPlanEditor.js') source = 'export const StagingPlanEditor = () => null'
16
+ }
17
+ return source === undefined ? next(specifier, context) : { url: `data:text/javascript,${encodeURIComponent(source)}`, shortCircuit: true }
18
+ } })
19
+ const { TeamSection } = await import('../lib/client/ActivityPanel.js')
20
+ hook.deregister()
21
+ const base = { workspace: '', teamId: 'summary', name: 'Summary', captainSessionId: 'captain', phase: 'running', members: [], tasks: [], messageCount: 0, captainInbox: [] }
22
+ const task = (id, status, state = status) => ({ id, subject: id, status, state, assignee: '', dependencies: [], depth: 0 })
23
+ const render = (team, dict, extra = {}) => renderToStaticMarkup(React.createElement(TeamSection, {
24
+ team, workspace: true, onNavigate() {}, t: (key, values = {}) => dict[key].replace(/\{(\w+)\}/g, (_, name) => String(values[name])), ...extra,
25
+ }))
26
+
27
+ for (const dict of [en, zh]) test(`workspace completion preserves lifecycle and stale-verdict warnings (${dict === en ? 'en' : 'zh'})`, () => {
28
+ const team = { ...base, tasks: [task('done', 'completed'), task('failed', 'failed'), task('cancelled', 'cancelled'), task('claimed', 'claimed'), task('running', 'in_progress', 'running')] }
29
+ assert.match(render(team, dict), /data-completed="1" data-total="5"/)
30
+ assert.match(render(base, dict), /stroke-dasharray="0 100"/)
31
+ assert.match(render({ ...team, phase: 'staged' }, dict, { historic: true }), /data-completed="0" data-total="5"/)
32
+ const stale = render({ ...base, tasks: [{ ...task('audit', 'completed'), verdict: 'pass', verdictStale: 'workspace content changed' }] }, dict)
33
+ const summary = stale.slice(stale.indexOf('class="completionTasks"'), stale.indexOf('class="inboxCard"'))
34
+ assert.match(summary, /data-verdict-stale="true"/)
35
+ assert.match(summary, /workspace content changed/)
36
+ assert.ok(summary.includes(dict['workspace.verdictStale']))
37
+ assert.doesNotMatch(summary, />✓</)
38
+ assert.match(stale, /data-completed="1" data-total="1"/, 'the warning must not rewrite durable task completion')
39
+ })
40
+
41
+ test('inbox renders unread snapshot content safely and keeps scroll regions keyboard reachable', () => {
42
+ const html = render({ ...base, tasks: [task('t1', 'completed')], captainInbox: [{ from: '<script>sender</script>', content: '<img src=x onerror=alert(1)>\nreport' }] }, en)
43
+ assert.match(html, /&lt;script&gt;sender&lt;\/script&gt;/)
44
+ assert.match(html, /&lt;img src=x onerror=alert\(1\)&gt;/)
45
+ assert.match(html, /class="inboxMessages" tabindex="0" aria-label="Captain inbox"/)
46
+ assert.match(html, /class="completionTasks" tabindex="0" aria-label="Task completion summary"/)
47
+ assert.ok(html.includes(en['workspace.inboxHint']))
48
+ assert.doesNotMatch(render(base, en, { workspace: false }), /class="workspaceSummary"/)
49
+ })