SaylorTwift HF Staff commited on
Commit
8c29c68
·
verified ·
1 Parent(s): 3a3c3e9

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. .jscpd.json +15 -0
  2. apps/desktop-host/config/desktop.cordis.patch.yml +34 -0
  3. apps/desktop-host/src/index.ts +608 -0
  4. apps/desktop-host/src/wire.ts +184 -0
  5. apps/desktop/src/host-protocol.ts +215 -0
  6. apps/desktop/src/ipc.ts +63 -0
  7. apps/desktop/src/owned-directory.ts +26 -0
  8. apps/desktop/src/paths.ts +42 -0
  9. apps/desktop/src/preload-app.ts +24 -0
  10. apps/desktop/src/preload.ts +38 -0
  11. apps/desktop/src/profile-packages.ts +269 -0
  12. apps/desktop/src/release.ts +35 -0
  13. apps/desktop/src/single-instance.ts +26 -0
  14. apps/desktop/src/startup-document.ts +26 -0
  15. apps/desktop/src/update-coordinator.ts +95 -0
  16. apps/desktop/tests/expected/startup-en-profile.txt +8 -0
  17. apps/desktop/tests/expected/startup-en-restart.txt +5 -0
  18. apps/desktop/tests/expected/startup-zh-CN-profile.txt +8 -0
  19. apps/desktop/tests/expected/startup-zh-CN-restart.txt +5 -0
  20. apps/desktop/tests/fixtures/installer-cleanup-smoke.nsi +70 -0
  21. apps/desktop/tests/fixtures/installer-write-failure-smoke.nsi +55 -0
  22. apps/desktop/tests/fixtures/owned-directory-smoke.mjs +29 -0
  23. apps/desktop/tests/fixtures/runtime-payload-smoke.mjs +138 -0
  24. apps/web/stress-tests/reasoning-chunks.stress.ts +235 -0
  25. apps/web/tests/README.zh.md +23 -0
  26. apps/web/tests/agent-team-panel.e2e.ts +110 -0
  27. apps/web/tests/assembled-remote.spec.ts +44 -0
  28. apps/web/tests/auto-review-fixture.ts +20 -0
  29. apps/web/tests/chat-continuous-conversation.e2e.ts +357 -0
  30. apps/web/tests/chat-long-interactions.e2e.ts +348 -0
  31. apps/web/tests/command-image-envelope.expected.e2e.ts +114 -0
  32. apps/web/tests/complex-history.perf.ts +1457 -0
  33. apps/web/tests/cordis-tool-round.e2e.ts +218 -0
  34. apps/web/tests/deepseek-messages-settings.e2e.ts +103 -0
  35. apps/web/tests/home-path-tilde.expected.e2e.ts +45 -0
  36. apps/web/tests/markdown-cjk-strong.e2e.ts +135 -0
  37. apps/web/tests/max-tokens-notice.expected.e2e.ts +56 -0
  38. apps/web/tests/navigation-panes.e2e.ts +529 -0
  39. apps/web/tests/pin-browse-picker.overlay.yml +13 -0
  40. apps/web/tests/present.overlay.yml +4 -0
  41. apps/web/tests/preview-boot.e2e.ts +509 -0
  42. apps/web/tests/produced-files.e2e.ts +216 -0
  43. apps/web/tests/produced-files.overlay.yml +9 -0
  44. apps/web/tests/pwsh-terminal.e2e.ts +106 -0
  45. apps/web/tests/rail-search-expand.e2e.ts +68 -0
  46. apps/web/tests/schedule-after.e2e.ts +826 -0
  47. apps/web/tests/session-unarchive.e2e.ts +161 -0
  48. apps/web/tests/skill-user-invoke.e2e.ts +188 -0
  49. apps/web/tests/stats-paged-history.e2e.ts +151 -0
  50. apps/web/tests/subagent-conversation.e2e.ts +606 -0
.jscpd.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "minTokens": 60,
3
+ "minLines": 6,
4
+ "mode": "mild",
5
+ "format": ["typescript", "tsx"],
6
+ "pattern": "**/*.{ts,tsx}",
7
+ "ignore": ["**/tests/**", "**/tsdown.config.ts"],
8
+ "ignorePattern": [
9
+ "(?s)/\\* jscpd:ignore-start \\*/.*?/\\* jscpd:ignore-end \\*/"
10
+ ],
11
+ "reporters": ["console"],
12
+ "exitCode": 1,
13
+ "noColors": true,
14
+ "noTips": true
15
+ }
apps/desktop-host/config/desktop.cordis.patch.yml ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Electron reuses the browser composition without its network and browser-launch rows.
2
+
3
+ - id: web-startup
4
+ disabled: true
5
+
6
+ - id: webserver
7
+ disabled: true
8
+
9
+ - id: web-runtime
10
+ disabled: true
11
+
12
+ - id: client-hmr
13
+ disabled: true
14
+
15
+ - id: open-in-app
16
+ disabled: true
17
+
18
+ - id: ui-open-in-app
19
+ disabled: true
20
+
21
+ - id: directory-picker
22
+ disabled: true
23
+
24
+ - id: connection
25
+ inject:
26
+ - credentials
27
+ config: {}
28
+
29
+ - insert:
30
+ - id: directory-picker-native
31
+ name: '@deepseek-ai/dsh-host-directory-picker-native'
32
+
33
+ - id: ui-directory-picker-native
34
+ name: '@deepseek-ai/dsh-client-ui-directory-picker-native'
apps/desktop-host/src/index.ts ADDED
@@ -0,0 +1,608 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Electron child-process entry: boots the desktop project without a listening
3
+ * socket and carries API plus validated Web assets over framed byte pipes.
4
+ * @module @deepseek-ai/dsh-desktop-host
5
+ */
6
+
7
+ import { createRequire } from 'node:module'
8
+ import { closeSync, createReadStream, createWriteStream, existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs'
9
+ import { once } from 'node:events'
10
+ import { readFile } from 'node:fs/promises'
11
+ import { dirname, extname, join, normalize, resolve, sep } from 'node:path'
12
+ import { fileURLToPath } from 'node:url'
13
+ import type { Context } from '@deepseek-ai/cordis'
14
+ import type { PatchOptions } from '@deepseek-ai/cordis-plugin-include'
15
+ import {
16
+ boot,
17
+ composeEntries,
18
+ createProfileResolutionGeneration,
19
+ loadLayeredEnv,
20
+ loadProfileDirectory,
21
+ loadOverlayPatches,
22
+ PluginPackages,
23
+ type Profile,
24
+ } from '@deepseek-ai/dsh-app-boot'
25
+ import { provideCmdline } from '@deepseek-ai/dsh-cmdline'
26
+ import { DSH_LAUNCH_ENVIRONMENT_KEY } from '@deepseek-ai/dsh-launch-environment'
27
+ import type {} from '@deepseek-ai/dsh-api-gateway'
28
+ import type { ConnectionFetchHandler } from '@deepseek-ai/dsh-client-connection'
29
+ import type {} from '@deepseek-ai/dsh-client-modules'
30
+ import { renderIndexInjections, type IndexInjection } from '@deepseek-ai/dsh-host-webserver'
31
+ import {
32
+ DESKTOP_HOST_PROTOCOL_VERSION,
33
+ DESKTOP_PIPE_CHUNK_BYTES,
34
+ DESKTOP_REQUEST_PIPE_FD,
35
+ DESKTOP_RESPONSE_PIPE_FD,
36
+ DesktopHostRequestDecoder,
37
+ encodeDesktopResponseData,
38
+ encodeDesktopResponseEnd,
39
+ encodeDesktopResponseError,
40
+ encodeDesktopResponseStart,
41
+ type DesktopHostRequestFrame,
42
+ } from './wire.ts'
43
+
44
+ export { DESKTOP_HOST_PROTOCOL_VERSION } from './wire.ts'
45
+
46
+ /** One request forwarded from Electron's `dsh-app://` handler. */
47
+ export interface DesktopHostFetchCommand {
48
+ readonly streamId: number
49
+ readonly request: {
50
+ readonly url: string
51
+ readonly method: string
52
+ readonly headers: readonly [string, string][]
53
+ }
54
+ }
55
+
56
+ /** Commands accepted by the desktop child process. */
57
+ export type DesktopHostCommand = {
58
+ readonly type: 'shutdown'
59
+ }
60
+
61
+ /** Events emitted by the desktop child process. */
62
+ export type DesktopHostEvent = {
63
+ readonly type: 'ready'
64
+ readonly protocolVersion: typeof DESKTOP_HOST_PROTOCOL_VERSION
65
+ readonly dshVersion: string
66
+ } | {
67
+ readonly type: 'fatal'
68
+ readonly message: string
69
+ }
70
+
71
+ /** Controller returned to tests and the self-executing process entry. */
72
+ export interface DesktopHostController {
73
+ /** Installed dsh version carried by this host. */
74
+ readonly dshVersion: string
75
+ /** Dispatch one custom-protocol request and stream its response to the response pipe. */
76
+ fetch(command: DesktopHostFetchCommand, body: ReadableStream<Uint8Array> | null): Promise<void>
77
+ /** Abort one in-flight request. */
78
+ cancel(streamId: number): void
79
+ /** Stop accepting messages and await complete host teardown. */
80
+ dispose(): Promise<void>
81
+ }
82
+
83
+ function isRecord(value: unknown): value is Record<string, unknown> {
84
+ return typeof value === 'object' && value !== null
85
+ }
86
+
87
+ function isDesktopHostCommand(message: unknown): message is DesktopHostCommand {
88
+ return typeof message === 'object' && message !== null && 'type' in message
89
+ && (message as Record<string, unknown>).type === 'shutdown'
90
+ }
91
+
92
+ interface PackageManifest {
93
+ readonly name?: string
94
+ readonly version?: string
95
+ }
96
+
97
+ const DESKTOP_PATCH = fileURLToPath(new URL('../config/desktop.cordis.patch.yml', import.meta.url))
98
+ const ROOT_CONFIG = '# Electron desktop composition root; package transactions own this file.\n[]\n'
99
+ const ROOT_CONFIG_FILENAME = 'desktop.cordis.yml'
100
+ const DESKTOP_STREAM_PATH = '/.dsh/remote-stream'
101
+
102
+ const DESKTOP_TRANSPORT_SCRIPT = `globalThis.__DSH_TRANSPORT__={
103
+ ownsHost:true,
104
+ async *openStream(endpoint,payload,signal){
105
+ const response=await fetch(${JSON.stringify(DESKTOP_STREAM_PATH)},{
106
+ method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({endpoint,payload}),signal
107
+ })
108
+ if(!response.ok||response.body===null)throw new Error('desktop stream transport failed: HTTP '+response.status)
109
+ const reader=response.body.getReader(),decoder=new TextDecoder()
110
+ let pending=''
111
+ for(;;){
112
+ const {done,value}=await reader.read()
113
+ pending+=decoder.decode(value,{stream:!done})
114
+ let newline
115
+ while((newline=pending.indexOf('\\n'))!==-1){
116
+ const line=pending.slice(0,newline);pending=pending.slice(newline+1)
117
+ if(line!=='')yield JSON.parse(line)
118
+ }
119
+ if(done)break
120
+ }
121
+ if(pending!=='')yield JSON.parse(pending)
122
+ }
123
+ }`
124
+
125
+ const MIME: Readonly<Record<string, string>> = {
126
+ '.css': 'text/css; charset=utf-8',
127
+ '.html': 'text/html; charset=utf-8',
128
+ '.js': 'text/javascript; charset=utf-8',
129
+ '.json': 'application/json',
130
+ '.svg': 'image/svg+xml',
131
+ '.webmanifest': 'application/manifest+json',
132
+ }
133
+
134
+ function readManifest(path: string): PackageManifest {
135
+ const value: unknown = JSON.parse(readFileSync(path, 'utf8'))
136
+ if (!isRecord(value)) throw new Error(`dsh desktop: ${path} must contain a package manifest`)
137
+ return {
138
+ ...(typeof value.name === 'string' ? { name: value.name } : {}),
139
+ ...(typeof value.version === 'string' ? { version: value.version } : {}),
140
+ }
141
+ }
142
+
143
+ function packageManifestPath(projectDir: string, packageName: string): string {
144
+ const path = join(projectDir, 'node_modules', ...packageName.split('/'), 'package.json')
145
+ if (!existsSync(path)) throw new Error(`dsh desktop: installed package ${JSON.stringify(packageName)} has no manifest`)
146
+ return path
147
+ }
148
+
149
+ function isProjectPath(projectDir: string, target: string): boolean {
150
+ const root = realpathSync(projectDir)
151
+ const path = realpathSync(target)
152
+ return path === root || path.startsWith(root + sep)
153
+ }
154
+
155
+ interface DesktopComposition {
156
+ readonly installAnchor: string
157
+ readonly profile: Profile
158
+ readonly patches: PatchOptions[]
159
+ }
160
+
161
+ function desktopComposition(
162
+ runtimeDir: string,
163
+ projectDir: string,
164
+ allowLinkedPackages: boolean,
165
+ ): DesktopComposition {
166
+ const installAnchor = packageManifestPath(runtimeDir, '@deepseek-ai/dsh')
167
+ const dshRoot = dirname(installAnchor)
168
+ const profile = loadProfileDirectory('dsh desktop', projectDir, installAnchor)
169
+ for (const layer of profile.layers) {
170
+ if (!allowLinkedPackages && !isProjectPath(projectDir, layer.packageDir) && !isProjectPath(runtimeDir, layer.packageDir)) {
171
+ throw new Error(`dsh desktop: profile bundle ${JSON.stringify(layer.packageName)} resolved outside the Desktop runtime and profile`)
172
+ }
173
+ }
174
+ const layers = [
175
+ ...profile.layers.map(layer => layer.patches),
176
+ profile.patches,
177
+ loadOverlayPatches('dsh desktop', DESKTOP_PATCH),
178
+ ]
179
+ const rows = new Map(composeEntries(layers).flatMap(row => typeof row.id === 'string' ? [[row.id, row] as const] : []))
180
+ const agentPresets = rows.get('agent-presets')
181
+ if (agentPresets !== undefined) {
182
+ layers.push([{
183
+ id: 'agent-presets',
184
+ config: {
185
+ ...(agentPresets.config ?? {}) as Record<string, unknown>,
186
+ roots: [{ path: join(dshRoot, 'config', 'agent-presets'), trust: 'system' }],
187
+ },
188
+ }])
189
+ }
190
+ return { installAnchor, profile, patches: layers.flat() }
191
+ }
192
+
193
+ function dshVersion(runtimeDir: string): string {
194
+ const manifest = readManifest(packageManifestPath(runtimeDir, '@deepseek-ai/dsh'))
195
+ if (typeof manifest.version !== 'string') throw new Error('dsh desktop: installed dsh manifest has no version')
196
+ return manifest.version
197
+ }
198
+
199
+ function assetHandler(ctx: Context, runtimeDir: string): ConnectionFetchHandler {
200
+ const require = createRequire(join(runtimeDir, 'package.json'))
201
+ const distIndex = require.resolve('@deepseek-ai/dsh-web-frontend/dist/index.html')
202
+ const distRoot = realpathSync(dirname(distIndex))
203
+ const renderIndex = async (): Promise<Response> => {
204
+ const rows: IndexInjection[] = [{ kind: 'script', placement: 'head', text: DESKTOP_TRANSPORT_SCRIPT }]
205
+ ctx.emit('webserver/index-inject', rows)
206
+ const body = renderIndexInjections(await readFile(distIndex, 'utf8'), rows)
207
+ return new Response(body, { headers: { 'content-type': MIME['.html'] ?? 'text/html; charset=utf-8' } })
208
+ }
209
+ return {
210
+ requestBodyMode: () => 'buffered',
211
+ async fetch(request): Promise<Response> {
212
+ if (request.method !== 'GET' && request.method !== 'HEAD') return new Response(null, { status: 405 })
213
+ const url = new URL(request.url)
214
+ if (url.pathname.startsWith('/plugins/')) return ctx.clientModules.fetchBundle(request)
215
+ let pathname: string
216
+ try {
217
+ pathname = decodeURIComponent(url.pathname)
218
+ } catch {
219
+ return new Response(null, { status: 400 })
220
+ }
221
+ if (pathname === '/' || pathname === '/index.html') return renderIndex()
222
+ const target = resolve(normalize(join(distRoot, pathname)))
223
+ if (target !== distRoot && !target.startsWith(distRoot + sep)) return new Response(null, { status: 403 })
224
+ try {
225
+ const realTarget = realpathSync(target)
226
+ if (realTarget !== distRoot && !realTarget.startsWith(distRoot + sep)) return new Response(null, { status: 403 })
227
+ return new Response(request.method === 'HEAD' ? null : await readFile(realTarget), {
228
+ headers: { 'content-type': MIME[extname(realTarget)] ?? 'application/octet-stream' },
229
+ })
230
+ } catch {
231
+ return renderIndex()
232
+ }
233
+ },
234
+ }
235
+ }
236
+
237
+ function remoteStreamHandler(ctx: Context): ConnectionFetchHandler {
238
+ return {
239
+ requestBodyMode: () => 'buffered',
240
+ async fetch(request): Promise<Response> {
241
+ if (request.method !== 'POST') return new Response(null, { status: 405 })
242
+ const gateway = ctx.get('typertGateway')
243
+ if (gateway === undefined) return new Response('gateway unavailable', { status: 503 })
244
+ let body: unknown
245
+ try {
246
+ body = await request.json()
247
+ } catch {
248
+ return new Response('body is not JSON', { status: 400 })
249
+ }
250
+ if (!isRecord(body) || typeof body.endpoint !== 'string') {
251
+ return new Response('invalid stream request', { status: 400 })
252
+ }
253
+ const abort = new AbortController()
254
+ const cancel = (): void => { abort.abort(request.signal.reason) }
255
+ request.signal.addEventListener('abort', cancel, { once: true })
256
+ const encoder = new TextEncoder()
257
+ const stream = new ReadableStream<Uint8Array>({
258
+ async start(controller) {
259
+ try {
260
+ const values = await gateway.wireStream.open(body.endpoint as string, body.payload, abort.signal)
261
+ for await (const value of values) {
262
+ controller.enqueue(encoder.encode(`${JSON.stringify(value)}\n`))
263
+ }
264
+ controller.close()
265
+ } catch (error) {
266
+ controller.error(error)
267
+ } finally {
268
+ request.signal.removeEventListener('abort', cancel)
269
+ }
270
+ },
271
+ cancel(reason) {
272
+ abort.abort(reason)
273
+ request.signal.removeEventListener('abort', cancel)
274
+ },
275
+ })
276
+ return new Response(stream, { headers: { 'content-type': 'application/x-ndjson' } })
277
+ },
278
+ }
279
+ }
280
+
281
+ interface NodeRequestInit extends RequestInit {
282
+ readonly duplex?: 'half'
283
+ }
284
+
285
+ /**
286
+ * Boot one installed desktop npm project.
287
+ * @param runtimeDir - immutable dsh packages supplied by the Electron application.
288
+ * @param projectDir - active or staged Electron-owned desktop profile.
289
+ * @param writeResponse - serialized response-pipe writer that applies byte backpressure.
290
+ * @param options - development-only allowance for workspace-linked bundle packages.
291
+ * @returns controller after every Host and client-manifest row is active.
292
+ */
293
+ export async function runDesktopHost(
294
+ runtimeDir: string,
295
+ projectDir: string,
296
+ writeResponse: (frame: Buffer) => Promise<void>,
297
+ options: { allowLinkedPackages?: boolean } = {},
298
+ ): Promise<DesktopHostController> {
299
+ const absoluteRuntime = resolve(runtimeDir)
300
+ const absoluteProject = resolve(projectDir)
301
+ mkdirSync(absoluteProject, { recursive: true })
302
+ const rootConfig = join(absoluteProject, ROOT_CONFIG_FILENAME)
303
+ writeFileSync(rootConfig, ROOT_CONFIG)
304
+ const environment = loadLayeredEnv('dsh desktop')
305
+ const composition = desktopComposition(absoluteRuntime, absoluteProject, options.allowLinkedPackages === true)
306
+ const resolution = await createProfileResolutionGeneration({
307
+ installAnchor: composition.installAnchor,
308
+ profile: composition.profile,
309
+ })
310
+ let current: Context | undefined
311
+ const ctx = await boot('dsh desktop', rootConfig, structuredClone(composition.patches), async (hostCtx) => {
312
+ current = hostCtx
313
+ hostCtx.provide(DSH_LAUNCH_ENVIRONMENT_KEY, environment)
314
+ await hostCtx.plugin(PluginPackages, { generation: resolution })
315
+ provideCmdline(hostCtx, { args: [], exit: () => {} })
316
+ })
317
+ current = ctx
318
+ const connection = ctx.get('connection')
319
+ const clientModules = ctx.get('clientModules')
320
+ const gateway = ctx.get('typertGateway')
321
+ if (connection === undefined || clientModules === undefined || gateway === undefined) {
322
+ await ctx.fiber.dispose()
323
+ throw new Error('dsh desktop: composition did not provide connection, typertGateway, and clientModules')
324
+ }
325
+ const api = connection.createSharedFetchHandler('/api')
326
+ const assets = assetHandler(ctx, absoluteRuntime)
327
+ const streams = remoteStreamHandler(ctx)
328
+ const requests = new Map<number, AbortController>()
329
+ let disposing: Promise<void> | undefined
330
+
331
+ const dispose = async (): Promise<void> => {
332
+ disposing ??= (async () => {
333
+ for (const controller of requests.values()) controller.abort()
334
+ requests.clear()
335
+ await current?.fiber.dispose()
336
+ current = undefined
337
+ })()
338
+ await disposing
339
+ }
340
+
341
+ return {
342
+ dshVersion: dshVersion(absoluteRuntime),
343
+ cancel(streamId) {
344
+ requests.get(streamId)?.abort()
345
+ },
346
+ async fetch(command, body) {
347
+ if (disposing !== undefined) throw new Error('dsh desktop: host is disposing')
348
+ const controller = new AbortController()
349
+ requests.set(command.streamId, controller)
350
+ try {
351
+ const url = new URL(command.request.url)
352
+ const init: NodeRequestInit = {
353
+ method: command.request.method,
354
+ headers: new Headers(command.request.headers.map(([name, value]) => [name, value] as [string, string])),
355
+ ...(body === null ? {} : { body, duplex: 'half' }),
356
+ signal: controller.signal,
357
+ }
358
+ const request = new Request(url, init)
359
+ const response = url.pathname === DESKTOP_STREAM_PATH
360
+ ? await streams.fetch(request)
361
+ : url.pathname.startsWith('/api/')
362
+ ? await api.fetch(request)
363
+ : await assets.fetch(request)
364
+ await writeResponse(encodeDesktopResponseStart(command.streamId, {
365
+ status: response.status,
366
+ headers: [...response.headers.entries()],
367
+ hasBody: response.body !== null,
368
+ }))
369
+ if (response.body !== null) {
370
+ for await (const chunk of response.body) {
371
+ const bytes = Buffer.from(chunk)
372
+ for (let offset = 0; offset < bytes.byteLength; offset += DESKTOP_PIPE_CHUNK_BYTES) {
373
+ await writeResponse(encodeDesktopResponseData(
374
+ command.streamId,
375
+ bytes.subarray(offset, offset + DESKTOP_PIPE_CHUNK_BYTES),
376
+ ))
377
+ }
378
+ }
379
+ }
380
+ await writeResponse(encodeDesktopResponseEnd(command.streamId))
381
+ } catch (error) {
382
+ if (!controller.signal.aborted) {
383
+ await writeResponse(encodeDesktopResponseError(
384
+ command.streamId,
385
+ error instanceof Error ? error.message : String(error),
386
+ ))
387
+ }
388
+ } finally {
389
+ requests.delete(command.streamId)
390
+ }
391
+ },
392
+ dispose,
393
+ }
394
+ }
395
+
396
+ async function main(): Promise<void> {
397
+ const runtimeDir = process.argv[2]
398
+ const projectDir = process.argv[3]
399
+ if (runtimeDir === undefined || projectDir === undefined || process.send === undefined) {
400
+ throw new Error('dsh desktop: expected runtime and profile directories, byte pipes, and a Node IPC channel')
401
+ }
402
+ const option = process.argv[4]
403
+ if (option !== undefined && option !== '--allow-linked-profile') {
404
+ throw new Error(`dsh desktop: unsupported internal option ${JSON.stringify(option)}`)
405
+ }
406
+ const requestPipe = createReadStream('', { fd: DESKTOP_REQUEST_PIPE_FD, autoClose: false })
407
+ const responsePipe = createWriteStream('', { fd: DESKTOP_RESPONSE_PIPE_FD, autoClose: false })
408
+ let responseWriteTail: Promise<void> = Promise.resolve()
409
+ const writeResponse = (frame: Buffer): Promise<void> => {
410
+ const write = responseWriteTail.then(async () => {
411
+ if (responsePipe.destroyed) throw new Error('dsh desktop: Electron response pipe is unavailable')
412
+ if (!responsePipe.write(frame)) await once(responsePipe, 'drain')
413
+ })
414
+ responseWriteTail = write.catch(() => undefined)
415
+ return write
416
+ }
417
+ const send = (event: DesktopHostEvent): void => {
418
+ if (process.send === undefined || !process.connected) return
419
+ try {
420
+ process.send(event)
421
+ } catch (error) {
422
+ // A concurrent parent disconnect owns teardown; only that closed-channel
423
+ // condition is safe to discard while streamed responses unwind.
424
+ if ((error as NodeJS.ErrnoException).code !== 'ERR_IPC_CHANNEL_CLOSED') throw error
425
+ }
426
+ }
427
+ const controller = await runDesktopHost(runtimeDir, projectDir, writeResponse, { allowLinkedPackages: option !== undefined })
428
+ send({
429
+ type: 'ready',
430
+ protocolVersion: DESKTOP_HOST_PROTOCOL_VERSION,
431
+ dshVersion: controller.dshVersion,
432
+ })
433
+ const decoder = new DesktopHostRequestDecoder()
434
+ const requestBodies = new Map<number, ReadableStreamDefaultController<Uint8Array>>()
435
+ const blockedRequests = new Set<number>()
436
+ const discardedRequestBodies = new Set<number>()
437
+ const runs = new Set<Promise<void>>()
438
+ let lastStreamId = 0
439
+ let requestedExitCode = 0
440
+ let stopping: Promise<void> | undefined
441
+
442
+ const resumeRequestPipe = (): void => {
443
+ if (blockedRequests.size === 0) requestPipe.resume()
444
+ }
445
+
446
+ const stop = (exitCode = 0): Promise<void> => {
447
+ requestedExitCode = Math.max(requestedExitCode, exitCode)
448
+ stopping ??= (async () => {
449
+ requestPipe.pause()
450
+ requestPipe.removeAllListeners('data')
451
+ const stopped = new Error('dsh desktop: Host is stopping')
452
+ for (const body of requestBodies.values()) body.error(stopped)
453
+ requestBodies.clear()
454
+ blockedRequests.clear()
455
+ discardedRequestBodies.clear()
456
+ requestPipe.destroy()
457
+ closeSync(DESKTOP_REQUEST_PIPE_FD)
458
+ await controller.dispose()
459
+ await Promise.allSettled([...runs])
460
+ await responseWriteTail.catch(() => undefined)
461
+ if (!responsePipe.destroyed) {
462
+ await new Promise<void>((resolvePromise) => { responsePipe.end(resolvePromise) })
463
+ responsePipe.destroy()
464
+ }
465
+ closeSync(DESKTOP_RESPONSE_PIPE_FD)
466
+ if (process.connected) process.disconnect()
467
+ process.exitCode = requestedExitCode
468
+ })()
469
+ return stopping
470
+ }
471
+
472
+ const failTransport = (error: unknown): void => {
473
+ const message = error instanceof Error ? error.message : String(error)
474
+ send({ type: 'fatal', message })
475
+ void stop(1)
476
+ }
477
+
478
+ const beginRequest = (frame: Extract<DesktopHostRequestFrame, { type: 'start' }>): void => {
479
+ if (frame.streamId <= lastStreamId) {
480
+ throw new Error(`dsh desktop: Electron reused or reordered request stream ${String(frame.streamId)}`)
481
+ }
482
+ lastStreamId = frame.streamId
483
+ let body: ReadableStream<Uint8Array> | null = null
484
+ if (frame.hasBody) {
485
+ body = new ReadableStream<Uint8Array>({
486
+ start(controllerOfBody) {
487
+ requestBodies.set(frame.streamId, controllerOfBody)
488
+ },
489
+ pull() {
490
+ blockedRequests.delete(frame.streamId)
491
+ resumeRequestPipe()
492
+ },
493
+ cancel() {
494
+ requestBodies.delete(frame.streamId)
495
+ blockedRequests.delete(frame.streamId)
496
+ controller.cancel(frame.streamId)
497
+ resumeRequestPipe()
498
+ },
499
+ })
500
+ }
501
+ const run = controller.fetch({
502
+ streamId: frame.streamId,
503
+ request: {
504
+ url: frame.url,
505
+ method: frame.method,
506
+ headers: frame.headers,
507
+ },
508
+ }, body)
509
+ runs.add(run)
510
+ void run.catch(failTransport).finally(() => {
511
+ runs.delete(run)
512
+ const openBody = requestBodies.get(frame.streamId)
513
+ if (openBody === undefined) return
514
+ openBody.error(new Error('dsh desktop: response completed before the request body ended'))
515
+ requestBodies.delete(frame.streamId)
516
+ blockedRequests.delete(frame.streamId)
517
+ discardedRequestBodies.add(frame.streamId)
518
+ resumeRequestPipe()
519
+ })
520
+ }
521
+
522
+ const handleRequestFrame = (frame: DesktopHostRequestFrame): void => {
523
+ switch (frame.type) {
524
+ case 'start':
525
+ beginRequest(frame)
526
+ return
527
+ case 'data': {
528
+ const body = requestBodies.get(frame.streamId)
529
+ if (body === undefined) {
530
+ if (discardedRequestBodies.has(frame.streamId)) return
531
+ throw new Error(`dsh desktop: Electron sent body data for inactive stream ${String(frame.streamId)}`)
532
+ }
533
+ body.enqueue(frame.data)
534
+ if ((body.desiredSize ?? 0) <= 0) {
535
+ blockedRequests.add(frame.streamId)
536
+ requestPipe.pause()
537
+ }
538
+ return
539
+ }
540
+ case 'end': {
541
+ const body = requestBodies.get(frame.streamId)
542
+ if (body === undefined) {
543
+ if (discardedRequestBodies.delete(frame.streamId)) return
544
+ throw new Error(`dsh desktop: Electron ended inactive body stream ${String(frame.streamId)}`)
545
+ }
546
+ body.close()
547
+ requestBodies.delete(frame.streamId)
548
+ blockedRequests.delete(frame.streamId)
549
+ resumeRequestPipe()
550
+ return
551
+ }
552
+ case 'cancel': {
553
+ if (frame.streamId > lastStreamId) {
554
+ throw new Error(`dsh desktop: Electron canceled unknown stream ${String(frame.streamId)}`)
555
+ }
556
+ const body = requestBodies.get(frame.streamId)
557
+ body?.error(new Error('dsh desktop: Electron canceled the request'))
558
+ requestBodies.delete(frame.streamId)
559
+ blockedRequests.delete(frame.streamId)
560
+ discardedRequestBodies.delete(frame.streamId)
561
+ controller.cancel(frame.streamId)
562
+ resumeRequestPipe()
563
+ return
564
+ }
565
+ default:
566
+ frame satisfies never
567
+ }
568
+ }
569
+
570
+ requestPipe.on('data', (chunk: string | Buffer) => {
571
+ try {
572
+ for (const frame of decoder.push(Buffer.from(chunk))) handleRequestFrame(frame)
573
+ } catch (error) {
574
+ failTransport(error)
575
+ }
576
+ })
577
+ requestPipe.once('end', () => {
578
+ if (stopping !== undefined) return
579
+ try {
580
+ decoder.finish()
581
+ failTransport(new Error('dsh desktop: Electron request pipe ended'))
582
+ } catch (error) {
583
+ failTransport(error)
584
+ }
585
+ })
586
+ requestPipe.once('error', failTransport)
587
+ responsePipe.once('error', failTransport)
588
+ process.on('message', (message: unknown) => {
589
+ if (!isDesktopHostCommand(message)) {
590
+ send({ type: 'fatal', message: 'dsh desktop: invalid Electron IPC command' })
591
+ void stop(1)
592
+ return
593
+ }
594
+ void stop()
595
+ })
596
+ process.once('disconnect', () => { void stop() })
597
+ process.once('SIGTERM', () => { void stop() })
598
+ process.once('SIGINT', () => { void stop() })
599
+ }
600
+
601
+ if (import.meta.main) {
602
+ main().catch((error: unknown) => {
603
+ const message = error instanceof Error ? error.message : String(error)
604
+ if (process.send !== undefined) process.send({ type: 'fatal', message } satisfies DesktopHostEvent)
605
+ else process.stderr.write(`dsh desktop: ${message}\n`)
606
+ process.exitCode = 1
607
+ })
608
+ }
apps/desktop-host/src/wire.ts ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** Framed request and response bytes for the Electron Desktop Host transport. */
2
+
3
+ /** Protocol version shared with the Electron shell. */
4
+ export const DESKTOP_HOST_PROTOCOL_VERSION = 3 as const
5
+
6
+ /** Child descriptor that receives Electron request frames. */
7
+ export const DESKTOP_REQUEST_PIPE_FD = 3
8
+
9
+ /** Child descriptor that emits Host response frames. */
10
+ export const DESKTOP_RESPONSE_PIPE_FD = 4
11
+
12
+ /** Maximum raw body bytes carried by one data frame. */
13
+ export const DESKTOP_PIPE_CHUNK_BYTES = 64 * 1024
14
+
15
+ const FRAME_MAGIC = 0x44534833
16
+ const FRAME_HEADER_BYTES = 13
17
+ const MAX_CONTROL_PAYLOAD_BYTES = 1024 * 1024
18
+
19
+ const REQUEST_FRAME_START = 1
20
+ const REQUEST_FRAME_DATA = 2
21
+ const REQUEST_FRAME_END = 3
22
+ const REQUEST_FRAME_CANCEL = 4
23
+
24
+ const RESPONSE_FRAME_START = 1
25
+ const RESPONSE_FRAME_DATA = 2
26
+ const RESPONSE_FRAME_END = 3
27
+ const RESPONSE_FRAME_ERROR = 4
28
+ type ResponseFrameType = typeof RESPONSE_FRAME_START | typeof RESPONSE_FRAME_DATA
29
+ | typeof RESPONSE_FRAME_END | typeof RESPONSE_FRAME_ERROR
30
+
31
+ /** One validated request-pipe frame. */
32
+ export type DesktopHostRequestFrame = {
33
+ readonly type: 'start'
34
+ readonly streamId: number
35
+ readonly url: string
36
+ readonly method: string
37
+ readonly headers: readonly [string, string][]
38
+ readonly hasBody: boolean
39
+ } | {
40
+ readonly type: 'data'
41
+ readonly streamId: number
42
+ readonly data: Buffer
43
+ } | {
44
+ readonly type: 'end' | 'cancel'
45
+ readonly streamId: number
46
+ }
47
+
48
+ function isRecord(value: unknown): value is Record<string, unknown> {
49
+ return typeof value === 'object' && value !== null
50
+ }
51
+
52
+ function isHeaders(value: unknown): value is readonly [string, string][] {
53
+ return Array.isArray(value) && value.every(header => Array.isArray(header) && header.length === 2
54
+ && typeof header[0] === 'string' && typeof header[1] === 'string')
55
+ }
56
+
57
+ function assertStreamId(streamId: number): void {
58
+ if (!Number.isInteger(streamId) || streamId < 1 || streamId > 0xffff_ffff) {
59
+ throw new Error(`dsh desktop: invalid pipe stream id ${String(streamId)}`)
60
+ }
61
+ }
62
+
63
+ function encodeFrame(type: ResponseFrameType, streamId: number, payload: Buffer): Buffer {
64
+ assertStreamId(streamId)
65
+ const limit = type === RESPONSE_FRAME_DATA ? DESKTOP_PIPE_CHUNK_BYTES : MAX_CONTROL_PAYLOAD_BYTES
66
+ if (payload.byteLength > limit) {
67
+ throw new Error(`dsh desktop: response pipe frame exceeds the ${String(limit)}-byte limit`)
68
+ }
69
+ const frame = Buffer.allocUnsafe(FRAME_HEADER_BYTES + payload.byteLength)
70
+ frame.writeUInt32BE(FRAME_MAGIC, 0)
71
+ frame.writeUInt8(type, 4)
72
+ frame.writeUInt32BE(streamId, 5)
73
+ frame.writeUInt32BE(payload.byteLength, 9)
74
+ payload.copy(frame, FRAME_HEADER_BYTES)
75
+ return frame
76
+ }
77
+
78
+ function encodeJsonFrame(type: ResponseFrameType, streamId: number, value: unknown): Buffer {
79
+ return encodeFrame(type, streamId, Buffer.from(JSON.stringify(value), 'utf8'))
80
+ }
81
+
82
+ /** Encode response metadata before any body frames. */
83
+ export function encodeDesktopResponseStart(
84
+ streamId: number,
85
+ response: {
86
+ readonly status: number
87
+ readonly headers: readonly [string, string][]
88
+ readonly hasBody: boolean
89
+ },
90
+ ): Buffer {
91
+ return encodeJsonFrame(RESPONSE_FRAME_START, streamId, response)
92
+ }
93
+
94
+ /** Encode one bounded raw response-body chunk. */
95
+ export function encodeDesktopResponseData(streamId: number, data: Uint8Array): Buffer {
96
+ return encodeFrame(RESPONSE_FRAME_DATA, streamId, Buffer.from(data))
97
+ }
98
+
99
+ /** Encode normal response completion. */
100
+ export function encodeDesktopResponseEnd(streamId: number): Buffer {
101
+ return encodeFrame(RESPONSE_FRAME_END, streamId, Buffer.alloc(0))
102
+ }
103
+
104
+ /** Encode one response failure without exposing an Error object across processes. */
105
+ export function encodeDesktopResponseError(streamId: number, message: string): Buffer {
106
+ return encodeJsonFrame(RESPONSE_FRAME_ERROR, streamId, { message })
107
+ }
108
+
109
+ /** Incrementally decode validated request frames from the Electron byte pipe. */
110
+ export class DesktopHostRequestDecoder {
111
+ private buffer: Buffer = Buffer.alloc(0)
112
+
113
+ /**
114
+ * Append bytes and return every complete request frame.
115
+ * @param chunk - next bytes read from the Electron request pipe.
116
+ * @returns complete frames in pipe order.
117
+ */
118
+ push(chunk: Buffer): DesktopHostRequestFrame[] {
119
+ this.buffer = this.buffer.byteLength === 0 ? chunk : Buffer.concat([this.buffer, chunk])
120
+ const frames: DesktopHostRequestFrame[] = []
121
+ for (;;) {
122
+ const frame = this.next()
123
+ if (frame === undefined) return frames
124
+ frames.push(frame)
125
+ }
126
+ }
127
+
128
+ /** Reject EOF that splits a frame. */
129
+ finish(): void {
130
+ if (this.buffer.byteLength !== 0) throw new Error('dsh desktop: Electron request pipe ended inside a frame')
131
+ }
132
+
133
+ private next(): DesktopHostRequestFrame | undefined {
134
+ if (this.buffer.byteLength < FRAME_HEADER_BYTES) return undefined
135
+ if (this.buffer.readUInt32BE(0) !== FRAME_MAGIC) throw new Error('dsh desktop: invalid Electron request frame marker')
136
+ const rawType = this.buffer.readUInt8(4)
137
+ const streamId = this.buffer.readUInt32BE(5)
138
+ const payloadLength = this.buffer.readUInt32BE(9)
139
+ assertStreamId(streamId)
140
+ const limit = rawType === REQUEST_FRAME_DATA ? DESKTOP_PIPE_CHUNK_BYTES : MAX_CONTROL_PAYLOAD_BYTES
141
+ if (payloadLength > limit) {
142
+ throw new Error(`dsh desktop: Electron request frame exceeds the ${String(limit)}-byte limit`)
143
+ }
144
+ const frameLength = FRAME_HEADER_BYTES + payloadLength
145
+ if (this.buffer.byteLength < frameLength) return undefined
146
+ const payload = this.buffer.subarray(FRAME_HEADER_BYTES, frameLength)
147
+ this.buffer = this.buffer.subarray(frameLength)
148
+ switch (rawType) {
149
+ case REQUEST_FRAME_START:
150
+ return this.parseStart(streamId, payload)
151
+ case REQUEST_FRAME_DATA:
152
+ return { type: 'data', streamId, data: payload }
153
+ case REQUEST_FRAME_END:
154
+ if (payloadLength !== 0) throw new Error('dsh desktop: Electron request end frame carried a payload')
155
+ return { type: 'end', streamId }
156
+ case REQUEST_FRAME_CANCEL:
157
+ if (payloadLength !== 0) throw new Error('dsh desktop: Electron request cancel frame carried a payload')
158
+ return { type: 'cancel', streamId }
159
+ default:
160
+ throw new Error(`dsh desktop: unknown Electron request frame type ${String(rawType)}`)
161
+ }
162
+ }
163
+
164
+ private parseStart(streamId: number, payload: Buffer): DesktopHostRequestFrame {
165
+ let value: unknown
166
+ try {
167
+ value = JSON.parse(payload.toString('utf8')) as unknown
168
+ } catch (error) {
169
+ throw new Error(`dsh desktop: Electron request start payload is not JSON: ${error instanceof Error ? error.message : String(error)}`)
170
+ }
171
+ if (!isRecord(value) || typeof value.url !== 'string' || typeof value.method !== 'string'
172
+ || !isHeaders(value.headers) || typeof value.hasBody !== 'boolean') {
173
+ throw new Error('dsh desktop: invalid Electron request start payload')
174
+ }
175
+ return {
176
+ type: 'start',
177
+ streamId,
178
+ url: value.url,
179
+ method: value.method,
180
+ headers: value.headers,
181
+ hasBody: value.hasBody,
182
+ }
183
+ }
184
+ }
apps/desktop/src/host-protocol.ts ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** Versioned control messages and framed byte transport for the Desktop Host child. */
2
+
3
+ /** Protocol version implemented by the Electron shell and installed dsh Host. */
4
+ export const DESKTOP_HOST_PROTOCOL_VERSION = 3 as const
5
+
6
+ /** Child descriptor Electron writes request frames to. */
7
+ export const DESKTOP_REQUEST_PIPE_FD = 3
8
+
9
+ /** Child descriptor Electron reads response frames from. */
10
+ export const DESKTOP_RESPONSE_PIPE_FD = 4
11
+
12
+ /** Child descriptor reserved for Node's lifecycle IPC channel. */
13
+ export const DESKTOP_CONTROL_IPC_FD = 5
14
+
15
+ /** Maximum raw body bytes carried by one data frame. */
16
+ export const DESKTOP_PIPE_CHUNK_BYTES = 64 * 1024
17
+
18
+ const FRAME_MAGIC = 0x44534833
19
+ const FRAME_HEADER_BYTES = 13
20
+ const MAX_CONTROL_PAYLOAD_BYTES = 1024 * 1024
21
+
22
+ const REQUEST_FRAME_START = 1
23
+ const REQUEST_FRAME_DATA = 2
24
+ const REQUEST_FRAME_END = 3
25
+ const REQUEST_FRAME_CANCEL = 4
26
+ type RequestFrameType = typeof REQUEST_FRAME_START | typeof REQUEST_FRAME_DATA
27
+ | typeof REQUEST_FRAME_END | typeof REQUEST_FRAME_CANCEL
28
+
29
+ const RESPONSE_FRAME_START = 1
30
+ const RESPONSE_FRAME_DATA = 2
31
+ const RESPONSE_FRAME_END = 3
32
+ const RESPONSE_FRAME_ERROR = 4
33
+
34
+ /** Metadata that precedes one optional request body on the request pipe. */
35
+ export interface DesktopHostRequestStart {
36
+ readonly url: string
37
+ readonly method: string
38
+ readonly headers: readonly [string, string][]
39
+ readonly hasBody: boolean
40
+ }
41
+
42
+ /** Commands retained on Node IPC because they do not carry Fetch payload bytes. */
43
+ export type DesktopHostCommand = {
44
+ readonly type: 'shutdown'
45
+ }
46
+
47
+ /** Lifecycle events retained on Node IPC. */
48
+ export type DesktopHostEvent = {
49
+ readonly type: 'ready'
50
+ readonly protocolVersion: typeof DESKTOP_HOST_PROTOCOL_VERSION
51
+ readonly dshVersion: string
52
+ } | {
53
+ readonly type: 'fatal'
54
+ readonly message: string
55
+ }
56
+
57
+ /** One decoded response-pipe frame. */
58
+ export type DesktopHostResponseFrame = {
59
+ readonly type: 'start'
60
+ readonly streamId: number
61
+ readonly status: number
62
+ readonly headers: readonly [string, string][]
63
+ readonly hasBody: boolean
64
+ } | {
65
+ readonly type: 'data'
66
+ readonly streamId: number
67
+ readonly data: Buffer
68
+ } | {
69
+ readonly type: 'end'
70
+ readonly streamId: number
71
+ } | {
72
+ readonly type: 'error'
73
+ readonly streamId: number
74
+ readonly message: string
75
+ }
76
+
77
+ function isRecord(value: unknown): value is Record<string, unknown> {
78
+ return typeof value === 'object' && value !== null
79
+ }
80
+
81
+ function isHeaders(value: unknown): value is readonly [string, string][] {
82
+ return Array.isArray(value) && value.every(header => Array.isArray(header) && header.length === 2
83
+ && typeof header[0] === 'string' && typeof header[1] === 'string')
84
+ }
85
+
86
+ function assertStreamId(streamId: number): void {
87
+ if (!Number.isInteger(streamId) || streamId < 1 || streamId > 0xffff_ffff) {
88
+ throw new Error(`dsh desktop: invalid pipe stream id ${String(streamId)}`)
89
+ }
90
+ }
91
+
92
+ function encodeFrame(type: RequestFrameType, streamId: number, payload: Buffer): Buffer {
93
+ assertStreamId(streamId)
94
+ const limit = type === REQUEST_FRAME_DATA ? DESKTOP_PIPE_CHUNK_BYTES : MAX_CONTROL_PAYLOAD_BYTES
95
+ if (payload.byteLength > limit) {
96
+ throw new Error(`dsh desktop: request pipe frame exceeds the ${String(limit)}-byte limit`)
97
+ }
98
+ const frame = Buffer.allocUnsafe(FRAME_HEADER_BYTES + payload.byteLength)
99
+ frame.writeUInt32BE(FRAME_MAGIC, 0)
100
+ frame.writeUInt8(type, 4)
101
+ frame.writeUInt32BE(streamId, 5)
102
+ frame.writeUInt32BE(payload.byteLength, 9)
103
+ payload.copy(frame, FRAME_HEADER_BYTES)
104
+ return frame
105
+ }
106
+
107
+ function encodeJsonFrame(type: RequestFrameType, streamId: number, value: unknown): Buffer {
108
+ return encodeFrame(type, streamId, Buffer.from(JSON.stringify(value), 'utf8'))
109
+ }
110
+
111
+ /** Encode the metadata opening one request stream. */
112
+ export function encodeDesktopRequestStart(streamId: number, request: DesktopHostRequestStart): Buffer {
113
+ return encodeJsonFrame(REQUEST_FRAME_START, streamId, request)
114
+ }
115
+
116
+ /** Encode one bounded raw request-body chunk. */
117
+ export function encodeDesktopRequestData(streamId: number, data: Uint8Array): Buffer {
118
+ return encodeFrame(REQUEST_FRAME_DATA, streamId, Buffer.from(data))
119
+ }
120
+
121
+ /** Encode normal request-body completion. */
122
+ export function encodeDesktopRequestEnd(streamId: number): Buffer {
123
+ return encodeFrame(REQUEST_FRAME_END, streamId, Buffer.alloc(0))
124
+ }
125
+
126
+ /** Encode cancellation of one request and its response. */
127
+ export function encodeDesktopRequestCancel(streamId: number): Buffer {
128
+ return encodeFrame(REQUEST_FRAME_CANCEL, streamId, Buffer.alloc(0))
129
+ }
130
+
131
+ /** Incrementally decode validated response frames from the Host byte pipe. */
132
+ export class DesktopHostResponseDecoder {
133
+ private buffer: Buffer = Buffer.alloc(0)
134
+
135
+ /**
136
+ * Append bytes and return every complete response frame.
137
+ * @param chunk - next bytes read from the Host response pipe.
138
+ * @returns complete frames in pipe order.
139
+ */
140
+ push(chunk: Buffer): DesktopHostResponseFrame[] {
141
+ this.buffer = this.buffer.byteLength === 0 ? chunk : Buffer.concat([this.buffer, chunk])
142
+ const frames: DesktopHostResponseFrame[] = []
143
+ for (;;) {
144
+ const frame = this.next()
145
+ if (frame === undefined) return frames
146
+ frames.push(frame)
147
+ }
148
+ }
149
+
150
+ /** Reject EOF that splits a frame. */
151
+ finish(): void {
152
+ if (this.buffer.byteLength !== 0) throw new Error('dsh desktop: Host response pipe ended inside a frame')
153
+ }
154
+
155
+ private next(): DesktopHostResponseFrame | undefined {
156
+ if (this.buffer.byteLength < FRAME_HEADER_BYTES) return undefined
157
+ if (this.buffer.readUInt32BE(0) !== FRAME_MAGIC) throw new Error('dsh desktop: invalid Host response frame marker')
158
+ const rawType = this.buffer.readUInt8(4)
159
+ const streamId = this.buffer.readUInt32BE(5)
160
+ const payloadLength = this.buffer.readUInt32BE(9)
161
+ assertStreamId(streamId)
162
+ const limit = rawType === RESPONSE_FRAME_DATA ? DESKTOP_PIPE_CHUNK_BYTES : MAX_CONTROL_PAYLOAD_BYTES
163
+ if (payloadLength > limit) {
164
+ throw new Error(`dsh desktop: Host response frame exceeds the ${String(limit)}-byte limit`)
165
+ }
166
+ const frameLength = FRAME_HEADER_BYTES + payloadLength
167
+ if (this.buffer.byteLength < frameLength) return undefined
168
+ const payload = this.buffer.subarray(FRAME_HEADER_BYTES, frameLength)
169
+ this.buffer = this.buffer.subarray(frameLength)
170
+ switch (rawType) {
171
+ case RESPONSE_FRAME_START:
172
+ return this.parseStart(streamId, payload)
173
+ case RESPONSE_FRAME_DATA:
174
+ return { type: 'data', streamId, data: payload }
175
+ case RESPONSE_FRAME_END:
176
+ if (payloadLength !== 0) throw new Error('dsh desktop: Host response end frame carried a payload')
177
+ return { type: 'end', streamId }
178
+ case RESPONSE_FRAME_ERROR:
179
+ return this.parseError(streamId, payload)
180
+ default:
181
+ throw new Error(`dsh desktop: unknown Host response frame type ${String(rawType)}`)
182
+ }
183
+ }
184
+
185
+ private parseStart(streamId: number, payload: Buffer): DesktopHostResponseFrame {
186
+ const value = this.parseJson(payload, 'start')
187
+ if (!isRecord(value) || !Number.isInteger(value.status) || (value.status as number) < 100
188
+ || (value.status as number) > 599 || !isHeaders(value.headers) || typeof value.hasBody !== 'boolean') {
189
+ throw new Error('dsh desktop: invalid Host response start payload')
190
+ }
191
+ return {
192
+ type: 'start',
193
+ streamId,
194
+ status: value.status as number,
195
+ headers: value.headers,
196
+ hasBody: value.hasBody,
197
+ }
198
+ }
199
+
200
+ private parseError(streamId: number, payload: Buffer): DesktopHostResponseFrame {
201
+ const value = this.parseJson(payload, 'error')
202
+ if (!isRecord(value) || typeof value.message !== 'string') {
203
+ throw new Error('dsh desktop: invalid Host response error payload')
204
+ }
205
+ return { type: 'error', streamId, message: value.message }
206
+ }
207
+
208
+ private parseJson(payload: Buffer, subject: string): unknown {
209
+ try {
210
+ return JSON.parse(payload.toString('utf8')) as unknown
211
+ } catch (error) {
212
+ throw new Error(`dsh desktop: Host response ${subject} payload is not JSON: ${error instanceof Error ? error.message : String(error)}`)
213
+ }
214
+ }
215
+ }
apps/desktop/src/ipc.ts ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** Typed preload operations exposed only by the Electron shell. */
2
+
3
+ import type { DesktopPluginRecord } from './project-manager.ts'
4
+ import type { DesktopLocale } from './locale.ts'
5
+ import type { DesktopBackendState } from './backend-controller.ts'
6
+
7
+ /** IPC channel names kept private to the desktop application bundle. */
8
+ export const DESKTOP_IPC = {
9
+ localeGet: 'dsh-desktop:locale-get',
10
+ pluginsList: 'dsh-desktop:plugins-list',
11
+ pluginsAdd: 'dsh-desktop:plugins-add',
12
+ pluginsRemove: 'dsh-desktop:plugins-remove',
13
+ pluginsUpdate: 'dsh-desktop:plugins-update',
14
+ pluginsToggle: 'dsh-desktop:plugins-toggle',
15
+ pluginsDisableAll: 'dsh-desktop:plugins-disable-all',
16
+ backendStatus: 'dsh-desktop:backend-status',
17
+ backendRetry: 'dsh-desktop:backend-retry',
18
+ applicationRestart: 'dsh-desktop:application-restart',
19
+ configurationReset: 'dsh-desktop:configuration-reset',
20
+ backendState: 'dsh-desktop:backend-state',
21
+ updatesCheck: 'dsh-desktop:updates-check',
22
+ updatesInstall: 'dsh-desktop:updates-install',
23
+ updatesState: 'dsh-desktop:updates-state',
24
+ } as const
25
+
26
+ /** Desktop release update state rendered by desktop-owned UI. */
27
+ export interface DesktopUpdateState {
28
+ readonly phase: 'idle' | 'checking' | 'available' | 'installing' | 'ready' | 'error'
29
+ readonly version?: string
30
+ readonly message?: string
31
+ }
32
+
33
+ /** Narrow bridge exposed through context isolation. */
34
+ export interface DshDesktopApi {
35
+ readonly protocolVersion: 1
36
+ locale(): Promise<DesktopLocale>
37
+ readonly plugins: {
38
+ list(): Promise<readonly DesktopPluginRecord[]>
39
+ add(spec: string): Promise<void>
40
+ remove(name: string): Promise<void>
41
+ update(name: string, version: string): Promise<void>
42
+ toggle(name: string, enabled: boolean): Promise<void>
43
+ disableAll(): Promise<void>
44
+ }
45
+ readonly backend: {
46
+ status(): Promise<DesktopBackendState>
47
+ retry(): Promise<void>
48
+ subscribe(listener: (state: DesktopBackendState) => void): () => void
49
+ }
50
+ readonly updates: {
51
+ check(): Promise<DesktopUpdateState>
52
+ install(): Promise<void>
53
+ subscribe(listener: (state: DesktopUpdateState) => void): () => void
54
+ }
55
+ }
56
+
57
+ /** Startup-page controls, unavailable to backend-provided application documents. */
58
+ export interface DshDesktopStartupApi extends Pick<DshDesktopApi, 'protocolVersion' | 'locale'> {
59
+ readonly backend: Omit<DshDesktopApi['backend'], 'retry'>
60
+ disablePlugins(): Promise<void>
61
+ restart(): Promise<void>
62
+ resetConfiguration(): Promise<void>
63
+ }
apps/desktop/src/owned-directory.ts ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** Desktop transaction cleanup that unlinks directory links without visiting their targets. */
2
+
3
+ import { lstatSync, readdirSync, rmdirSync, unlinkSync } from 'node:fs'
4
+ import { join } from 'node:path'
5
+
6
+ /**
7
+ * Remove an owned directory and its contents, unlinking root and nested links.
8
+ * Missing roots are ignored; existing roots must be directories or links.
9
+ * @param path - Owned directory or link to remove; link targets are preserved.
10
+ */
11
+ export function removeOwnedDirectory(path: string): void {
12
+ const stat = lstatSync(path, { throwIfNoEntry: false })
13
+ if (stat === undefined) return
14
+ if (stat.isSymbolicLink()) {
15
+ unlinkSync(path)
16
+ return
17
+ }
18
+ if (!stat.isDirectory()) throw new Error(`desktop project: owned directory path is not a directory: ${path}`)
19
+ // Electron's recursive rm follows nested Windows junctions into installed resources.
20
+ for (const entry of readdirSync(path, { withFileTypes: true })) {
21
+ const child = join(path, entry.name)
22
+ if (entry.isDirectory()) removeOwnedDirectory(child)
23
+ else unlinkSync(child)
24
+ }
25
+ rmdirSync(path)
26
+ }
apps/desktop/src/paths.ts ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** Filesystem ownership for the Electron-managed desktop installation. */
2
+
3
+ import { join } from 'node:path'
4
+ import { resolveDshHome } from '@deepseek-ai/dsh-home-paths'
5
+
6
+ /** Stable desktop installation paths under the shared Harness home. */
7
+ export interface DesktopPaths {
8
+ readonly root: string
9
+ readonly profile: string
10
+ readonly lock: string
11
+ readonly pnpm: {
12
+ readonly root: string
13
+ readonly store: string
14
+ readonly cache: string
15
+ readonly state: string
16
+ readonly config: string
17
+ readonly home: string
18
+ }
19
+ }
20
+
21
+ /**
22
+ * Resolve every Electron-owned path without changing the shared data roots.
23
+ * @param dshHome - Harness home shared with npm-installed dsh.
24
+ * @returns immutable desktop path set.
25
+ */
26
+ export function resolveDesktopPaths(dshHome: string = resolveDshHome()): DesktopPaths {
27
+ const root = join(dshHome, 'desktop')
28
+ const pnpm = join(root, 'pnpm')
29
+ return {
30
+ root,
31
+ profile: join(dshHome, 'profiles', 'desktop'),
32
+ lock: join(dshHome, 'profiles', 'desktop', 'lock'),
33
+ pnpm: {
34
+ root: pnpm,
35
+ store: join(pnpm, 'store'),
36
+ cache: join(pnpm, 'cache'),
37
+ state: join(pnpm, 'state'),
38
+ config: join(pnpm, 'config'),
39
+ home: join(pnpm, 'home'),
40
+ },
41
+ }
42
+ }
apps/desktop/src/preload-app.ts ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** Startup controls for shell documents; application documents receive only the carrier marker. */
2
+
3
+ import { contextBridge, ipcRenderer } from 'electron'
4
+ import { DESKTOP_IPC, type DshDesktopStartupApi } from './ipc.ts'
5
+ import type { DesktopBackendState } from './backend-controller.ts'
6
+
7
+ const startup: DshDesktopStartupApi = {
8
+ protocolVersion: 1,
9
+ locale: () => ipcRenderer.invoke(DESKTOP_IPC.localeGet) as ReturnType<DshDesktopStartupApi['locale']>,
10
+ backend: {
11
+ status: () => ipcRenderer.invoke(DESKTOP_IPC.backendStatus) as ReturnType<DshDesktopStartupApi['backend']['status']>,
12
+ subscribe(listener) {
13
+ const handle = (_event: Electron.IpcRendererEvent, state: DesktopBackendState): void => { listener(state) }
14
+ ipcRenderer.on(DESKTOP_IPC.backendState, handle)
15
+ return () => { ipcRenderer.off(DESKTOP_IPC.backendState, handle) }
16
+ },
17
+ },
18
+ disablePlugins: () => ipcRenderer.invoke(DESKTOP_IPC.pluginsDisableAll) as Promise<void>,
19
+ restart: () => ipcRenderer.invoke(DESKTOP_IPC.applicationRestart) as Promise<void>,
20
+ resetConfiguration: () => ipcRenderer.invoke(DESKTOP_IPC.configurationReset) as Promise<void>,
21
+ }
22
+
23
+ contextBridge.exposeInMainWorld('dshDesktop', location.protocol === 'dsh-app:' && location.hostname === 'shell'
24
+ ? startup : { protocolVersion: 1 })
apps/desktop/src/preload.ts ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** Context-isolated renderer bridge for desktop package and update operations. */
2
+
3
+ import { contextBridge, ipcRenderer } from 'electron'
4
+ import { DESKTOP_IPC, type DshDesktopApi, type DesktopUpdateState } from './ipc.ts'
5
+ import type { DesktopBackendState } from './backend-controller.ts'
6
+
7
+ const api: DshDesktopApi = {
8
+ protocolVersion: 1,
9
+ locale: () => ipcRenderer.invoke(DESKTOP_IPC.localeGet) as Promise<ReturnType<DshDesktopApi['locale']> extends Promise<infer T> ? T : never>,
10
+ plugins: {
11
+ list: () => ipcRenderer.invoke(DESKTOP_IPC.pluginsList) as Promise<ReturnType<DshDesktopApi['plugins']['list']> extends Promise<infer T> ? T : never>,
12
+ add: spec => ipcRenderer.invoke(DESKTOP_IPC.pluginsAdd, spec) as Promise<void>,
13
+ remove: name => ipcRenderer.invoke(DESKTOP_IPC.pluginsRemove, name) as Promise<void>,
14
+ toggle: (name, enabled) => ipcRenderer.invoke(DESKTOP_IPC.pluginsToggle, name, enabled) as Promise<void>,
15
+ disableAll: () => ipcRenderer.invoke(DESKTOP_IPC.pluginsDisableAll) as Promise<void>,
16
+ update: (name, version) => ipcRenderer.invoke(DESKTOP_IPC.pluginsUpdate, name, version) as Promise<void>,
17
+ },
18
+ backend: {
19
+ status: () => ipcRenderer.invoke(DESKTOP_IPC.backendStatus) as ReturnType<DshDesktopApi['backend']['status']>,
20
+ retry: () => ipcRenderer.invoke(DESKTOP_IPC.backendRetry) as Promise<void>,
21
+ subscribe(listener) {
22
+ const handle = (_event: Electron.IpcRendererEvent, state: DesktopBackendState): void => { listener(state) }
23
+ ipcRenderer.on(DESKTOP_IPC.backendState, handle)
24
+ return () => { ipcRenderer.off(DESKTOP_IPC.backendState, handle) }
25
+ },
26
+ },
27
+ updates: {
28
+ check: () => ipcRenderer.invoke(DESKTOP_IPC.updatesCheck) as Promise<DesktopUpdateState>,
29
+ install: () => ipcRenderer.invoke(DESKTOP_IPC.updatesInstall) as Promise<void>,
30
+ subscribe(listener) {
31
+ const handle = (_event: Electron.IpcRendererEvent, state: DesktopUpdateState): void => { listener(state) }
32
+ ipcRenderer.on(DESKTOP_IPC.updatesState, handle)
33
+ return () => { ipcRenderer.off(DESKTOP_IPC.updatesState, handle) }
34
+ },
35
+ },
36
+ }
37
+
38
+ contextBridge.exposeInMainWorld('dshDesktop', api)
apps/desktop/src/profile-packages.ts ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** Desktop-owned host links and validation of the external plugin dependency graph. */
2
+
3
+ import { createHash } from 'node:crypto'
4
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, realpathSync, readdirSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs'
5
+ import { createRequire } from 'node:module'
6
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
7
+ import { satisfies } from 'semver'
8
+ import { desktopRuntimeId, runtimePath, type DesktopRuntimeDescriptor } from './runtime-tree.ts'
9
+
10
+ /** Applied runtime identity and the only links Desktop may replace. */
11
+ export const DESKTOP_PROFILE_STATE = 'desktop-runtime-state.json'
12
+
13
+ /** Durable ownership of a package-directory link. */
14
+ export interface DesktopPackageLink {
15
+ readonly name: string
16
+ readonly target: string
17
+ }
18
+
19
+ /** Runtime identity and managed links; package preparation may still be pending. */
20
+ export interface DesktopProfileState {
21
+ readonly schemaVersion: 1
22
+ readonly runtimeId: string
23
+ readonly version: string
24
+ readonly nodeVersion: string
25
+ readonly platform: string
26
+ readonly arch: string
27
+ readonly lockHash: string
28
+ readonly links: readonly DesktopPackageLink[]
29
+ }
30
+
31
+ const PACKAGE_NAME = /^(?:@[a-z0-9][a-z0-9._~-]*\/[a-z0-9][a-z0-9._~-]*|[a-z0-9][a-z0-9._~-]*)$/u
32
+
33
+ function record(value: unknown): value is Record<string, unknown> {
34
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
35
+ }
36
+
37
+ function stat(path: string): ReturnType<typeof lstatSync> | undefined {
38
+ try { return lstatSync(path) } catch (error) {
39
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
40
+ return undefined
41
+ }
42
+ }
43
+
44
+ function inside(root: string, path: string): boolean {
45
+ const child = relative(root, path)
46
+ return child === '' || (!isAbsolute(child) && child !== '..' && !child.startsWith(`..${sep}`))
47
+ }
48
+
49
+ /**
50
+ * Read profile state without interpreting an unpublished predecessor format.
51
+ * @param profile - Desktop profile directory.
52
+ * @returns Validated state, or undefined for an uninitialized profile.
53
+ */
54
+ export function readDesktopProfileState(profile: string): DesktopProfileState | undefined {
55
+ const path = join(profile, DESKTOP_PROFILE_STATE)
56
+ if (!existsSync(path)) return undefined
57
+ const value: unknown = JSON.parse(readFileSync(path, 'utf8'))
58
+ if (!record(value) || value.schemaVersion !== 1 || typeof value.runtimeId !== 'string'
59
+ || !/^[a-f0-9]{64}$/u.test(value.runtimeId) || typeof value.version !== 'string'
60
+ || typeof value.nodeVersion !== 'string' || typeof value.platform !== 'string' || typeof value.arch !== 'string'
61
+ || typeof value.lockHash !== 'string' || !Array.isArray(value.links)) {
62
+ throw new Error('desktop profile: invalid runtime state')
63
+ }
64
+ const links = value.links.map((link: unknown): DesktopPackageLink => {
65
+ if (!record(link) || typeof link.name !== 'string' || !PACKAGE_NAME.test(link.name)
66
+ || typeof link.target !== 'string' || !isAbsolute(link.target)) {
67
+ throw new Error('desktop profile: invalid managed link')
68
+ }
69
+ return { name: link.name, target: link.target }
70
+ })
71
+ if (new Set(links.map(link => link.name)).size !== links.length) throw new Error('desktop profile: duplicate managed link')
72
+ return { schemaVersion: 1, runtimeId: value.runtimeId, version: value.version, nodeVersion: value.nodeVersion,
73
+ platform: value.platform, arch: value.arch, lockHash: value.lockHash, links }
74
+ }
75
+
76
+ /**
77
+ * Hash the plugin lockfile, including the empty-profile case.
78
+ * @param profile - Desktop profile directory.
79
+ * @returns Lockfile content identity.
80
+ */
81
+ export function desktopPluginLockHash(profile: string): string {
82
+ const lock = join(profile, 'pnpm-lock.yaml')
83
+ return createHash('sha256').update(existsSync(lock) ? readFileSync(lock) : '').digest('hex')
84
+ }
85
+
86
+ /**
87
+ * Remove only recorded host links, without following even broken targets.
88
+ * @param profile - Desktop profile.
89
+ */
90
+ export function unlinkDesktopHostPackages(profile: string): void {
91
+ for (const link of readDesktopProfileState(profile)?.links ?? []) {
92
+ const path = join(profile, 'node_modules', link.name)
93
+ const entry = stat(path)
94
+ if (entry === undefined) continue
95
+ if (!entry.isSymbolicLink() || resolve(dirname(path), readlinkSync(path)) !== resolve(link.target)) {
96
+ throw new Error(`desktop profile: refusing to replace unowned package ${link.name}`)
97
+ }
98
+ unlinkSync(path)
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Bind an external profile to this application's real package directories.
104
+ * @param profile - Candidate profile.
105
+ * @param root - Current immutable runtime directory.
106
+ * @param runtime - Verified release descriptor.
107
+ */
108
+ export function linkDesktopHostPackages(profile: string, root: string, runtime: DesktopRuntimeDescriptor): void {
109
+ unlinkDesktopHostPackages(profile)
110
+ const links = runtime.sharedPackages.map(entry => ({ name: entry.name, target: runtimePath(root, entry.path) }))
111
+ for (const link of links) {
112
+ const path = join(profile, 'node_modules', link.name)
113
+ if (stat(path) !== undefined) throw new Error(`desktop profile: plugin installed reserved host package ${link.name}`)
114
+ mkdirSync(dirname(path), { recursive: true })
115
+ symlinkSync(link.target, path, process.platform === 'win32' ? 'junction' : 'dir')
116
+ }
117
+ const state: DesktopProfileState = { schemaVersion: 1, runtimeId: desktopRuntimeId(runtime), version: runtime.release.version,
118
+ nodeVersion: runtime.release.nodeVersion, platform: runtime.platform, arch: runtime.arch,
119
+ lockHash: desktopPluginLockHash(profile), links }
120
+ writeFileSync(join(profile, DESKTOP_PROFILE_STATE), `${JSON.stringify(state, undefined, 2)}\n`, { mode: 0o600 })
121
+ }
122
+
123
+ /**
124
+ * Record a runtime-resolved profile without changing links left by an earlier release.
125
+ * @param profile - Active Desktop profile.
126
+ * @param runtime - Verified release descriptor supplying the runtime generation.
127
+ */
128
+ export function recordDesktopRuntimeProfile(profile: string, runtime: DesktopRuntimeDescriptor): void {
129
+ const links = readDesktopProfileState(profile)?.links ?? []
130
+ const state: DesktopProfileState = { schemaVersion: 1, runtimeId: desktopRuntimeId(runtime), version: runtime.release.version,
131
+ nodeVersion: runtime.release.nodeVersion, platform: runtime.platform, arch: runtime.arch,
132
+ lockHash: desktopPluginLockHash(profile), links }
133
+ writeFileSync(join(profile, DESKTOP_PROFILE_STATE), `${JSON.stringify(state, undefined, 2)}\n`, { mode: 0o600 })
134
+ }
135
+
136
+ interface PackageManifest {
137
+ readonly name: string
138
+ readonly version: string
139
+ readonly dependencies: Readonly<Record<string, string>>
140
+ readonly optionalDependencies: Readonly<Record<string, string>>
141
+ readonly peerDependencies: Readonly<Record<string, string>>
142
+ readonly optionalPeers: ReadonlySet<string>
143
+ }
144
+
145
+ function manifest(path: string): PackageManifest {
146
+ const value: unknown = JSON.parse(readFileSync(join(path, 'package.json'), 'utf8'))
147
+ if (!record(value) || typeof value.name !== 'string' || typeof value.version !== 'string') {
148
+ throw new Error(`desktop profile: invalid package manifest ${path}`)
149
+ }
150
+ const dependencies = (key: string): Record<string, string> => {
151
+ const field = value[key]
152
+ if (field === undefined) return {}
153
+ if (!record(field) || Object.entries(field).some(([name, spec]) => !PACKAGE_NAME.test(name) || typeof spec !== 'string')) {
154
+ throw new Error(`desktop profile: invalid ${key} in ${path}`)
155
+ }
156
+ return field as Record<string, string>
157
+ }
158
+ const optionalPeers = new Set<string>()
159
+ if (record(value.peerDependenciesMeta)) {
160
+ for (const [name, meta] of Object.entries(value.peerDependenciesMeta)) {
161
+ if (record(meta) && meta.optional === true) optionalPeers.add(name)
162
+ }
163
+ }
164
+ return { name: value.name, version: value.version, dependencies: dependencies('dependencies'),
165
+ optionalDependencies: dependencies('optionalDependencies'), peerDependencies: dependencies('peerDependencies'), optionalPeers }
166
+ }
167
+
168
+ function packageFrom(anchor: string, name: string): string | undefined {
169
+ if (!PACKAGE_NAME.test(name)) throw new Error(`desktop profile: invalid package name ${name}`)
170
+ for (const modules of createRequire(join(anchor, 'package.json')).resolve.paths(name) ?? []) {
171
+ const path = join(modules, name)
172
+ if (existsSync(join(path, 'package.json'))) return realpathSync.native(path)
173
+ }
174
+ return undefined
175
+ }
176
+
177
+ /**
178
+ * Prove active plugin dependencies stay local and share the host's exact package instances.
179
+ * @param profile - Profile with its generated host links present.
180
+ * @param root - Immutable runtime directory.
181
+ * @param runtime - Verified shared package inventory.
182
+ * @param activePlugins - Explicit enabled plugin roots whose peer compatibility is required.
183
+ * @param resolutionMode - Whether host packages are linked or supplied by a runtime generation.
184
+ */
185
+ export function validateDesktopPluginGraph(
186
+ profile: string, root: string, runtime: DesktopRuntimeDescriptor, activePlugins: readonly string[],
187
+ resolutionMode: 'link' | 'runtime' = 'link',
188
+ ): void {
189
+ const profileRoot = realpathSync.native(profile)
190
+ const shared = new Map(runtime.sharedPackages.map((entry) => {
191
+ const path = runtimePath(root, entry.path)
192
+ let canonical: string
193
+ try {
194
+ canonical = realpathSync.native(path)
195
+ } catch (error) {
196
+ if (!existsSync(path)) throw error
197
+ canonical = resolve(path)
198
+ }
199
+ return [entry.name, { path: canonical, version: entry.version }] as const
200
+ }))
201
+ if (resolutionMode === 'link') {
202
+ for (const [name, entry] of shared) {
203
+ if (packageFrom(profile, name) !== entry.path) throw new Error(`desktop profile: missing or incorrect host link ${name}`)
204
+ }
205
+ }
206
+ if (activePlugins.length === 0) return
207
+ const scanned = new Set<string>()
208
+ const scan = (modules: string): void => {
209
+ if (!existsSync(modules)) return
210
+ if (lstatSync(modules).isSymbolicLink()) throw new Error(`desktop profile: linked package container ${modules}`)
211
+ const directory = realpathSync.native(modules)
212
+ if (scanned.has(directory)) return
213
+ scanned.add(directory)
214
+ for (const entry of readdirSync(modules, { withFileTypes: true })) {
215
+ if (entry.name.startsWith('.')) continue
216
+ const path = join(modules, entry.name)
217
+ if (entry.name.startsWith('@')) { scan(path); continue }
218
+ if (!existsSync(join(path, 'package.json'))) throw new Error(`desktop profile: invalid installed package ${path}`)
219
+ const canonical = realpathSync.native(path)
220
+ const info = manifest(canonical)
221
+ const host = shared.get(info.name)
222
+ if (host !== undefined) {
223
+ if (resolutionMode !== 'runtime' && (canonical !== host.path || path !== join(profile, 'node_modules', info.name))) {
224
+ throw new Error(`desktop profile: duplicate or aliased host package ${info.name} at ${path}`)
225
+ }
226
+ continue
227
+ }
228
+ if (entry.isSymbolicLink()) throw new Error(`desktop profile: linked private package ${path}`)
229
+ if (!inside(profileRoot, canonical)) throw new Error(`desktop profile: package resolves outside profile: ${path}`)
230
+ scan(join(path, 'node_modules'))
231
+ }
232
+ }
233
+ scan(join(profile, 'node_modules'))
234
+ const visited = new Set<string>()
235
+ const visit = (path: string, chain: string): void => {
236
+ if (visited.has(path)) return
237
+ visited.add(path)
238
+ const info = manifest(path)
239
+ const deps = { ...info.dependencies, ...info.optionalDependencies }
240
+ for (const [name, range] of Object.entries({ ...deps, ...info.peerDependencies })) {
241
+ const peer = name in info.peerDependencies
242
+ const optional = peer ? info.optionalPeers.has(name) : name in info.optionalDependencies
243
+ const host = shared.get(name)
244
+ if (host !== undefined && name in deps) throw new Error(`desktop profile: ${chain} must declare ${name} as a peer dependency`)
245
+ if (host !== undefined) {
246
+ if (peer && !satisfies(host.version, range)) {
247
+ throw new Error(`desktop profile: ${chain} requires ${name}@${range}, found ${host.version}`)
248
+ }
249
+ continue
250
+ }
251
+ const target = packageFrom(path, name)
252
+ if (target === undefined && optional) continue
253
+ if (target === undefined) throw new Error(`desktop profile: ${chain} requires missing ${name}@${range}`)
254
+ if (!inside(profileRoot, target)) {
255
+ throw new Error(`desktop profile: ${chain} resolves ${name} outside its owned packages`)
256
+ }
257
+ const dependency = manifest(target)
258
+ if (peer && !satisfies(dependency.version, range)) {
259
+ throw new Error(`desktop profile: ${chain} requires ${name}@${range}, found ${dependency.version}`)
260
+ }
261
+ visit(target, `${chain} -> ${name}`)
262
+ }
263
+ }
264
+ for (const name of activePlugins) {
265
+ const path = packageFrom(profile, name)
266
+ if (path === undefined || !inside(profileRoot, path)) throw new Error(`desktop profile: missing local plugin ${name}`)
267
+ visit(path, name)
268
+ }
269
+ }
apps/desktop/src/release.ts ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** Immutable version identity shared by one Electron shell and its bundled dsh runtime. */
2
+
3
+ import { valid } from 'semver'
4
+ import { DESKTOP_HOST_PROTOCOL_VERSION } from './host-protocol.ts'
5
+
6
+ /** Release facts embedded in the bundled runtime descriptor. */
7
+ export interface DesktopRelease {
8
+ readonly schemaVersion: 1
9
+ /** Exact version used by both Electron and `@deepseek-ai/dsh`. */
10
+ readonly version: string
11
+ readonly hostProtocolVersion: typeof DESKTOP_HOST_PROTOCOL_VERSION
12
+ readonly nodeVersion: string
13
+ readonly pnpmVersion: string
14
+ }
15
+
16
+ function isRecord(value: unknown): value is Record<string, unknown> {
17
+ return typeof value === 'object' && value !== null
18
+ }
19
+
20
+ /** Validate release data read from an installed or packaged filesystem resource. */
21
+ export function parseDesktopRelease(value: unknown): DesktopRelease {
22
+ if (!isRecord(value) || value.schemaVersion !== 1 || typeof value.version !== 'string'
23
+ || valid(value.version) === null || value.hostProtocolVersion !== DESKTOP_HOST_PROTOCOL_VERSION
24
+ || typeof value.nodeVersion !== 'string' || valid(value.nodeVersion) === null
25
+ || typeof value.pnpmVersion !== 'string' || valid(value.pnpmVersion) === null) {
26
+ throw new Error('dsh desktop: invalid desktop release metadata')
27
+ }
28
+ return {
29
+ schemaVersion: 1,
30
+ version: value.version,
31
+ hostProtocolVersion: DESKTOP_HOST_PROTOCOL_VERSION,
32
+ nodeVersion: value.nodeVersion,
33
+ pnpmVersion: value.pnpmVersion,
34
+ }
35
+ }
apps/desktop/src/single-instance.ts ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** Electron single-instance ownership before any Desktop profile lifecycle begins. */
2
+
3
+ /** Minimal Electron application operations needed for instance ownership. */
4
+ export interface DesktopSingleInstanceApplication {
5
+ requestSingleInstanceLock(): boolean
6
+ quit(): void
7
+ on(event: 'second-instance', listener: () => void): unknown
8
+ }
9
+
10
+ /**
11
+ * Claim the process-lifetime Desktop lock and route later launches to the owner.
12
+ * @param application - Electron application singleton.
13
+ * @param focusOwner - focus or recreate the primary window after a later launch.
14
+ * @returns true only in the process that may access the Desktop profile.
15
+ */
16
+ export function claimDesktopSingleInstance(
17
+ application: DesktopSingleInstanceApplication,
18
+ focusOwner: () => void,
19
+ ): boolean {
20
+ if (!application.requestSingleInstanceLock()) {
21
+ application.quit()
22
+ return false
23
+ }
24
+ application.on('second-instance', focusOwner)
25
+ return true
26
+ }
apps/desktop/src/startup-document.ts ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** Self-contained recovery document for an unavailable shell renderer or preload. */
2
+
3
+ import type { DesktopLocale } from './locale.ts'
4
+
5
+ /**
6
+ * Render escaped diagnostics without depending on application resource files.
7
+ * @param locale - Shell-owned translations.
8
+ * @param message - Failure details displayed as plain text.
9
+ * @param profileRecovery - Whether the initialized application can repair its profile.
10
+ * @returns An HTML document suitable for an isolated emergency window.
11
+ */
12
+ export function startupFailureDocument(locale: DesktopLocale, message: string, profileRecovery = false): string {
13
+ const escape = (value: string): string => value.replaceAll('&', '&amp;').replaceAll('<', '&lt;')
14
+ .replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&#39;')
15
+ return `<!doctype html><html lang="${locale.id}"><meta charset="utf-8">
16
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; form-action dsh-recovery:">
17
+ <title>${escape(locale.messages.startupFailed)}</title>
18
+ <style>:root{color-scheme:light dark;font-family:system-ui}body{max-width:720px;margin:10vh auto;padding:24px}pre{white-space:pre-wrap;overflow-wrap:anywhere}</style>
19
+ <main><h1>${escape(locale.messages.startupFailed)}</h1><p>${escape(locale.messages.startupReinstallAdvice)}</p>
20
+ ${profileRecovery ? `<p>${escape(locale.messages.startupConfigurationAdvice)}</p>` : ''}
21
+ <pre role="alert">${escape(message)}</pre>
22
+ <form action="dsh-recovery://restart"><button>${escape(locale.messages.restartApplication)}</button></form>
23
+ ${profileRecovery ? `<form action="dsh-recovery://plugins"><button>${escape(locale.messages.disableThirdPartyPlugins)}</button></form>
24
+ <form action="dsh-recovery://reset"><button>${escape(locale.messages.resetConfiguration)}</button></form>` : ''}
25
+ </main></html>`
26
+ }
apps/desktop/src/update-coordinator.ts ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** One Electron release stream for the version-bound shell and bundled dsh runtime. */
2
+
3
+ import { existsSync } from 'node:fs'
4
+ import { join } from 'node:path'
5
+ import { app } from 'electron'
6
+ import electronUpdater, { type AppUpdater } from 'electron-updater'
7
+ import type { DesktopUpdateState } from './ipc.ts'
8
+ const { autoUpdater } = electronUpdater
9
+
10
+ /** Checks, downloads, and installs one complete Desktop release. */
11
+ export class DesktopUpdateCoordinator {
12
+ private availableVersion: string | undefined
13
+ private checkOperation: Promise<DesktopUpdateState> | undefined
14
+ private installOperation: Promise<DesktopUpdateState> | undefined
15
+
16
+ /**
17
+ * @param publish - state sink for every desktop window.
18
+ * @param beforeRestart - stop application-owned processes before replacement.
19
+ * @param updater - Electron artifact updater; replaceable for tests.
20
+ * @param enabled - whether this packaged process carries updater configuration.
21
+ */
22
+ constructor(
23
+ private readonly publish: (state: DesktopUpdateState) => DesktopUpdateState,
24
+ private readonly beforeRestart: () => Promise<void> = async () => {},
25
+ private readonly updater: AppUpdater = autoUpdater,
26
+ private readonly enabled: () => boolean = () => (
27
+ app.isPackaged && existsSync(join(process.resourcesPath, 'app-update.yml'))
28
+ ),
29
+ ) {
30
+ this.updater.autoDownload = false
31
+ this.updater.autoInstallOnAppQuit = false
32
+ }
33
+
34
+ /** Check the configured Desktop release stream and retain an available version. */
35
+ async check(): Promise<DesktopUpdateState> {
36
+ if (this.installOperation !== undefined) return this.installOperation
37
+ if (this.checkOperation !== undefined) return this.checkOperation
38
+ this.checkOperation = this.doCheck().finally(() => { this.checkOperation = undefined })
39
+ return this.checkOperation
40
+ }
41
+
42
+ /** Wait for an in-flight check, then download and install its retained release. */
43
+ async install(): Promise<DesktopUpdateState> {
44
+ if (this.installOperation !== undefined) return this.installOperation
45
+ this.installOperation = (async () => {
46
+ await this.checkOperation
47
+ return this.doInstall()
48
+ })().finally(() => { this.installOperation = undefined })
49
+ return this.installOperation
50
+ }
51
+
52
+ private async doCheck(): Promise<DesktopUpdateState> {
53
+ this.publish({ phase: 'checking' })
54
+ try {
55
+ if (!this.enabled()) {
56
+ this.availableVersion = undefined
57
+ return this.publish({ phase: 'idle' })
58
+ }
59
+ const result = await this.updater.checkForUpdates()
60
+ const version = result?.isUpdateAvailable === true ? result.updateInfo.version : undefined
61
+ this.availableVersion = version
62
+ return version === undefined
63
+ ? this.publish({ phase: 'idle' })
64
+ : this.publish({ phase: 'available', version })
65
+ } catch (error) {
66
+ this.availableVersion = undefined
67
+ return this.publish({
68
+ phase: 'error',
69
+ message: error instanceof Error ? error.message : String(error),
70
+ })
71
+ }
72
+ }
73
+
74
+ private async doInstall(): Promise<DesktopUpdateState> {
75
+ const version = this.availableVersion
76
+ if (version === undefined) {
77
+ throw new Error('desktop update: no verified update is available')
78
+ }
79
+ this.publish({ phase: 'installing', version })
80
+ try {
81
+ await this.updater.downloadUpdate()
82
+ this.availableVersion = undefined
83
+ const ready = this.publish({ phase: 'ready', version })
84
+ await this.beforeRestart()
85
+ this.updater.quitAndInstall(false, true)
86
+ return ready
87
+ } catch (error) {
88
+ return this.publish({
89
+ phase: 'error',
90
+ version,
91
+ message: error instanceof Error ? error.message : String(error),
92
+ })
93
+ }
94
+ }
95
+ }
apps/desktop/tests/expected/startup-en-profile.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ DeepSeek Harness could not start
2
+ Choose a recovery action below. Disabling third-party plugins retains their files.
3
+ Reset Desktop deletes all Desktop profile configuration and third-party plugins without a backup, then starts a fresh profile. Shared tasks and settings are retained.
4
+ If application files are missing or damaged, close the application and reinstall it. Your tasks are stored separately.
5
+ Failure details
6
+ Close and restart
7
+ Disable all third-party plugins and retry
8
+ Reset Desktop and retry
apps/desktop/tests/expected/startup-en-restart.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ DeepSeek Harness could not start
2
+ Choose a recovery action below. Disabling third-party plugins retains their files.
3
+ If application files are missing or damaged, close the application and reinstall it. Your tasks are stored separately.
4
+ Failure details
5
+ Close and restart
apps/desktop/tests/expected/startup-zh-CN-profile.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ DeepSeek Harness 无法启动
2
+ 请选择下方的恢复操作。禁用第三方插件会保留插件文件。
3
+ 重置 Desktop 会删除桌面端的全部 profile 配置和第三方插件,不保留备份,然后重新初始化并启动。共享任务和设置会保留。
4
+ 如果应用文件缺失或损坏,请关闭应用并重新安装。任务数据存储在独立位置。
5
+ Failure details
6
+ 关闭并重启
7
+ 禁用全部第三方插件并重试
8
+ 重置 Desktop 并重试
apps/desktop/tests/expected/startup-zh-CN-restart.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ DeepSeek Harness 无法启动
2
+ 请选择下方的恢复操作。禁用第三方插件会保留插件文件。
3
+ 如果应用文件缺失或损坏,请关闭应用并重新安装。任务数据存储在独立位置。
4
+ Failure details
5
+ 关闭并重启
apps/desktop/tests/fixtures/installer-cleanup-smoke.nsi ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ; Compile with OUTPUT_FILE and RESULT_FILE in a private test directory, then run silently.
2
+ Unicode true
3
+ RequestExecutionLevel user
4
+ SilentInstall silent
5
+ Name "Desktop installer cleanup smoke"
6
+ OutFile "${OUTPUT_FILE}"
7
+ !include "..\..\scripts\installer.nsh"
8
+
9
+ Section
10
+ InitPluginsDir
11
+ SetOutPath "$PLUGINSDIR"
12
+ CreateDirectory "$PLUGINSDIR\7z-out\nested"
13
+ FileOpen $1 "$PLUGINSDIR\7z-out\nested\extracted-file" w
14
+ FileWrite $1 "remove"
15
+ FileClose $1
16
+ FileOpen $1 "$PLUGINSDIR\archive.7z" w
17
+ FileWrite $1 "archive sentinel"
18
+ FileClose $1
19
+ FileOpen $1 "$PLUGINSDIR\plugin.dll" w
20
+ FileWrite $1 "plugin sentinel"
21
+ FileClose $1
22
+ CreateDirectory "$PLUGINSDIR\old-install"
23
+ FileOpen $1 "$PLUGINSDIR\old-install\sentinel" w
24
+ FileWrite $1 "rollback sentinel"
25
+ FileClose $1
26
+
27
+ StrCpy $0 "register sentinel"
28
+ ClearErrors
29
+ !insertmacro customInstall
30
+ IfErrors failed
31
+ StrCmp $0 "register sentinel" 0 failed
32
+ StrCmp $OUTDIR $PLUGINSDIR 0 failed
33
+ IfFileExists "$PLUGINSDIR\7z-out\*.*" failed
34
+
35
+ FileOpen $1 "$PLUGINSDIR\archive.7z" r
36
+ FileRead $1 $2
37
+ FileClose $1
38
+ StrCmp $2 "archive sentinel" 0 failed
39
+ FileOpen $1 "$PLUGINSDIR\plugin.dll" r
40
+ FileRead $1 $2
41
+ FileClose $1
42
+ StrCmp $2 "plugin sentinel" 0 failed
43
+ FileOpen $1 "$PLUGINSDIR\old-install\sentinel" r
44
+ FileRead $1 $2
45
+ FileClose $1
46
+ StrCmp $2 "rollback sentinel" 0 failed
47
+
48
+ CreateDirectory "$PLUGINSDIR\7z-out"
49
+ SetErrors
50
+ !insertmacro customInstall
51
+ IfErrors +2
52
+ Goto failed
53
+ IfFileExists "$PLUGINSDIR\7z-out\*.*" failed
54
+
55
+ ClearErrors
56
+ !insertmacro customInstall
57
+ IfErrors failed
58
+ FileOpen $1 "${RESULT_FILE}" w
59
+ FileWrite $1 "scratch removed; archive, plugin, rollback, registers and error flags preserved"
60
+ FileClose $1
61
+ SetErrorLevel 0
62
+ Quit
63
+
64
+ failed:
65
+ FileOpen $1 "${RESULT_FILE}" w
66
+ FileWrite $1 "cleanup smoke failed"
67
+ FileClose $1
68
+ SetErrorLevel 1
69
+ Quit
70
+ SectionEnd
apps/desktop/tests/fixtures/installer-write-failure-smoke.nsi ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ; Compile with OUTPUT_FILE, RESULT_FILE, PAYLOAD_FILE, TARGET_DIR and PLUGIN_DIR.
2
+ ; All paths must belong to a private test directory, except the NSIS plugin directory.
3
+ ; PAYLOAD_FILE contains locked.txt="new runtime" and asset.txt="new asset".
4
+ ; Before running /S, create TARGET_DIR\locked.txt="old runtime" and hold it open
5
+ ; for reading with FileShare.Read until the native process exits. asset.txt is absent.
6
+ ; Define DIRECT for direct extraction; otherwise extract to temporary files and copy.
7
+ ; Both modes retain "old runtime" and write "new asset" under that lock. The copy
8
+ ; sets errorFlag=true; direct extraction reports false despite the mixed versions.
9
+ ; Exit code 0 alone cannot establish successful extraction; inspect RESULT_FILE.
10
+ Unicode true
11
+ RequestExecutionLevel user
12
+ SilentInstall silent
13
+ Name "Desktop occupied-file extraction smoke"
14
+ OutFile "${OUTPUT_FILE}"
15
+ !addplugindir /x86-unicode "${PLUGIN_DIR}"
16
+
17
+ Section
18
+ InitPluginsDir
19
+ SetOutPath "${TARGET_DIR}"
20
+ !ifdef DIRECT
21
+ ClearErrors
22
+ Nsis7z::Extract "${PAYLOAD_FILE}"
23
+ !else
24
+ SetOutPath "$PLUGINSDIR\7z-out"
25
+ Nsis7z::Extract "${PAYLOAD_FILE}"
26
+ SetOutPath "${TARGET_DIR}"
27
+ ClearErrors
28
+ CopyFiles /SILENT "$PLUGINSDIR\7z-out\*" $OUTDIR
29
+ !endif
30
+
31
+ StrCpy $0 "false"
32
+ IfErrors 0 +2
33
+ StrCpy $0 "true"
34
+ ClearErrors
35
+ FileOpen $1 "${RESULT_FILE}" w
36
+ IfErrors failed
37
+ FileWrite $1 "errorFlag=$0$\r$\n"
38
+ FileOpen $2 "${TARGET_DIR}\locked.txt" r
39
+ IfErrors failed
40
+ FileRead $2 $3
41
+ FileClose $2
42
+ FileWrite $1 "locked=$3$\r$\n"
43
+ FileOpen $2 "${TARGET_DIR}\asset.txt" r
44
+ IfErrors failed
45
+ FileRead $2 $3
46
+ FileClose $2
47
+ FileWrite $1 "asset=$3$\r$\n"
48
+ FileClose $1
49
+ SetErrorLevel 0
50
+ Quit
51
+
52
+ failed:
53
+ SetErrorLevel 1
54
+ Quit
55
+ SectionEnd
apps/desktop/tests/fixtures/owned-directory-smoke.mjs ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** Built Desktop cleanup smoke; run with Electron and ELECTRON_RUN_AS_NODE=1. */
2
+
3
+ import assert from 'node:assert/strict'
4
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, symlinkSync, writeFileSync } from 'node:fs'
5
+ import { tmpdir } from 'node:os'
6
+ import { join } from 'node:path'
7
+ import { removeOwnedDirectory } from '../../lib/types/owned-directory.js'
8
+ import { inventoryDesktopRuntime } from '../../lib/types/runtime-tree.js'
9
+
10
+ assert.ok(process.versions.electron, 'This regression must run under Electron')
11
+ const root = mkdtempSync(join(tmpdir(), 'desktop-electron-cleanup-'))
12
+ try {
13
+ const resources = join(root, 'resources')
14
+ mkdirSync(resources)
15
+ writeFileSync(join(resources, 'sentinel'), 'installed runtime bytes')
16
+ const inventory = inventoryDesktopRuntime(resources)
17
+ const profile = join(root, 'rollback-profile')
18
+ const packages = join(profile, 'node_modules', '@unknown')
19
+ mkdirSync(packages, { recursive: true })
20
+ symlinkSync(resources, join(packages, 'host-package'), process.platform === 'win32' ? 'junction' : 'dir')
21
+ writeFileSync(join(packages, 'private-file'), 'removed')
22
+ removeOwnedDirectory(profile)
23
+ assert.equal(existsSync(profile), false)
24
+ assert.deepEqual(inventoryDesktopRuntime(resources), inventory)
25
+ assert.equal(readFileSync(join(resources, 'sentinel'), 'utf8'), 'installed runtime bytes')
26
+ console.log(JSON.stringify({ electron: process.versions.electron, node: process.version, preservedLinkTarget: true }))
27
+ } finally {
28
+ removeOwnedDirectory(root)
29
+ }
apps/desktop/tests/fixtures/runtime-payload-smoke.mjs ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** Exercise filtered Desktop native and HTML dependencies under its bundled Node. */
2
+
3
+ import assert from 'node:assert/strict'
4
+ import { closeSync, mkdtempSync, openSync, readFileSync, readSync, writeFileSync } from 'node:fs'
5
+ import { rm } from 'node:fs/promises'
6
+ import { createRequire } from 'node:module'
7
+ import { tmpdir } from 'node:os'
8
+ import { join, resolve } from 'node:path'
9
+
10
+ const runtime = process.argv[2]
11
+ assert.ok(runtime, 'Pass the filtered resources/dsh directory')
12
+ const root = resolve(runtime)
13
+ const descriptor = JSON.parse(readFileSync(join(root, 'desktop-runtime.json'), 'utf8'))
14
+ assert.equal(process.versions.node, descriptor.release.nodeVersion, 'Run with the bundled Node version')
15
+ assert.equal(process.platform, descriptor.platform)
16
+ assert.equal(process.arch, descriptor.arch)
17
+ const requireRuntime = createRequire(join(root, 'package.json'))
18
+ const scratch = mkdtempSync(join(tmpdir(), 'dsh-runtime-payload-'))
19
+
20
+ /** Spawn only a fixed Node program and await the terminal's drained exit event. */
21
+ async function checkPty() {
22
+ const pty = requireRuntime('node-pty')
23
+ const script = join(scratch, 'pty.cjs')
24
+ writeFileSync(script, "process.stdout.write('runtime-payload-pty-ok\\n')\n", { flag: 'wx', mode: 0o600 })
25
+ const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => (
26
+ /^(?:path|systemroot|windir|comspec)$/iu.test(name)
27
+ )))
28
+ Object.assign(env, { HOME: scratch, USERPROFILE: scratch, TMP: scratch, TEMP: scratch, TMPDIR: scratch })
29
+ const terminal = pty.spawn(process.execPath, [script], { cwd: scratch, env, cols: 80, rows: 24 })
30
+ let output = ''
31
+ let exited = false
32
+ let timedOut = false
33
+ let exitSubscription
34
+ const exit = new Promise(resolveExit => {
35
+ exitSubscription = terminal.onExit(event => {
36
+ exited = true
37
+ resolveExit(event)
38
+ })
39
+ })
40
+ const dataSubscription = terminal.onData(data => { output += data })
41
+ let timer
42
+ try {
43
+ const deadline = new Promise((_, reject) => {
44
+ timer = setTimeout(() => {
45
+ timedOut = true
46
+ reject(new Error('Packaged PTY did not exit within 45 seconds'))
47
+ }, 45_000)
48
+ })
49
+ const result = await Promise.race([exit, deadline])
50
+ assert.equal(timedOut, false)
51
+ assert.ok(result.signal === undefined || result.signal === 0, 'PTY exited without a signal')
52
+ assert.equal(result.exitCode, 0)
53
+ assert.match(output, /runtime-payload-pty-ok/u)
54
+ } finally {
55
+ clearTimeout(timer)
56
+ dataSubscription.dispose()
57
+ try {
58
+ // node-pty's Windows natural-exit event closes output but leaves its ConPTY worker owned by kill().
59
+ if (!exited || process.platform === 'win32') terminal.kill()
60
+ await exit
61
+ } finally {
62
+ exitSubscription.dispose()
63
+ }
64
+ }
65
+ }
66
+
67
+ /** fs-ext implements seek on Windows through SetFilePointerEx and on POSIX through lseek. */
68
+ function checkFsExt() {
69
+ const fsExt = requireRuntime('fs-ext')
70
+ const file = join(scratch, 'seek.txt')
71
+ writeFileSync(file, 'abcdef', { flag: 'wx', mode: 0o600 })
72
+ const fd = openSync(file, 'r')
73
+ try {
74
+ assert.equal(fsExt.seekSync(fd, 2, fsExt.constants.SEEK_SET), 2)
75
+ const bytes = Buffer.alloc(4)
76
+ assert.equal(readSync(fd, bytes, 0, bytes.length, null), 4)
77
+ assert.equal(bytes.toString(), 'cdef')
78
+ } finally {
79
+ closeSync(fd)
80
+ }
81
+ }
82
+
83
+ /** Resolve one system function through Koffi's packaged native module. */
84
+ function checkKoffi() {
85
+ const koffi = requireRuntime('koffi')
86
+ const library = koffi.load(process.platform === 'win32' ? 'kernel32.dll' : null)
87
+ try {
88
+ const getPid = process.platform === 'win32'
89
+ ? library.func('uint32_t __stdcall GetCurrentProcessId(void)')
90
+ : library.func('int getpid(void)')
91
+ assert.equal(getPid(), process.pid)
92
+ } finally {
93
+ library.unload()
94
+ }
95
+ }
96
+
97
+ /** Encode and decode a pixel through the packaged libvips binary. */
98
+ async function checkSharp() {
99
+ const sharp = requireRuntime('sharp')
100
+ const pixel = Buffer.from([17, 103, 231])
101
+ const png = await sharp(pixel, { raw: { width: 1, height: 1, channels: 3 } }).png().toBuffer()
102
+ const decoded = await sharp(png).raw().toBuffer({ resolveWithObject: true })
103
+ assert.equal(decoded.info.width, 1)
104
+ assert.equal(decoded.info.height, 1)
105
+ assert.equal(decoded.info.channels, 3)
106
+ assert.deepEqual(decoded.data, pixel)
107
+ }
108
+
109
+ /** Exercise Domino parsing through the HTML converter and GFM plugin used by web_fetch. */
110
+ function checkHtml() {
111
+ const Turndown = requireRuntime('turndown')
112
+ const { gfm } = requireRuntime('@joplin/turndown-plugin-gfm')
113
+ const converter = new Turndown({ bulletListMarker: '-' })
114
+ converter.use(gfm)
115
+ const markdown = converter.turndown('<p>A &amp; B &copy;</p><ul><li>first</li><li>second</li></ul>'
116
+ + '<table><thead><tr><th>Name</th><th>Value</th></tr></thead><tbody><tr><td>x</td><td>7</td></tr></tbody></table>')
117
+ assert.match(markdown, /A & B ©/u)
118
+ assert.match(markdown, /-\s+first\n-\s+second/u)
119
+ assert.match(markdown, /\| Name \| Value \|/u)
120
+ assert.match(markdown, /\| x\s+\| 7\s+\|/u)
121
+ }
122
+
123
+ try {
124
+ checkFsExt()
125
+ checkKoffi()
126
+ await checkSharp()
127
+ checkHtml()
128
+ await checkPty()
129
+ } finally {
130
+ // This private tree contains only fixture files; Windows may release handles after terminal exit.
131
+ await rm(scratch, { recursive: true, force: true, maxRetries: 20, retryDelay: 50 })
132
+ }
133
+
134
+ // Natural event-loop drain includes node-pty's worker and console-list helper teardown.
135
+ process.once('beforeExit', () => {
136
+ console.log(JSON.stringify({ node: process.versions.node, platform: process.platform, arch: process.arch,
137
+ fsExt: true, koffi: true, sharp: true, html: true, pty: true }))
138
+ })
apps/web/stress-tests/reasoning-chunks.stress.ts ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Opt-in browser stress reproduction for reasoning-stream renderer stalls.
3
+ * A test-owned model adapter emits 100,000 individual chunks through the real
4
+ * Host, Gateway, and browser carriers; the test measures event-loop and
5
+ * scheduled-interaction delay while the assembled React surface keeps a
6
+ * collapsed Think row live.
7
+ */
8
+ import type { Browser, Page } from 'playwright'
9
+ import { chromium } from 'playwright'
10
+ import { expect, it, onTestFailed } from 'vitest'
11
+ import { LlmAdapter, type GenerateOptions, type StreamChunk } from '@deepseek-ai/dsh-llm'
12
+ import type {} from '@deepseek-ai/dsh-agent-default-model'
13
+ import { launchWebScaffold, watchConsole, type WebScaffold } from '../tests/scaffold.ts'
14
+ import {
15
+ connectFreshWorkspace, newEnglishPage, saveFailureShot, writeComposerDraft,
16
+ } from '../tests/support.ts'
17
+
18
+ const CHUNK_COUNT = 100_000
19
+ const CHUNKS_PER_INTERVAL = 128
20
+ const CHUNK_INTERVAL_MS = 16
21
+ const MAIN_THREAD_DELAY_BUDGET_MS = 250
22
+ const PROVIDER = 'reasoning-stress-test'
23
+ const MODEL = 'reasoning-storm'
24
+ const MARKER = `REASONING_STRESS_COMPLETE:${String(CHUNK_COUNT)}`
25
+
26
+ interface ReasoningChunkStormState {
27
+ chunkCount: number
28
+ chunksPerInterval: number
29
+ intervalMs: number
30
+ emitted: number
31
+ marker: string
32
+ emitting: boolean
33
+ }
34
+
35
+ /** Externally paced model stream whose counters are observed outside the browser. */
36
+ class ReasoningStressAdapter extends LlmAdapter {
37
+ private finishStream!: () => void
38
+ private resolveStarted!: () => void
39
+ private resolveCompleted!: () => void
40
+ private releaseBatch: (() => void) | undefined
41
+ private resolveBatch: (() => void) | undefined
42
+ private batchInFlight = false
43
+ private finishRequested = false
44
+ private readonly finishGate = new Promise<void>((resolve) => { this.finishStream = resolve })
45
+ readonly started = new Promise<void>((resolve) => { this.resolveStarted = resolve })
46
+ readonly completed = new Promise<void>((resolve) => { this.resolveCompleted = resolve })
47
+ private emitted = 0
48
+ private emitting = false
49
+
50
+ finish(): void {
51
+ this.finishRequested = true
52
+ this.releaseBatch?.()
53
+ this.finishStream()
54
+ }
55
+
56
+ async emitNextBatch(): Promise<void> {
57
+ if (!this.emitting || this.releaseBatch === undefined) {
58
+ throw new Error('reasoning stress adapter has no batch awaiting release')
59
+ }
60
+ if (this.batchInFlight) throw new Error('reasoning stress adapter accepts one batch release at a time')
61
+ this.batchInFlight = true
62
+ const delivered = new Promise<void>((resolve) => { this.resolveBatch = resolve })
63
+ const release = this.releaseBatch
64
+ this.releaseBatch = undefined
65
+ release()
66
+ await delivered
67
+ }
68
+
69
+ state(): ReasoningChunkStormState {
70
+ return {
71
+ chunkCount: CHUNK_COUNT,
72
+ chunksPerInterval: CHUNKS_PER_INTERVAL,
73
+ intervalMs: CHUNK_INTERVAL_MS,
74
+ emitted: this.emitted,
75
+ marker: MARKER,
76
+ emitting: this.emitting,
77
+ }
78
+ }
79
+
80
+ override async *stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
81
+ if (this.emitting || this.emitted !== 0) throw new Error('reasoning stress adapter accepts one model call')
82
+ this.emitting = true
83
+ const parts: string[] = []
84
+ yield { type: 'block-start', index: 0, blockType: 'reasoning' }
85
+ while (this.emitted < CHUNK_COUNT) {
86
+ await new Promise<void>((resolve) => {
87
+ this.releaseBatch = resolve
88
+ if (this.emitted === 0) this.resolveStarted()
89
+ if (this.finishRequested) resolve()
90
+ })
91
+ if (this.finishRequested) break
92
+ options.signal?.throwIfAborted()
93
+ const end = Math.min(this.emitted + CHUNKS_PER_INTERVAL, CHUNK_COUNT)
94
+ while (this.emitted < end) {
95
+ const text = this.emitted === CHUNK_COUNT - 1
96
+ ? `\n${MARKER}`
97
+ : this.emitted % 64 === 63 ? '推理\n' : '推理'
98
+ parts.push(text)
99
+ yield { type: 'reasoning-delta', index: 0, text }
100
+ this.emitted += 1
101
+ }
102
+ this.batchInFlight = false
103
+ this.resolveBatch?.()
104
+ this.resolveBatch = undefined
105
+ }
106
+ this.emitting = false
107
+ if (this.emitted === CHUNK_COUNT) this.resolveCompleted()
108
+ await this.finishGate
109
+ options.signal?.throwIfAborted()
110
+ yield { type: 'block-end', index: 0, block: { type: 'reasoning', text: parts.join('') } }
111
+ yield { type: 'finish', reason: { kind: 'stop' } }
112
+ }
113
+ }
114
+
115
+ interface StressProbe {
116
+ intervalId: number
117
+ intervalMs: number
118
+ lastTickAt: number
119
+ maxDelayMs: number
120
+ samples: number
121
+ interactionDueAt: number
122
+ interactionHandledAt: number | null
123
+ }
124
+
125
+ interface StressWindow extends Window {
126
+ __reasoningStressProbe?: StressProbe
127
+ }
128
+
129
+ it('keeps the browser responsive while rendering 100,000 reasoning chunks', async () => {
130
+ let scaffold: WebScaffold | undefined
131
+ let browser: Browser | undefined
132
+ let page: Page | undefined
133
+ const adapter = new ReasoningStressAdapter()
134
+ try {
135
+ scaffold = await launchWebScaffold()
136
+ scaffold.ctx.effect(
137
+ () => scaffold!.ctx.llm.registerAdapter([PROVIDER], adapter),
138
+ 'reasoning stress adapter',
139
+ )
140
+ await scaffold.ctx.agentDefaultModel.saveSelection({ provider: PROVIDER, model: MODEL })
141
+ browser = await chromium.launch({ headless: process.env.DSH_WEB_STRESS_HEADFUL !== '1' })
142
+ page = await newEnglishPage(browser)
143
+ const activePage = page
144
+ const tripwire = watchConsole(activePage)
145
+ onTestFailed(() => saveFailureShot(activePage, 'web-stress-reasoning-chunks'))
146
+ await activePage.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
147
+ await activePage.waitForSelector('[class*="frame"]', { timeout: 30_000 })
148
+ await connectFreshWorkspace(activePage, scaffold.workspaceCwd)
149
+
150
+ await activePage.evaluate(() => {
151
+ const intervalMs = 50
152
+ const now = performance.now()
153
+ const probe: StressProbe = {
154
+ intervalId: 0,
155
+ intervalMs,
156
+ lastTickAt: now,
157
+ maxDelayMs: 0,
158
+ samples: 0,
159
+ interactionDueAt: now + 1_000,
160
+ interactionHandledAt: null,
161
+ }
162
+ probe.intervalId = window.setInterval(() => {
163
+ const tickAt = performance.now()
164
+ probe.maxDelayMs = Math.max(probe.maxDelayMs, tickAt - probe.lastTickAt - intervalMs)
165
+ probe.lastTickAt = tickAt
166
+ probe.samples++
167
+ }, intervalMs)
168
+ document.body.addEventListener('reasoning-stress-interaction', () => {
169
+ probe.interactionHandledAt = performance.now()
170
+ }, { once: true })
171
+ window.setTimeout(() => {
172
+ document.body.dispatchEvent(new CustomEvent('reasoning-stress-interaction'))
173
+ }, 1_000)
174
+ ;(window as StressWindow).__reasoningStressProbe = probe
175
+ })
176
+
177
+ const settled = scaffold.whenTurnSettled(540_000)
178
+ const input = activePage.locator('[data-composer-input]').first()
179
+ await writeComposerDraft(activePage, input, `Render ${String(CHUNK_COUNT)} reasoning chunks.`)
180
+ await input.press('Enter')
181
+ await adapter.started
182
+
183
+ await adapter.emitNextBatch()
184
+ const liveThink = activePage.locator('[data-variant="think"][data-state="running"]').last()
185
+ await liveThink.waitFor({ timeout: 60_000 })
186
+ await activePage.evaluate(intervalMs => new Promise<void>((resolve) => {
187
+ window.setTimeout(resolve, intervalMs)
188
+ }), CHUNK_INTERVAL_MS)
189
+ while (adapter.state().emitted < CHUNK_COUNT) {
190
+ await adapter.emitNextBatch()
191
+ await activePage.evaluate(intervalMs => new Promise<void>((resolve) => {
192
+ window.setTimeout(resolve, intervalMs)
193
+ }), CHUNK_INTERVAL_MS)
194
+ }
195
+ await adapter.completed
196
+ await expect.poll(() => liveThink.textContent(), { timeout: 60_000, interval: 100 }).toContain(MARKER)
197
+
198
+ const browserReport = await activePage.evaluate(() => {
199
+ const win = window as StressWindow
200
+ const probe = win.__reasoningStressProbe
201
+ if (probe === undefined) throw new Error('reasoning stress metrics unavailable')
202
+ window.clearInterval(probe.intervalId)
203
+ const interactionDelayMs = probe.interactionHandledAt === null
204
+ ? null
205
+ : probe.interactionHandledAt - probe.interactionDueAt
206
+ return {
207
+ maxMainThreadDelayMs: Math.max(0, probe.maxDelayMs),
208
+ interactionDelayMs,
209
+ heartbeatSamples: probe.samples,
210
+ }
211
+ })
212
+ const report = { ...adapter.state(), ...browserReport }
213
+ process.stdout.write(`reasoning-chunk stress report: ${JSON.stringify(report)}\n`)
214
+
215
+ expect(report).toMatchObject({
216
+ chunkCount: CHUNK_COUNT,
217
+ chunksPerInterval: CHUNKS_PER_INTERVAL,
218
+ intervalMs: CHUNK_INTERVAL_MS,
219
+ emitted: CHUNK_COUNT,
220
+ })
221
+ expect(report.heartbeatSamples).toBeGreaterThan(0)
222
+ const interactionDelayMs = report.interactionDelayMs
223
+ if (interactionDelayMs === null) throw new Error(`scheduled interaction was not handled: ${JSON.stringify(report)}`)
224
+ expect(report.maxMainThreadDelayMs, JSON.stringify(report)).toBeLessThan(MAIN_THREAD_DELAY_BUDGET_MS)
225
+ expect(interactionDelayMs, JSON.stringify(report)).toBeLessThan(MAIN_THREAD_DELAY_BUDGET_MS)
226
+ expect(tripwire.pageErrors).toEqual([])
227
+ expect(tripwire.warnings).toEqual([])
228
+ adapter.finish()
229
+ await settled
230
+ } finally {
231
+ adapter.finish()
232
+ await browser?.close()
233
+ await scaffold?.close()
234
+ }
235
+ }, 600_000)
apps/web/tests/README.zh.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # apps/web 浏览器 e2e
2
+
3
+ [English](README.md) | 中文
4
+
5
+ 这些测试在进程内启动真实的 web 组合,并用真实 Chromium 通过真实 HTTP 驱动它。该 lane 的运行机制——模式、fixture(测试前置数据)、golden,以及与 `dsh web` 之间刻意保留的组合差异——记录在 [`scaffold.ts`](scaffold.ts) 和 [浏览器 e2e Agent Note](../../../.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.zh.md) 中。
6
+
7
+ ## 完成状态观察
8
+
9
+ 依赖状态的用例使用 Workspace、接纳、附件和模型流屏障,区分可见中间状态与已完成操作。详情关闭等待框架过渡结束;归档验证为 seed Session 设置显式标题,并跨重载跟踪该身份。参见 [CI fixture 同步决策](../../../.agents/notes/implemented/testing/2026-09-08-ci-completion-observations.zh.md)。
10
+
11
+ ## 这些是 Host 面的测试
12
+
13
+ 它们在根 `tsconfig.host.json` 中做类型检查,而不在 Client aggregate 中,因为它们直接读取 Host 服务:`ctx.connection`、Host 侧 `SessionStore` 与 `ctx.sessionProjectionCache`。运行时驱动浏览器并不使一个文件成为 Client 程序的一部分——两个 face 在相同的键上以不同服务合并 Cordis `Context`,因此单个程序无法同时看见两者。把这些文件挪进 Client aggregate 会让每一处 Host 服务访问都无法编译。
14
+
15
+ ## 不要在此 import `@deepseek-ai/dsh-client-*`
16
+
17
+ import 一个 Client 包——无论值还是类型——都会把它整个 TypeScript 工程、以及它引用的每个工程拉进 **Host 构建图**。这已经坑过本 lane 一次:四个 Client 消费方包引用了 `api/remotes` 的 Client face,而该 face 必须等 Host tsdown 生成 `@deepseek-ai/dsh-goal/remote` 之后才能编译,于是 Host 构建阶段变成在等一个由它自己产出的产物。
18
+
19
+ 当某个场景需要 Client 持有的常量或纯函数时,改为在此处镜像一份,并紧挨着一条注释掉的 import 点明源模块。这样漂移会表现为选择器未命中或镜像值陈旧——是响亮的失败,绝不会是静默通过。`scaffold.ts` 按此规则镜像 welcome-notice 的 namespace、确认字段、版本和被断言的中文文案。
20
+
21
+ built-client harness 是例外。`assembled-boot.ts` import `AppWebEntry`、boot manifest(元数据清单)类型与 `RemoteMock`;`assembled-remote.ts` import Client test runtime 的默认响应与 `RemoteMock`。这些包是显式的工程引用,用于通过测试持有的 carrier 启动真实 shell。chat 场景仍在 `support.ts` 中镜像 `conversationContextKey`,而不 import 其 Client owner。
22
+
23
+ 没有任何机制强制这条规则;靠 review 守住它。
apps/web/tests/agent-team-panel.e2e.ts ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Keyless assembled-browser coverage for the opt-in Agent Teams Web profiles
2
+ // over the real Host Typert Remote flow.
3
+ import { fileURLToPath } from 'node:url'
4
+ import { join } from 'node:path'
5
+ import { readFileSync } from 'node:fs'
6
+ import type { Browser, Page } from 'playwright'
7
+ import { chromium } from 'playwright'
8
+ import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
9
+ import * as yaml from 'js-yaml'
10
+ import { entryListSchema } from '@deepseek-ai/cordis-plugin-include'
11
+ import { createMessage, createUserMessage } from '@deepseek-ai/dsh-llm'
12
+ import {
13
+ assertFixtureInventory, captureStableAria, compareOrRefreshGolden,
14
+ launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold,
15
+ } from './scaffold.ts'
16
+ import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts'
17
+
18
+ const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/agent-team-panel', import.meta.url))
19
+ const PANEL_EXPECTED = join(SNAPSHOT_DIR, 'task.expected.md')
20
+ const OVERLAY = fileURLToPath(new URL('./agent-team-panel.overlay.yml', import.meta.url))
21
+ const HOST_PATCH = fileURLToPath(new URL('../../../packages/experimental/agent-team-profile/cordis.patch.yml', import.meta.url))
22
+ const WEB_PATCH = fileURLToPath(new URL('../../../packages/experimental/agent-team-web-profile/cordis.patch.yml', import.meta.url))
23
+ const INSTALL_ANCHORS = [
24
+ fileURLToPath(new URL('../../../packages/experimental/agent-team-profile/package.json', import.meta.url)),
25
+ fileURLToPath(new URL('../../../packages/experimental/agent-team-web-profile/package.json', import.meta.url)),
26
+ ]
27
+ const MODE = webSnapshotMode()
28
+
29
+ function profileEntries(path: string): unknown[] {
30
+ const parsed = yaml.load(readFileSync(path, 'utf8'), { schema: entryListSchema })
31
+ if (!Array.isArray(parsed)) throw new Error(`profile layer at ${path} must be a list`)
32
+ return parsed
33
+ }
34
+
35
+ describe('Agent Teams panel overlay', () => {
36
+ it('matches the shipped Host and Web profile layers', () => {
37
+ expect(profileEntries(OVERLAY)).toEqual([
38
+ ...profileEntries(HOST_PATCH),
39
+ ...profileEntries(WEB_PATCH),
40
+ ])
41
+ })
42
+ })
43
+
44
+ describe('web e2e: Agent Teams panel', () => {
45
+ let scaffold: WebScaffold
46
+ let browser: Browser
47
+ let page: Page
48
+ let tripwire: ReturnType<typeof watchConsole>
49
+
50
+ beforeAll(async () => {
51
+ scaffold = await launchWebScaffold({ extraOverlayPath: OVERLAY, extraInstallAnchors: INSTALL_ANCHORS })
52
+ browser = await chromium.launch()
53
+ page = await newEnglishPage(browser)
54
+ tripwire = watchConsole(page)
55
+ await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
56
+ await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
57
+ await connectFreshWorkspace(page, scaffold.workspaceCwd)
58
+ const agent = scaffold.ctx.agents.list()[0]
59
+ if (agent === undefined) throw new Error('connected Team workspace did not create an Agent')
60
+ agent.session.append('turn/start', { turn: 1 })
61
+ agent.session.append('user/message', createUserMessage({
62
+ content: [{ type: 'text', text: 'Open the Agent Team controls.' }],
63
+ source: { kind: 'user' },
64
+ }), { surfaceOp: 'append' })
65
+ agent.session.append('step/start', { turn: 1, step: 1 })
66
+ agent.session.append('assistant/message', {
67
+ stream: [],
68
+ turn: 1,
69
+ step: 1,
70
+ message: createMessage({
71
+ role: 'assistant',
72
+ content: [{ type: 'text', text: 'Ready.' }],
73
+ source: { kind: 'model', provider: 'fixture', model: 'fixture' },
74
+ }),
75
+ }, { surfaceOp: 'append' })
76
+ agent.session.append('step/end', { turn: 1, step: 1 })
77
+ agent.session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
78
+ await scaffold.ctx.sessions.flush(agent.session)
79
+ await page.getByText('Ready.').waitFor({ timeout: 10_000 })
80
+ }, 120_000)
81
+
82
+ afterAll(async () => {
83
+ await browser?.close()
84
+ await scaffold?.close()
85
+ })
86
+
87
+ it('loads the roster and creates one shared task through generated Remote', async () => {
88
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-agent-team-panel'))
89
+ const action = page.locator('[data-team-action]')
90
+ await action.getByRole('button', { name: /Agent Team/iu }).click()
91
+ await action.getByText('No shared tasks yet').waitFor()
92
+ await action.getByText('lead').waitFor()
93
+
94
+ await action.getByRole('button', { name: 'New task' }).click()
95
+ await action.getByPlaceholder('Task subject').fill('Browser task')
96
+ await action.getByPlaceholder('Task description').fill('Created through the assembled browser')
97
+ await action.getByPlaceholder(/Write scopes/iu).fill('src/web')
98
+ await action.getByRole('button', { name: 'Save' }).click()
99
+ await action.getByText('Browser task').waitFor()
100
+
101
+ const snapshot = await captureStableAria(page, '[data-team-action]', scaffold.workspaceCwd)
102
+ await compareOrRefreshGolden(PANEL_EXPECTED, snapshot, MODE)
103
+ expect(tripwire.pageErrors).toEqual([])
104
+ expect(tripwire.warnings).toEqual([])
105
+ }, 60_000)
106
+
107
+ it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => {
108
+ await assertFixtureInventory(SNAPSHOT_DIR, ['task.expected.md'])
109
+ })
110
+ })
apps/web/tests/assembled-remote.spec.ts ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** Stateful behavior of the app-owned RemoteMock scenario. */
2
+
3
+ import { expect, it } from 'vitest'
4
+ import { createAssembledRemote } from './assembled-remote.ts'
5
+
6
+ it('advances turns and updates the Session summary after accepted prompts', async () => {
7
+ const { mock } = createAssembledRemote()
8
+ await mock.dispatch('session/create', [{ request: { cwd: '/work' } }])
9
+ await mock.dispatch('session/prompt', [{
10
+ request: { sessionId: 'fx-1', requestId: 'request-1', mode: 'queue', content: [] },
11
+ }])
12
+ await mock.dispatch('session/prompt', [{
13
+ request: { sessionId: 'fx-1', requestId: 'request-2', mode: 'queue', content: [] },
14
+ }])
15
+
16
+ const listed = await mock.dispatch('session/list', []) as {
17
+ readonly ok: true
18
+ readonly value: {
19
+ readonly items: readonly { readonly sessionId: string; readonly blank: boolean; readonly running: boolean }[]
20
+ }
21
+ }
22
+ expect(listed.ok).toBe(true)
23
+ expect(listed.value.items.find(item => item.sessionId === 'fx-1')).toMatchObject({
24
+ blank: false,
25
+ running: true,
26
+ })
27
+
28
+ const iterator = mock.open('session/follow', [{
29
+ request: { address: { kind: 'session', sessionId: 'fx-1' } },
30
+ }], new AbortController().signal)[Symbol.asyncIterator]()
31
+ await expect(iterator.next()).resolves.toMatchObject({
32
+ done: false,
33
+ value: {
34
+ records: [
35
+ { event: { type: 'turn/start', data: { turn: 0 } } },
36
+ { event: { type: 'user/message' } },
37
+ { event: { type: 'turn/start', data: { turn: 1 } } },
38
+ { event: { type: 'user/message' } },
39
+ ],
40
+ },
41
+ })
42
+ await iterator.return?.()
43
+ mock.assertNoUnmatched()
44
+ })
apps/web/tests/auto-review-fixture.ts ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** Explicit source Web layer and optional visual evidence for Auto scenarios. */
2
+ import { mkdir } from 'node:fs/promises'
3
+ import { join } from 'node:path'
4
+ import { fileURLToPath } from 'node:url'
5
+ import type { Page } from 'playwright'
6
+ import type { LaunchOptions } from './scaffold.ts'
7
+
8
+ /** The same private bundle patch installed by the source Web CLI. */
9
+ export const AUTO_REVIEW_FIXTURE = {
10
+ extraOverlayPath: fileURLToPath(new URL('../../../packages/experimental/auto-review/cordis.patch.yml', import.meta.url)),
11
+ extraInstallAnchors: [fileURLToPath(new URL('../../../packages/experimental/auto-review/package.json', import.meta.url))],
12
+ } satisfies Pick<LaunchOptions, 'extraOverlayPath' | 'extraInstallAnchors'>
13
+
14
+ /** Save a fixed-state screenshot when the calling validation requests evidence. */
15
+ export async function captureAutoReviewState(page: Page, name: string): Promise<void> {
16
+ const directory = process.env.DSH_AUTO_REVIEW_SCREENSHOT_DIR
17
+ if (directory === undefined) return
18
+ await mkdir(directory, { recursive: true })
19
+ await page.screenshot({ path: join(directory, `${name}.png`), fullPage: true })
20
+ }
apps/web/tests/chat-continuous-conversation.e2e.ts ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Web e2e contract for a conversation grown through the real composer rather
2
+ // than pre-seeded history. Twelve deterministic replay turns exercise repeated
3
+ // send/settle/render cycles, including two real bash executions and one long,
4
+ // multi-chunk final turn. Assertions stay semantic: no host timing, heap, or
5
+ // mounted-row cardinality is treated as a correctness contract.
6
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises'
7
+ import { tmpdir } from 'node:os'
8
+ import { join } from 'node:path'
9
+ import type { Browser, Page } from 'playwright'
10
+ import { chromium } from 'playwright'
11
+ import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
12
+ import { ToolCallId, expandAssistantStream, type StreamChunk } from '@deepseek-ai/dsh-llm'
13
+ import type { ReplayEntry, ReplayOverrideDoc } from '@deepseek-ai/dsh-llm-replay'
14
+ import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session'
15
+ import {
16
+ launchWebScaffold,
17
+ watchConsole,
18
+ webSnapshotMode,
19
+ type WebScaffold,
20
+ } from './scaffold.ts'
21
+ import {
22
+ connectFreshWorkspace, conversationContextKey, expandOwningTurnProcess, newEnglishPage, saveFailureShot,
23
+ } from './support.ts'
24
+
25
+ const MODE = webSnapshotMode()
26
+ const TURN_COUNT = 12
27
+ const TOOL_TURNS = [4, 9] as const
28
+ const STREAM_PACE_MS = 10
29
+
30
+ interface TurnSpec {
31
+ readonly index: number
32
+ readonly prompt: string
33
+ readonly userMarker: string
34
+ readonly firstMarker: string
35
+ readonly doneMarker: string
36
+ readonly deltas: readonly string[]
37
+ readonly callId?: ReturnType<typeof ToolCallId>
38
+ readonly toolResultMarker?: string
39
+ }
40
+
41
+ function suffix(index: number): string {
42
+ return String(index).padStart(3, '0')
43
+ }
44
+
45
+ function longFinalPrompt(userMarker: string): string {
46
+ return [
47
+ `${userMarker} Reconcile this accumulated conversation without losing earlier turn ownership.`,
48
+ ...Array.from(
49
+ { length: 36 },
50
+ (_, index) => `Context ${String(index + 1).padStart(2, '0')}: preserve token-${String(index)} and verify ${'payload '.repeat(12).trimEnd()}.`,
51
+ ),
52
+ 'Return one continuous response and finish with the requested completion marker.',
53
+ ].join('\n')
54
+ }
55
+
56
+ function turnSpec(index: number): TurnSpec {
57
+ const id = suffix(index)
58
+ const userMarker = `CONTINUOUS_CHAT_USER_${id}`
59
+ const firstMarker = `CONTINUOUS_CHAT_FIRST_${id}`
60
+ const doneMarker = `CONTINUOUS_CHAT_DONE_${id}`
61
+ const deltaCount = index === TURN_COUNT ? 36 : 8
62
+ const deltas = Array.from({ length: deltaCount }, (_, chunkIndex) => {
63
+ if (chunkIndex === 0) return `${firstMarker} `
64
+ if (chunkIndex === deltaCount - 1) return `${doneMarker}.`
65
+ return `turn-${id}-chunk-${String(chunkIndex).padStart(2, '0')} keeps semantic ownership stable. `
66
+ })
67
+ if (!TOOL_TURNS.includes(index as (typeof TOOL_TURNS)[number])) {
68
+ return {
69
+ index,
70
+ prompt: index === TURN_COUNT
71
+ ? longFinalPrompt(userMarker)
72
+ : `${userMarker} Continue this same conversation through turn ${String(index)}.`,
73
+ userMarker,
74
+ firstMarker,
75
+ doneMarker,
76
+ deltas,
77
+ }
78
+ }
79
+ return {
80
+ index,
81
+ prompt: `${userMarker} Run the requested deterministic tool for turn ${String(index)}, then continue.`,
82
+ userMarker,
83
+ firstMarker,
84
+ doneMarker,
85
+ deltas,
86
+ callId: ToolCallId(`continuous-chat-tool-${id}`),
87
+ toolResultMarker: `CONTINUOUS_CHAT_TOOL_RESULT_${id}`,
88
+ }
89
+ }
90
+
91
+ function textStream(spec: TurnSpec): StreamChunk[] {
92
+ const response = spec.deltas.join('')
93
+ return [
94
+ { type: 'block-start', index: 0, blockType: 'text' },
95
+ ...spec.deltas.map(text => ({ type: 'text-delta' as const, index: 0, text })),
96
+ { type: 'block-end', index: 0, block: { type: 'text', text: response } },
97
+ {
98
+ type: 'usage',
99
+ usage: {
100
+ inputTokens: Math.ceil(spec.prompt.length / 4),
101
+ outputTokens: Math.ceil(response.length / 4),
102
+ },
103
+ },
104
+ { type: 'finish', reason: { kind: 'stop' } },
105
+ ]
106
+ }
107
+
108
+ function toolStream(spec: TurnSpec): StreamChunk[] {
109
+ if (spec.callId === undefined || spec.toolResultMarker === undefined) {
110
+ throw new Error(`turn ${String(spec.index)} has no tool identity`)
111
+ }
112
+ const args = JSON.stringify({
113
+ command: `printf '${spec.toolResultMarker}\\n'`,
114
+ description: spec.toolResultMarker,
115
+ })
116
+ return [
117
+ { type: 'block-start', index: 0, blockType: 'tool-call' },
118
+ {
119
+ type: 'tool-call-delta',
120
+ index: 0,
121
+ id: spec.callId,
122
+ name: 'bash',
123
+ argumentsDelta: args,
124
+ },
125
+ {
126
+ type: 'block-end',
127
+ index: 0,
128
+ block: { type: 'tool-call', id: spec.callId, name: 'bash', arguments: args },
129
+ },
130
+ { type: 'usage', usage: { inputTokens: 256, outputTokens: 24 } },
131
+ { type: 'finish', reason: { kind: 'tool-calls' } },
132
+ ]
133
+ }
134
+
135
+ function replayScript(specs: readonly TurnSpec[]): ReplayOverrideDoc {
136
+ return specs.flatMap((spec): ReplayEntry[] => {
137
+ const final: ReplayEntry = { kind: 'chunks', chunks: textStream(spec) }
138
+ return spec.callId === undefined
139
+ ? [final]
140
+ : [{ kind: 'chunks', chunks: toolStream(spec) }, final]
141
+ })
142
+ }
143
+
144
+ function userText(event: Extract<SessionEvent, { type: 'user/message' }>): string {
145
+ return event.data.content
146
+ .filter(block => block.type === 'text')
147
+ .map(block => block.text)
148
+ .join('')
149
+ }
150
+
151
+ function assistantText(event: Extract<SessionEvent, { type: 'assistant/message' }>): string {
152
+ return event.data.message.content
153
+ .filter(block => block.type === 'text')
154
+ .map(block => block.text)
155
+ .join('')
156
+ }
157
+
158
+ function toolResultText(event: Extract<SessionEvent, { type: 'tool/result' }>): string {
159
+ return event.data.message.content[0].content
160
+ .filter(block => block.type === 'text')
161
+ .map(block => block.text)
162
+ .join('')
163
+ }
164
+
165
+ function messageKey(event: SessionEvent<'user/message'>): string {
166
+ return conversationContextKey('input-message', String(event.data.id))
167
+ }
168
+
169
+ function assistantKey(event: SessionEvent<'assistant/message'>): string {
170
+ return conversationContextKey('assistant-step', `${event.data.turn}:${event.data.step}`)
171
+ }
172
+
173
+ describe('web e2e: continuous conversation grown through the composer', () => {
174
+ let browser: Browser
175
+ let page: Page
176
+ let replayDir: string
177
+ let scaffold: WebScaffold
178
+ let tripwire: ReturnType<typeof watchConsole>
179
+ const consoleWarnings: string[] = []
180
+ const sessionEvents: SessionEvent[] = []
181
+ const specs = Array.from({ length: TURN_COUNT }, (_, offset) => turnSpec(offset + 1))
182
+
183
+ beforeAll(async () => {
184
+ replayDir = await mkdtemp(join(tmpdir(), 'dsh-continuous-chat-replay-'))
185
+ const replayOverride = join(replayDir, 'replay.override.json')
186
+ await writeFile(replayOverride, JSON.stringify(replayScript(specs)))
187
+ scaffold = await launchWebScaffold({
188
+ replayFixture: join(replayDir, 'override-only.jsonl'),
189
+ replayOverride,
190
+ replayContextWindow: 10_000_000,
191
+ paceMs: STREAM_PACE_MS,
192
+ })
193
+ scaffold.ctx.on('session/event', (_session, event: SessionEvent) => {
194
+ sessionEvents.push(event)
195
+ })
196
+ browser = await chromium.launch()
197
+ page = await newEnglishPage(browser, 900)
198
+ tripwire = watchConsole(page)
199
+ page.on('console', (message) => {
200
+ if (message.type() === 'warning') consoleWarnings.push(message.text())
201
+ })
202
+ await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
203
+ await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
204
+ await connectFreshWorkspace(page, scaffold.workspaceCwd, 'continuous-chat-e2e')
205
+ }, 120_000)
206
+
207
+ afterAll(async () => {
208
+ const failures: unknown[] = []
209
+ await browser?.close().catch((error: unknown) => failures.push(error))
210
+ await scaffold?.close().catch((error: unknown) => failures.push(error))
211
+ if (replayDir !== undefined) {
212
+ await rm(replayDir, { recursive: true, force: true })
213
+ .catch((error: unknown) => failures.push(error))
214
+ }
215
+ if (failures.length === 1) throw failures[0]
216
+ if (failures.length > 1) throw new AggregateError(failures, 'continuous Chat e2e cleanup failed')
217
+ })
218
+
219
+ it.skipIf(MODE === 'record')('keeps twelve generated turns and tool rows bound to one live session', async () => {
220
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-chat-continuous-conversation'))
221
+ const composer = page.locator('[data-composer-input][contenteditable="true"]').last()
222
+ await composer.waitFor({ timeout: 15_000 })
223
+ let sessionId: SessionId | undefined
224
+
225
+ for (const spec of specs) {
226
+ const eventStart = sessionEvents.length
227
+ expect(await composer.textContent()).toBe('')
228
+ expect(await composer.isEnabled()).toBe(true)
229
+ await composer.fill(spec.prompt)
230
+ expect(await composer.textContent()).toBe(spec.prompt)
231
+
232
+ const settled = scaffold.whenTurnSettled(60_000)
233
+ await page.getByRole('button', { name: 'Send message', exact: true }).click()
234
+ await page.getByText(spec.userMarker, { exact: false }).last().waitFor({ timeout: 15_000 })
235
+ await expect.poll(() => sessionEvents.slice(eventStart).some(event => (
236
+ event.type === 'user/message'
237
+ && event.data.source.kind === 'user'
238
+ && userText(event).includes(spec.userMarker)
239
+ )), { timeout: 15_000 }).toBe(true)
240
+ const echoedUser = sessionEvents.slice(eventStart).find(
241
+ (event): event is SessionEvent<'user/message'> => (
242
+ event.type === 'user/message'
243
+ && event.data.source.kind === 'user'
244
+ && userText(event).includes(spec.userMarker)
245
+ ),
246
+ )
247
+ if (echoedUser === undefined) throw new Error(`turn ${String(spec.index)} has no user echo event`)
248
+ const userRow = page.locator(`[data-chat-anchor-key="${messageKey(echoedUser)}"]`)
249
+ await expect.poll(() => userRow.count(), { timeout: 10_000 }).toBe(1)
250
+ expect(await userRow.getAttribute('data-chat-flow-kind')).toBe('user')
251
+ expect(await userRow.textContent()).toContain(spec.userMarker)
252
+ await page.getByText(spec.firstMarker, { exact: false }).last().waitFor({ timeout: 15_000 })
253
+ const settledSessionId = await settled
254
+ if (sessionId === undefined) {
255
+ sessionId = settledSessionId
256
+ } else {
257
+ expect(settledSessionId).toBe(sessionId)
258
+ }
259
+
260
+ await expect.poll(() => page.locator('[data-streaming="true"]').count(), { timeout: 15_000 }).toBe(0)
261
+ await page.getByText(spec.doneMarker, { exact: false }).last().waitFor({ timeout: 15_000 })
262
+ await expect.poll(() => composer.textContent(), { timeout: 10_000 }).toBe('')
263
+ await expect.poll(() => composer.isEnabled(), { timeout: 10_000 }).toBe(true)
264
+
265
+ const turnEvents = sessionEvents.slice(eventStart)
266
+ const turnStarts = turnEvents.filter((event): event is SessionEvent<'turn/start'> => (
267
+ event.type === 'turn/start'
268
+ ))
269
+ const users = turnEvents.filter((event): event is SessionEvent<'user/message'> => (
270
+ event.type === 'user/message' && event.data.source.kind === 'user'
271
+ ))
272
+ const assistants = turnEvents.filter((event): event is SessionEvent<'assistant/message'> => (
273
+ event.type === 'assistant/message'
274
+ ))
275
+ const finalAssistants = assistants.filter(event => assistantText(event).includes(spec.doneMarker))
276
+ const turnEnds = turnEvents.filter((event): event is SessionEvent<'turn/end'> => (
277
+ event.type === 'turn/end'
278
+ ))
279
+ const chunks = turnEvents.flatMap(event => (
280
+ event.type === 'assistant/message' || event.type === 'assistant/attempt'
281
+ ? expandAssistantStream(event.data.stream)
282
+ : []
283
+ ))
284
+
285
+ expect(turnStarts).toHaveLength(1)
286
+ expect(turnStarts[0]?.data.turn).toBe(spec.index)
287
+ expect(users).toHaveLength(1)
288
+ expect(users[0]?.seq).toBe(echoedUser.seq)
289
+ expect(userText(users[0]!)).toBe(spec.prompt)
290
+ expect(finalAssistants).toHaveLength(1)
291
+ expect(assistants).toHaveLength(spec.callId === undefined ? 1 : 2)
292
+ expect(turnEnds).toHaveLength(1)
293
+ expect(turnEnds[0]?.data).toEqual({ turn: spec.index, reason: { kind: 'completed' } })
294
+ expect(chunks).toHaveLength(spec.deltas.length + (spec.callId === undefined ? 4 : 9))
295
+
296
+ const assistantRow = page.locator(`[data-chat-anchor-key="${assistantKey(finalAssistants[0]!)}"]`)
297
+ await expect.poll(() => assistantRow.count(), { timeout: 10_000 }).toBe(1)
298
+ expect(await assistantRow.getAttribute('data-chat-flow-kind')).toBe('assistant-step')
299
+ expect(await assistantRow.textContent()).toContain(spec.doneMarker)
300
+
301
+ const calls = turnEvents.filter((event): event is SessionEvent<'tool/call'> => event.type === 'tool/call')
302
+ const results = turnEvents.filter((event): event is SessionEvent<'tool/result'> => event.type === 'tool/result')
303
+ if (spec.callId === undefined || spec.toolResultMarker === undefined) {
304
+ expect(calls).toHaveLength(0)
305
+ expect(results).toHaveLength(0)
306
+ continue
307
+ }
308
+
309
+ expect(calls).toHaveLength(1)
310
+ expect(results).toHaveLength(1)
311
+ expect(calls[0]?.data).toMatchObject({
312
+ turn: spec.index,
313
+ callId: spec.callId,
314
+ name: 'bash',
315
+ })
316
+ expect(results[0]?.data.turn).toBe(spec.index)
317
+ expect(results[0]?.data.message.source.callId).toBe(spec.callId)
318
+ expect(results[0]?.data.message.content[0].isError).toBe(false)
319
+ expect(toolResultText(results[0]!)).toBe(`${spec.toolResultMarker}\n`)
320
+
321
+ const toolRow = page.locator(`[data-chat-call-id="${spec.callId}"]`)
322
+ await expect.poll(() => toolRow.count(), { timeout: 10_000 }).toBe(1)
323
+ expect(await toolRow.textContent()).toContain(spec.toolResultMarker)
324
+ await expandOwningTurnProcess(page, toolRow)
325
+ const disclosure = toolRow.locator('[data-sample="bash"]')
326
+ expect(await disclosure.getAttribute('aria-expanded')).toBe('false')
327
+ await disclosure.click()
328
+ await expect.poll(() => disclosure.getAttribute('aria-expanded'), { timeout: 10_000 }).toBe('true')
329
+ // The collapsed summary deliberately repeats the result marker; the
330
+ // last exact match is the expanded terminal output owned by this call.
331
+ await toolRow.getByText(spec.toolResultMarker, { exact: true }).last().waitFor({ timeout: 10_000 })
332
+ await disclosure.click()
333
+ await expect.poll(() => disclosure.getAttribute('aria-expanded'), { timeout: 10_000 }).toBe('false')
334
+ }
335
+
336
+ if (sessionId === undefined) throw new Error('continuous conversation completed no turn')
337
+ expect(scaffold.ctx.agents.get(sessionId)?.session.snapshotEvents().filter(event => (
338
+ event.type === 'turn/end' && event.data.reason.kind === 'completed'
339
+ ))).toHaveLength(TURN_COUNT)
340
+ expect(sessionEvents.flatMap(event =>
341
+ event.type === 'request/header' ? [event.data.reason] : [])).toEqual(['initial'])
342
+ expect(await page.getByRole('button', { name: 'System prompt' }).count()).toBe(1)
343
+ expect(await page.locator(
344
+ '[data-chat-flow-kind="system-prompt"][hidden="until-found"]',
345
+ ).count()).toBe(0)
346
+ expect(specs.at(-1)?.prompt.length).toBeGreaterThan(4_000)
347
+ expect(sessionEvents.flatMap(event => (
348
+ (event.type === 'assistant/message' || event.type === 'assistant/attempt')
349
+ && event.data.turn === TURN_COUNT
350
+ ? expandAssistantStream(event.data.stream)
351
+ : []
352
+ )).length).toBeGreaterThan(30)
353
+ expect(consoleWarnings).toEqual([])
354
+ expect(tripwire.pageErrors).toEqual([])
355
+ expect(tripwire.warnings).toEqual([])
356
+ }, 180_000)
357
+ })
apps/web/tests/chat-long-interactions.e2e.ts ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Long-history Chat behavior contract that stays valid under a virtualized
2
+ // renderer: wheel input only navigates to the semantic target; assertions pin
3
+ // content identity and interaction routing rather than scroll geometry or
4
+ // mounted row counts.
5
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises'
6
+ import { tmpdir } from 'node:os'
7
+ import { join } from 'node:path'
8
+ import type { Browser, Page } from 'playwright'
9
+ import { chromium } from 'playwright'
10
+ import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
11
+ import type { StreamChunk } from '@deepseek-ai/dsh-llm'
12
+ import type { ReplayEntry, ReplayOverrideDoc } from '@deepseek-ai/dsh-llm-replay'
13
+ import { SessionId, type SessionEvent } from '@deepseek-ai/dsh-session'
14
+ import { createChatScrollFixture } from './chat-scroll-fixture.ts'
15
+ import {
16
+ launchWebScaffold,
17
+ seedSession,
18
+ watchConsole,
19
+ webSnapshotMode,
20
+ type WebScaffold,
21
+ } from './scaffold.ts'
22
+ import { conversationContextKey, expandOwningTurnProcess, newEnglishPage, saveFailureShot } from './support.ts'
23
+
24
+ const MODE = webSnapshotMode()
25
+ const SESSION_ID = 'chat-long-interactions-e2e'
26
+ const FIXTURE_TURNS = 88
27
+ const TOOL_TURN = FIXTURE_TURNS
28
+ const BRANCH_TURN = 80
29
+ const TARGET_CALL_1 = 'chat-scroll-088-1'
30
+ const TARGET_CALL_2 = 'chat-scroll-088-2'
31
+ const CONTINUE_PROMPT = 'CHAT_INTERACTION_CONTINUE Continue from this exact branch point.'
32
+ const CONTINUE_FIRST = 'CHAT_INTERACTION_CONTINUE_FIRST'
33
+ const CONTINUE_DONE = 'CHAT_INTERACTION_CONTINUE_DONE'
34
+ const FIXTURE = createChatScrollFixture({
35
+ markerPrefix: 'INTERACTION',
36
+ title: 'CHAT_INTERACTION long semantic identity session',
37
+ turns: FIXTURE_TURNS,
38
+ })
39
+
40
+ function continuationChunks(): StreamChunk[] {
41
+ const response = `${CONTINUE_FIRST} The fork retained the intended prefix. ${CONTINUE_DONE}.`
42
+ return [
43
+ { type: 'block-start', index: 0, blockType: 'text' },
44
+ { type: 'text-delta', index: 0, text: `${CONTINUE_FIRST} ` },
45
+ { type: 'text-delta', index: 0, text: `The fork retained the intended prefix. ${CONTINUE_DONE}.` },
46
+ { type: 'block-end', index: 0, block: { type: 'text', text: response } },
47
+ { type: 'usage', usage: { inputTokens: 512, outputTokens: 32 } },
48
+ { type: 'finish', reason: { kind: 'stop' } },
49
+ ]
50
+ }
51
+
52
+ function replayEntry(chunks: StreamChunk[]): ReplayEntry {
53
+ return { kind: 'chunks', chunks }
54
+ }
55
+
56
+ function carries(event: SessionEvent, marker: string): boolean {
57
+ return JSON.stringify(event).includes(marker)
58
+ }
59
+
60
+ function textContent(content: readonly unknown[]): string {
61
+ return content.flatMap((block) => {
62
+ if (typeof block !== 'object' || block === null) return []
63
+ const candidate = block as { type?: unknown; text?: unknown }
64
+ return candidate.type === 'text' && typeof candidate.text === 'string'
65
+ ? [candidate.text]
66
+ : []
67
+ }).join('')
68
+ }
69
+
70
+ async function nextPaint(page: Page): Promise<void> {
71
+ await page.evaluate(async () => {
72
+ await document.fonts.ready
73
+ await new Promise<void>(resolve => requestAnimationFrame(() => {
74
+ requestAnimationFrame(() => { resolve() })
75
+ }))
76
+ })
77
+ }
78
+
79
+ async function openSeed(page: Page): Promise<void> {
80
+ // The compact layout dropped group session counts; the seeded baseline is
81
+ // the Ungrouped bucket once cold summaries load.
82
+ await page.getByText('Ungrouped', { exact: true }).waitFor({ timeout: 30_000 })
83
+ // Search collapsed into a header action; expand it before filling.
84
+ const searchButton = page.getByRole('button', { name: 'Search sessions' })
85
+ if (await searchButton.getAttribute('aria-expanded') !== 'true') await searchButton.click()
86
+ const search = page.getByRole('textbox', { name: 'Search sessions...', exact: true })
87
+ await search.fill(FIXTURE.markers.user(1))
88
+ const results = page.getByRole('tree', { name: 'Search results' }).getByRole('treeitem')
89
+ await results.first().waitFor({ timeout: 60_000 })
90
+ const resultCount = await results.count()
91
+ if (resultCount !== 1) throw new Error(`expected one seeded search result, received ${String(resultCount)}`)
92
+ await results.click()
93
+ await page.getByText(FIXTURE.markers.assistant(FIXTURE.turns), { exact: false })
94
+ .last().waitFor({ timeout: 30_000 })
95
+ await nextPaint(page)
96
+ }
97
+
98
+ async function wheelUntilMounted(page: Page, selector: string, deltaY: number): Promise<void> {
99
+ const scrollport = page.locator('[data-conversation-scroll]')
100
+ const box = await scrollport.boundingBox()
101
+ if (box === null) throw new Error('conversation scrollport has no layout box')
102
+ await page.mouse.move(box.x + box.width / 2, box.y + Math.min(140, box.height / 3))
103
+ for (let attempt = 0; attempt < 20; attempt += 1) {
104
+ if (await page.locator(selector).count() > 0) return
105
+ await page.mouse.wheel(0, deltaY)
106
+ await nextPaint(page)
107
+ }
108
+ throw new Error(`semantic Chat target did not mount: ${selector}`)
109
+ }
110
+
111
+ function requiredEvent<T extends SessionEvent['type']>(
112
+ events: readonly SessionEvent[],
113
+ type: T,
114
+ marker: string,
115
+ ): Extract<SessionEvent, { type: T }> {
116
+ const event = events.find((candidate): candidate is Extract<SessionEvent, { type: T }> => (
117
+ candidate.type === type && carries(candidate, marker)
118
+ ))
119
+ if (event === undefined) throw new Error(`${type} carrying ${marker} is absent`)
120
+ return event
121
+ }
122
+
123
+ function messageKey(event: SessionEvent<'user/message'>): string {
124
+ return conversationContextKey('input-message', String(event.data.id))
125
+ }
126
+
127
+ function assistantKey(event: SessionEvent<'assistant/message'>): string {
128
+ return conversationContextKey('assistant-step', `${event.data.turn}:${event.data.step}`)
129
+ }
130
+
131
+ function turnTailKey(turn: number): string {
132
+ return conversationContextKey('turn-tail', String(turn))
133
+ }
134
+
135
+ describe('web e2e: long Chat interaction contract', () => {
136
+ let browser: Browser
137
+ let page: Page
138
+ let replayDir: string
139
+ let scaffold: WebScaffold
140
+ let tripwire: ReturnType<typeof watchConsole>
141
+
142
+ beforeAll(async () => {
143
+ replayDir = await mkdtemp(join(tmpdir(), 'dsh-chat-interaction-replay-'))
144
+ const replayOverride = join(replayDir, 'replay.override.json')
145
+ const replay: ReplayOverrideDoc = [replayEntry(continuationChunks())]
146
+ await writeFile(replayOverride, JSON.stringify(replay))
147
+ scaffold = await launchWebScaffold({
148
+ replayFixture: join(replayDir, 'override-only.jsonl'),
149
+ replayOverride,
150
+ replayContextWindow: 10_000_000,
151
+ paceMs: 18,
152
+ })
153
+ await seedSession(scaffold, FIXTURE.log, SESSION_ID)
154
+ browser = await chromium.launch()
155
+ page = await newEnglishPage(browser, 900)
156
+ tripwire = watchConsole(page)
157
+ await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
158
+ await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
159
+ await openSeed(page)
160
+ }, 120_000)
161
+
162
+ afterAll(async () => {
163
+ const failures: unknown[] = []
164
+ await browser?.close().catch((error: unknown) => failures.push(error))
165
+ await scaffold?.close().catch((error: unknown) => failures.push(error))
166
+ if (replayDir !== undefined) {
167
+ await rm(replayDir, { recursive: true, force: true })
168
+ .catch((error: unknown) => failures.push(error))
169
+ }
170
+ if (failures.length === 1) throw failures[0]
171
+ if (failures.length > 1) throw new AggregateError(failures, 'long Chat interaction cleanup failed')
172
+ })
173
+
174
+ it.skipIf(MODE === 'record')('keeps heterogeneous rows and their actions bound to exact semantic identities', async () => {
175
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-chat-long-interactions'))
176
+ await expect.poll(
177
+ () => scaffold.ctx.agents.get(SessionId(SESSION_ID)) !== undefined,
178
+ { timeout: 10_000 },
179
+ ).toBe(true)
180
+ const source = scaffold.ctx.agents.get(SessionId(SESSION_ID))
181
+ if (source === undefined) throw new Error('seeded long-history agent is not attached')
182
+
183
+ const toolUserMarker = FIXTURE.markers.user(TOOL_TURN)
184
+ const toolAssistantMarker = FIXTURE.markers.assistant(TOOL_TURN)
185
+ const toolMarker1 = FIXTURE.markers.tool(TOOL_TURN, 1)
186
+ const toolMarker2 = FIXTURE.markers.tool(TOOL_TURN, 2)
187
+ const toolUserEvent = requiredEvent(source.session.snapshotEvents(), 'user/message', toolUserMarker)
188
+ const toolAssistantEvent = requiredEvent(source.session.snapshotEvents(), 'assistant/message', toolAssistantMarker)
189
+ const branchUserMarker = FIXTURE.markers.user(BRANCH_TURN)
190
+ const branchAssistantMarker = FIXTURE.markers.assistant(BRANCH_TURN)
191
+ const branchUserEvent = requiredEvent(source.session.snapshotEvents(), 'user/message', branchUserMarker)
192
+ const branchAssistantEvent = requiredEvent(source.session.snapshotEvents(), 'assistant/message', branchAssistantMarker)
193
+ const boundary = source.session.snapshotEvents().find((event): event is SessionEvent<'turn/end'> => (
194
+ event.type === 'turn/end' && event.data.turn === BRANCH_TURN
195
+ ))
196
+ if (boundary === undefined) throw new Error(`turn ${String(BRANCH_TURN)} has no turn/end event`)
197
+ const expectedUserText = textContent(branchUserEvent.data.content)
198
+
199
+ const turnNavigation = page.getByRole('navigation', { name: 'Turn navigation' })
200
+ await turnNavigation.waitFor({ state: 'visible', timeout: 15_000 })
201
+ // The whole-log outline offers every fixture turn before any paging, with
202
+ // the live tail mark current.
203
+ const marks = turnNavigation.getByRole('button')
204
+ await expect.poll(() => marks.count(), { timeout: 15_000 }).toBe(FIXTURE_TURNS)
205
+ expect(await marks.last().getAttribute('aria-current')).toBe('true')
206
+ // The oldest turn is an unloaded mark whose outline preview already
207
+ // carries both the prompt and the settled response.
208
+ const firstTurnButton = turnNavigation
209
+ .getByRole('button', { name: 'Load and jump to turn 1', exact: true })
210
+ await firstTurnButton.focus()
211
+ const preview = page.getByRole('tooltip')
212
+ await preview.waitFor({ state: 'visible', timeout: 5_000 })
213
+ expect(await preview.textContent()).toContain(FIXTURE.markers.user(1))
214
+ expect(await preview.textContent()).toContain(FIXTURE.markers.assistant(1))
215
+ const firstTurnPosition = await firstTurnButton.evaluate(button => (
216
+ button.parentElement?.style.getPropertyValue('--turn-natural-position') ?? ''
217
+ ))
218
+ expect(firstTurnPosition).toBe('0px')
219
+
220
+ const loadEarlier = page.getByRole('button', { name: 'Load earlier', exact: true })
221
+ const loadedMarks = turnNavigation.getByRole('button', { name: /^Jump to turn / })
222
+ const loadedBefore = await loadedMarks.count()
223
+ await loadEarlier.click()
224
+ // Paging converts marks to their loaded form without moving the
225
+ // fixed-pitch ladder.
226
+ await expect.poll(() => loadedMarks.count(), { timeout: 15_000 }).toBeGreaterThan(loadedBefore)
227
+ expect(await firstTurnButton.evaluate(button => (
228
+ button.parentElement?.style.getPropertyValue('--turn-natural-position') ?? ''
229
+ ))).toBe(firstTurnPosition)
230
+ // Activating the still-unloaded oldest mark pages the rest in and lands
231
+ // on the turn's own row.
232
+ await firstTurnButton.focus()
233
+ await firstTurnButton.press('Enter')
234
+ const firstLoaded = turnNavigation.getByRole('button', { name: 'Jump to turn 1', exact: true })
235
+ await firstLoaded.waitFor({ timeout: 60_000 })
236
+ await expect.poll(() => firstLoaded.getAttribute('aria-current'), { timeout: 15_000 }).toBe('true')
237
+ await expect.poll(
238
+ () => page.locator('[data-chat-turn="1"][data-chat-flow-kind="user"]').count(),
239
+ { timeout: 5_000 },
240
+ ).toBe(1)
241
+
242
+ // Desktop-only affordance: a narrow Chat container hides the rail outright.
243
+ await page.setViewportSize({ width: 800, height: 900 })
244
+ await turnNavigation.waitFor({ state: 'hidden', timeout: 5_000 })
245
+ await page.setViewportSize({ width: 1_680, height: 900 })
246
+ await turnNavigation.waitFor({ state: 'visible', timeout: 5_000 })
247
+
248
+ await wheelUntilMounted(page, `[data-chat-call-id="${TARGET_CALL_2}"]`, -1_100)
249
+ const toolUserKey = messageKey(toolUserEvent)
250
+ const toolAssistantKey = assistantKey(toolAssistantEvent)
251
+ const toolUserRow = page.locator(`[data-chat-anchor-key="${toolUserKey}"]`)
252
+ const toolAssistantRow = page.locator(`[data-chat-anchor-key="${toolAssistantKey}"]`)
253
+ const call1 = page.locator(`[data-chat-call-id="${TARGET_CALL_1}"]`)
254
+ const call2 = page.locator(`[data-chat-call-id="${TARGET_CALL_2}"]`)
255
+
256
+ await expect.poll(() => toolUserRow.count(), { timeout: 10_000 }).toBe(1)
257
+ await expect.poll(() => toolAssistantRow.count(), { timeout: 10_000 }).toBe(1)
258
+ expect(await call1.count()).toBe(1)
259
+ expect(await call2.count()).toBe(1)
260
+ expect(await toolUserRow.getAttribute('data-chat-flow-kind')).toBe('user')
261
+ expect(await toolAssistantRow.getAttribute('data-chat-flow-kind')).toBe('assistant-step')
262
+ expect(await toolUserRow.textContent()).toContain(toolUserMarker)
263
+ expect(await toolAssistantRow.textContent()).toContain(toolAssistantMarker)
264
+ expect(await call1.textContent()).toContain(toolMarker1)
265
+ expect(await call2.textContent()).toContain(toolMarker2)
266
+
267
+ const expectedOrder = [
268
+ toolUserKey,
269
+ conversationContextKey('tool-call', TARGET_CALL_1),
270
+ conversationContextKey('tool-call', TARGET_CALL_2),
271
+ toolAssistantKey,
272
+ ]
273
+ const actualOrder = await page.locator('[data-chat-anchor-key]').evaluateAll((rows, keys) => (
274
+ rows.map(row => (row as HTMLElement).dataset.chatAnchorKey)
275
+ .filter((key): key is string => key !== undefined && keys.includes(key))
276
+ ), expectedOrder)
277
+ expect(actualOrder).toEqual(expectedOrder)
278
+ const toolKinds = await Promise.all([call1, call2].map(row => row.evaluate(element => (
279
+ element.closest<HTMLElement>('[data-chat-flow-kind]')?.dataset.chatFlowKind ?? null
280
+ ))))
281
+ expect(toolKinds).toEqual(['tool-call', 'tool-call'])
282
+
283
+ const summary1 = call1.locator('[data-sample="bash"]')
284
+ const summary2 = call2.locator('[data-sample="bash"]')
285
+ await expandOwningTurnProcess(page, call2)
286
+ expect(await summary1.getAttribute('aria-expanded')).toBe('false')
287
+ expect(await summary2.getAttribute('aria-expanded')).toBe('false')
288
+ await summary2.focus()
289
+ await summary2.press('Enter')
290
+ await expect.poll(() => summary2.getAttribute('aria-expanded'), { timeout: 10_000 }).toBe('true')
291
+ expect(await summary1.getAttribute('aria-expanded')).toBe('false')
292
+ await call2.getByText(`${toolMarker2} output line 12`, { exact: true }).waitFor({ timeout: 10_000 })
293
+
294
+ const branchUserKey = messageKey(branchUserEvent)
295
+ const branchAssistantKey = assistantKey(branchAssistantEvent)
296
+ await wheelUntilMounted(page, `[data-chat-anchor-key="${branchUserKey}"]`, -1_100)
297
+ const userRow = page.locator(`[data-chat-anchor-key="${branchUserKey}"]`)
298
+ const assistantRow = page.locator(`[data-chat-anchor-key="${branchAssistantKey}"]`)
299
+ const turnTailRow = page.locator(`[data-chat-anchor-key="${turnTailKey(BRANCH_TURN)}"]`)
300
+ expect(await userRow.textContent()).toContain(branchUserMarker)
301
+ expect(await assistantRow.textContent()).toContain(branchAssistantMarker)
302
+ await page.context().grantPermissions(['clipboard-read', 'clipboard-write'])
303
+ await userRow.hover()
304
+ await userRow.getByRole('button', { name: 'Copy', exact: true }).click()
305
+ await expect.poll(() => page.evaluate(() => navigator.clipboard.readText()), { timeout: 5_000 })
306
+ .toBe(expectedUserText)
307
+
308
+ await turnTailRow.hover()
309
+ await turnTailRow.getByRole('button', { name: 'Branch into a new conversation', exact: true }).click()
310
+ await expect.poll(
311
+ () => scaffold.ctx.agents.list().find(agent => agent.session.header.parentSession === SessionId(SESSION_ID)),
312
+ { timeout: 15_000 },
313
+ ).toBeDefined()
314
+ const child = scaffold.ctx.agents.list()
315
+ .find(agent => agent.session.header.parentSession === SessionId(SESSION_ID))
316
+ if (child === undefined) throw new Error('message branch did not create a child session')
317
+ expect(child.session.inheritedEventCount).toBe(boundary.seq + 1)
318
+ expect(child.session.snapshotEvents().some(event => carries(event, branchAssistantMarker))).toBe(true)
319
+ expect(child.session.snapshotEvents().some(event => carries(event, FIXTURE.markers.user(BRANCH_TURN + 1)))).toBe(false)
320
+ expect(child.session.snapshotEvents().some(event => carries(event, FIXTURE.markers.user(FIXTURE.turns)))).toBe(false)
321
+
322
+ const currentCrumb = page.getByRole('navigation', { name: 'Session hierarchy' })
323
+ .getByRole('button').last()
324
+ await expect.poll(() => currentCrumb.textContent(), { timeout: 15_000 })
325
+ .toBe(`${FIXTURE.title} (1)`)
326
+ await page.getByText(branchAssistantMarker, { exact: false }).last().waitFor({ timeout: 15_000 })
327
+ const settled = scaffold.whenTurnSettled(60_000)
328
+ const composer = page.locator('[data-composer-input][contenteditable="true"]').last()
329
+ await composer.fill(CONTINUE_PROMPT)
330
+ await page.getByRole('button', { name: 'Send message', exact: true }).click()
331
+ await expect.poll(() => page.getByText(CONTINUE_PROMPT, { exact: true }).count(), { timeout: 15_000 }).toBe(1)
332
+ expect(await settled).toBe(child.session.id)
333
+ await page.getByText(CONTINUE_DONE, { exact: false }).last().waitFor({ timeout: 15_000 })
334
+ await expect.poll(() => page.locator('[data-streaming="true"]').count(), { timeout: 15_000 }).toBe(0)
335
+ expect(await composer.textContent()).toBe('')
336
+ expect(await composer.isEnabled()).toBe(true)
337
+ expect(source.session.snapshotEvents().some(event => carries(event, CONTINUE_PROMPT))).toBe(false)
338
+ expect(child.session.snapshotEvents().filter(event => (
339
+ event.type === 'user/message' && carries(event, CONTINUE_PROMPT)
340
+ ))).toHaveLength(1)
341
+ const lastTurnEnd = child.session.snapshotEvents().findLast((event): event is SessionEvent<'turn/end'> => (
342
+ event.type === 'turn/end'
343
+ ))
344
+ expect(lastTurnEnd?.data.reason).toEqual({ kind: 'completed' })
345
+ expect(tripwire.pageErrors).toEqual([])
346
+ expect(tripwire.warnings).toEqual([])
347
+ }, 180_000)
348
+ })
apps/web/tests/command-image-envelope.expected.e2e.ts ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @vitest-environment jsdom
2
+ // The command attachment envelope over the BUILT client graph (real
3
+ // bundles via AppWebEntry, keyless RemoteMock transport): an enter
4
+ // submission carrying composer attachments resolves only through a command whose
5
+ // descriptor declares `input.attachments`. A non-declaring command refuses with
6
+ // one composer error banner and everything retained; a declaring command
7
+ // consumes the images — serialized through the real draft-image chain into
8
+ // the commands/execute payload — and clears the composer on success, including
9
+ // when the image is the whole `/plan` task.
10
+ import { fireEvent, screen, waitFor } from '@testing-library/react'
11
+ import { expect, it } from 'vitest'
12
+ import { installAssembledBootEnv, mountAssembledApp } from './assembled-boot.ts'
13
+
14
+ installAssembledBootEnv()
15
+
16
+ /** Open a fresh fixture session and return its composer surface. */
17
+ async function freshComposer(): Promise<HTMLElement> {
18
+ const tree = await screen.findByRole('tree', { name: 'Sessions' }, { timeout: 10_000 })
19
+ const start = tree.querySelector<HTMLButtonElement>('button[aria-label="New session in fixture"]')
20
+ if (start === null) throw new Error('fixture Workspace new-session action missing')
21
+ fireEvent.click(start)
22
+ return await waitFor(() => {
23
+ const surface = document.querySelector<HTMLElement>(
24
+ '[data-composer-input][data-placeholder="Describe what you want to build, / commands, @ files or sessions"]',
25
+ )
26
+ if (surface === null) throw new Error('composer surface missing')
27
+ return surface
28
+ }, { timeout: 10_000 })
29
+ }
30
+
31
+ /** Type through the clipboard: jsdom carries no editable beforeinput; the
32
+ * paste command inserts at the caret, committing a microtask later. */
33
+ async function pasteText(surface: HTMLElement, text: string): Promise<void> {
34
+ fireEvent.paste(surface, {
35
+ clipboardData: { items: [], getData: () => text },
36
+ })
37
+ await waitFor(() => { expect(surface.textContent).toContain(text) })
38
+ }
39
+
40
+ /** Paste one tiny PNG into the composer and wait for its rail thumbnail. */
41
+ async function pasteImage(textarea: HTMLElement, name: string): Promise<void> {
42
+ const image = new File([new Uint8Array([137, 80, 78, 71])], name, { type: 'image/png' })
43
+ fireEvent.paste(textarea, {
44
+ clipboardData: {
45
+ items: [{ kind: 'file', type: 'image/png', getAsFile: () => image }],
46
+ getData: () => '',
47
+ },
48
+ })
49
+ await waitFor(() => {
50
+ const rail = document.querySelector('[role="group"][aria-label="Pending attachments"]')
51
+ if (rail === null) throw new Error('attachment rail missing')
52
+ expect([...rail.querySelectorAll('img')].map(img => img.getAttribute('alt'))).toContain(name)
53
+ }, { timeout: 5_000 })
54
+ }
55
+
56
+ it('refuses an image-carrying submit to a non-declaring command and keeps draft and images', async () => {
57
+ mountAssembledApp()
58
+ const textarea = await freshComposer()
59
+ await pasteImage(textarea, 'ref.png')
60
+
61
+ // /echo is a leadingInput fixture command without `input.attachments`.
62
+ await pasteText(textarea, '/echo hello')
63
+ fireEvent.keyDown(textarea, { key: 'Enter' })
64
+
65
+ // The refusal rides the same transient error banner as other composer
66
+ // failures; session activity remains on its separate status live region.
67
+ const notice = await waitFor(() => {
68
+ const el = [...document.querySelectorAll('[role="alert"]')]
69
+ .find(candidate => candidate.textContent?.includes('attachments') ?? false)
70
+ if (el === undefined) throw new Error('composer refusal banner missing')
71
+ return el
72
+ }, { timeout: 5_000 })
73
+ expect(notice.textContent).toBe('/echo does not accept attachments; remove them first')
74
+ expect([...document.querySelectorAll('[role="status"]')]
75
+ .some(candidate => candidate.textContent?.includes('attachments') ?? false)).toBe(false)
76
+ // The whole envelope is retained: draft text and the rail thumbnail.
77
+ await waitFor(() => { expect(textarea.textContent).toBe('/echo hello') })
78
+ const rail = document.querySelector('[role="group"][aria-label="Pending attachments"]')
79
+ expect([...(rail?.querySelectorAll('img') ?? [])].map(img => img.getAttribute('alt'))).toEqual(['ref.png'])
80
+ })
81
+
82
+ it('consumes images through a declaring command and clears the composer on success', async () => {
83
+ mountAssembledApp()
84
+ const textarea = await freshComposer()
85
+ await pasteImage(textarea, 'goal-ref.png')
86
+
87
+ // /goal declares `input.attachments` in the fixture catalog; the claim submit
88
+ // serializes the pasted bytes and the fixture executor admits them.
89
+ await pasteText(textarea, '/goal rebuild the cathedral')
90
+ fireEvent.keyDown(textarea, { key: 'Enter' })
91
+
92
+ await waitFor(() => {
93
+ expect(textarea.textContent).toBe('')
94
+ expect(document.querySelector('[role="group"][aria-label="Pending attachments"]')).toBeNull()
95
+ }, { timeout: 5_000 })
96
+ })
97
+
98
+ it('submits a bare /plan with an image as an image-only plan request', async () => {
99
+ mountAssembledApp()
100
+ const textarea = await freshComposer()
101
+ await pasteImage(textarea, 'plan-task.png')
102
+
103
+ // Trailing separator: a bare '/plan' leaves the caret on the token, where
104
+ // the re-track opens the menu and Enter would pick instead of submit.
105
+ await pasteText(textarea, '/plan ')
106
+ fireEvent.keyDown(textarea, { key: 'Enter' })
107
+
108
+ await waitFor(() => {
109
+ expect(textarea.textContent).toBe('')
110
+ expect(document.querySelector('[role="group"][aria-label="Pending attachments"]')).toBeNull()
111
+ }, { timeout: 5_000 })
112
+ expect([...document.querySelectorAll('[role="alert"]')]
113
+ .some(candidate => candidate.textContent?.includes('/plan') ?? false)).toBe(false)
114
+ })
apps/web/tests/complex-history.perf.ts ADDED
@@ -0,0 +1,1457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Opt-in browser benchmark for high-cardinality workspace and history
2
+ // rendering. It reports measurements without timing assertions because host
3
+ // speed is not a correctness contract; structural assertions keep the number
4
+ // of workspaces and history entries from silently shrinking.
5
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises'
6
+ import { tmpdir } from 'node:os'
7
+ import { join } from 'node:path'
8
+ import { performance } from 'node:perf_hooks'
9
+ import type { Browser, CDPSession, Locator, Page } from 'playwright'
10
+ import { chromium } from 'playwright'
11
+ import { afterAll, beforeAll, describe, expect, it } from 'vitest'
12
+ import type { StreamChunk } from '@deepseek-ai/dsh-llm'
13
+ import {
14
+ ToolCallId,
15
+ createAssistantMessage,
16
+ createSystemMessage,
17
+ createToolResultMessage,
18
+ createUserMessage,
19
+ expandAssistantStream,
20
+ } from '@deepseek-ai/dsh-llm'
21
+ import type { ReplayEntry, ReplayOverrideDoc } from '@deepseek-ai/dsh-llm-replay'
22
+ import type { SessionEvent, SessionSeq } from '@deepseek-ai/dsh-session'
23
+ import {
24
+ SESSION_FORMAT_VERSION,
25
+ Session,
26
+ SessionId,
27
+ } from '@deepseek-ai/dsh-session'
28
+ // Carries the session/title event declaration into the fixture builder.
29
+ import type {} from '@deepseek-ai/dsh-session-title'
30
+ import {
31
+ launchWebScaffold,
32
+ seedSession,
33
+ watchConsole,
34
+ webSnapshotMode,
35
+ type WebScaffold,
36
+ } from './scaffold.ts'
37
+ import { connectFreshWorkspace, newEnglishPage } from './support.ts'
38
+
39
+ const SIDEBAR_SESSION_COUNT = 1_000
40
+ const LONG_SESSION_ID = 'perf-long-history'
41
+ const LONG_SESSION_TITLE = 'LONG_PERF_SENTINEL 500-turn session'
42
+ const LONG_HISTORY_TURNS = 500
43
+ const TOOL_TURN_INTERVAL = 10
44
+ const TOOLS_PER_TOOL_TURN = 10
45
+ const EXPECTED_TOOL_CALLS = LONG_HISTORY_TURNS / TOOL_TURN_INTERVAL * TOOLS_PER_TOOL_TURN
46
+ const EXPECTED_TRAJECTORY_ROWS = 2_100
47
+ const DEFAULT_HISTORY_TURNS = 24
48
+ const PERF_REPLAY_CONTEXT_WINDOW = 10_000_000
49
+ const STREAM_PACE_MS = 8
50
+ const STREAM_DELTA_COUNT = 120
51
+ const COMPARISON_TURNS = 8
52
+ const COMPARISON_DELTA_COUNT = 24
53
+ const COMPARISON_TOOL_INTERVAL = 3
54
+ const SOAK_TURNS = 100
55
+ const POST_SOAK_RENDER_TURN = SOAK_TURNS + 1
56
+ const SOAK_DELTA_COUNT = 8
57
+ const SOAK_TOOL_INTERVAL = 10
58
+ const SOAK_CHECKPOINT_INTERVAL = 10
59
+ const LONG_CONTINUATION_USER_PREFIX = 'LONG_CONTINUATION_USER'
60
+ const LONG_CONTINUATION_FIRST_PREFIX = 'LONG_CONTINUATION_FIRST'
61
+ const LONG_CONTINUATION_DONE_PREFIX = 'LONG_CONTINUATION_DONE'
62
+ const SOAK_USER_PREFIX = 'SOAK_CONVERSATION_USER'
63
+ const SOAK_FIRST_PREFIX = 'SOAK_CONVERSATION_FIRST'
64
+ const SOAK_DONE_PREFIX = 'SOAK_CONVERSATION_DONE'
65
+ const LIVE_PROMPT_MARKER = 'STREAM_PERF_USER_INPUT'
66
+ const STREAM_FIRST_MARKER = 'STREAM_PERF_FIRST'
67
+ const STREAM_DONE_MARKER = 'STREAM_PERF_DONE'
68
+ const LIVE_PROMPT = [
69
+ LIVE_PROMPT_MARKER,
70
+ 'Analyze the following mixed-language project context and return a concise diagnostic.',
71
+ ...Array.from(
72
+ { length: 48 },
73
+ (_, index) =>
74
+ `Context ${String(index + 1).padStart(2, '0')}: 用户正在检查长会话中的增量渲染性能。`
75
+ + ` Preserve item ${String(index)} and compare ${'payload'.repeat(8)}.`,
76
+ ),
77
+ '```ts',
78
+ ...Array.from(
79
+ { length: 40 },
80
+ (_, index) => `const sample_${String(index)} = ${JSON.stringify(`value-${String(index)}-${'x'.repeat(32)}`)}`,
81
+ ),
82
+ '```',
83
+ ].join('\n')
84
+ const STREAM_DELTAS = Array.from({ length: STREAM_DELTA_COUNT }, (_, index) => {
85
+ if (index === 0) return `${STREAM_FIRST_MARKER} `
86
+ if (index === STREAM_DELTA_COUNT - 1) return `${STREAM_DONE_MARKER}.`
87
+ return `chunk-${String(index).padStart(3, '0')} ${'response'.repeat(3)} `
88
+ })
89
+
90
+ interface ChromiumMetrics {
91
+ readonly [name: string]: number
92
+ }
93
+
94
+ interface Measurement {
95
+ readonly wallMs: number
96
+ readonly taskMs: number
97
+ readonly scriptMs: number
98
+ readonly layoutMs: number
99
+ readonly recalcStyleMs: number
100
+ readonly devtoolsMs: number
101
+ readonly nodesDelta: number
102
+ readonly listenersDelta: number
103
+ readonly heapDeltaMb: number
104
+ readonly totalNodes: number
105
+ readonly heapMb: number
106
+ }
107
+
108
+ interface MutationProbeResult {
109
+ readonly batches: number
110
+ readonly records: number
111
+ }
112
+
113
+ interface UserRenderProbeResult {
114
+ readonly trustedClick: boolean
115
+ readonly sendToDomMs: number
116
+ readonly sendToPaintMs: number
117
+ readonly domToPaintMs: number
118
+ readonly mutationBatches: number
119
+ readonly mutationRecords: number
120
+ }
121
+
122
+ interface RetainedBrowserState {
123
+ readonly domElements: number
124
+ readonly nodes: number
125
+ readonly listeners: number
126
+ readonly heapMb: number
127
+ }
128
+
129
+ interface ContinuedTurnReport {
130
+ readonly ordinal: number
131
+ readonly resultingTurns: number
132
+ readonly kind: 'text' | 'tool'
133
+ readonly promptChars: number
134
+ readonly composerFill: Measurement
135
+ readonly stream: MutationProbeResult & Measurement & {
136
+ readonly paceMs: number
137
+ readonly deltaChunks: number
138
+ readonly persistedChunks: number
139
+ readonly toolCalls: number
140
+ readonly toolResults: number
141
+ readonly clickToUserEchoMs: number
142
+ readonly clickToFirstChunkMs: number
143
+ readonly firstChunkToSettledMs: number
144
+ }
145
+ }
146
+
147
+ interface ConversationTurnSpec {
148
+ readonly prompt: string
149
+ readonly deltas: readonly string[]
150
+ readonly userMarker: string
151
+ readonly firstMarker: string
152
+ readonly doneMarker: string
153
+ readonly toolResultMarker?: string
154
+ }
155
+
156
+ interface RetainedCheckpoint {
157
+ readonly turns: number
158
+ readonly state: RetainedBrowserState
159
+ }
160
+
161
+ interface ConversationReport {
162
+ readonly startingTurns: number
163
+ readonly turnsAdded: number
164
+ readonly toolTurns: number
165
+ readonly retainedBefore: RetainedBrowserState
166
+ readonly retainedAfter: RetainedBrowserState
167
+ readonly retainedDelta: RetainedBrowserState
168
+ readonly checkpoints: readonly RetainedCheckpoint[]
169
+ readonly turns: readonly ContinuedTurnReport[]
170
+ }
171
+
172
+ interface PerformanceWorld {
173
+ readonly scaffold: WebScaffold
174
+ readonly page: Page
175
+ readonly tripwire: ReturnType<typeof watchConsole>
176
+ readonly sessionEvents: SessionEvent[]
177
+ readonly setupMs: number
178
+ readonly replayDir?: string
179
+ }
180
+
181
+ interface PerformanceWorldOptions {
182
+ readonly browser: Browser
183
+ readonly replay?: ReplayOverrideDoc
184
+ readonly sidebarSessions?: number
185
+ readonly seedLongHistory?: boolean
186
+ }
187
+
188
+ function text(value: string): { type: 'text'; text: string }[] {
189
+ return [{ type: 'text', text: value }]
190
+ }
191
+
192
+ function appendTitle(session: Session, title: string, messageSeq: SessionSeq): void {
193
+ session.append('session/title', {
194
+ title,
195
+ messageSeqs: [messageSeq],
196
+ source: { kind: 'fallback' },
197
+ })
198
+ }
199
+
200
+ function appendSystemPrompt(session: Session, turn: number, step: number): void {
201
+ session.append('system/message', {
202
+ turn,
203
+ step,
204
+ message: createSystemMessage(
205
+ 'Synthetic performance system prompt.',
206
+ '@deepseek-ai/dsh-system-prompt',
207
+ ),
208
+ }, { surfaceOp: 'append' })
209
+ }
210
+
211
+ function appendRequestHeader(session: Session, turn: number, step: number): void {
212
+ session.append('request/header', {
213
+ header: {
214
+ config: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
215
+ },
216
+ reason: turn === 1 && step === 1 ? 'initial' : 'change',
217
+ })
218
+ }
219
+
220
+ function appendAssistant(
221
+ session: Session,
222
+ turn: number,
223
+ step: number,
224
+ body: string,
225
+ ): void {
226
+ session.append('assistant/message', {
227
+ stream: [],
228
+ turn,
229
+ step,
230
+ message: createAssistantMessage({
231
+ content: text(body),
232
+ source: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
233
+ }),
234
+ usage: {
235
+ inputTokens: 4_000 + turn * 10,
236
+ outputTokens: 200 + step * 20,
237
+ cacheReadTokens: turn % 2 === 0 ? 2_000 : 0,
238
+ },
239
+ }, { surfaceOp: 'append' })
240
+ }
241
+
242
+ function appendToolStep(
243
+ session: Session,
244
+ turn: number,
245
+ step: number,
246
+ toolCount: number,
247
+ ): void {
248
+ const calls = Array.from({ length: toolCount }, (_, index) => {
249
+ const callId = ToolCallId(`perf-call-${String(turn)}-${String(index)}`)
250
+ const args = JSON.stringify({
251
+ turn,
252
+ index,
253
+ payload: 'x'.repeat(120),
254
+ })
255
+ return { callId, index, args }
256
+ })
257
+
258
+ session.append('assistant/message', {
259
+ stream: [],
260
+ turn,
261
+ step,
262
+ message: createAssistantMessage({
263
+ content: [
264
+ {
265
+ type: 'reasoning',
266
+ text: `Dispatching ${String(toolCount)} synthetic tools for turn ${String(turn)}.`,
267
+ },
268
+ ...calls.map(({ callId, args }) => ({
269
+ type: 'tool-call' as const,
270
+ id: callId,
271
+ name: 'synthetic_tool',
272
+ arguments: args,
273
+ })),
274
+ ],
275
+ source: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
276
+ }),
277
+ usage: {
278
+ inputTokens: 6_000 + turn * 10,
279
+ outputTokens: 500,
280
+ cacheReadTokens: 3_000,
281
+ reasoningTokens: 50,
282
+ },
283
+ }, { surfaceOp: 'append' })
284
+
285
+ const callEvents = calls.map(({ callId, args }) =>
286
+ session.append('tool/call', {
287
+ turn,
288
+ step,
289
+ callId,
290
+ name: 'synthetic_tool',
291
+ arguments: args,
292
+ }))
293
+
294
+ for (const [index, call] of calls.entries()) {
295
+ const source = callEvents[index]
296
+ if (source === undefined) throw new Error(`missing synthetic tool call ${String(index)}`)
297
+ session.append('tool/result', {
298
+ turn,
299
+ step,
300
+ message: createToolResultMessage({
301
+ callId: call.callId,
302
+ content: text(
303
+ `synthetic result turn=${String(turn)} index=${String(call.index)} ${'r'.repeat(400)}`,
304
+ ),
305
+ isError: false,
306
+ }),
307
+ }, { surfaceOp: 'append', sourceEventSeqs: [source.seq] })
308
+ }
309
+ }
310
+
311
+ function fencedCode(turn: number): string {
312
+ if (turn % 25 !== 0) return ''
313
+ const lines = Array.from(
314
+ { length: 80 },
315
+ (_, index) => `const value_${String(index)} = ${String(turn + index)}`,
316
+ )
317
+ return `\n\n\`\`\`ts\n${lines.join('\n')}\n\`\`\``
318
+ }
319
+
320
+ function fixtureLog(session: Session): string {
321
+ const header = {
322
+ type: 'session',
323
+ version: SESSION_FORMAT_VERSION,
324
+ id: '{{sessionId}}',
325
+ createdAt: Date.now() - 60_000,
326
+ cwd: '{{cwd}}',
327
+ isSeeded: false,
328
+ delegationDepth: 0,
329
+ }
330
+ return [
331
+ JSON.stringify(header),
332
+ ...session.snapshotEvents().map(event => JSON.stringify(event)),
333
+ '',
334
+ ].join('\n')
335
+ }
336
+
337
+ function smallSidebarFixture(): string {
338
+ const session = Session.create(SessionId('perf-small-template'))
339
+ session.append('turn/start', {
340
+ turn: 1,
341
+ })
342
+ const user = session.append('user/message', createUserMessage({
343
+ content: text('Inspect this compact synthetic session.'),
344
+ source: { kind: 'user' },
345
+ }), { surfaceOp: 'append' })
346
+ appendTitle(session, 'Synthetic sidebar session', user.seq)
347
+ session.append('step/start', { turn: 1, step: 1 })
348
+ appendSystemPrompt(session, 1, 1)
349
+ appendRequestHeader(session, 1, 1)
350
+ appendToolStep(session, 1, 1, 2)
351
+ session.append('step/end', { turn: 1, step: 1 })
352
+ session.append('step/start', { turn: 1, step: 2 })
353
+ appendRequestHeader(session, 1, 2)
354
+ appendAssistant(session, 1, 2, 'Synthetic sidebar fixture complete.')
355
+ session.append('step/end', { turn: 1, step: 2 })
356
+ session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
357
+ return fixtureLog(session)
358
+ }
359
+
360
+ function longHistoryFixture(): string {
361
+ const session = Session.create(SessionId(LONG_SESSION_ID))
362
+ for (let turn = 1; turn <= LONG_HISTORY_TURNS; turn += 1) {
363
+ session.append('turn/start', {
364
+ turn,
365
+ })
366
+ const user = session.append('user/message', createUserMessage({
367
+ content: text(
368
+ `LONG_PERF_SENTINEL turn ${String(turn)}: analyze payload ${'u'.repeat(200)}`,
369
+ ),
370
+ source: { kind: 'user' },
371
+ }), { surfaceOp: 'append' })
372
+ if (turn === 1) appendTitle(session, LONG_SESSION_TITLE, user.seq)
373
+
374
+ session.append('step/start', { turn, step: 1 })
375
+ if (turn === 1) appendSystemPrompt(session, turn, 1)
376
+ appendRequestHeader(session, turn, 1)
377
+ if (turn % TOOL_TURN_INTERVAL === 0) {
378
+ appendToolStep(session, turn, 1, TOOLS_PER_TOOL_TURN)
379
+ session.append('step/end', { turn, step: 1 })
380
+ session.append('step/start', { turn, step: 2 })
381
+ appendRequestHeader(session, turn, 2)
382
+ appendAssistant(
383
+ session,
384
+ turn,
385
+ 2,
386
+ `All synthetic tools completed for turn ${String(turn)}. ${'z'.repeat(320)}${fencedCode(turn)}`,
387
+ )
388
+ session.append('step/end', { turn, step: 2 })
389
+ } else {
390
+ appendAssistant(
391
+ session,
392
+ turn,
393
+ 1,
394
+ `Synthetic assistant response for turn ${String(turn)}. ${'a'.repeat(320)}${fencedCode(turn)}`,
395
+ )
396
+ session.append('step/end', { turn, step: 1 })
397
+ }
398
+ session.append('turn/end', { turn, reason: { kind: 'completed' } })
399
+ }
400
+ return fixtureLog(session)
401
+ }
402
+
403
+ function textStream(deltas: readonly string[], inputTokens: number): StreamChunk[] {
404
+ const response = deltas.join('')
405
+ return [
406
+ { type: 'block-start', index: 0, blockType: 'text' },
407
+ ...deltas.map(text => ({
408
+ type: 'text-delta' as const,
409
+ index: 0,
410
+ text,
411
+ })),
412
+ {
413
+ type: 'block-end',
414
+ index: 0,
415
+ block: { type: 'text', text: response },
416
+ },
417
+ {
418
+ type: 'usage',
419
+ usage: {
420
+ inputTokens,
421
+ outputTokens: Math.ceil(response.length / 4),
422
+ },
423
+ },
424
+ { type: 'finish', reason: { kind: 'stop' } },
425
+ ]
426
+ }
427
+
428
+ function comparisonPrompt(index: number): string {
429
+ if (index === COMPARISON_TURNS) return LIVE_PROMPT
430
+ return (`${LONG_CONTINUATION_USER_PREFIX}_${String(index)} `
431
+ + `继续分析这个长会话的第 ${String(index)} 个增量问题,并保留当前滚动和输入响应。 `
432
+ + 'context '.repeat(80)).trimEnd()
433
+ }
434
+
435
+ function comparisonDeltas(index: number): string[] {
436
+ if (index === COMPARISON_TURNS) return STREAM_DELTAS
437
+ return Array.from({ length: COMPARISON_DELTA_COUNT }, (_, chunkIndex) => {
438
+ if (chunkIndex === 0) return `${LONG_CONTINUATION_FIRST_PREFIX}_${String(index)} `
439
+ if (chunkIndex === COMPARISON_DELTA_COUNT - 1) {
440
+ return `${LONG_CONTINUATION_DONE_PREFIX}_${String(index)}.`
441
+ }
442
+ return `turn-${String(index)}-chunk-${String(chunkIndex).padStart(2, '0')} ${'response'.repeat(2)} `
443
+ })
444
+ }
445
+
446
+ function comparisonTurn(index: number): ConversationTurnSpec {
447
+ const toolResultMarker = index % COMPARISON_TOOL_INTERVAL === 0
448
+ ? `LONG_CONTINUATION_TOOL_RESULT_${String(index)}`
449
+ : undefined
450
+ return {
451
+ prompt: comparisonPrompt(index),
452
+ deltas: comparisonDeltas(index),
453
+ userMarker: index === COMPARISON_TURNS
454
+ ? LIVE_PROMPT_MARKER
455
+ : `${LONG_CONTINUATION_USER_PREFIX}_${String(index)}`,
456
+ firstMarker: index === COMPARISON_TURNS
457
+ ? STREAM_FIRST_MARKER
458
+ : `${LONG_CONTINUATION_FIRST_PREFIX}_${String(index)}`,
459
+ doneMarker: index === COMPARISON_TURNS
460
+ ? STREAM_DONE_MARKER
461
+ : `${LONG_CONTINUATION_DONE_PREFIX}_${String(index)}`,
462
+ ...toolResultMarker === undefined ? {} : { toolResultMarker },
463
+ }
464
+ }
465
+
466
+ function soakTurn(index: number): ConversationTurnSpec {
467
+ const suffix = String(index).padStart(3, '0')
468
+ const toolResultMarker = index % SOAK_TOOL_INTERVAL === 0
469
+ ? `SOAK_CONVERSATION_TOOL_RESULT_${suffix}`
470
+ : undefined
471
+ return {
472
+ prompt: (`${SOAK_USER_PREFIX}_${suffix} `
473
+ + `持续对话第 ${String(index)} 轮,检查增量渲染与保留状态。 `
474
+ + 'context '.repeat(20)).trimEnd(),
475
+ deltas: Array.from({ length: SOAK_DELTA_COUNT }, (_, chunkIndex) => {
476
+ if (chunkIndex === 0) return `${SOAK_FIRST_PREFIX}_${suffix} `
477
+ if (chunkIndex === SOAK_DELTA_COUNT - 1) return `${SOAK_DONE_PREFIX}_${suffix}.`
478
+ return `soak-${suffix}-${String(chunkIndex).padStart(2, '0')} response `
479
+ }),
480
+ userMarker: `${SOAK_USER_PREFIX}_${suffix}`,
481
+ firstMarker: `${SOAK_FIRST_PREFIX}_${suffix}`,
482
+ doneMarker: `${SOAK_DONE_PREFIX}_${suffix}`,
483
+ ...toolResultMarker === undefined ? {} : { toolResultMarker },
484
+ }
485
+ }
486
+
487
+ function toolStream(index: number, marker: string): StreamChunk[] {
488
+ const callId = ToolCallId(`performance-tool-${marker.toLowerCase()}-${String(index)}`)
489
+ const args = JSON.stringify({
490
+ command: `printf '${marker}\\n'`,
491
+ description: `Emit performance marker ${String(index)}`,
492
+ })
493
+ return [
494
+ { type: 'block-start', index: 0, blockType: 'tool-call' },
495
+ {
496
+ type: 'tool-call-delta',
497
+ index: 0,
498
+ id: callId,
499
+ name: 'bash',
500
+ argumentsDelta: args,
501
+ },
502
+ {
503
+ type: 'block-end',
504
+ index: 0,
505
+ block: { type: 'tool-call', id: callId, name: 'bash', arguments: args },
506
+ },
507
+ { type: 'usage', usage: { inputTokens: 256, outputTokens: 32 } },
508
+ { type: 'finish', reason: { kind: 'tool-calls' } },
509
+ ]
510
+ }
511
+
512
+ function performanceReplayOverride(
513
+ turnCount: number,
514
+ turnSpec: (index: number) => ConversationTurnSpec,
515
+ ): ReplayOverrideDoc {
516
+ const continuationEntries = Array.from(
517
+ { length: turnCount },
518
+ (_, offset): ReplayEntry[] => {
519
+ const index = offset + 1
520
+ const spec = turnSpec(index)
521
+ const finalResponse: ReplayEntry = {
522
+ kind: 'chunks',
523
+ chunks: textStream(spec.deltas, Math.ceil(spec.prompt.length / 4)),
524
+ }
525
+ return spec.toolResultMarker === undefined
526
+ ? [finalResponse]
527
+ : [{ kind: 'chunks', chunks: toolStream(index, spec.toolResultMarker) }, finalResponse]
528
+ },
529
+ ).flat()
530
+ return continuationEntries
531
+ }
532
+
533
+ function rounded(value: number): number {
534
+ return Math.round(value * 1_000) / 1_000
535
+ }
536
+
537
+ async function chromiumMetrics(cdp: CDPSession): Promise<ChromiumMetrics> {
538
+ const payload = await cdp.send('Performance.getMetrics')
539
+ return Object.fromEntries(payload.metrics.map(metric => [metric.name, metric.value]))
540
+ }
541
+
542
+ async function retainedBrowserState(
543
+ cdp: CDPSession,
544
+ page: Page,
545
+ ): Promise<RetainedBrowserState> {
546
+ await cdp.send('HeapProfiler.collectGarbage')
547
+ const metrics = await chromiumMetrics(cdp)
548
+ return {
549
+ domElements: await page.evaluate(() => document.querySelectorAll('*').length),
550
+ nodes: requiredMetric(metrics, 'Nodes'),
551
+ listeners: requiredMetric(metrics, 'JSEventListeners'),
552
+ heapMb: rounded(requiredMetric(metrics, 'JSHeapUsedSize') / 1_048_576),
553
+ }
554
+ }
555
+
556
+ function requiredMetric(metrics: ChromiumMetrics, name: string): number {
557
+ const value = metrics[name]
558
+ if (value === undefined) throw new Error(`Chromium performance metric ${name} is unavailable`)
559
+ return value
560
+ }
561
+
562
+ function metricDelta(
563
+ before: ChromiumMetrics,
564
+ after: ChromiumMetrics,
565
+ wallMs: number,
566
+ ): Measurement {
567
+ return {
568
+ wallMs: rounded(wallMs),
569
+ taskMs: rounded((requiredMetric(after, 'TaskDuration') - requiredMetric(before, 'TaskDuration')) * 1_000),
570
+ scriptMs: rounded((requiredMetric(after, 'ScriptDuration') - requiredMetric(before, 'ScriptDuration')) * 1_000),
571
+ layoutMs: rounded((requiredMetric(after, 'LayoutDuration') - requiredMetric(before, 'LayoutDuration')) * 1_000),
572
+ recalcStyleMs: rounded(
573
+ (requiredMetric(after, 'RecalcStyleDuration') - requiredMetric(before, 'RecalcStyleDuration')) * 1_000,
574
+ ),
575
+ devtoolsMs: rounded(
576
+ (requiredMetric(after, 'DevToolsCommandDuration') - requiredMetric(before, 'DevToolsCommandDuration')) * 1_000,
577
+ ),
578
+ nodesDelta: requiredMetric(after, 'Nodes') - requiredMetric(before, 'Nodes'),
579
+ listenersDelta: requiredMetric(after, 'JSEventListeners') - requiredMetric(before, 'JSEventListeners'),
580
+ heapDeltaMb: rounded(
581
+ (requiredMetric(after, 'JSHeapUsedSize') - requiredMetric(before, 'JSHeapUsedSize')) / 1_048_576,
582
+ ),
583
+ totalNodes: requiredMetric(after, 'Nodes'),
584
+ heapMb: rounded(requiredMetric(after, 'JSHeapUsedSize') / 1_048_576),
585
+ }
586
+ }
587
+
588
+ async function measure<T>(
589
+ cdp: CDPSession,
590
+ action: () => Promise<T>,
591
+ ): Promise<{ measurement: Measurement; value: T }> {
592
+ const before = await chromiumMetrics(cdp)
593
+ const started = performance.now()
594
+ const value = await action()
595
+ const wallMs = performance.now() - started
596
+ const after = await chromiumMetrics(cdp)
597
+ return { measurement: metricDelta(before, after, wallMs), value }
598
+ }
599
+
600
+ async function startMutationProbe(page: Page): Promise<void> {
601
+ await page.evaluate(() => {
602
+ const target = document.querySelector('[class*="centerCol"]')
603
+ if (target === null) throw new Error('stream mutation probe target is unavailable')
604
+ const probe = {
605
+ batches: 0,
606
+ records: 0,
607
+ observer: undefined as MutationObserver | undefined,
608
+ }
609
+ const observer = new MutationObserver((records) => {
610
+ probe.batches += 1
611
+ probe.records += records.length
612
+ })
613
+ probe.observer = observer
614
+ observer.observe(target, {
615
+ attributes: true,
616
+ attributeFilter: ['data-streaming'],
617
+ characterData: true,
618
+ childList: true,
619
+ subtree: true,
620
+ })
621
+ Reflect.set(globalThis, '__dshPerfMutationProbe', probe)
622
+ })
623
+ }
624
+
625
+ async function stopMutationProbe(page: Page): Promise<MutationProbeResult> {
626
+ return page.evaluate(() => {
627
+ const probe = Reflect.get(globalThis, '__dshPerfMutationProbe') as
628
+ | { batches: number; records: number; observer: MutationObserver }
629
+ | undefined
630
+ if (probe === undefined) throw new Error('stream mutation probe was not started')
631
+ probe.observer.disconnect()
632
+ Reflect.deleteProperty(globalThis, '__dshPerfMutationProbe')
633
+ return { batches: probe.batches, records: probe.records }
634
+ })
635
+ }
636
+
637
+ async function startUserRenderProbe(
638
+ page: Page,
639
+ marker: string,
640
+ ): Promise<void> {
641
+ const send = page.getByRole('button', { name: 'Send message', exact: true })
642
+ await send.waitFor({ timeout: 15_000 })
643
+ await expect.poll(() => send.isEnabled(), { timeout: 15_000 }).toBe(true)
644
+ await page.evaluate((expectedMarker) => {
645
+ const target = document.querySelector('[data-conversation-scroll]')
646
+ if (target === null) throw new Error('user render probe target is unavailable')
647
+ const probe: {
648
+ sendAt?: number
649
+ domAt?: number
650
+ paintAt?: number
651
+ trustedClick?: boolean
652
+ batches: number
653
+ records: number
654
+ observer?: MutationObserver
655
+ pollForMarker?: () => void
656
+ } = { batches: 0, records: 0 }
657
+ const transcriptContainsMarker = (): boolean => {
658
+ // The composer projects the draft into a backdrop and hidden sizing
659
+ // mirror; only a matching text node outside that card proves delivery.
660
+ const walker = document.createTreeWalker(target, NodeFilter.SHOW_TEXT)
661
+ for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {
662
+ if (!node.textContent?.includes(expectedMarker)) continue
663
+ const parent = node.parentElement
664
+ if (parent !== null && parent.closest('[data-composer-card]') === null) return true
665
+ }
666
+ return false
667
+ }
668
+ const markDomVisible = (): void => {
669
+ if (
670
+ probe.sendAt === undefined
671
+ || probe.domAt !== undefined
672
+ || !transcriptContainsMarker()
673
+ ) return
674
+ probe.domAt = globalThis.performance.now()
675
+ // The second callback runs only after a render opportunity for the DOM
676
+ // insertion observed before the first callback.
677
+ requestAnimationFrame(() => {
678
+ requestAnimationFrame(() => {
679
+ probe.paintAt = globalThis.performance.now()
680
+ observer.disconnect()
681
+ })
682
+ })
683
+ }
684
+ const pollForMarker = (): void => {
685
+ markDomVisible()
686
+ if (probe.domAt === undefined) requestAnimationFrame(pollForMarker)
687
+ }
688
+ const observer = new MutationObserver((records) => {
689
+ if (probe.sendAt === undefined) return
690
+ probe.batches += 1
691
+ probe.records += records.length
692
+ markDomVisible()
693
+ })
694
+ probe.observer = observer
695
+ probe.pollForMarker = pollForMarker
696
+ observer.observe(target, {
697
+ attributes: true,
698
+ attributeFilter: ['data-streaming'],
699
+ characterData: true,
700
+ childList: true,
701
+ subtree: true,
702
+ })
703
+ Reflect.set(globalThis, '__dshPerfUserRenderProbe', probe)
704
+ }, marker)
705
+ await send.evaluate((button) => {
706
+ button.addEventListener('click', (event) => {
707
+ const probe = Reflect.get(globalThis, '__dshPerfUserRenderProbe') as
708
+ | { sendAt?: number; trustedClick?: boolean; pollForMarker?: () => void }
709
+ | undefined
710
+ if (probe?.pollForMarker === undefined) throw new Error('user render probe was not started')
711
+ probe.trustedClick = event.isTrusted
712
+ probe.sendAt = globalThis.performance.now()
713
+ requestAnimationFrame(probe.pollForMarker)
714
+ }, { capture: true, once: true })
715
+ })
716
+ }
717
+
718
+ async function triggerUserRenderProbe(page: Page): Promise<void> {
719
+ const send = page.getByRole('button', { name: 'Send message', exact: true })
720
+ await send.click()
721
+ }
722
+
723
+ async function stopUserRenderProbe(
724
+ page: Page,
725
+ marker: string,
726
+ ): Promise<UserRenderProbeResult> {
727
+ try {
728
+ await page.waitForFunction(() => {
729
+ const probe = Reflect.get(globalThis, '__dshPerfUserRenderProbe') as
730
+ | { paintAt?: number }
731
+ | undefined
732
+ return probe?.paintAt !== undefined
733
+ }, undefined, { timeout: 15_000 })
734
+ } catch (error) {
735
+ const diagnostic = await page.evaluate((expectedMarker) => {
736
+ const probe = Reflect.get(globalThis, '__dshPerfUserRenderProbe') as
737
+ | {
738
+ sendAt?: number
739
+ domAt?: number
740
+ paintAt?: number
741
+ trustedClick?: boolean
742
+ batches: number
743
+ records: number
744
+ }
745
+ | undefined
746
+ const target = document.querySelector('[data-conversation-scroll]')
747
+ let markerOutsideComposer = false
748
+ if (target !== null) {
749
+ const walker = document.createTreeWalker(target, NodeFilter.SHOW_TEXT)
750
+ for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {
751
+ if (!node.textContent?.includes(expectedMarker)) continue
752
+ const parent = node.parentElement
753
+ if (parent !== null && parent.closest('[data-composer-card]') === null) {
754
+ markerOutsideComposer = true
755
+ break
756
+ }
757
+ }
758
+ }
759
+ return {
760
+ probe,
761
+ markerOutsideComposer,
762
+ markerInComposer: document.querySelector('[data-composer-card]')
763
+ ?.textContent?.includes(expectedMarker) ?? false,
764
+ }
765
+ }, marker)
766
+ throw new Error(`user render probe timed out: ${JSON.stringify(diagnostic)}`, { cause: error })
767
+ }
768
+ return page.evaluate(() => {
769
+ const probe = Reflect.get(globalThis, '__dshPerfUserRenderProbe') as
770
+ | {
771
+ sendAt?: number
772
+ domAt?: number
773
+ paintAt?: number
774
+ trustedClick?: boolean
775
+ batches: number
776
+ records: number
777
+ }
778
+ | undefined
779
+ Reflect.deleteProperty(globalThis, '__dshPerfUserRenderProbe')
780
+ if (
781
+ probe?.trustedClick !== true
782
+ || probe.sendAt === undefined
783
+ || probe.domAt === undefined
784
+ || probe.paintAt === undefined
785
+ ) {
786
+ throw new Error('user render probe did not observe a trusted click, DOM insertion, and paint')
787
+ }
788
+ return {
789
+ trustedClick: probe.trustedClick,
790
+ sendToDomMs: probe.domAt - probe.sendAt,
791
+ sendToPaintMs: probe.paintAt - probe.sendAt,
792
+ domToPaintMs: probe.paintAt - probe.domAt,
793
+ mutationBatches: probe.batches,
794
+ mutationRecords: probe.records,
795
+ }
796
+ })
797
+ }
798
+
799
+ async function stableCount(
800
+ locator: Locator,
801
+ accepts: (count: number) => boolean,
802
+ timeoutMs = 60_000,
803
+ ): Promise<number> {
804
+ const deadline = performance.now() + timeoutMs
805
+ let previous = -1
806
+ let stableReads = 0
807
+ while (performance.now() < deadline) {
808
+ const count = await locator.count()
809
+ stableReads = accepts(count) && count === previous ? stableReads + 1 : 0
810
+ if (stableReads >= 4) return count
811
+ previous = count
812
+ await new Promise(resolve => setTimeout(resolve, 50))
813
+ }
814
+ throw new Error(`browser row count did not stabilize; last count ${String(previous)}`)
815
+ }
816
+
817
+ async function conversationTurns(page: Page): Promise<number> {
818
+ // Loaded-window turn count: one mounted turn-tail footer per settled turn in
819
+ // the window (context keys are `${kind.length}:${kind}${id}`). The stats
820
+ // strip cannot serve as this probe: its counts ride the whole-log
821
+ // sessionStats projection and stay fixed across paging by design.
822
+ return stableCount(page.locator('[data-chat-flow-key^="9:turn-tail"]'), count => count > 0)
823
+ }
824
+
825
+ function retainedDelta(
826
+ before: RetainedBrowserState,
827
+ after: RetainedBrowserState,
828
+ ): RetainedBrowserState {
829
+ return {
830
+ domElements: after.domElements - before.domElements,
831
+ nodes: after.nodes - before.nodes,
832
+ listeners: after.listeners - before.listeners,
833
+ heapMb: rounded(after.heapMb - before.heapMb),
834
+ }
835
+ }
836
+
837
+ async function launchPerformanceWorld(
838
+ options: PerformanceWorldOptions,
839
+ ): Promise<PerformanceWorld> {
840
+ const setupStarted = performance.now()
841
+ let replayDir: string | undefined
842
+ let scaffold: WebScaffold | undefined
843
+ let page: Page | undefined
844
+ try {
845
+ if (options.replay === undefined) {
846
+ scaffold = await launchWebScaffold()
847
+ } else {
848
+ replayDir = await mkdtemp(join(tmpdir(), 'dsh-web-perf-replay-'))
849
+ const replayOverride = join(replayDir, 'replay.override.json')
850
+ await writeFile(replayOverride, JSON.stringify(options.replay))
851
+ scaffold = await launchWebScaffold({
852
+ // The override-only fixture supplies one positional script for this
853
+ // world's single live session.
854
+ replayFixture: join(replayDir, 'override-only.jsonl'),
855
+ replayOverride,
856
+ paceMs: STREAM_PACE_MS,
857
+ replayContextWindow: PERF_REPLAY_CONTEXT_WINDOW,
858
+ })
859
+ }
860
+
861
+ const sessionEvents: SessionEvent[] = []
862
+ scaffold.ctx.on('session/event', (_session, event: SessionEvent) => {
863
+ sessionEvents.push(event)
864
+ })
865
+ if ((options.sidebarSessions ?? 0) > 0) {
866
+ const small = smallSidebarFixture()
867
+ for (let index = 0; index < (options.sidebarSessions ?? 0); index += 1) {
868
+ await seedSession(scaffold, small, `perf-sidebar-${String(index).padStart(4, '0')}`)
869
+ }
870
+ }
871
+ if (options.seedLongHistory === true) {
872
+ await seedSession(scaffold, longHistoryFixture(), LONG_SESSION_ID)
873
+ }
874
+ const setupMs = performance.now() - setupStarted
875
+ page = await newEnglishPage(options.browser)
876
+ return {
877
+ scaffold,
878
+ page,
879
+ tripwire: watchConsole(page),
880
+ sessionEvents,
881
+ setupMs,
882
+ ...replayDir === undefined ? {} : { replayDir },
883
+ }
884
+ } catch (error) {
885
+ const failures: unknown[] = [error]
886
+ if (page !== undefined) {
887
+ try {
888
+ await page.close()
889
+ } catch (cleanupError) {
890
+ failures.push(cleanupError)
891
+ }
892
+ }
893
+ if (scaffold !== undefined) {
894
+ try {
895
+ await scaffold.close()
896
+ } catch (cleanupError) {
897
+ failures.push(cleanupError)
898
+ }
899
+ }
900
+ if (replayDir !== undefined) {
901
+ try {
902
+ await rm(replayDir, { recursive: true, force: true })
903
+ } catch (cleanupError) {
904
+ failures.push(cleanupError)
905
+ }
906
+ }
907
+ if (failures.length === 1) throw error
908
+ throw new AggregateError(failures, 'web performance setup and cleanup failed')
909
+ }
910
+ }
911
+
912
+ async function closePerformanceWorld(world: PerformanceWorld): Promise<void> {
913
+ const failures: unknown[] = []
914
+ await world.page.close().catch((error: unknown) => failures.push(error))
915
+ await world.scaffold.close().catch((error: unknown) => failures.push(error))
916
+ if (world.replayDir !== undefined) {
917
+ await rm(world.replayDir, { recursive: true, force: true })
918
+ .catch((error: unknown) => failures.push(error))
919
+ }
920
+ if (failures.length === 1) throw failures[0]
921
+ if (failures.length > 1) throw new AggregateError(failures, 'web performance teardown failed')
922
+ }
923
+
924
+ async function openPerformancePage(
925
+ world: PerformanceWorld,
926
+ expectedSessions: number,
927
+ ): Promise<Locator> {
928
+ await world.page.goto(world.scaffold.authenticatedUrl, { waitUntil: 'load' })
929
+ await world.page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
930
+ const group = world.page.getByRole('treeitem').first()
931
+ await expect.poll(() => group.textContent(), { timeout: 30_000 })
932
+ .toContain(`${String(expectedSessions)} ${expectedSessions === 1 ? 'session' : 'sessions'}`)
933
+ return group
934
+ }
935
+
936
+ async function openLongHistory(page: Page): Promise<number> {
937
+ await page.getByRole('textbox', { name: 'Search name, keywords...', exact: true })
938
+ .fill('LONG_PERF_SENTINEL')
939
+ const results = page.getByRole('tree', { name: 'Search results' }).getByRole('treeitem')
940
+ await expect.poll(() => results.count(), { timeout: 60_000 }).toBe(1)
941
+ await results.first().click()
942
+ await page.getByRole('tab', { name: 'Chat', exact: true }).waitFor({ timeout: 30_000 })
943
+ return conversationTurns(page)
944
+ }
945
+
946
+ async function continueConversation(
947
+ world: PerformanceWorld,
948
+ cdp: CDPSession,
949
+ options: {
950
+ readonly startingTurns: number
951
+ readonly turnCount: number
952
+ readonly turnSpec: (index: number) => ConversationTurnSpec
953
+ readonly expectedSessionId?: SessionId
954
+ readonly checkpointInterval?: number
955
+ },
956
+ ): Promise<ConversationReport> {
957
+ const composer = world.page.locator('[data-composer-input][contenteditable="true"]').last()
958
+ await composer.waitFor({ timeout: 15_000 })
959
+ const retainedBefore = await retainedBrowserState(cdp, world.page)
960
+ const checkpoints: RetainedCheckpoint[] = [{ turns: options.startingTurns, state: retainedBefore }]
961
+ const turns: ContinuedTurnReport[] = []
962
+ let liveSessionId = options.expectedSessionId
963
+
964
+ for (let index = 1; index <= options.turnCount; index += 1) {
965
+ const spec = options.turnSpec(index)
966
+ const composerFill = await measure(cdp, async () => {
967
+ await composer.fill(spec.prompt)
968
+ await expect.poll(() => composer.textContent()).toBe(spec.prompt)
969
+ return ((await composer.textContent()) ?? '').length
970
+ })
971
+ expect(composerFill.value).toBe(spec.prompt.length)
972
+
973
+ const eventStart = world.sessionEvents.length
974
+ await startMutationProbe(world.page)
975
+ const streamBefore = await chromiumMetrics(cdp)
976
+ const streamStarted = performance.now()
977
+ const settled = world.scaffold.whenTurnSettled(60_000)
978
+ await world.page.getByRole('button', { name: 'Send message', exact: true }).click()
979
+ await world.page.getByText(spec.userMarker, { exact: false }).last().waitFor({ timeout: 15_000 })
980
+ const clickToUserEchoMs = performance.now() - streamStarted
981
+ await world.page.getByText(spec.firstMarker, { exact: false }).last().waitFor({ timeout: 15_000 })
982
+ const clickToFirstChunkMs = performance.now() - streamStarted
983
+ const settledSessionId = await settled
984
+ if (liveSessionId === undefined) {
985
+ liveSessionId = settledSessionId
986
+ } else {
987
+ expect(settledSessionId).toBe(liveSessionId)
988
+ }
989
+ await expect.poll(
990
+ () => world.page.locator('[data-streaming="true"]').count(),
991
+ { timeout: 15_000 },
992
+ ).toBe(0)
993
+ await world.page.getByText(spec.doneMarker, { exact: false }).last().waitFor({ timeout: 15_000 })
994
+ const clickToSettledMs = performance.now() - streamStarted
995
+ const streamAfter = await chromiumMetrics(cdp)
996
+ const mutations = await stopMutationProbe(world.page)
997
+ const turnEvents = world.sessionEvents.slice(eventStart)
998
+ const chunks = turnEvents.flatMap(event => (
999
+ event.type === 'assistant/message' || event.type === 'assistant/attempt'
1000
+ ? expandAssistantStream(event.data.stream)
1001
+ : []
1002
+ ))
1003
+ const toolCalls = turnEvents.filter(event => event.type === 'tool/call')
1004
+ const toolResults = turnEvents.filter(event => event.type === 'tool/result')
1005
+ const toolTurn = spec.toolResultMarker !== undefined
1006
+ expect(chunks).toHaveLength(spec.deltas.length + (toolTurn ? 9 : 4))
1007
+ expect(toolCalls).toHaveLength(toolTurn ? 1 : 0)
1008
+ expect(toolResults).toHaveLength(toolTurn ? 1 : 0)
1009
+ if (spec.toolResultMarker !== undefined) {
1010
+ expect(toolCalls[0]?.data.name).toBe('bash')
1011
+ const toolResult = toolResults[0]
1012
+ if (toolResult?.type !== 'tool/result') {
1013
+ throw new Error(`continued turn ${String(index)} did not log its tool result`)
1014
+ }
1015
+ const resultBlock = toolResult.data.message.content.find(block => block.type === 'tool-result')
1016
+ expect(resultBlock?.isError).toBe(false)
1017
+ expect(resultBlock?.content
1018
+ .filter(block => block.type === 'text')
1019
+ .map(block => block.text)
1020
+ .join('')).toContain(spec.toolResultMarker)
1021
+ }
1022
+ const user = turnEvents.find(
1023
+ event => event.type === 'user/message' && event.data.source.kind === 'user',
1024
+ )
1025
+ if (user?.type !== 'user/message') {
1026
+ throw new Error(`continued turn ${String(index)} did not log its user message`)
1027
+ }
1028
+ expect(user.data.content
1029
+ .filter(block => block.type === 'text')
1030
+ .map(block => block.text)
1031
+ .join('')).toBe(spec.prompt)
1032
+ const resultingTurns = await conversationTurns(world.page)
1033
+ expect(resultingTurns).toBe(options.startingTurns + index)
1034
+ turns.push({
1035
+ ordinal: index,
1036
+ resultingTurns,
1037
+ kind: toolTurn ? 'tool' : 'text',
1038
+ promptChars: spec.prompt.length,
1039
+ composerFill: composerFill.measurement,
1040
+ stream: {
1041
+ paceMs: STREAM_PACE_MS,
1042
+ deltaChunks: spec.deltas.length,
1043
+ persistedChunks: chunks.length,
1044
+ toolCalls: toolCalls.length,
1045
+ toolResults: toolResults.length,
1046
+ clickToUserEchoMs: rounded(clickToUserEchoMs),
1047
+ clickToFirstChunkMs: rounded(clickToFirstChunkMs),
1048
+ firstChunkToSettledMs: rounded(clickToSettledMs - clickToFirstChunkMs),
1049
+ ...mutations,
1050
+ ...metricDelta(streamBefore, streamAfter, clickToSettledMs),
1051
+ },
1052
+ })
1053
+
1054
+ if (options.checkpointInterval !== undefined && index % options.checkpointInterval === 0) {
1055
+ checkpoints.push({
1056
+ turns: options.startingTurns + index,
1057
+ state: await retainedBrowserState(cdp, world.page),
1058
+ })
1059
+ }
1060
+ }
1061
+
1062
+ const lastCheckpoint = checkpoints.at(-1)
1063
+ const retainedAfter = lastCheckpoint?.turns === options.startingTurns + options.turnCount
1064
+ ? lastCheckpoint.state
1065
+ : await retainedBrowserState(cdp, world.page)
1066
+ if (lastCheckpoint?.turns !== options.startingTurns + options.turnCount) {
1067
+ checkpoints.push({ turns: options.startingTurns + options.turnCount, state: retainedAfter })
1068
+ }
1069
+ return {
1070
+ startingTurns: options.startingTurns,
1071
+ turnsAdded: options.turnCount,
1072
+ toolTurns: turns.filter(turn => turn.kind === 'tool').length,
1073
+ retainedBefore,
1074
+ retainedAfter,
1075
+ retainedDelta: retainedDelta(retainedBefore, retainedAfter),
1076
+ checkpoints,
1077
+ turns,
1078
+ }
1079
+ }
1080
+
1081
+ async function measurePostSoakUserRender(
1082
+ world: PerformanceWorld,
1083
+ cdp: CDPSession,
1084
+ ): Promise<object> {
1085
+ const spec = soakTurn(POST_SOAK_RENDER_TURN)
1086
+ if (spec.toolResultMarker !== undefined) {
1087
+ throw new Error('post-soak render probe must remain a text-only turn')
1088
+ }
1089
+ const composer = world.page.locator('[data-composer-input][contenteditable="true"]').last()
1090
+ const composerFill = await measure(cdp, async () => {
1091
+ await composer.fill(spec.prompt)
1092
+ await expect.poll(() => composer.textContent()).toBe(spec.prompt)
1093
+ return ((await composer.textContent()) ?? '').length
1094
+ })
1095
+ expect(composerFill.value).toBe(spec.prompt.length)
1096
+
1097
+ const eventStart = world.sessionEvents.length
1098
+ await startUserRenderProbe(world.page, spec.userMarker)
1099
+ const browserBefore = await chromiumMetrics(cdp)
1100
+ const fullTurnStarted = performance.now()
1101
+ const settled = world.scaffold.whenTurnSettled(60_000)
1102
+ await triggerUserRenderProbe(world.page)
1103
+ const browserTiming = await stopUserRenderProbe(world.page, spec.userMarker)
1104
+ const browserAfter = await chromiumMetrics(cdp)
1105
+ const browserAfterPaintSample = metricDelta(
1106
+ browserBefore,
1107
+ browserAfter,
1108
+ performance.now() - fullTurnStarted,
1109
+ )
1110
+ await world.page.getByText(spec.firstMarker, { exact: false }).last().waitFor({ timeout: 15_000 })
1111
+ const settledSessionId = await settled
1112
+ await expect.poll(
1113
+ () => world.page.locator('[data-streaming="true"]').count(),
1114
+ { timeout: 15_000 },
1115
+ ).toBe(0)
1116
+ await world.page.getByText(spec.doneMarker, { exact: false }).last().waitFor({ timeout: 15_000 })
1117
+ const fullTurnMs = performance.now() - fullTurnStarted
1118
+
1119
+ const turnEvents = world.sessionEvents.slice(eventStart)
1120
+ const chunks = turnEvents.flatMap(event => (
1121
+ event.type === 'assistant/message' || event.type === 'assistant/attempt'
1122
+ ? expandAssistantStream(event.data.stream)
1123
+ : []
1124
+ ))
1125
+ const user = turnEvents.find(
1126
+ event => event.type === 'user/message' && event.data.source.kind === 'user',
1127
+ )
1128
+ if (user?.type !== 'user/message') throw new Error('post-soak render probe did not log its user message')
1129
+ expect(user.data.content
1130
+ .filter(block => block.type === 'text')
1131
+ .map(block => block.text)
1132
+ .join('')).toBe(spec.prompt)
1133
+ expect(chunks).toHaveLength(spec.deltas.length + 4)
1134
+ expect(turnEvents.filter(event => event.type === 'tool/call')).toHaveLength(0)
1135
+ expect(turnEvents.filter(event => event.type === 'tool/result')).toHaveLength(0)
1136
+ expect(world.scaffold.ctx.agents.get(settledSessionId)).toBeDefined()
1137
+ expect(await conversationTurns(world.page)).toBe(POST_SOAK_RENDER_TURN)
1138
+
1139
+ return {
1140
+ ordinal: POST_SOAK_RENDER_TURN,
1141
+ resultingTurns: POST_SOAK_RENDER_TURN,
1142
+ promptChars: spec.prompt.length,
1143
+ composerFill: composerFill.measurement,
1144
+ trustedClick: browserTiming.trustedClick,
1145
+ sendToDomMs: rounded(browserTiming.sendToDomMs),
1146
+ sendToPaintMs: rounded(browserTiming.sendToPaintMs),
1147
+ domToPaintMs: rounded(browserTiming.domToPaintMs),
1148
+ mutationBatchesThroughPaint: browserTiming.mutationBatches,
1149
+ mutationRecordsThroughPaint: browserTiming.mutationRecords,
1150
+ browserAfterPaintSample,
1151
+ fullTurnMs: rounded(fullTurnMs),
1152
+ persistedChunks: chunks.length,
1153
+ }
1154
+ }
1155
+
1156
+ function average(values: readonly number[]): number {
1157
+ return rounded(values.reduce((sum, value) => sum + value, 0) / values.length)
1158
+ }
1159
+
1160
+ function p95(values: readonly number[]): number {
1161
+ const sorted = [...values].sort((left, right) => left - right)
1162
+ return sorted[Math.max(0, Math.ceil(sorted.length * 0.95) - 1)] ?? 0
1163
+ }
1164
+
1165
+ function summarizeTurnWindows(
1166
+ turns: readonly ContinuedTurnReport[],
1167
+ windowSize: number,
1168
+ ): object[] {
1169
+ const windows: object[] = []
1170
+ for (let start = 0; start < turns.length; start += windowSize) {
1171
+ const window = turns.slice(start, start + windowSize)
1172
+ const streamWall = window.map(turn => turn.stream.wallMs)
1173
+ const userEcho = window.map(turn => turn.stream.clickToUserEchoMs)
1174
+ const firstChunk = window.map(turn => turn.stream.clickToFirstChunkMs)
1175
+ windows.push({
1176
+ turns: `${String(start + 1)}-${String(start + window.length)}`,
1177
+ toolTurns: window.filter(turn => turn.kind === 'tool').length,
1178
+ average: {
1179
+ composerFillWallMs: average(window.map(turn => turn.composerFill.wallMs)),
1180
+ streamWallMs: average(streamWall),
1181
+ clickToUserEchoMs: average(userEcho),
1182
+ clickToFirstChunkMs: average(firstChunk),
1183
+ taskMs: average(window.map(turn => turn.stream.taskMs)),
1184
+ scriptMs: average(window.map(turn => turn.stream.scriptMs)),
1185
+ recalcStyleMs: average(window.map(turn => turn.stream.recalcStyleMs)),
1186
+ mutationBatches: average(window.map(turn => turn.stream.batches)),
1187
+ },
1188
+ p95: {
1189
+ streamWallMs: rounded(p95(streamWall)),
1190
+ clickToUserEchoMs: rounded(p95(userEcho)),
1191
+ clickToFirstChunkMs: rounded(p95(firstChunk)),
1192
+ },
1193
+ })
1194
+ }
1195
+ return windows
1196
+ }
1197
+
1198
+ describe('manual web performance: complex workspace and history', () => {
1199
+ let browser: Browser
1200
+
1201
+ beforeAll(async () => {
1202
+ if (webSnapshotMode() === 'record') {
1203
+ throw new Error('manual web performance runs only with deterministic replay')
1204
+ }
1205
+ browser = await chromium.launch()
1206
+ })
1207
+
1208
+ afterAll(async () => {
1209
+ await browser?.close()
1210
+ })
1211
+
1212
+ it('reports workspace, history, and trajectory cardinality costs', async () => {
1213
+ const world = await launchPerformanceWorld({
1214
+ browser,
1215
+ sidebarSessions: SIDEBAR_SESSION_COUNT,
1216
+ seedLongHistory: true,
1217
+ })
1218
+ try {
1219
+ const bootStarted = performance.now()
1220
+ const group = await openPerformancePage(world, SIDEBAR_SESSION_COUNT + 1)
1221
+ const bootReadyMs = performance.now() - bootStarted
1222
+ const page = world.page
1223
+ const cdp = await page.context().newCDPSession(page)
1224
+ await cdp.send('Performance.enable')
1225
+ const firstContentfulPaintMs = await page.evaluate(
1226
+ () => globalThis.performance.getEntriesByName('first-contentful-paint')[0]?.startTime,
1227
+ )
1228
+
1229
+ const sidebar = await measure(cdp, async () => {
1230
+ await group.click()
1231
+ return stableCount(
1232
+ page.getByRole('treeitem'),
1233
+ count => count === SIDEBAR_SESSION_COUNT + 2,
1234
+ )
1235
+ })
1236
+ expect(sidebar.value).toBe(SIDEBAR_SESSION_COUNT + 2)
1237
+ await group.click()
1238
+ await expect.poll(() => page.getByRole('treeitem').count()).toBe(1)
1239
+
1240
+ const contentSearch = await measure(cdp, async () => {
1241
+ await page.getByRole('textbox', { name: 'Search name, keywords...', exact: true })
1242
+ .fill('LONG_PERF_SENTINEL')
1243
+ const results = page.getByRole('tree', { name: 'Search results' }).getByRole('treeitem')
1244
+ await expect.poll(() => results.count(), { timeout: 60_000 }).toBe(1)
1245
+ await results.first().waitFor({ timeout: 60_000 })
1246
+ return results.first()
1247
+ })
1248
+ const opened = await measure(cdp, async () => {
1249
+ await contentSearch.value.click()
1250
+ await page.getByRole('tab', { name: 'Trajectory', exact: true }).waitFor({ timeout: 30_000 })
1251
+ return conversationTurns(page)
1252
+ })
1253
+ expect(opened.value).toBe(DEFAULT_HISTORY_TURNS)
1254
+
1255
+ const trajectoryRows = page.getByRole('row')
1256
+ const coldTrajectory = await measure(cdp, async () => {
1257
+ await page.getByRole('tab', { name: 'Trajectory', exact: true }).click()
1258
+ return stableCount(trajectoryRows, count => count === EXPECTED_TRAJECTORY_ROWS)
1259
+ })
1260
+ expect(coldTrajectory.value).toBe(EXPECTED_TRAJECTORY_ROWS)
1261
+
1262
+ const collapseTurns = await measure(cdp, async () => {
1263
+ await page.getByRole('button', { name: 'Collapse turns', exact: true }).click()
1264
+ return stableCount(trajectoryRows, count => count > 0 && count < EXPECTED_TRAJECTORY_ROWS)
1265
+ })
1266
+ expect(collapseTurns.value).toBeLessThan(EXPECTED_TRAJECTORY_ROWS)
1267
+ const trajectorySearch = await measure(cdp, async () => {
1268
+ await page.getByRole('searchbox', { name: 'Search trajectory', exact: true }).fill('turn 499')
1269
+ return stableCount(trajectoryRows, count => count > 0 && count < 20)
1270
+ })
1271
+ expect(trajectorySearch.value).toBeLessThan(20)
1272
+
1273
+ await page.getByRole('tab', { name: 'Chat', exact: true }).click()
1274
+ const historyPages: { turns: number; measurement: Measurement }[] = []
1275
+ let turns = await conversationTurns(page)
1276
+ while (turns < LONG_HISTORY_TURNS) {
1277
+ const previousTurns = turns
1278
+ const older = await measure(cdp, async () => {
1279
+ await page.getByRole('button', { name: 'Load earlier', exact: true }).click()
1280
+ await expect.poll(() => conversationTurns(page), { timeout: 30_000 })
1281
+ .toBeGreaterThan(previousTurns)
1282
+ return conversationTurns(page)
1283
+ })
1284
+ turns = older.value
1285
+ historyPages.push({ turns, measurement: older.measurement })
1286
+ }
1287
+
1288
+ const warmTrajectory = await measure(cdp, async () => {
1289
+ await page.getByRole('tab', { name: 'Trajectory', exact: true }).click()
1290
+ return stableCount(trajectoryRows, count => count === EXPECTED_TRAJECTORY_ROWS)
1291
+ })
1292
+ expect(warmTrajectory.value).toBe(EXPECTED_TRAJECTORY_ROWS)
1293
+ const warmConversation = await measure(cdp, async () => {
1294
+ await page.getByRole('tab', { name: 'Chat', exact: true }).click()
1295
+ return conversationTurns(page)
1296
+ })
1297
+ expect(warmConversation.value).toBe(LONG_HISTORY_TURNS)
1298
+
1299
+ console.info(`WEB_PERF_RESULT ${JSON.stringify({
1300
+ scenario: 'workspace-history-trajectory',
1301
+ fixture: {
1302
+ sidebarSessions: SIDEBAR_SESSION_COUNT,
1303
+ totalSessions: SIDEBAR_SESSION_COUNT + 1,
1304
+ longHistoryTurns: LONG_HISTORY_TURNS,
1305
+ toolCalls: EXPECTED_TOOL_CALLS,
1306
+ trajectoryRows: EXPECTED_TRAJECTORY_ROWS,
1307
+ },
1308
+ setupMs: rounded(world.setupMs),
1309
+ boot: {
1310
+ readyMs: rounded(bootReadyMs),
1311
+ firstContentfulPaintMs: firstContentfulPaintMs === undefined
1312
+ ? null
1313
+ : rounded(firstContentfulPaintMs),
1314
+ },
1315
+ sidebarExpand: sidebar.measurement,
1316
+ contentSearch: contentSearch.measurement,
1317
+ openLongHistory: { initialTurns: opened.value, ...opened.measurement },
1318
+ coldTrajectory: { rows: coldTrajectory.value, ...coldTrajectory.measurement },
1319
+ collapseTurns: { rows: collapseTurns.value, ...collapseTurns.measurement },
1320
+ trajectorySearch: { rows: trajectorySearch.value, ...trajectorySearch.measurement },
1321
+ historyPages,
1322
+ warmTrajectory: { rows: warmTrajectory.value, ...warmTrajectory.measurement },
1323
+ warmConversation: { turns: warmConversation.value, ...warmConversation.measurement },
1324
+ }, null, 2)}`)
1325
+ expect(world.tripwire.warnings).toEqual([])
1326
+ expect(world.tripwire.pageErrors).toEqual([])
1327
+ } finally {
1328
+ await closePerformanceWorld(world)
1329
+ }
1330
+ })
1331
+
1332
+ it('reports default 24-turn history plus eight continued turns', async () => {
1333
+ const world = await launchPerformanceWorld({
1334
+ browser,
1335
+ replay: performanceReplayOverride(COMPARISON_TURNS, comparisonTurn),
1336
+ seedLongHistory: true,
1337
+ })
1338
+ try {
1339
+ await openPerformancePage(world, 1)
1340
+ const cdp = await world.page.context().newCDPSession(world.page)
1341
+ await cdp.send('Performance.enable')
1342
+ const opened = await measure(cdp, () => openLongHistory(world.page))
1343
+ expect(opened.value).toBe(DEFAULT_HISTORY_TURNS)
1344
+ const conversation = await continueConversation(world, cdp, {
1345
+ startingTurns: DEFAULT_HISTORY_TURNS,
1346
+ turnCount: COMPARISON_TURNS,
1347
+ turnSpec: comparisonTurn,
1348
+ expectedSessionId: SessionId(LONG_SESSION_ID),
1349
+ })
1350
+ expect(conversation.toolTurns).toBe(2)
1351
+ console.info(`WEB_PERF_RESULT ${JSON.stringify({
1352
+ scenario: 'default-resume-24-plus-8',
1353
+ setupMs: rounded(world.setupMs),
1354
+ replayContextWindow: PERF_REPLAY_CONTEXT_WINDOW,
1355
+ openLongHistory: { turns: opened.value, ...opened.measurement },
1356
+ conversation,
1357
+ }, null, 2)}`)
1358
+ expect(world.tripwire.warnings).toEqual([])
1359
+ expect(world.tripwire.pageErrors).toEqual([])
1360
+ } finally {
1361
+ await closePerformanceWorld(world)
1362
+ }
1363
+ })
1364
+
1365
+ it('reports fully expanded 500-turn history plus eight continued turns', async () => {
1366
+ const world = await launchPerformanceWorld({
1367
+ browser,
1368
+ replay: performanceReplayOverride(COMPARISON_TURNS, comparisonTurn),
1369
+ seedLongHistory: true,
1370
+ })
1371
+ try {
1372
+ await openPerformancePage(world, 1)
1373
+ const cdp = await world.page.context().newCDPSession(world.page)
1374
+ await cdp.send('Performance.enable')
1375
+ expect(await openLongHistory(world.page)).toBe(DEFAULT_HISTORY_TURNS)
1376
+ const historyPages: { turns: number; measurement: Measurement }[] = []
1377
+ let turns = DEFAULT_HISTORY_TURNS
1378
+ while (turns < LONG_HISTORY_TURNS) {
1379
+ const previousTurns = turns
1380
+ const older = await measure(cdp, async () => {
1381
+ await world.page.getByRole('button', { name: 'Load earlier', exact: true }).click()
1382
+ await expect.poll(() => conversationTurns(world.page), { timeout: 30_000 })
1383
+ .toBeGreaterThan(previousTurns)
1384
+ return conversationTurns(world.page)
1385
+ })
1386
+ turns = older.value
1387
+ historyPages.push({ turns, measurement: older.measurement })
1388
+ }
1389
+ expect(turns).toBe(LONG_HISTORY_TURNS)
1390
+ const conversation = await continueConversation(world, cdp, {
1391
+ startingTurns: LONG_HISTORY_TURNS,
1392
+ turnCount: COMPARISON_TURNS,
1393
+ turnSpec: comparisonTurn,
1394
+ expectedSessionId: SessionId(LONG_SESSION_ID),
1395
+ })
1396
+ expect(conversation.toolTurns).toBe(2)
1397
+ console.info(`WEB_PERF_RESULT ${JSON.stringify({
1398
+ scenario: 'expanded-history-500-plus-8',
1399
+ setupMs: rounded(world.setupMs),
1400
+ replayContextWindow: PERF_REPLAY_CONTEXT_WINDOW,
1401
+ historyPages,
1402
+ conversation,
1403
+ }, null, 2)}`)
1404
+ expect(world.tripwire.warnings).toEqual([])
1405
+ expect(world.tripwire.pageErrors).toEqual([])
1406
+ } finally {
1407
+ await closePerformanceWorld(world)
1408
+ }
1409
+ })
1410
+
1411
+ it('reports one hundred generated turns and the next user-message paint', async () => {
1412
+ const world = await launchPerformanceWorld({
1413
+ browser,
1414
+ replay: performanceReplayOverride(POST_SOAK_RENDER_TURN, soakTurn),
1415
+ })
1416
+ let testFailure: unknown
1417
+ try {
1418
+ await world.page.goto(world.scaffold.authenticatedUrl, { waitUntil: 'load' })
1419
+ await world.page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
1420
+ await connectFreshWorkspace(world.page, world.scaffold.workspaceCwd, 'continuous-conversation-perf')
1421
+ const cdp = await world.page.context().newCDPSession(world.page)
1422
+ await cdp.send('Performance.enable')
1423
+ const conversation = await continueConversation(world, cdp, {
1424
+ startingTurns: 0,
1425
+ turnCount: SOAK_TURNS,
1426
+ turnSpec: soakTurn,
1427
+ checkpointInterval: SOAK_CHECKPOINT_INTERVAL,
1428
+ })
1429
+ expect(conversation.toolTurns).toBe(SOAK_TURNS / SOAK_TOOL_INTERVAL)
1430
+ const postSoakUserRender = await measurePostSoakUserRender(world, cdp)
1431
+ const { turns, ...retained } = conversation
1432
+ console.info(`WEB_PERF_RESULT ${JSON.stringify({
1433
+ scenario: 'continuous-100-turn-soak',
1434
+ setupMs: rounded(world.setupMs),
1435
+ replayContextWindow: PERF_REPLAY_CONTEXT_WINDOW,
1436
+ ...retained,
1437
+ windows: summarizeTurnWindows(turns, SOAK_CHECKPOINT_INTERVAL),
1438
+ postSoakUserRender,
1439
+ }, null, 2)}`)
1440
+ expect(world.tripwire.warnings).toEqual([])
1441
+ expect(world.tripwire.pageErrors).toEqual([])
1442
+ } catch (error) {
1443
+ testFailure = error
1444
+ throw error
1445
+ } finally {
1446
+ try {
1447
+ await closePerformanceWorld(world)
1448
+ } catch (cleanupError) {
1449
+ if (testFailure === undefined) throw cleanupError
1450
+ throw new AggregateError(
1451
+ [testFailure, cleanupError],
1452
+ 'continuous conversation performance test and teardown failed',
1453
+ )
1454
+ }
1455
+ }
1456
+ })
1457
+ })
apps/web/tests/cordis-tool-round.e2e.ts ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Web e2e scenario for the opt-in Cordis tools. Record mode drives a real
2
+ // model through inspect, define, run, and stop; replay pins the same shipped Web
3
+ // composition, durable calls, Cordis-owned rows, the define card's own source view,
4
+ // and conversation accessibility tree.
5
+ //
6
+ // The approval is never in the fixture. The fixture pins what the MODEL said;
7
+ // tools execute for real, and this test answers the approval before starting the
8
+ // stop turn. The package therefore carries a browser half whose only
9
+ // job is to be visible (`[data-snapshot-probe]`): its absence before the answer
10
+ // and presence after it is the v3 user gate, proven rather than described.
11
+ import { readFile } from 'node:fs/promises'
12
+ import { fileURLToPath } from 'node:url'
13
+ import type { Browser, Page } from 'playwright'
14
+ import { chromium } from 'playwright'
15
+ import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
16
+ import type { SessionEvent } from '@deepseek-ai/dsh-session'
17
+ import {
18
+ captureStableAria, compareOrRefreshGolden, fixtureUserPrompts,
19
+ launchWebScaffold, recordFixture, watchConsole, webSnapshotMode, type WebScaffold,
20
+ } from './scaffold.ts'
21
+ import { connectFreshWorkspace, expandOwningTurnProcess, newEnglishPage, saveFailureShot } from './support.ts'
22
+
23
+ const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/cordis-tool-round/session.v3.jsonl', import.meta.url))
24
+ const UI_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/cordis-tool-round/ui.expected.md', import.meta.url))
25
+ const MODE = webSnapshotMode()
26
+ const CORDIS_TOOLS = ['cordis_inspect_self', 'cordis_define', 'cordis_run', 'cordis_stop'] as const
27
+ const PACKAGE_CODE = 'return { name: "snapshot-noop", apply(ctx) {} }'
28
+ // The browser half is the PROBE this scenario turns on: it renders a marker into
29
+ // the frame-wide overlay, so "did the plugin actually run in this page" becomes a
30
+ // DOM fact. A host-only package would sidestep the approval round trip entirely
31
+ // (the host runs those immediately), which would drop the v3 user gate out of
32
+ // coverage — the one thing this scenario exists to prove.
33
+ const CLIENT_CODE = 'return { inject: ["slots"], apply(ctx) { ctx.slots.register('
34
+ + '{ name: "shell.overlay", id: "snapshot-probe" }, '
35
+ + '() => React.createElement("div", { "data-snapshot-probe": "loaded" })) } }'
36
+ const PROMPT = 'Use only Cordis tools. First call cordis_inspect_self with no arguments. '
37
+ + 'Then call cordis_define with plugin kind "new", idPrefix "snap", name "snapshot noop", '
38
+ + 'purpose "does nothing, for the snapshot", '
39
+ + `code.host exactly ${JSON.stringify(PACKAGE_CODE)} and code.client exactly ${JSON.stringify(CLIENT_CODE)}. `
40
+ + 'Read its returned pluginId and packageId, then call cordis_run with those exact IDs and mode "run". '
41
+ + 'After the run request returns, reply exactly CORDIS_UI_READY and stop.'
42
+ const STOP_PROMPT = 'Use only Cordis tools. Call cordis_stop with pluginId "snap-1". '
43
+ + 'After it succeeds, reply exactly CORDIS_UI_DONE and stop.'
44
+
45
+ function assertCompleteCordisLifecycle(events: readonly SessionEvent[]): void {
46
+ const turnEnd = events.findLast(
47
+ (event): event is Extract<SessionEvent, { type: 'turn/end' }> => event.type === 'turn/end',
48
+ )
49
+ const reason = turnEnd?.data.reason
50
+ expect(reason).toEqual({ kind: 'completed' })
51
+
52
+ const calls = events.filter(
53
+ (event): event is Extract<SessionEvent, { type: 'tool/call' }> => event.type === 'tool/call',
54
+ )
55
+ expect(calls.map(event => event.data.name)).toEqual(CORDIS_TOOLS)
56
+
57
+ const callIds = new Set(calls.map(event => String(event.data.callId)))
58
+ const results = events.filter(
59
+ (event): event is Extract<SessionEvent, { type: 'tool/result' }> =>
60
+ event.type === 'tool/result' && callIds.has(String(event.data.message.source.callId)),
61
+ )
62
+ expect(results).toHaveLength(CORDIS_TOOLS.length)
63
+ expect(results.every(event => !event.data.message.content[0].isError)).toBe(true)
64
+ }
65
+
66
+ describe('web e2e: Cordis tools use their owned cards', () => {
67
+ let scaffold: WebScaffold
68
+ let browser: Browser
69
+ let page: Page
70
+ let tripwire: ReturnType<typeof watchConsole>
71
+ const sessionEvents: SessionEvent[] = []
72
+ const modelFrames: string[] = []
73
+ const modelChanges: string[] = []
74
+
75
+ beforeAll(async () => {
76
+ scaffold = await launchWebScaffold({
77
+ cordisTools: true,
78
+ compareReplaySession: true,
79
+ ...(MODE === 'record' ? {} : { replayFixture: FIXTURE, paceMs: 15 }),
80
+ })
81
+ scaffold.ctx.on('session/event', (_session, event: SessionEvent) => { sessionEvents.push(event) })
82
+ scaffold.ctx.sessionProjections.onChanged((_session, key, value, seq) => {
83
+ if (key === 'modelSelection') modelChanges.push(`${String(seq)}:${JSON.stringify(value)}`)
84
+ })
85
+ browser = await chromium.launch()
86
+ page = await newEnglishPage(browser)
87
+ page.on('websocket', (socket) => {
88
+ socket.on('framereceived', (frame) => {
89
+ const payload = String(frame.payload)
90
+ if (payload.includes('modelSelection')) modelFrames.push(payload)
91
+ })
92
+ })
93
+ tripwire = watchConsole(page)
94
+ await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
95
+ await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
96
+ await connectFreshWorkspace(page, scaffold.workspaceCwd)
97
+ }, 120_000)
98
+
99
+ afterAll(async () => {
100
+ await browser?.close()
101
+ await scaffold?.close()
102
+ })
103
+
104
+ it('drives the recorded Cordis lifecycle to a settled turn (all modes)', async () => {
105
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-cordis-drive'))
106
+ if (MODE !== 'record') {
107
+ expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT, STOP_PROMPT])
108
+ }
109
+ const input = page.locator('[data-composer-input]').first()
110
+ await input.waitFor({ timeout: 10_000 })
111
+ const runTurnSettled = scaffold.whenTurnSettled()
112
+ await input.fill(PROMPT)
113
+ await input.press('Enter')
114
+
115
+ // The approval is the TEST's action in every mode: the fixture pins what the
116
+ // model said, and the gate is a real round trip through the real panel.
117
+ const approve = page.locator('[data-cordis-approve]').first()
118
+ await approve.waitFor({ timeout: 90_000 })
119
+ // The one assertion this scenario cannot give up: the model asking to run is
120
+ // NOT the plugin running. Until a person answers, the browser half has not
121
+ // been fetched, evaluated, or mounted anywhere on this page.
122
+ expect(await page.locator('[data-snapshot-probe]').count()).toBe(0)
123
+ const sessionId = await runTurnSettled
124
+ // Approving from idle makes the run-outcome steer a distinct continuation
125
+ // turn, matching the recorded replay and keeping turn grouping deterministic.
126
+ const approvalTurnSettled = scaffold.whenTurnSettled()
127
+ await approve.click()
128
+ await expect.poll(() => page.locator('[data-snapshot-probe]').count(), { timeout: 30_000 }).toBe(1)
129
+ await approvalTurnSettled
130
+ await expect.poll(() => page.getByText('The Cordis Plugin is running.', { exact: true }).count(), { timeout: 15_000 })
131
+ .toBeGreaterThanOrEqual(1)
132
+ await expect.poll(() => input.isEnabled(), { timeout: 15_000 }).toBe(true)
133
+ const stopTurnSettled = scaffold.whenTurnSettled()
134
+ await input.fill(STOP_PROMPT)
135
+ await input.press('Enter')
136
+ await stopTurnSettled
137
+ await expect.poll(() => {
138
+ const stop = sessionEvents.find(
139
+ (event): event is Extract<SessionEvent, { type: 'tool/call' }> =>
140
+ event.type === 'tool/call' && event.data.name === 'cordis_stop',
141
+ )
142
+ return stop !== undefined && sessionEvents.some(
143
+ event => event.type === 'tool/result'
144
+ && String(event.data.message.source.callId) === String(stop.data.callId),
145
+ )
146
+ }, { timeout: 15_000 }).toBe(true)
147
+ if (MODE === 'record') {
148
+ assertCompleteCordisLifecycle(sessionEvents)
149
+ await expect.poll(() => page.getByText('CORDIS_UI_DONE', { exact: true }).count(), { timeout: 15_000 })
150
+ .toBeGreaterThanOrEqual(1)
151
+ await recordFixture(scaffold, sessionId, FIXTURE)
152
+ }
153
+ }, 200_000)
154
+
155
+ it.skipIf(MODE === 'record')('the durable log carries one complete Cordis lifecycle', () => {
156
+ assertCompleteCordisLifecycle(sessionEvents)
157
+ })
158
+
159
+ it.skipIf(MODE === 'record')('renders localized Cordis lifecycle cards', async () => {
160
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-cordis-rows'))
161
+ await expect.poll(() => page.getByText('CORDIS_UI_DONE', { exact: true }).count(), { timeout: 15_000 })
162
+ .toBeGreaterThanOrEqual(1)
163
+
164
+ const inspectRow = page.locator('[data-tool="cordis_inspect_self"]').filter({ hasText: 'Inspect' }).first()
165
+ await expandOwningTurnProcess(page, inspectRow)
166
+ await inspectRow.waitFor({ timeout: 10_000 })
167
+
168
+ // cordis_define does NOT go through the generic row: ui-cordis registers a
169
+ // keyed toolview for it, and a keyed hit replaces the generic card. So the
170
+ // title here is the CARD's ("Cordis Plugin"), and the expanded body is the
171
+ // card's own two code sections rather than a generic args dump.
172
+ const defineRow = page.locator('[data-tool="cordis_define"]').filter({ hasText: 'Cordis Plugin' }).first()
173
+ await expandOwningTurnProcess(page, defineRow)
174
+ await defineRow.waitFor({ timeout: 10_000 })
175
+ // The whole summary row is the expand toggle (unified tool-row interaction).
176
+ await defineRow.locator('[aria-expanded]').first().click()
177
+ await expect.poll(() => defineRow.textContent(), { timeout: 10_000 }).toContain('data-snapshot-probe')
178
+ await defineRow.getByRole('tab', { name: 'Host' }).click()
179
+ await expect.poll(() => defineRow.textContent()).toContain(PACKAGE_CODE)
180
+
181
+ const runRow = page.locator('[data-tool="cordis_run"]').filter({ hasText: 'Run Cordis Plugin' }).first()
182
+ await expandOwningTurnProcess(page, runRow)
183
+ await runRow.waitFor({ timeout: 10_000 })
184
+ await expect.poll(() => runRow.textContent()).toContain('snap-')
185
+
186
+ const stopRow = page.locator('[data-tool="cordis_stop"]').filter({ hasText: 'Stop Cordis Plugin' }).first()
187
+ await expandOwningTurnProcess(page, stopRow)
188
+ await stopRow.waitFor({ timeout: 10_000 })
189
+ await expect.poll(() => stopRow.textContent()).toContain('snap-')
190
+ await expect(stopRow.getAttribute('data-state')).resolves.toBe('ok')
191
+ // Stopping withdraws the browser half from every page, probe included.
192
+ await expect.poll(() => page.locator('[data-snapshot-probe]').count(), { timeout: 15_000 }).toBe(0)
193
+ })
194
+
195
+ it.skipIf(MODE === 'record')('matches the conversation aria golden', async () => {
196
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-cordis-aria'))
197
+ console.log('MODEL_TRACE', { modelChanges, frameCount: modelFrames.length, modelFrames })
198
+ // Final Assistant text precedes turn/end. Three footers prove every turn
199
+ // reached the render state covered by the ARIA golden.
200
+ await expect.poll(
201
+ () => page.getByRole('button', { name: 'Branch into a new conversation', exact: true }).count(),
202
+ { timeout: 15_000 },
203
+ ).toBe(3)
204
+ await page.locator('[data-conversation-scroll]').evaluate((host) => { host.scrollTop = host.scrollHeight })
205
+ await expect.poll(
206
+ async () => page.getByRole('button', { name: 'Back to bottom', exact: true }).count(),
207
+ { timeout: 10_000 },
208
+ ).toBe(0)
209
+ await page.mouse.move(0, 0)
210
+ const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
211
+ await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE)
212
+ })
213
+
214
+ it.skipIf(MODE === 'record')('stayed clean: no page errors or reconnect churn', () => {
215
+ expect(tripwire.pageErrors).toEqual([])
216
+ expect(tripwire.warnings).toEqual([])
217
+ })
218
+ })
apps/web/tests/deepseek-messages-settings.e2e.ts ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** Opt-in Web Messages configuration, credential reuse, and recovery from a saved Chat Completions selection. */
2
+ import { readFile } from 'node:fs/promises'
3
+ import { join } from 'node:path'
4
+ import { fileURLToPath } from 'node:url'
5
+ import { chromium, type Browser, type Page } from 'playwright'
6
+ import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
7
+ import {
8
+ captureStableAria, compareOrRefreshGolden, launchWebScaffold,
9
+ watchConsole, webSnapshotMode, type WebScaffold,
10
+ } from './scaffold.ts'
11
+ import { connectFreshWorkspaceZh, saveFailureShot, ZH_BROWSER_LOCALE } from './support.ts'
12
+
13
+ const EXPECTED = fileURLToPath(new URL('./expected/deepseek-messages-settings/', import.meta.url))
14
+
15
+ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages opt-in', () => {
16
+ let scaffold: WebScaffold
17
+ let browser: Browser
18
+ let page: Page
19
+ let tripwire: ReturnType<typeof watchConsole>
20
+
21
+ beforeAll(async () => {
22
+ scaffold = await launchWebScaffold({ deepSeekMissingCredential: true, deepSeekMessages: true })
23
+ browser = await chromium.launch()
24
+ page = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
25
+ tripwire = watchConsole(page)
26
+ await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
27
+ }, 120_000)
28
+
29
+ afterAll(async () => {
30
+ try {
31
+ await browser?.close()
32
+ } finally {
33
+ await scaffold?.close()
34
+ }
35
+ })
36
+
37
+ it('offers one DeepSeek card and saves Messages settings using the existing credential reference', async () => {
38
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-deepseek-messages-settings'))
39
+ expect(scaffold.ctx.llm.listProviders()).toContainEqual({ id: 'deepseek-official', name: 'DeepSeek' })
40
+ expect(scaffold.ctx.llm.listProviders().filter(provider => provider.id === 'deepseek-official')).toHaveLength(1)
41
+ expect(scaffold.ctx.agentDefaultModel.currentSelection()).toEqual({ provider: 'deepseek-official', model: 'deepseek-flash' })
42
+ const onboarding = page.getByRole('dialog', { name: '添加一个 API Key 开始使用' })
43
+ await onboarding.getByLabel('API 密钥', { exact: true }).fill('sk-messages-onboarding')
44
+ await onboarding.getByRole('button', { name: '保存并继续' }).click()
45
+ await onboarding.waitFor({ state: 'detached' })
46
+ await page.getByRole('button', { name: '设置', exact: true }).click()
47
+ const dialog = page.getByRole('dialog', { name: '设置', exact: true })
48
+ await dialog.getByRole('button', { name: '模型', exact: true }).click()
49
+ await dialog.getByText('DeepSeek', { exact: true }).waitFor()
50
+ expect(await dialog.getByText('DeepSeek', { exact: true }).count()).toBe(1)
51
+ await dialog.getByText('DeepSeek', { exact: true }).locator('xpath=ancestor::li').getByRole('button', { name: '编辑' }).click()
52
+ const messages = dialog
53
+ await messages.getByText('自定义设置', { exact: true }).click()
54
+ expect(await messages.getByLabel('API 地址', { exact: true }).getAttribute('placeholder'))
55
+ .toBe('https://api.deepseek.com/anthropic')
56
+ await compareOrRefreshGolden(join(EXPECTED, 'cards.expected.md'),
57
+ await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd), webSnapshotMode())
58
+ await messages.getByLabel('API 密钥', { exact: true }).fill('sk-e2e-messages')
59
+ await messages.getByLabel('API 地址', { exact: true }).fill('https://messages.example/anthropic')
60
+ expect(await messages.getByLabel('模型 ID 1').inputValue()).toBe('deepseek-flash')
61
+ await messages.getByLabel('显示名称 1', { exact: true }).fill('Messages Flash')
62
+ await messages.getByRole('button', { name: '保存', exact: true }).click()
63
+ await dialog.getByText('已保存 DeepSeek (deepseek-official)。', { exact: true }).waitFor()
64
+
65
+ const settings = await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')
66
+ expect(settings).toContain('https://messages.example/anthropic')
67
+ expect(settings).toContain('llm-deepseek:')
68
+ await expect(scaffold.ctx.llm.resolveModelInfo('deepseek-official', 'deepseek-flash')).resolves.toMatchObject({
69
+ name: 'Messages Flash', inputModalities: ['text', 'image'], systemPromptUpdate: 'in-history',
70
+ })
71
+ expect(scaffold.ctx.settings.get('llm-deepseek')).toMatchObject({ protocol: 'messages' })
72
+ expect(settings).not.toContain('sk-e2e-')
73
+ const credentials = await readFile(join(scaffold.harnessHome, '.credentials.yaml'), 'utf8')
74
+ expect(credentials).toContain('DEEPSEEK_API_KEY: sk-e2e-messages')
75
+ expect(credentials).not.toContain('DEEPSEEK_MESSAGES_API_KEY')
76
+ expect(await page.locator('body').innerText()).not.toContain('sk-e2e-')
77
+ await page.keyboard.press('Escape')
78
+ await connectFreshWorkspaceZh(page, scaffold.workspaceCwd, 'messages-settings-e2e')
79
+ await page.getByRole('button', { name: /^选择模型/ }).click()
80
+ await page.getByRole('menuitem', { name: /模型/ }).click()
81
+ await page.getByRole('menuitemradio', { name: 'Messages Flash', exact: true }).waitFor()
82
+ await compareOrRefreshGolden(join(EXPECTED, 'picker.expected.md'),
83
+ await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd), webSnapshotMode())
84
+ expect(tripwire.pageErrors).toEqual([])
85
+ }, 60_000)
86
+
87
+ it('keeps a saved Chat Completions selection available after the YAML protocol switch', async () => {
88
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-deepseek-messages-default'))
89
+ await page.keyboard.press('Escape')
90
+ await scaffold.ctx.agentDefaultModel.saveSelection({ provider: 'deepseek-official', model: 'deepseek-v4-flash' })
91
+ await page.reload({ waitUntil: 'load' })
92
+ const input = page.locator('[data-composer-input]').first()
93
+ await expect.poll(() => input.isEnabled()).toBe(true)
94
+ await page.getByRole('button', { name: /^选择模型/ }).click()
95
+ await page.getByRole('menuitem', { name: /模型/ }).click()
96
+ await page.getByRole('menuitemradio', { name: 'Messages Flash', exact: true }).click()
97
+ await expect.poll(() => input.isEnabled()).toBe(true)
98
+ await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().provider).toBe('deepseek-official')
99
+ const settings = await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')
100
+ expect(settings).toContain('provider: deepseek-official')
101
+ expect(tripwire.pageErrors).toEqual([])
102
+ }, 60_000)
103
+ })
apps/web/tests/home-path-tilde.expected.e2e.ts ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @vitest-environment jsdom
2
+ // Assembled POSIX home-path display: the fixture Host home is `/home/fixture`
3
+ // and a second Workspace lives under it. The sidebar hover card must show
4
+ // `~/Documents/project` while copy still writes the full path.
5
+ import { mkdirSync, writeFileSync } from 'node:fs'
6
+ import { dirname, join } from 'node:path'
7
+ import { act, fireEvent, screen, waitFor, within } from '@testing-library/react'
8
+ import { describe, expect, it } from 'vitest'
9
+ import { installAssembledBootEnv, mountAssembledApp, REFRESHING_GOLDEN } from './assembled-boot.ts'
10
+
11
+ const EXPECTED = join(process.cwd(), 'apps/web/tests/expected/home-path-tilde/workspace-hover.expected.txt')
12
+
13
+ installAssembledBootEnv()
14
+
15
+ describe('assembled POSIX home-path display', () => {
16
+ it('shows the home-descendant Workspace path as ~ and copies the full path', async () => {
17
+ mountAssembledApp()
18
+
19
+ const tree = await screen.findByRole('tree', { name: 'Sessions' }, { timeout: 10_000 })
20
+ const group = (await within(tree).findAllByText('project'))
21
+ .map(el => el.closest<HTMLElement>('[role="treeitem"]'))
22
+ .find(el => el?.getAttribute('aria-expanded') !== null)
23
+ if (group == null) throw new Error('home-descendant Workspace group missing')
24
+
25
+ fireEvent.pointerEnter(group.parentElement as HTMLElement)
26
+ const hoverPath = await waitFor(() => {
27
+ const found = screen.getByText('~/Documents/project')
28
+ expect(found).toBeTruthy()
29
+ return found
30
+ }, { timeout: 2_000 })
31
+ expect(screen.queryByText('/home/fixture/Documents/project')).toBeNull()
32
+ const copy = screen.getByRole('button', { name: 'Copy: /home/fixture/Documents/project' })
33
+
34
+ const shape = [
35
+ `hover=${hoverPath.textContent}`,
36
+ `copy=${copy.getAttribute('aria-label')}`,
37
+ ].join('\n') + '\n'
38
+ if (REFRESHING_GOLDEN) {
39
+ mkdirSync(dirname(EXPECTED), { recursive: true })
40
+ writeFileSync(EXPECTED, shape)
41
+ }
42
+ await expect(shape).toMatchFileSnapshot(EXPECTED)
43
+ act(() => { fireEvent.pointerLeave(group.parentElement as HTMLElement) })
44
+ })
45
+ })
apps/web/tests/markdown-cjk-strong.e2e.ts ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { fileURLToPath } from 'node:url'
2
+ import type { Browser, Page } from 'playwright'
3
+ import { chromium } from 'playwright'
4
+ import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
5
+ import { createMessage, createUserMessage } from '@deepseek-ai/dsh-llm'
6
+ import { SESSION_FORMAT_VERSION, Session, SessionId } from '@deepseek-ai/dsh-session'
7
+ import type {} from '@deepseek-ai/dsh-session-title'
8
+ import {
9
+ assertFixtureInventory,
10
+ captureStableAria,
11
+ compareOrRefreshGolden,
12
+ launchWebScaffold,
13
+ seedSession,
14
+ watchConsole,
15
+ webSnapshotMode,
16
+ type WebScaffold,
17
+ } from './scaffold.ts'
18
+ import { newEnglishPage, saveFailureShot } from './support.ts'
19
+
20
+ const SNAPSHOT_DIR = fileURLToPath(new URL('./expected/markdown-cjk-strong', import.meta.url))
21
+ const UI_EXPECTED = fileURLToPath(new URL('./expected/markdown-cjk-strong/ui.expected.md', import.meta.url))
22
+ const MODE = webSnapshotMode()
23
+ const SEED_ID = 'markdown-cjk-strong-web-e2e'
24
+ const DONE = 'CJK_STRONG_DONE'
25
+ const CASES = [
26
+ ['**注意:**内容', '注意:', '注意:内容'],
27
+ ['**Notice:**内容', 'Notice:', 'Notice:内容'],
28
+ ['**事件中间件(waterfall)**实现', '事件中间件(waterfall)', '事件中间件(waterfall)实现'],
29
+ ['**事件中间件(waterfall)**实现', '事件中间件(waterfall)', '事件中间件(waterfall)实现'],
30
+ ['**句号。**后续', '句号。', '句号。后续'],
31
+ ['**Period.**后续', 'Period.', 'Period.后续'],
32
+ ['**提醒!**继续', '提醒!', '提醒!继续'],
33
+ ['**Warning!**继续', 'Warning!', 'Warning!继续'],
34
+ ] as const
35
+
36
+ /** Build one settled assistant reply covering CJK-adjacent strong punctuation boundaries. */
37
+ function markdownFixture(): string {
38
+ const session = Session.create(SessionId('markdown-cjk-strong-source'))
39
+ const eventTimeOrigin = new Date().setHours(12, 0, 0, 0)
40
+ session.append('turn/start', { turn: 1 })
41
+ const user = session.append('user/message', createUserMessage({
42
+ content: [{ type: 'text', text: 'Render adjacent CJK strong emphasis.' }],
43
+ source: { kind: 'user' },
44
+ }), { surfaceOp: 'append' })
45
+ session.append('session/title', {
46
+ title: 'CJK strong emphasis',
47
+ messageSeqs: [user.seq],
48
+ source: { kind: 'fallback' },
49
+ })
50
+ session.append('step/start', { turn: 1, step: 1 })
51
+ session.append('assistant/message', {
52
+ stream: [],
53
+ turn: 1,
54
+ step: 1,
55
+ message: createMessage({
56
+ role: 'assistant',
57
+ content: [{
58
+ type: 'text',
59
+ text: [
60
+ '## CJK strong emphasis',
61
+ '',
62
+ ...CASES.flatMap(([markdown]) => [markdown, '']),
63
+ DONE,
64
+ ].join('\n'),
65
+ }],
66
+ source: { kind: 'model', provider: 'fixture', model: 'fixture' },
67
+ }),
68
+ }, { surfaceOp: 'append' })
69
+ session.append('step/end', { turn: 1, step: 1 })
70
+ session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
71
+
72
+ return [
73
+ JSON.stringify({
74
+ type: 'session',
75
+ version: SESSION_FORMAT_VERSION,
76
+ id: '{{sessionId}}',
77
+ createdAt: 0,
78
+ cwd: '{{cwd}}',
79
+ isSeeded: false,
80
+ delegationDepth: 0,
81
+ }),
82
+ ...session.snapshotEvents().map(event => JSON.stringify({
83
+ ...event,
84
+ time: eventTimeOrigin + event.seq * 1_000,
85
+ })),
86
+ '',
87
+ ].join('\n')
88
+ }
89
+
90
+ describe('web e2e: CJK-adjacent Markdown strong emphasis', () => {
91
+ let scaffold: WebScaffold
92
+ let browser: Browser
93
+ let page: Page
94
+ let tripwire: ReturnType<typeof watchConsole>
95
+
96
+ beforeAll(async () => {
97
+ scaffold = await launchWebScaffold({})
98
+ await seedSession(scaffold, markdownFixture(), SEED_ID)
99
+ browser = await chromium.launch()
100
+ page = await newEnglishPage(browser)
101
+ tripwire = watchConsole(page)
102
+ await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
103
+ await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
104
+ }, 120_000)
105
+
106
+ afterAll(async () => {
107
+ await browser?.close()
108
+ await scaffold?.close()
109
+ })
110
+
111
+ it.skipIf(MODE === 'record')('renders punctuation-terminated strong spans before adjacent CJK text', async () => {
112
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-markdown-cjk-strong'))
113
+ const groupRow = page.locator('[role="treeitem"]').first()
114
+ await groupRow.waitFor({ timeout: 15_000 })
115
+ await groupRow.click()
116
+ const sessionRow = page.locator('[role="treeitem"]').nth(1)
117
+ await sessionRow.waitFor({ timeout: 10_000 })
118
+ await sessionRow.click()
119
+ await expect.poll(() => page.getByText(DONE, { exact: true }).count(), { timeout: 15_000 }).toBe(1)
120
+
121
+ const strong = page.locator('[class*="markdown"] strong')
122
+ await expect.poll(() => strong.count(), { timeout: 10_000 }).toBe(CASES.length)
123
+ expect(await strong.allTextContents()).toEqual(CASES.map(([, expected]) => expected))
124
+ for (const [, , paragraph] of CASES) {
125
+ expect(await page.getByText(paragraph, { exact: true }).count()).toBe(1)
126
+ }
127
+
128
+ const snapshot = (await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd))
129
+ .split(SEED_ID).join('{{seededId}}')
130
+ await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE)
131
+ expect(tripwire.pageErrors).toEqual([])
132
+ expect(tripwire.warnings).toEqual([])
133
+ await assertFixtureInventory(SNAPSHOT_DIR, ['ui.expected.md'])
134
+ }, 60_000)
135
+ })
apps/web/tests/max-tokens-notice.expected.e2e.ts ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @vitest-environment jsdom
2
+ // Assembled max-tokens snapshot: boots the real built `packages/client/*/lib/
3
+ // client.js` bundles through AppWebEntry's ModuleLoader path against the
4
+ // keyless RemoteMock transport, opens the fixture session, and pins the
5
+ // surface its max-tokens turn (72) reaches — the turn-end notice row that a
6
+ // provider output-cap truncation must render instead of ending silently.
7
+ //
8
+ // The dot state is pinned beside the copy on purpose: `dot=warning` is what
9
+ // distinguishes this notice from the error row, so a regression that routes
10
+ // max-tokens through the turn-error presentation changes this file even when
11
+ // its own copy still renders.
12
+ import { mkdirSync, writeFileSync } from 'node:fs'
13
+ import { dirname, join } from 'node:path'
14
+ import { fireEvent, screen, waitFor, within } from '@testing-library/react'
15
+ import { describe, expect, it } from 'vitest'
16
+ import { hasClass, installAssembledBootEnv, mountAssembledApp, REFRESHING_GOLDEN } from './assembled-boot.ts'
17
+
18
+ const EXPECTED = join(process.cwd(), 'apps/web/tests/expected/max-tokens-notice/history-turn.expected.txt')
19
+
20
+ installAssembledBootEnv()
21
+
22
+ /** Normalize the notice row to stable fields: its dot state, title, and hint. */
23
+ function noticeShape(row: Element): string {
24
+ const first = (name: string): string =>
25
+ [...row.querySelectorAll('*')].filter(el => hasClass(el, name))[0]?.textContent?.trim() ?? '<absent>'
26
+ return [
27
+ `dot=${row.querySelector('[data-state]')?.getAttribute('data-state') ?? '<absent>'}`,
28
+ `title=${first('maxTokensTitle')}`,
29
+ `hint=${first('turnErrorMessage')}`,
30
+ ].join('\n')
31
+ }
32
+
33
+ describe('assembled max-tokens turn-end notice', () => {
34
+ it('renders the localized truncation notice after the cut-off answer instead of ending silently', async () => {
35
+ mountAssembledApp()
36
+
37
+ const tree = await screen.findByRole('tree', { name: 'Sessions' }, { timeout: 10_000 })
38
+ fireEvent.click(await within(tree).findByText('Fixture 历史会话'))
39
+ // The truncated answer itself stays in the flow: the notice supplements the
40
+ // partial output, it never replaces it.
41
+ await screen.findByText(/条目 3:这一条写到一半被/, undefined, { timeout: 10_000 })
42
+ const row = await waitFor(() => {
43
+ const found = [...document.querySelectorAll('[role="status"]')]
44
+ .find(candidate => [...candidate.querySelectorAll('*')].some(el => hasClass(el, 'maxTokensTitle')))
45
+ expect(found).not.toBeUndefined()
46
+ return found!
47
+ }, { timeout: 10_000 })
48
+
49
+ const shape = noticeShape(row)
50
+ if (REFRESHING_GOLDEN) {
51
+ mkdirSync(dirname(EXPECTED), { recursive: true })
52
+ writeFileSync(EXPECTED, shape)
53
+ }
54
+ await expect(shape).toMatchFileSnapshot(EXPECTED)
55
+ })
56
+ })
apps/web/tests/navigation-panes.e2e.ts ADDED
@@ -0,0 +1,529 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Web e2e scenarios: navigation & panes — the Trajectory view and timing
2
+ // overview, its local details inspector, and sidebar search, all over ONE rich
3
+ // two-turn seeded fixture rendered purely from the log (the seeded-history
4
+ // pattern: zero model calls in replay, so every surface here is the client
5
+ // fold + host history RPC, not replay binding). The seed is recorded live
6
+ // under the standard discipline: turn 1 produces a bash call plus two
7
+ // parallel reads in one assistant message (tool-call density for the
8
+ // trajectory ledger/timing lanes), turn 2 a markdown-rich reply.
9
+ import { mkdir, readFile, writeFile } from 'node:fs/promises'
10
+ import { fileURLToPath } from 'node:url'
11
+ import { join } from 'node:path'
12
+ import type { Browser, Page, Response } from 'playwright'
13
+ import { chromium } from 'playwright'
14
+ import { strFromU8, unzipSync } from 'fflate'
15
+ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, onTestFailed } from 'vitest'
16
+ import { parseSessionLog } from '@deepseek-ai/dsh-llm-replay'
17
+ import { SESSION_FORMAT_VERSION, type SessionEvent } from '@deepseek-ai/dsh-session'
18
+ import {
19
+ assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts,
20
+ launchWebScaffold, recordFixture, seedSession, watchConsole, webSnapshotMode, type WebScaffold,
21
+ } from './scaffold.ts'
22
+ import { expandOwningTurnProcess, newEnglishPage, saveFailureShot } from './support.ts'
23
+
24
+ const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/navigation-panes', import.meta.url))
25
+ const SEED = join(SNAPSHOT_DIR, 'session.v3.jsonl')
26
+ const TRAJECTORY_EXPECTED = join(SNAPSHOT_DIR, 'trajectory.expected.md')
27
+ const TIMING_EXPECTED = join(SNAPSHOT_DIR, 'timing.expected.md')
28
+ const SEARCH_EXPECTED = join(SNAPSHOT_DIR, 'search-results.expected.md')
29
+ const TERMINAL_EXPECTED = join(SNAPSHOT_DIR, 'terminal-card.expected.md')
30
+ const MODE = webSnapshotMode()
31
+ const SEED_ID = 'navigation-panes-web-e2e'
32
+ const EXPORTED_LOG_FILE = `session.v${SESSION_FORMAT_VERSION}.jsonl`
33
+
34
+ // Turn 1 leads with a distinctive word: the session-title fallback takes the
35
+ // first words of the first message, so the sidebar-search scenario has a
36
+ // known-matching query ('navscenario') without depending on a live title call.
37
+ const PROMPT_TURN1 = 'NavScenario: first run bash to print exactly NAVIGATION_OK, then read nav-a.md and nav-b.md using two read calls in ONE assistant message, then reply with the single word FIRST_DONE and stop.'
38
+ const PROMPT_TURN2 = 'Reply in markdown with: a level-2 heading "Navigation Summary", a bulleted list of exactly two items, and a fenced code block containing echo WATERFALL. Then stop.'
39
+
40
+ async function baselineResponse(
41
+ page: Page,
42
+ ): Promise<Response> {
43
+ return page.waitForResponse(response => (
44
+ response.request().method() === 'POST'
45
+ && new URL(response.url()).pathname === '/api/session/list'
46
+ ), { timeout: 30_000 })
47
+ }
48
+
49
+ async function assertBaselineSucceeded(response: Response, method: string): Promise<void> {
50
+ expect(response.ok(), `${method} baseline HTTP response`).toBe(true)
51
+ const body = await response.json() as { result?: { ok?: unknown } }
52
+ expect(body.result?.ok, `${method} baseline RPC result`).toBe(true)
53
+ }
54
+
55
+ async function ensureSeedOpen(page: Page): Promise<void> {
56
+ const welcome = page.locator('[class*="onboardingOverlay"]')
57
+ if (await welcome.count() > 0) {
58
+ await welcome.getByRole('button').click()
59
+ await welcome.waitFor({ state: 'detached', timeout: 15_000 })
60
+ }
61
+ const chat = page.getByRole('tab', { name: 'Chat', exact: true })
62
+ // Search is a collapsed header action; expand it so the input is actionable.
63
+ const searchButton = page.getByRole('button', { name: 'Search sessions' })
64
+ if (await searchButton.getAttribute('aria-expanded') !== 'true') await searchButton.click()
65
+ const search = page.getByPlaceholder('Search sessions', { exact: false })
66
+ if (await chat.count() === 0) {
67
+ await search.fill('WATERFALL')
68
+ const result = page.getByRole('tree', { name: 'Search results' }).getByRole('treeitem')
69
+ await expect.poll(() => result.count(), { timeout: 15_000 }).toBe(1)
70
+ await result.click()
71
+ await chat.waitFor({ timeout: 15_000 })
72
+ }
73
+ await chat.click()
74
+ await page.getByText('FIRST_DONE', { exact: true }).waitFor({ timeout: 15_000 })
75
+ if (await search.inputValue() !== '') {
76
+ await search.fill('')
77
+ await expect.poll(() => search.inputValue(), { timeout: 5_000 }).toBe('')
78
+ }
79
+ }
80
+
81
+ describe('web e2e: navigation & panes over a rich seeded session', () => {
82
+ let scaffold: WebScaffold
83
+ let browser: Browser
84
+ let page: Page
85
+ let tripwire: ReturnType<typeof watchConsole> = { warnings: [], pageErrors: [] }
86
+ let slotErrors: string[] = []
87
+
88
+ beforeAll(async () => {
89
+ scaffold = await launchWebScaffold({})
90
+ // The workspace-aware flow runs sessions in <workspaceCwd>/workspace;
91
+ // the read targets must live in that session cwd (pre-creation is safe
92
+ // because the picker adopts an existing directory by path).
93
+ const sessionCwd = join(scaffold.workspaceCwd, 'workspace')
94
+ await mkdir(sessionCwd, { recursive: true })
95
+ await writeFile(join(sessionCwd, 'nav-a.md'), '# alpha nav\n')
96
+ await writeFile(join(sessionCwd, 'nav-b.md'), '# beta nav\n')
97
+ if (MODE !== 'record') {
98
+ const raw = await readFile(SEED, 'utf8')
99
+ expect(fixtureUserPrompts(raw), 'seed fixture must carry exactly the two drive prompts')
100
+ .toEqual([PROMPT_TURN1, PROMPT_TURN2])
101
+ // The inspector's calendar date must not depend on the day the test runs.
102
+ await seedSession(scaffold, raw, SEED_ID, undefined, { createdAt: Date.UTC(2026, 0, 1) })
103
+ }
104
+ browser = await chromium.launch()
105
+ }, 120_000)
106
+
107
+ beforeEach(async () => {
108
+ page = await newEnglishPage(browser)
109
+ tripwire = watchConsole(page)
110
+ slotErrors = []
111
+ page.on('console', (message) => {
112
+ if (message.type() === 'error' && /slot entry crashed/i.test(message.text())) {
113
+ slotErrors.push(message.text())
114
+ }
115
+ })
116
+ // Arm before navigation so the Session response cannot be missed. The
117
+ // Workspace stream settles through the user-visible Ungrouped barrier.
118
+ const sessionBaseline = baselineResponse(page)
119
+ const [, sessionResponse] = await Promise.all([
120
+ page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }),
121
+ sessionBaseline,
122
+ ])
123
+ await assertBaselineSucceeded(sessionResponse, 'session.list')
124
+ await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
125
+ // The frame mounts before the asynchronous session-list baseline lands.
126
+ // Search must target the settled seeded row, not the startup input that
127
+ // the ready projection replaces (the compact layout dropped group session
128
+ // counts; the Ungrouped bucket row is the barrier).
129
+ await page.getByText('Ungrouped', { exact: true }).waitFor({ timeout: 30_000 })
130
+ }, 120_000)
131
+
132
+ afterEach(async () => {
133
+ const failures: unknown[] = []
134
+ try {
135
+ expect({
136
+ pageErrors: tripwire.pageErrors,
137
+ slotErrors,
138
+ warnings: tripwire.warnings,
139
+ }).toEqual({
140
+ pageErrors: [],
141
+ slotErrors: [],
142
+ warnings: [],
143
+ })
144
+ } catch (error) {
145
+ failures.push(error)
146
+ }
147
+ await page?.close().catch((error: unknown) => failures.push(error))
148
+ if (failures.length === 1) throw failures[0]
149
+ if (failures.length > 1) throw new AggregateError(failures, 'navigation case cleanup failed')
150
+ })
151
+
152
+ afterAll(async () => {
153
+ const failures: unknown[] = []
154
+ await browser?.close().catch((error: unknown) => failures.push(error))
155
+ await scaffold?.close().catch((error: unknown) => failures.push(error))
156
+ if (failures.length === 1) throw failures[0]
157
+ if (failures.length > 1) throw new AggregateError(failures, 'navigation e2e cleanup failed')
158
+ })
159
+
160
+ it.skipIf(MODE !== 'record')('records the two-turn seed live through the composer', async () => {
161
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-navigation-record'))
162
+ const input = page.locator('[data-composer-input]').first()
163
+ await input.waitFor({ timeout: 10_000 })
164
+ let sessionId: Awaited<ReturnType<WebScaffold['whenTurnSettled']>> | undefined
165
+ for (const prompt of [PROMPT_TURN1, PROMPT_TURN2]) {
166
+ const settled = scaffold.whenTurnSettled()
167
+ // Turn 2 types into the same composer once turn 1 unlocks it.
168
+ await expect.poll(() => input.isEnabled(), { timeout: 15_000 }).toBe(true)
169
+ await input.fill(prompt)
170
+ await input.press('Enter')
171
+ sessionId = await settled
172
+ }
173
+ await recordFixture(scaffold, sessionId!, SEED)
174
+ // Fixture honesty: the recording must contain the events the replay
175
+ // scenarios assert on: three calls in turn 1 and two closed turns.
176
+ const recorded = parseSessionLog(await readFile(SEED, 'utf8'))
177
+ expect(recorded.filter(e => e.type === 'turn/end')).toHaveLength(2)
178
+ const calls = recorded.filter((e): e is SessionEvent & { data: { name: string } } => e.type === 'tool/call')
179
+ expect(calls.map(e => e.data.name).sort()).toEqual(['bash', 'read', 'read'])
180
+ }, 400_000)
181
+
182
+ it.skipIf(MODE === 'record')('finds an unopened seeded session by message content and opens it', async () => {
183
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-navigation-search'))
184
+ // The API baselines can settle before React commits their projection. The
185
+ // seeded Ungrouped bucket row is the final user-visible barrier before
186
+ // editing search (the compact layout dropped group session counts).
187
+ await page.getByText('Ungrouped', { exact: true }).waitFor({ timeout: 30_000 })
188
+ // Search is a collapsed header action; expand it so the input is actionable.
189
+ const searchButton = page.getByRole('button', { name: 'Search sessions' })
190
+ if (await searchButton.getAttribute('aria-expanded') !== 'true') await searchButton.click()
191
+ const search = page.getByPlaceholder('Search sessions', { exact: false })
192
+ // The cold row has not been opened, so only the persisted log can satisfy
193
+ // this query. First search lazily reconciles the SQLite content index.
194
+ await search.fill('zzzqx-no-such-session')
195
+ await page.getByText('No matching sessions').waitFor({ timeout: 30_000 })
196
+ await expect.poll(
197
+ () => page.getByRole('tree', { name: 'Search results' }).getByRole('treeitem').count(),
198
+ { timeout: 10_000 },
199
+ ).toBe(0)
200
+
201
+ await search.fill('WATERFALL')
202
+ const resultTree = page.getByRole('tree', { name: 'Search results' })
203
+ const result = resultTree.getByRole('treeitem')
204
+ await expect.poll(() => result.count(), { timeout: 30_000 }).toBe(1)
205
+ await expect.poll(() => result.getByText('WATERFALL', { exact: false }).count(), {
206
+ timeout: 10_000,
207
+ }).toBeGreaterThanOrEqual(1)
208
+ const snapshot = (await captureStableAria(page, '[class*="listArea"]', scaffold.workspaceCwd))
209
+ .split(SEED_ID).join('{{seededId}}')
210
+ await compareOrRefreshGolden(SEARCH_EXPECTED, snapshot, MODE)
211
+
212
+ await result.click()
213
+ // Search navigation returns to the browser with the opened Session row exposed.
214
+ await expect.poll(() => search.inputValue(), { timeout: 5_000 }).toBe('')
215
+ const selectedRow = page.locator('[role="tree"][aria-label="Sessions"] [role="treeitem"][aria-selected="true"]')
216
+ await expect.poll(() => selectedRow.count(), { timeout: 10_000 }).toBe(1)
217
+ await expect.poll(() => page.getByText('FIRST_DONE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1)
218
+ await expect.poll(() => page.getByRole('heading', { name: 'Navigation Summary' }).count(), { timeout: 15_000 }).toBe(1)
219
+ }, 90_000)
220
+
221
+ it.skipIf(MODE === 'record')('renders the trajectory ledger and opens its local record inspector', async () => {
222
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-navigation-trajectory'))
223
+ await ensureSeedOpen(page)
224
+ await page.getByRole('tab', { name: 'Trajectory' }).click()
225
+ await page.waitForTimeout(100)
226
+ const overlayLayout = await page.getByRole('table').evaluate((table) => {
227
+ const host = table.closest('[data-conversation-scroll]')
228
+ const seat = host?.querySelector('[data-composer-seat]') ?? null
229
+ const pane = table.parentElement
230
+ return {
231
+ hostPosition: host === null ? null : getComputedStyle(host).position,
232
+ paneOverflowX: pane === null ? null : getComputedStyle(pane).overflowX,
233
+ paneScrollableWidth: pane === null ? null : pane.scrollWidth - pane.clientWidth,
234
+ seatPosition: seat === null ? null : getComputedStyle(seat).position,
235
+ }
236
+ })
237
+ expect(overlayLayout).toEqual({
238
+ hostPosition: 'relative',
239
+ paneOverflowX: 'hidden',
240
+ paneScrollableWidth: 0,
241
+ seatPosition: 'absolute',
242
+ })
243
+ expect({
244
+ pageErrors: tripwire.pageErrors,
245
+ slotErrors,
246
+ warnings: tripwire.warnings,
247
+ }).toEqual({
248
+ pageErrors: [],
249
+ slotErrors: [],
250
+ warnings: [],
251
+ })
252
+ // Turn rules partition the ledger without restoring a separate header row.
253
+ await expect.poll(() => page.locator('tr[data-turn-start="true"]').count(), { timeout: 15_000 }).toBe(2)
254
+ await expect.poll(() => page.getByRole('columnheader').count(), { timeout: 10_000 }).toBe(0)
255
+ await page.locator('tr[data-kind="tool"]').first().click()
256
+ const details = page.getByRole('complementary', { name: 'Event details' })
257
+ await expect.poll(() => details.count(), { timeout: 10_000 }).toBe(1)
258
+ expect(await details.getByRole('tabpanel').evaluate(panel => getComputedStyle(panel).overflowX))
259
+ .toBe('hidden')
260
+ await page.evaluate(() => { document.body.setAttribute('data-ds-dark-theme', '') })
261
+ const darkSummarySurfaces = await details.getByRole('heading', { name: 'Payload' }).evaluate(heading => ({
262
+ heading: getComputedStyle(heading).backgroundColor,
263
+ panel: getComputedStyle(heading.closest('[aria-label="Event details"]')!).backgroundColor,
264
+ }))
265
+ expect(darkSummarySurfaces.heading).toBe(darkSummarySurfaces.panel)
266
+ await page.evaluate(() => { document.body.removeAttribute('data-ds-dark-theme') })
267
+ await page.getByRole('tab', { name: 'Result' }).click()
268
+ await expect.poll(() => page.getByText('NAVIGATION_OK', { exact: false }).count(), { timeout: 10_000 }).toBeGreaterThanOrEqual(1)
269
+ expect(await page.locator('[data-timeline-span="message"][data-assistant-timing="true"]').count()).toBeGreaterThan(0)
270
+ const snapshot = (await captureStableAria(page, '[class*="viewArea"]', scaffold.workspaceCwd))
271
+ .split(SEED_ID).join('{{seededId}}')
272
+ await compareOrRefreshGolden(TRAJECTORY_EXPECTED, snapshot, MODE)
273
+ await details.getByRole('button', { name: 'Close details' }).click()
274
+ }, 60_000)
275
+
276
+ it.skipIf(MODE === 'record')('restores Assistant timing from recorded history', async () => {
277
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-navigation-timing'))
278
+ await ensureSeedOpen(page)
279
+ await page.getByRole('tab', { name: 'Trajectory' }).click()
280
+ await page.getByRole('button', { name: 'Request #1', exact: true }).click()
281
+ const details = page.getByRole('complementary', { name: 'Event details' })
282
+ await details.getByRole('tab', { name: 'Timing', exact: true }).click()
283
+ const panel = details.getByRole('tabpanel', { name: 'Timing' })
284
+ for (const metric of ['TTFT', 'Generation', 'Throughput']) {
285
+ const value = panel.getByText(metric, { exact: true }).locator('..').locator('dd')
286
+ await expect.poll(() => value.textContent()).toMatch(/^\d/)
287
+ }
288
+ expect(await panel.getByText('First token unavailable', { exact: true }).count()).toBe(0)
289
+ const snapshot = await captureStableAria(page, '#trajectory-detail-panel', scaffold.workspaceCwd)
290
+ await compareOrRefreshGolden(TIMING_EXPECTED, snapshot, MODE)
291
+ }, 60_000)
292
+
293
+ it.skipIf(MODE === 'record')('downloads through the Session Header and /export with one dialog', async () => {
294
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-navigation-export'))
295
+ await ensureSeedOpen(page)
296
+ const exportButton = page.getByRole('button', { name: 'More actions' })
297
+ expect(await exportButton.isDisabled()).toBe(false)
298
+ const header = exportButton.locator('xpath=ancestor::header[1]')
299
+ // The right Sidebar's expand button holds the header's corner; the export
300
+ // control sits immediately to its left.
301
+ const sidebarButton = page.getByRole('button', { name: 'Open right sidebar' })
302
+ const [buttonBox, sidebarBox, headerBox] = await Promise.all([
303
+ exportButton.boundingBox(), sidebarButton.boundingBox(), header.boundingBox(),
304
+ ])
305
+ if (buttonBox === null || sidebarBox === null || headerBox === null) {
306
+ throw new Error('Session Header export geometry is unavailable')
307
+ }
308
+ expect(headerBox.x + headerBox.width - (sidebarBox.x + sidebarBox.width)).toBeLessThanOrEqual(32)
309
+ expect(sidebarBox.x - (buttonBox.x + buttonBox.width)).toBeLessThanOrEqual(32)
310
+ const responsePromise = page.waitForResponse(response =>
311
+ response.request().method() === 'HEAD'
312
+ && new URL(response.url()).pathname === '/api/session.export', { timeout: 30_000 })
313
+ const downloadPromise = page.waitForEvent('download', { timeout: 30_000 })
314
+ await exportButton.click()
315
+ await page.getByRole('menuitem', { name: 'Download session log' }).click()
316
+ const response = await responsePromise
317
+ expect(response.status()).toBe(200)
318
+ const download = await downloadPromise
319
+ expect(download.suggestedFilename()).toMatch(/^dsh-session-.+\.zip$/)
320
+ const dialog = page.getByRole('dialog', { name: 'Session download started' })
321
+ await dialog.waitFor({ timeout: 30_000 })
322
+ // The real host streamed the ZIP; its root entry is the persisted log
323
+ // text verbatim (the assembled seam: real route, real persistence read).
324
+ const files = unzipSync(await readFile(await download.path()))
325
+ expect(Object.keys(files)).toEqual([EXPORTED_LOG_FILE])
326
+ const content = strFromU8(files[EXPORTED_LOG_FILE] as Uint8Array)
327
+ expect(JSON.parse(content.split('\n')[0] ?? '')).toMatchObject({
328
+ type: 'session', version: SESSION_FORMAT_VERSION,
329
+ })
330
+ expect(content.split('\n')[0]).toContain(SEED_ID)
331
+ expect(content).toContain('FIRST_DONE')
332
+ await dialog.getByText('Close', { exact: true }).click()
333
+
334
+ const observer = await newEnglishPage(browser)
335
+ const observerTripwire = watchConsole(observer)
336
+ const observerSlotErrors: string[] = []
337
+ let observerDownloads = 0
338
+ observer.on('download', () => { observerDownloads += 1 })
339
+ observer.on('console', (message) => {
340
+ if (message.type() === 'error' && /slot entry crashed/i.test(message.text())) {
341
+ observerSlotErrors.push(message.text())
342
+ }
343
+ })
344
+ const observerSessionBaseline = baselineResponse(observer)
345
+ const [, observerSessionResponse] = await Promise.all([
346
+ observer.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }),
347
+ observerSessionBaseline,
348
+ ])
349
+ await assertBaselineSucceeded(observerSessionResponse, 'observer session.list')
350
+ await observer.getByText('Ungrouped', { exact: true }).waitFor({ timeout: 30_000 })
351
+ await ensureSeedOpen(observer)
352
+
353
+ try {
354
+ const input = page.locator('[data-composer-input]').first()
355
+ const slashDownloadPromise = page.waitForEvent('download', { timeout: 30_000 })
356
+ await input.fill('/export')
357
+ await page.getByRole('option', { name: /^Export/u }).waitFor({ timeout: 10_000 })
358
+ await input.press('Enter')
359
+ const slashDownload = await slashDownloadPromise
360
+ expect(slashDownload.suggestedFilename()).toBe(download.suggestedFilename())
361
+ const slashFiles = unzipSync(await readFile(await slashDownload.path()))
362
+ expect(Object.keys(slashFiles)).toEqual([EXPORTED_LOG_FILE])
363
+ const slashContent = strFromU8(slashFiles[EXPORTED_LOG_FILE] as Uint8Array)
364
+ expect(JSON.parse(slashContent.split('\n')[0] ?? '')).toMatchObject({
365
+ type: 'session', version: SESSION_FORMAT_VERSION,
366
+ })
367
+ const slashEvents = parseSessionLog(slashContent)
368
+ const exportRun = slashEvents.findLast(event => event.type === 'command/run' && event.data.name === 'export')
369
+ if (exportRun?.type !== 'command/run') throw new Error('slash ZIP has no export command/run')
370
+ const exportDone = slashEvents.find(event =>
371
+ event.type === 'command/done' && event.data.commandId === exportRun.data.commandId)
372
+ expect(exportDone?.type).toBe('command/done')
373
+ await page.getByRole('dialog', { name: 'Session download started' }).waitFor({ timeout: 30_000 })
374
+ await page.getByRole('dialog', { name: 'Session download started' })
375
+ .getByText('Close', { exact: true }).click()
376
+ await observer.getByText('Session log download requested.', { exact: true }).waitFor({ timeout: 30_000 })
377
+ expect(observerDownloads).toBe(0)
378
+ expect(await observer.getByRole('dialog', { name: 'Session download started' }).count()).toBe(0)
379
+ expect({
380
+ pageErrors: observerTripwire.pageErrors,
381
+ slotErrors: observerSlotErrors,
382
+ warnings: observerTripwire.warnings,
383
+ }).toEqual({ pageErrors: [], slotErrors: [], warnings: [] })
384
+ } finally {
385
+ await observer.close()
386
+ }
387
+ }, 120_000)
388
+
389
+ it.skipIf(MODE === 'record')('focuses the ledger by dragging an overview interval', async () => {
390
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-navigation-timeline'))
391
+ await ensureSeedOpen(page)
392
+ await page.getByRole('tab', { name: 'Trajectory' }).click()
393
+ const plot = page.getByLabel('Timeline overview; drag horizontally to focus events')
394
+ await plot.waitFor({ timeout: 15_000 })
395
+ const before = await page.locator('tr[data-kind]').count()
396
+ const box = await plot.boundingBox()
397
+ if (box === null) throw new Error('trajectory timeline plot has no layout box')
398
+ await page.mouse.move(box.x + box.width * 0.55, box.y + box.height / 2)
399
+ await page.mouse.down()
400
+ await page.mouse.move(box.x + box.width * 0.9, box.y + box.height / 2)
401
+ await page.mouse.up()
402
+ await expect.poll(() => page.locator('tr[data-timeline-focus="outside"]').count(), { timeout: 10_000 })
403
+ .toBeGreaterThan(0)
404
+ await expect.poll(() => page.locator('tr[data-kind]').count(), { timeout: 10_000 }).toBe(before)
405
+ await plot.click({ button: 'right' })
406
+ await expect.poll(() => page.locator('tr[data-timeline-focus]').count(), { timeout: 10_000 }).toBe(0)
407
+ }, 60_000)
408
+
409
+ it.skipIf(MODE === 'record')('bash rows leave the right column at its rail; a file link opens the Sidebar', async () => {
410
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-navigation-rightbar'))
411
+ await ensureSeedOpen(page)
412
+ const bashRow = page.locator('[data-sample="bash"]').first()
413
+ await expandOwningTurnProcess(page, bashRow)
414
+ await bashRow.waitFor({ timeout: 15_000 })
415
+ const frame = page.locator('[style*="grid-template-columns"]').first()
416
+ expect(await frame.getAttribute('data-rightbar-collapsed')).toBe('true')
417
+ // The row click is the card's expand toggle (unified tool-row
418
+ // interaction); it must not drive layout geometry either way.
419
+ await bashRow.click()
420
+ await expect.poll(() => frame.getAttribute('data-rightbar-collapsed'), { timeout: 5_000 }).toBe('true')
421
+ // The card's own controls are outside the summary row and must not expand
422
+ // the right column either — the expanded terminal card is read in place.
423
+ await page.locator('[data-sample="bash"] ~ div [data-terminal] [class*="_copyButton_"]').first().click()
424
+ await expect.poll(() => frame.getAttribute('data-rightbar-collapsed'), { timeout: 5_000 }).toBe('true')
425
+ // Opening a file into the empty column creates only its preview tab.
426
+ const fileLink = page.locator('[data-variant="read"] button').first()
427
+ await fileLink.waitFor({ timeout: 10_000 })
428
+ await fileLink.click()
429
+ await expect.poll(() => frame.getAttribute('data-rightbar-collapsed'), { timeout: 5_000 }).toBe(null)
430
+ const column = page.locator('[data-rightbar-col]')
431
+ await expect.poll(() => column.locator('[data-dockkit-tab-title]').allTextContents(), { timeout: 5_000 }).toEqual(['nav-a.md'])
432
+ // Put the column back so later cases start from the default frame.
433
+ await column.locator('[data-sidebar-right-toggle]').click()
434
+ await expect.poll(() => frame.getAttribute('data-rightbar-collapsed'), { timeout: 5_000 }).toBe('true')
435
+ }, 60_000)
436
+
437
+ it.skipIf(MODE === 'record')('renders the bash row as a terminal card in the real browser', async () => {
438
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-navigation-terminal'))
439
+ await ensureSeedOpen(page)
440
+ // The card is expand-gated behind the whole-row toggle (the unified
441
+ // tool-row interaction): open it if this fresh view leaves it collapsed.
442
+ // Expanded, the recorded command's own output sits in the message flow,
443
+ // derived from the logged call/result presentations alone.
444
+ const bashRow = page.locator('[data-sample="bash"]').first()
445
+ await expandOwningTurnProcess(page, bashRow)
446
+ await bashRow.waitFor({ timeout: 15_000 })
447
+ if (await bashRow.getAttribute('aria-expanded') !== 'true') await bashRow.click()
448
+ const card = page.locator('[data-sample="bash"] ~ div [data-terminal]').first()
449
+ await card.waitFor({ timeout: 15_000 })
450
+ // Real layout, not jsdom's stub (which computes no geometry at all):
451
+ // squeeze the output pane below its content width and the line must keep
452
+ // its single row and overflow sideways instead of folding. Soft-wrapping
453
+ // here shreds the column alignment this card exists to hold.
454
+ const layout = await card.locator('[class*="_output_"]').first().evaluate((node) => {
455
+ const pane = node as HTMLElement
456
+ const row = pane.querySelector<HTMLElement>('[class*="_line_"]')
457
+ if (row === null) throw new Error('output pane has no line')
458
+ const before = row.offsetHeight
459
+ const restore = pane.style.width
460
+ pane.style.width = '8px'
461
+ const squeezed = { wrapped: row.offsetHeight > before, scrollsSideways: pane.scrollWidth > pane.clientWidth }
462
+ pane.style.width = restore
463
+ return { whiteSpace: getComputedStyle(row).whiteSpace, overflowX: getComputedStyle(pane).overflowX, ...squeezed }
464
+ })
465
+ expect(layout).toEqual({ whiteSpace: 'pre', overflowX: 'auto', wrapped: false, scrollsSideways: true })
466
+ // The run-state dot's color is the whole point of it and is the one thing
467
+ // jsdom cannot report: --dsw-* tokens resolve only against the real theme
468
+ // stylesheet. This command settled cleanly, so the dot must be the green
469
+ // success token — a red one here would read as a failed command.
470
+ const dot = await card.locator('[class*="_runState_"][data-state]').first().evaluate((node) => {
471
+ // The token lives on body, so the probe must sit in the same cascade.
472
+ const probe = document.createElement('span')
473
+ probe.style.color = 'var(--dsw-alias-state-success-primary)'
474
+ document.body.appendChild(probe)
475
+ const success = getComputedStyle(probe).color
476
+ probe.remove()
477
+ return {
478
+ state: node.getAttribute('data-state'),
479
+ color: getComputedStyle(node as HTMLElement).color,
480
+ success,
481
+ // One label per card (the state is the call's), so it hangs off the
482
+ // prompt column rather than the row the dot sits in.
483
+ label: node.closest('[class*="_prompt_"]')?.querySelector('[class*="_runStateLabel_"]')?.textContent ?? null,
484
+ // The dot precedes the prompt label in document order, which is what
485
+ // puts it to the left of the `$`.
486
+ beforePrompt: node.compareDocumentPosition(node.parentElement!.querySelector('[class*="_cwd_"]')!)
487
+ === Node.DOCUMENT_POSITION_FOLLOWING,
488
+ // The dot lives in the card's OWN left padding, so it sits inside the
489
+ // card box yet left of the prompt text. Owning the reservation as padding
490
+ // rather than margin is what keeps a consumer's own margin from
491
+ // cancelling it and letting a container clip the dot — geometry jsdom
492
+ // cannot compute.
493
+ insideCard: (node as HTMLElement).getBoundingClientRect().left
494
+ >= (node.closest('[data-terminal]')?.getBoundingClientRect().left ?? Infinity),
495
+ leftOfPrompt: (node as HTMLElement).getBoundingClientRect().right
496
+ <= (node.closest('[class*="_promptLine_"]')
497
+ ?.querySelector('[class*="_cwd_"]')
498
+ ?.getBoundingClientRect().left ?? -Infinity),
499
+ }
500
+ })
501
+ expect(dot.state).toBe('done')
502
+ expect(dot.label).toBe('Done')
503
+ expect(dot.beforePrompt).toBe(true)
504
+ expect(dot.insideCard).toBe(true)
505
+ expect(dot.leftOfPrompt).toBe(true)
506
+ // Resolved through the theme token, not a literal hex in the component.
507
+ expect(dot.success).toMatch(/^rgb/)
508
+ expect(dot.color).toBe(dot.success)
509
+ // Golden of the card at rest — captured before the copy click, whose
510
+ // confirmation label self-reverts on a timer and would not hold still.
511
+ const snapshot = (await captureStableAria(page, '[data-terminal]', scaffold.workspaceCwd))
512
+ .split(SEED_ID).join('{{seededId}}')
513
+ await compareOrRefreshGolden(TERMINAL_EXPECTED, snapshot, MODE)
514
+ // Copy writes the raw output through the browser's own clipboard, which in
515
+ // a real page is the async Clipboard API rather than the jsdom fallback.
516
+ await page.context().grantPermissions(['clipboard-read', 'clipboard-write'])
517
+ await card.locator('[class*="_copyButton_"]').first().click()
518
+ await expect.poll(() => card.locator('[class*="_copyButton_"]').first().textContent(), { timeout: 5_000 })
519
+ .toBe('Copied')
520
+ expect(await page.evaluate(() => navigator.clipboard.readText())).toContain('NAVIGATION_OK')
521
+ }, 60_000)
522
+
523
+ it.skipIf(MODE === 'record')('keeps the recorded fixture inventory exact', async () => {
524
+ await assertFixtureInventory(SNAPSHOT_DIR, [
525
+ 'session.v3.jsonl', 'search-results.expected.md', 'trajectory.expected.md',
526
+ 'terminal-card.expected.md', 'timing.expected.md',
527
+ ])
528
+ })
529
+ })
apps/web/tests/pin-browse-picker.overlay.yml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Loader overlay for the real-host smoke (`dsh web --patch`): pin the
2
+ # in-browser directory picker. The shipped row is `-auto`, which resolves to
3
+ # the native OS chooser on a loopback bind with a local display — an
4
+ # interaction a Playwright page cannot drive, so the resolved backend would
5
+ # otherwise decide whether the smoke passes. The disable+insert pair mirrors
6
+ # apps/web/tests/scaffold.ts.
7
+ - id: directory-picker
8
+ disabled: true
9
+ - insert:
10
+ - id: directory-picker-browse
11
+ name: '@deepseek-ai/dsh-host-directory-picker-browse'
12
+ - id: ui-directory-picker-browse
13
+ name: '@deepseek-ai/dsh-client-ui-directory-picker-browse'
apps/web/tests/present.overlay.yml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Native commands are owned fixtures; desktop availability must be identical in headless CI.
2
+ - id: session-controller
3
+ config:
4
+ nativeOpen: true
apps/web/tests/preview-boot.e2e.ts ADDED
@@ -0,0 +1,509 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Preview acceptance: the browser-only worker deployment boots the real Cordis
3
+ * tree out of the packed VFS image and reaches an interactive page.
4
+ *
5
+ * `dist/preview.html` is the served page plus one bootstrap script tag, so this
6
+ * run exercises the shipped startup chain: the worker mounts the image,
7
+ * activates the tree, and answers the page's tunnel until the client settles.
8
+ * Two milestones prove that happened — the host's `tree active` boot line,
9
+ * whose lowering contract must be the one this checkout's packer emits, and the
10
+ * workspace hero, which paints only after the client tree comes up over the
11
+ * tunnel. The same page opens the seeded Workspace and showcase Session,
12
+ * verifies its tool/subagent/history examples, then writes through the
13
+ * settings and credentials providers. That keeps the upstream Chokidar
14
+ * instances exercised over the Worker filesystem implementation.
15
+ *
16
+ * The site is served the way a static host serves it: bytes from `dist/` with
17
+ * no rewrite rules, so a missing file is a 404 rather than the index page.
18
+ */
19
+ import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
20
+ import { readFile } from 'node:fs/promises'
21
+ import { createServer } from 'node:http'
22
+ import type { IncomingMessage, ServerResponse } from 'node:http'
23
+ import { tmpdir } from 'node:os'
24
+ import { dirname, extname, join, normalize } from 'node:path'
25
+ import { fileURLToPath } from 'node:url'
26
+ import { chromium } from 'playwright'
27
+ import type { Browser } from 'playwright'
28
+ import { expect, it } from 'vitest'
29
+ import {
30
+ composeProfile, configTrees, indexWorkspacePackages, packVfsImage, packVfsOverlay,
31
+ previewFixtures, WRAPPER_CONTRACT,
32
+ } from '@deepseek-ai/dsh-experimental-webworker-packer'
33
+ import {
34
+ IMAGE_FILE_NAME, PREVIEW_FIXTURE_MANIFEST_FILE, PREVIEW_FIXTURE_MANIFEST_VERSION,
35
+ type PreviewFixtureManifest,
36
+ } from '@deepseek-ai/dsh-experimental-webworker-runtime'
37
+ import {
38
+ VFS_EXAMPLE_SESSION_IDS,
39
+ buildVfsExampleFiles,
40
+ } from '../../../packages/experimental/webworker-runtime/tests/vfs-example-fixture.ts'
41
+ import { captureStableAria, compareOrRefreshGolden, webSnapshotMode } from './scaffold.ts'
42
+ import { newEnglishPage, REPO_ROOT, saveFailureShot } from './support.ts'
43
+
44
+ const DIST_ROOT = fileURLToPath(new URL('../dist', import.meta.url))
45
+
46
+ /** Where the client looks for the image: the runtime's own name, beside the page. */
47
+ const IMAGE_FILE = join(DIST_ROOT, 'preview', IMAGE_FILE_NAME)
48
+
49
+ /** Keyless browser golden for the pre-Worker source chooser. */
50
+ const SOURCE_CHOOSER_EXPECTED = fileURLToPath(new URL('./snapshots/preview-boot/source-chooser.expected.md', import.meta.url))
51
+
52
+ const SNAPSHOT_MODE = webSnapshotMode()
53
+
54
+ /** Profile the preview deployment composes; `build:preview` packs the same one. */
55
+ const PROFILE = 'web'
56
+
57
+ /** Stable labels authored by the deterministic VFS example fixture. */
58
+ const SHOWCASE_TITLE = 'WebWorker Preview Showcase'
59
+ const SHOWCASE_TAIL = 'Preview tour complete'
60
+ const SHOWCASE_OLDEST = 'History checkpoint 01: verify deterministic preview state.'
61
+
62
+ /** Pages the preview needs; the Vite build emits both. */
63
+ const PAGES = ['index.html', 'preview.html']
64
+
65
+ /**
66
+ * Content types the preview loads. Anything else is served as opaque bytes.
67
+ *
68
+ * The image goes out as `application/gzip` with no `content-encoding`: the
69
+ * worker inflates the gzip member itself, so a transport-decoded body would
70
+ * leave its `DecompressionStream('gzip')` with plain tar bytes to inflate.
71
+ */
72
+ const MIME: Record<string, string> = {
73
+ '.html': 'text/html; charset=utf-8',
74
+ '.js': 'text/javascript; charset=utf-8',
75
+ '.css': 'text/css; charset=utf-8',
76
+ '.json': 'application/json; charset=utf-8',
77
+ '.map': 'application/json; charset=utf-8',
78
+ '.svg': 'image/svg+xml',
79
+ '.gz': 'application/gzip',
80
+ '.webmanifest': 'application/manifest+json',
81
+ '.woff2': 'font/woff2',
82
+ }
83
+
84
+ /** Boot line the worker host writes once its tree finished activating. */
85
+ const TREE_ACTIVE = 'webworker host: tree active'
86
+
87
+ /** Image fetch, mount, and tree activation on a loaded machine. */
88
+ const BOOT_TIMEOUT_MS = 240_000
89
+
90
+ /** Client tree settle after the tunnel starts answering. */
91
+ const HERO_TIMEOUT_MS = 240_000
92
+
93
+ /** One served origin over `dist/`. */
94
+ interface Site {
95
+ readonly origin: string
96
+ /** Release the port; call after the browser is gone. */
97
+ close(): Promise<void>
98
+ }
99
+
100
+ interface PreviewAssets {
101
+ /** Static-host-relative path to a generated file outside `dist/`. */
102
+ readonly overrides: ReadonlyMap<string, string>
103
+ cleanup(): void
104
+ }
105
+
106
+ /**
107
+ * Fail before the browser opens a page the build never produced.
108
+ * @throws When either preview page is missing from `dist/`.
109
+ */
110
+ function requirePreviewPages(): void {
111
+ for (const page of PAGES) {
112
+ if (existsSync(join(DIST_ROOT, page))) continue
113
+ throw new Error(`preview boot needs apps/web/dist/${page} — run \`pnpm run build\` from the repository root`)
114
+ }
115
+ }
116
+
117
+ /**
118
+ * The base image, fixture manifest, and overlays to serve. `pnpm run build`
119
+ * emits the pages but only `build:preview` packs the image, so this lane packs
120
+ * a missing image rather than skipping the deployment it accepts. The example
121
+ * overlay pairs its committed Session generations with the generator-owned
122
+ * current projection cache. The worker therefore exercises historical reads
123
+ * without relying on a stale cache schema. Generated files land in a temp
124
+ * directory, never in `dist/`: the
125
+ * client-artifact digest record treats `dist/` as build-owned, so a test write
126
+ * there fails the record check for every later consumer.
127
+ * @returns Static-path overrides and their teardown.
128
+ * @throws When the closure leaves dependencies unresolved, which would pack an
129
+ * incomplete image the tree fails on later and further from the cause.
130
+ */
131
+ function requireVfsAssets(): PreviewAssets {
132
+ const fixtureDefinitions = previewFixtures(REPO_ROOT)
133
+ const directory = mkdtempSync(join(tmpdir(), 'dsh-preview-boot-'))
134
+ const overrides = new Map<string, string>()
135
+ const writeAsset = (relativePath: string, bytes: Uint8Array | string): void => {
136
+ const path = join(directory, relativePath)
137
+ mkdirSync(dirname(path), { recursive: true })
138
+ writeFileSync(path, bytes)
139
+ overrides.set(relativePath, path)
140
+ }
141
+ if (!existsSync(IMAGE_FILE)) {
142
+ const packed = packVfsImage({
143
+ config: composeProfile(REPO_ROOT, PROFILE),
144
+ profile: PROFILE,
145
+ workspaces: indexWorkspacePackages(REPO_ROOT),
146
+ resolveFrom: REPO_ROOT,
147
+ configTrees: configTrees(REPO_ROOT),
148
+ })
149
+ if (packed.missing.length > 0) {
150
+ throw new Error(`preview boot: ${String(packed.missing.length)} dependencies did not resolve: ${packed.missing.join(', ')}`)
151
+ }
152
+ writeAsset(`preview/${IMAGE_FILE_NAME}`, packed.image)
153
+ }
154
+ const currentCache = buildVfsExampleFiles().get('home/storages/session_projcache.json')
155
+ if (currentCache === undefined) throw new Error('preview boot: generated example has no projection cache')
156
+ const cacheDirectory = join(directory, 'current-projection-cache')
157
+ mkdirSync(cacheDirectory, { recursive: true })
158
+ writeFileSync(join(cacheDirectory, 'session_projcache.json'), currentCache)
159
+ const fixtures = fixtureDefinitions.map((fixture) => {
160
+ const relativePath = `preview/fixtures/${fixture.id}.tar.gz`
161
+ const trees = fixture.id === 'vfs-example'
162
+ ? [...fixture.trees, { mount: 'home/storages', directory: cacheDirectory }]
163
+ : fixture.trees
164
+ writeAsset(relativePath, packVfsOverlay(trees).image)
165
+ return {
166
+ id: fixture.id,
167
+ label: fixture.label,
168
+ description: fixture.description,
169
+ overlays: [`fixtures/${fixture.id}.tar.gz`],
170
+ }
171
+ })
172
+ const manifest: PreviewFixtureManifest = {
173
+ version: PREVIEW_FIXTURE_MANIFEST_VERSION,
174
+ defaultFixture: fixtures[0]?.id ?? null,
175
+ fixtures,
176
+ }
177
+ writeAsset(`preview/${PREVIEW_FIXTURE_MANIFEST_FILE}`, `${JSON.stringify(manifest, null, 2)}\n`)
178
+ return { overrides, cleanup: () => { rmSync(directory, { recursive: true, force: true }) } }
179
+ }
180
+
181
+ /**
182
+ * Answer one request with its generated override or the file under `dist/`.
183
+ * @param request - Incoming request; only its path is read.
184
+ * @param response - Response to write the bytes or the 404 to.
185
+ * @param overrides - Generated deployment files served before `dist/`.
186
+ */
187
+ async function respond(
188
+ request: IncomingMessage,
189
+ response: ServerResponse,
190
+ overrides: ReadonlyMap<string, string>,
191
+ ): Promise<void> {
192
+ const path = new URL(request.url ?? '/', 'http://127.0.0.1').pathname
193
+ const relative = normalize(decodeURIComponent(path)).replace(/^\/+/, '')
194
+ try {
195
+ const body = await readFile(overrides.get(relative) ?? join(DIST_ROOT, relative))
196
+ response.writeHead(200, { 'content-type': MIME[extname(relative)] ?? 'application/octet-stream' })
197
+ response.end(body)
198
+ } catch {
199
+ // A miss is a miss: the deployment has no SPA fallback, and hiding one
200
+ // behind the index page would make a broken asset URL look like a boot
201
+ // failure.
202
+ response.writeHead(404)
203
+ response.end(`not found: ${relative}`)
204
+ }
205
+ }
206
+
207
+ /**
208
+ * Serve `dist/` over loopback with static-host semantics.
209
+ * @param overrides - Generated deployment files used when `dist/` has none.
210
+ * @returns The origin to navigate, and its teardown.
211
+ */
212
+ async function serveDist(overrides: ReadonlyMap<string, string>): Promise<Site> {
213
+ const server = createServer((request, response) => { void respond(request, response, overrides) })
214
+ await new Promise<void>((listening) => { server.listen(0, '127.0.0.1', listening) })
215
+ const address = server.address()
216
+ if (address === null || typeof address === 'string') throw new Error('preview boot: the static server bound no port')
217
+ return {
218
+ origin: `http://127.0.0.1:${String(address.port)}`,
219
+ close: async () => {
220
+ server.closeAllConnections()
221
+ await new Promise<void>((closed, reject) => {
222
+ server.close((error) => {
223
+ if (error === undefined) closed()
224
+ else reject(error)
225
+ })
226
+ })
227
+ },
228
+ }
229
+ }
230
+
231
+ /**
232
+ * Bound one boot milestone so a stall names the milestone instead of surfacing
233
+ * as the lane's generic test timeout.
234
+ * @param work - The milestone to wait for.
235
+ * @param ms - How long it may take.
236
+ * @param stalled - Error message when it does not arrive in time.
237
+ * @returns What `work` resolved to.
238
+ */
239
+ async function within<T>(work: Promise<T>, ms: number, stalled: string): Promise<T> {
240
+ let timer: NodeJS.Timeout | undefined
241
+ try {
242
+ return await Promise.race([
243
+ work,
244
+ new Promise<never>((_, reject) => { timer = setTimeout(() => { reject(new Error(stalled)) }, ms) }),
245
+ ])
246
+ } finally {
247
+ clearTimeout(timer)
248
+ }
249
+ }
250
+
251
+ it('boots the packed worker deployment to an interactive page', async () => {
252
+ requirePreviewPages()
253
+ const assets = requireVfsAssets()
254
+ try {
255
+ const site = await serveDist(assets.overrides)
256
+ try {
257
+ const browser = await chromium.launch({ headless: true, args: ['--no-sandbox', '--disable-dev-shm-usage'] })
258
+ try {
259
+ await bootEmptyPreview(site.origin, browser)
260
+ await bootPreview(site.origin, browser)
261
+ } finally {
262
+ await browser.close()
263
+ }
264
+ } finally {
265
+ await site.close()
266
+ }
267
+ } finally {
268
+ assets.cleanup()
269
+ }
270
+ }, 600_000)
271
+
272
+ /**
273
+ * Open the preview page and hold it to both boot milestones.
274
+ * @param origin - Origin serving `dist/`.
275
+ * @param browser - Browser to open the page in.
276
+ */
277
+ async function bootPreview(origin: string, browser: Browser): Promise<void> {
278
+ const page = await newEnglishPage(browser)
279
+ const pageErrors: Error[] = []
280
+ const consoleErrors: string[] = []
281
+ page.on('pageerror', (error) => { pageErrors.push(error) })
282
+ // Registered before navigation: the worker reports its tree long before the
283
+ // tunnel serves the client, so a listener added later would miss the line.
284
+ const treeActive = new Promise<string>((reported) => {
285
+ page.on('console', (message) => {
286
+ const text = message.text()
287
+ if (text.includes(TREE_ACTIVE)) reported(text)
288
+ if (message.type() === 'error' || message.type() === 'warning') consoleErrors.push(text)
289
+ })
290
+ })
291
+ try {
292
+ await page.goto(`${origin}/preview.html`, { waitUntil: 'domcontentloaded' })
293
+ await page.getByRole('heading', { name: 'Choose Preview data' }).waitFor()
294
+ expect(await page.locator('input[name="preview-source"][value="vfs-example"]').isChecked()).toBe(true)
295
+ expect(await page.getByText('Empty environment', { exact: true }).count()).toBe(1)
296
+ expect(await page.getByText('WebFS directory', { exact: true }).count()).toBe(1)
297
+ expect(await page.locator('input[name="preview-source"][value="webfs"]').isDisabled()).toBe(true)
298
+ expect(await page.getByRole('textbox', { name: 'Choose workspace' }).count()).toBe(0)
299
+ await compareOrRefreshGolden(
300
+ SOURCE_CHOOSER_EXPECTED,
301
+ await captureStableAria(page, '[data-preview-source-card]', '/__preview_no_workspace__'),
302
+ SNAPSHOT_MODE,
303
+ )
304
+ await page.getByRole('button', { name: 'Start Preview' }).click()
305
+ await page.getByText('Loading plugins…', { exact: true }).waitFor({ timeout: 10_000 })
306
+ const bootLine = await within(treeActive, BOOT_TIMEOUT_MS, `preview boot: the worker never reported "${TREE_ACTIVE}"`)
307
+ // The activated tree ran bodies lowered against the contract this
308
+ // checkout's packer emits; a dist built before a contract change would
309
+ // report the older one.
310
+ expect(bootLine).toContain(`image lowering=${WRAPPER_CONTRACT}`)
311
+ expect(bootLine).toContain('data overlays=1')
312
+ // The versioned notice is the seeded preview's first stable interactive
313
+ // surface after the startup chain completes over the tunnel.
314
+ const continueButton = page.getByRole('button', { name: 'Continue' })
315
+ await continueButton.waitFor({ timeout: HERO_TIMEOUT_MS })
316
+ await continueButton.click()
317
+ const configureLater = page.getByRole('button', { name: 'Configure later' })
318
+ await configureLater.waitFor({ timeout: 30_000 })
319
+ await configureLater.click()
320
+ await page.locator('[data-composer-input][data-placeholder="Describe what you want to build, / commands, @ files or sessions"]')
321
+ .waitFor({ timeout: 30_000 })
322
+
323
+ const exercised = await page.evaluate(async ({ seededSessionId, seededSessionTitle }) => {
324
+ type Result<T> = { result: { ok: true; value: T } | { ok: false; error: { code: string; message: string } } }
325
+ interface PreviewTransport {
326
+ fetch(input: string, init: RequestInit): Promise<Response>
327
+ }
328
+ const transport = (globalThis as typeof globalThis & { __DSH_TRANSPORT__?: PreviewTransport }).__DSH_TRANSPORT__
329
+ if (transport === undefined) throw new Error('preview transport is absent after boot')
330
+ const response = await transport.fetch('/api/session/list', {
331
+ method: 'POST',
332
+ headers: { 'content-type': 'application/json' },
333
+ body: JSON.stringify({
334
+ type: 'client-request', rpcId: 'preview-session-list', method: 'session/list',
335
+ payload: { args: { _request: {} } },
336
+ }),
337
+ })
338
+ const sessions = await response.json() as Result<{ items: Array<{ sessionId: string }> }>
339
+ if (!sessions.result.ok) throw new Error(`session/list failed: ${sessions.result.error.message}`)
340
+ const sessionId = sessions.result.value.items[0]?.sessionId
341
+ if (sessionId === undefined) throw new Error('workspace adoption created no Session')
342
+
343
+ // Remote namespaces answer over the same unary carrier; the args object
344
+ // keys every wire parameter by its name.
345
+ const remote = async <T>(endpoint: string, args: object): Promise<T> => {
346
+ const answered = await transport.fetch(`/api/${endpoint}`, {
347
+ method: 'POST',
348
+ headers: { 'content-type': 'application/json' },
349
+ body: JSON.stringify({
350
+ type: 'client-request', rpcId: `preview-${endpoint.replace('/', '-')}`,
351
+ method: endpoint, payload: { args },
352
+ }),
353
+ })
354
+ const body = await answered.json() as Result<T>
355
+ if (!body.result.ok) throw new Error(`${endpoint} failed: ${body.result.error.message}`)
356
+ return body.result.value
357
+ }
358
+ // Keep the fixture title stable for later UI assertions; increasing seqs
359
+ // prove that the cold Session acquired its write lease and appended.
360
+ const firstRename = await remote<{ title: string; seq: number }>('session/rename', {
361
+ request: { sessionId: seededSessionId, title: seededSessionTitle },
362
+ })
363
+ const secondRename = await remote<{ title: string; seq: number }>('session/rename', {
364
+ request: { sessionId: seededSessionId, title: seededSessionTitle },
365
+ })
366
+ const skills = await remote<{ skills: Array<{ name: string }> }>(
367
+ 'skills/list', { request: { sessionId } },
368
+ )
369
+ const createDirectory = async (path: string, name: string): Promise<void> => {
370
+ await remote<string>('directoryPicker/createDirectory', { path, name })
371
+ await new Promise((resolve) => { setTimeout(resolve, 250) })
372
+ await remote<{ skills: Array<{ name: string }> }>(
373
+ 'skills/list', { request: { sessionId } },
374
+ )
375
+ }
376
+ await createDirectory('/dsh/workspace/.agents/skills', 'runtime-created')
377
+ // Settings and credentials both answer over the Remote carrier, so this
378
+ // half of the sweep posts the generated endpoints directly like the
379
+ // session read above.
380
+ const settings = await remote<{ namespaces: { ns: string; revision: number }[] }>(
381
+ 'settings/describe', {},
382
+ )
383
+ const shell = settings.namespaces.find(namespace => namespace.ns === 'shell')
384
+ if (shell === undefined) throw new Error('settings/describe omitted the shell namespace')
385
+ await remote('settings/update', {
386
+ ns: 'shell',
387
+ patch: { timeoutMs: 61_000 },
388
+ expectedRevision: shell.revision,
389
+ })
390
+ await remote('credentials/set', { ref: 'PREVIEW_TEST_SECRET', value: 'worker-only' })
391
+ const credentials = await remote<Record<string, { configured: boolean }>>(
392
+ 'credentials/describe',
393
+ { refs: ['PREVIEW_TEST_SECRET'] },
394
+ )
395
+ await remote('credentials/unset', { ref: 'PREVIEW_TEST_SECRET' })
396
+ await new Promise((resolve) => { setTimeout(resolve, 250) })
397
+ return {
398
+ renamedTitle: secondRename.title,
399
+ renameAdvanced: secondRename.seq > firstRename.seq,
400
+ skillCount: skills.skills.length,
401
+ credentialConfigured: credentials.PREVIEW_TEST_SECRET?.configured,
402
+ }
403
+ }, {
404
+ seededSessionId: VFS_EXAMPLE_SESSION_IDS.main,
405
+ seededSessionTitle: SHOWCASE_TITLE,
406
+ })
407
+ expect(exercised.renamedTitle).toBe(SHOWCASE_TITLE)
408
+ expect(exercised.renameAdvanced).toBe(true)
409
+ expect(exercised.skillCount).toBeGreaterThan(0)
410
+ expect(exercised.credentialConfigured).toBe(true)
411
+
412
+ const sessions = page.getByRole('tree', { name: 'Sessions' })
413
+ const showcase = sessions.getByRole('treeitem').filter({ hasText: SHOWCASE_TITLE })
414
+ await expect.poll(() => showcase.count(), { timeout: 15_000 }).toBe(1)
415
+ await showcase.click()
416
+ await page.getByText(SHOWCASE_TAIL, { exact: true }).waitFor({ timeout: 30_000 })
417
+
418
+ expect(await page.getByText(SHOWCASE_OLDEST, { exact: true }).count()).toBe(0)
419
+ await page.getByRole('button', { name: 'PREVIEW.md', exact: true }).waitFor()
420
+ await page.getByRole('button', { name: 'src/preview.ts', exact: true }).waitFor()
421
+ await page.getByText('Update to-do list', { exact: true }).waitFor()
422
+ await page.getByText('Error: ENOENT: no such file, open missing.txt', { exact: true }).waitFor()
423
+
424
+ const subagents = page.getByRole('button', { name: '2 subagents' })
425
+ await subagents.waitFor({ timeout: 15_000 })
426
+ await subagents.hover()
427
+ const catalog = page.getByRole('tree', { name: 'Subagent sessions' })
428
+ await catalog.getByRole('treeitem', { name: /Review preview architecture/ }).waitFor()
429
+ await catalog.getByRole('treeitem', { name: /Continue preview verification/ }).waitFor()
430
+ await catalog.press('Escape')
431
+
432
+ await page.getByRole('button', { name: 'Load earlier', exact: true }).click()
433
+ await page.getByText(SHOWCASE_OLDEST, { exact: true }).waitFor({ timeout: 15_000 })
434
+ expect(pageErrors.map(error => error.message)).toEqual([])
435
+ expect(consoleErrors.filter(line =>
436
+ /watchFile|failed to watch|node-addon-system\.probe|sandbox backend is usable|SANDBOX_UNAVAILABLE/i.test(line))).toEqual([])
437
+ } catch (error) {
438
+ await saveFailureShot(page, 'preview-boot')
439
+ throw pageErrors.length === 0
440
+ ? error
441
+ : new AggregateError([error, ...pageErrors], 'preview boot failed, with uncaught page errors')
442
+ }
443
+ }
444
+
445
+ /** Verify the chooser can boot the untouched base image and reach first-run UI. */
446
+ async function bootEmptyPreview(origin: string, browser: Browser): Promise<void> {
447
+ const page = await newEnglishPage(browser)
448
+ const pageErrors: Error[] = []
449
+ const consoleErrors: string[] = []
450
+ const failedResponses: string[] = []
451
+ page.on('pageerror', (error) => { pageErrors.push(error) })
452
+ page.on('response', (response) => {
453
+ if (response.status() >= 400) failedResponses.push(new URL(response.url()).pathname)
454
+ })
455
+ const treeActive = new Promise<string>((reported) => {
456
+ page.on('console', (message) => {
457
+ const text = message.text()
458
+ if (text.includes(TREE_ACTIVE)) reported(text)
459
+ if (message.type() === 'error' || message.type() === 'warning') consoleErrors.push(text)
460
+ })
461
+ })
462
+ try {
463
+ await page.goto(`${origin}/preview.html?preview-fixture=none`, { waitUntil: 'domcontentloaded' })
464
+ expect(await page.getByRole('heading', { name: '选择 Preview 数据源' }).count()).toBe(0)
465
+ const bootLine = await within(
466
+ treeActive,
467
+ BOOT_TIMEOUT_MS,
468
+ `empty preview boot: the worker never reported "${TREE_ACTIVE}"`,
469
+ )
470
+ expect(bootLine).toContain(`image lowering=${WRAPPER_CONTRACT}`)
471
+ expect(bootLine).toContain('data overlays=0')
472
+ await page.getByRole('textbox', { name: 'Choose workspace' }).waitFor({ timeout: HERO_TIMEOUT_MS })
473
+ const sessionCount = await page.evaluate(async () => {
474
+ const transport = (globalThis as typeof globalThis & {
475
+ __DSH_TRANSPORT__?: { fetch(input: string, init: RequestInit): Promise<Response> }
476
+ }).__DSH_TRANSPORT__
477
+ if (transport === undefined) throw new Error('empty preview transport is absent after boot')
478
+ const response = await transport.fetch('/api/session/list', {
479
+ method: 'POST',
480
+ headers: { 'content-type': 'application/json' },
481
+ body: JSON.stringify({
482
+ type: 'client-request', rpcId: 'empty-preview-session-list', method: 'session/list',
483
+ payload: { args: { _request: {} } },
484
+ }),
485
+ })
486
+ const body = await response.json() as {
487
+ result: { ok: true; value: { items: unknown[] } } | { ok: false; error: { message: string } }
488
+ }
489
+ if (!body.result.ok) throw new Error(`empty session/list failed: ${body.result.error.message}`)
490
+ return body.result.value.items.length
491
+ })
492
+ expect(sessionCount).toBe(0)
493
+ expect(pageErrors.map(error => error.message)).toEqual([])
494
+ // Two accepted static-host 404s, sorted (the boot fetches race): the HMR
495
+ // event stream has no server here, and the open-in-app availability read
496
+ // has no host routes — the controller publishes an empty list and the
497
+ // header renders no button, which is that surface's designed degradation.
498
+ expect([...failedResponses].sort()).toEqual(['/open-in-app/apps', '/plugins/events'])
499
+ expect(consoleErrors.filter(line => !line.includes('Failed to load resource: the server responded with a status of 404')))
500
+ .toEqual([])
501
+ } catch (error) {
502
+ await saveFailureShot(page, 'preview-boot-empty')
503
+ throw pageErrors.length === 0
504
+ ? error
505
+ : new AggregateError([error, ...pageErrors], 'empty preview boot failed, with uncaught page errors')
506
+ } finally {
507
+ await page.close()
508
+ }
509
+ }
apps/web/tests/produced-files.e2e.ts ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Web e2e scenario: the single-line produced-files summary a finished turn
2
+ // ends with. Cold-seeds ten writes (zero model calls), then verifies the real
3
+ // assembled lane adapts from a coarse width budget and offers no folder
4
+ // handoff: chips open in the right Sidebar's text preview, which has no
5
+ // directory form, so the row shows nothing rather than a dead button.
6
+ import { fileURLToPath } from 'node:url'
7
+ import type { Browser, Page } from 'playwright'
8
+ import { chromium } from 'playwright'
9
+ import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
10
+ import { ToolCallId, createAssistantMessage, createToolResultMessage, createUserMessage } from '@deepseek-ai/dsh-llm'
11
+ import { SESSION_FORMAT_VERSION, Session, SessionId } from '@deepseek-ai/dsh-session'
12
+ import type {} from '@deepseek-ai/dsh-session-title'
13
+ import {
14
+ launchWebScaffold, seedSession, watchConsole, webSnapshotMode, type WebScaffold,
15
+ } from './scaffold.ts'
16
+ import { newEnglishPage, saveFailureShot } from './support.ts'
17
+
18
+ const MODE = webSnapshotMode()
19
+ const OVERLAY = fileURLToPath(new URL('./produced-files.overlay.yml', import.meta.url))
20
+ const SEED_ID = 'produced-files-web-e2e'
21
+ const DONE = 'PRODUCED_FILES_DONE'
22
+
23
+ /** Ten varied names exercise estimated prefix selection and CSS shrinking. */
24
+ const PRODUCED = [
25
+ '关于我.md',
26
+ 'index.html',
27
+ 'long-generated-experience-specification-for-produced-files-overflow.md',
28
+ 'styles.css',
29
+ 'app.ts',
30
+ 'schema.json',
31
+ 'README.md',
32
+ 'preview.svg',
33
+ 'notes.txt',
34
+ 'manifest.yaml',
35
+ ] as const
36
+
37
+ /** Build one settled turn whose successful write calls carry ten locations. */
38
+ function producedFixture(): string {
39
+ const session = Session.create(SessionId('produced-files-source'))
40
+ const eventTimeOrigin = new Date().setHours(12, 0, 0, 0)
41
+ session.append('turn/start', { turn: 1 })
42
+ const user = session.append('user/message', createUserMessage({
43
+ content: [{ type: 'text', text: 'Create the site files.' }],
44
+ source: { kind: 'user' },
45
+ }), { surfaceOp: 'append' })
46
+ session.append('session/title', {
47
+ title: 'Produced files overflow', messageSeqs: [user.seq], source: { kind: 'fallback' },
48
+ })
49
+ session.append('step/start', { turn: 1, step: 1 })
50
+ const calls = PRODUCED.map((path, index) => ({
51
+ path,
52
+ callId: ToolCallId(`produced-files-${String(index)}`),
53
+ args: JSON.stringify({ file_path: path, content: `content of ${path}\n` }),
54
+ }))
55
+ session.append('assistant/message', {
56
+ stream: [],
57
+ turn: 1,
58
+ step: 1,
59
+ message: createAssistantMessage({
60
+ content: calls.map(call => ({
61
+ type: 'tool-call' as const,
62
+ id: call.callId,
63
+ name: 'write',
64
+ arguments: call.args,
65
+ })),
66
+ source: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
67
+ }),
68
+ }, { surfaceOp: 'append' })
69
+ for (const call of calls) {
70
+ const source = session.append('tool/call', {
71
+ turn: 1, step: 1, callId: call.callId, name: 'write', arguments: call.args,
72
+ })
73
+ session.append('tool/result', {
74
+ turn: 1,
75
+ step: 1,
76
+ message: createToolResultMessage({
77
+ callId: call.callId,
78
+ content: [{ type: 'text', text: `Created ${call.path}` }],
79
+ isError: false,
80
+ }),
81
+ }, { surfaceOp: 'append', sourceEventSeqs: [source.seq] })
82
+ }
83
+ session.append('step/end', { turn: 1, step: 1 })
84
+ session.append('step/start', { turn: 1, step: 2 })
85
+ session.append('assistant/message', {
86
+ stream: [],
87
+ turn: 1,
88
+ step: 2,
89
+ message: createAssistantMessage({
90
+ content: [{ type: 'text', text: `Created the site.\n\n${DONE}` }],
91
+ source: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
92
+ }),
93
+ }, { surfaceOp: 'append' })
94
+ session.append('step/end', { turn: 1, step: 2 })
95
+ session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
96
+
97
+ return [
98
+ JSON.stringify({
99
+ type: 'session', version: SESSION_FORMAT_VERSION, id: '{{sessionId}}',
100
+ createdAt: 0, cwd: '{{cwd}}', isSeeded: false, delegationDepth: 0,
101
+ }),
102
+ ...session.snapshotEvents().map(event => JSON.stringify({
103
+ ...event, time: eventTimeOrigin + event.seq * 1_000,
104
+ })),
105
+ '',
106
+ ].join('\n')
107
+ }
108
+
109
+ describe('web e2e: a finished turn ends with the files it produced', () => {
110
+ let scaffold: WebScaffold
111
+ let browser: Browser
112
+ let page: Page
113
+ let tripwire: ReturnType<typeof watchConsole>
114
+
115
+ beforeAll(async () => {
116
+ scaffold = await launchWebScaffold({ extraOverlayPath: OVERLAY })
117
+ await seedSession(scaffold, producedFixture(), SEED_ID)
118
+ browser = await chromium.launch()
119
+ page = await newEnglishPage(browser)
120
+ // Keep the responsive sidebar available while selecting the cold seed;
121
+ // the assertion itself narrows the conversation after navigation.
122
+ await page.setViewportSize({ width: 1800, height: 900 })
123
+ tripwire = watchConsole(page)
124
+ await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
125
+ await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
126
+ }, 120_000)
127
+
128
+ afterAll(async () => {
129
+ await browser?.close()
130
+ await scaffold?.close()
131
+ })
132
+
133
+ it.skipIf(MODE === 'record')('adapts a ten-file summary without leaving one line', async () => {
134
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-produced-files'))
135
+ const groupRow = page.locator('[role="treeitem"]').first()
136
+ await groupRow.waitFor({ timeout: 15_000 })
137
+ if (await groupRow.getAttribute('aria-expanded') !== 'true') await groupRow.click()
138
+ const sessionRow = page.locator('[role="treeitem"]').nth(1)
139
+ await sessionRow.waitFor({ timeout: 10_000 })
140
+ await sessionRow.click()
141
+
142
+ await expect.poll(() => page.getByText(DONE, { exact: true }).count(), { timeout: 15_000 }).toBe(1)
143
+ const row = page.locator('[data-produced-files-row]')
144
+ await row.waitFor({ timeout: 15_000 })
145
+ const chips = row.getByRole('button')
146
+ await expect.poll(() => chips.count()).toBe(6)
147
+ await expect.poll(() => row.getByText('+ 4 files', { exact: true }).isVisible()).toBe(true)
148
+
149
+ await page.setViewportSize({ width: 750, height: 900 })
150
+ await page.evaluate(async () => { await document.fonts.ready })
151
+ await page.waitForFunction(() => {
152
+ const frame = document.querySelector('[data-sidebar-collapsed][data-rightbar-collapsed]')
153
+ if (frame === null) return false
154
+ const tracks = getComputedStyle(frame).gridTemplateColumns.split(' ').map(Number.parseFloat)
155
+ // The responsive sidebar's settled collapsed track is 56px.
156
+ return tracks[0] === 56 && tracks.at(-1) === 0
157
+ && frame.getAnimations().every(animation =>
158
+ animation.playState === 'finished' || animation.playState === 'idle')
159
+ }, undefined, { timeout: 10_000 })
160
+ await expect.poll(() => chips.count()).toBe(4)
161
+ const laneWidth = await row.evaluate(element => element.clientWidth)
162
+ // Keep font-metric differences away from the 479px and 583px container-query edges.
163
+ expect(laneWidth).toBeGreaterThan(503)
164
+ expect(laneWidth).toBeLessThan(559)
165
+ expect(await chips.nth(0).innerText()).toBe('关于我.md')
166
+ expect(await chips.nth(1).innerText()).toBe('index.html')
167
+ expect(await chips.nth(3).innerText()).toBe('styles.css')
168
+ await expect.poll(() => row.getByText('+ 6 files', { exact: true }).isVisible()).toBe(true)
169
+ // Chips open in the right Sidebar's text preview, and a directory is not
170
+ // something that preview can show, so the row offers no folder action.
171
+ expect(await page.getByRole('button', { name: /folder/i }).count()).toBe(0)
172
+ expect(await page.getByText('Files changed', { exact: true }).count()).toBe(1)
173
+
174
+ const turnSpacing = await page.evaluate((done) => {
175
+ const requiredElement = <T extends Element>(value: T | null | undefined, name: string): T => {
176
+ if (value === null || value === undefined) throw new Error(`produced-file layout is missing ${name}`)
177
+ return value
178
+ }
179
+ const answer = requiredElement(
180
+ [...document.querySelectorAll<HTMLElement>('[data-chat-flow-kind="assistant-step"]')]
181
+ .find(element => element.textContent?.includes(done)),
182
+ 'final answer',
183
+ )
184
+ const producedRow = requiredElement(
185
+ document.querySelector<HTMLElement>('[data-produced-files-row]'),
186
+ 'produced row',
187
+ )
188
+ const producedRoot = requiredElement(producedRow.parentElement?.parentElement, 'produced root')
189
+ const turnTail = requiredElement(producedRoot.closest<HTMLElement>('[data-turn-tail]'), 'turn tail')
190
+ const actions = requiredElement(
191
+ turnTail.querySelector<HTMLButtonElement>('button[aria-label="Copy"]')?.parentElement,
192
+ 'action row',
193
+ )
194
+ const answerRect = answer.getBoundingClientRect()
195
+ const producedRect = producedRoot.getBoundingClientRect()
196
+ const actionsRect = actions.getBoundingClientRect()
197
+ return {
198
+ answerToProduced: producedRect.top - answerRect.bottom,
199
+ producedToActions: actionsRect.top - producedRect.bottom,
200
+ }
201
+ }, DONE)
202
+ expect(turnSpacing.answerToProduced).toBeCloseTo(20, 1)
203
+ expect(turnSpacing.producedToActions).toBeCloseTo(20, 1)
204
+
205
+ const tops = await row.locator(':scope > *:visible').evaluateAll(elements =>
206
+ elements.map(element => element.getBoundingClientRect().top))
207
+ expect(new Set(tops.map(top => Math.round(top))).size).toBe(1)
208
+ const geometry = await row.evaluate(element => ({
209
+ clientWidth: element.clientWidth, scrollWidth: element.scrollWidth,
210
+ }))
211
+ expect(geometry.scrollWidth).toBeLessThanOrEqual(geometry.clientWidth)
212
+
213
+ expect(tripwire.pageErrors).toEqual([])
214
+ expect(tripwire.warnings).toEqual([])
215
+ }, 90_000)
216
+ })
apps/web/tests/produced-files.overlay.yml ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # The summary test asserts the native-folder action without launching it. Pin
2
+ # the capability so headless Linux CI and desktop developer hosts expose the
3
+ # same UI branch; platform opener behavior belongs to the Host unit tests.
4
+ - id: session-controller
5
+ config:
6
+ nativeOpen: true
7
+ - id: settings-controller
8
+ config:
9
+ nativeOpen: true
apps/web/tests/pwsh-terminal.e2e.ts ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Keyless browser regression for pwsh UI parity with bash: a seeded session
2
+ // whose pwsh call/result is presented by the REAL tool-pwsh on replay (the
3
+ // api-proxy recomputes presentation views from logged args/result content)
4
+ // must render with the same terminal card layout as bash and show the parsed exit-status
5
+ // pill — not a generic console-fenced card. The seed is authored, not
6
+ // recorded: its header line carries no `cwd`
7
+ // field (seedSession writes the session cwd itself, and a Windows temp path
8
+ // substituted into the header would not round-trip through its JSON parse),
9
+ // and no event references the workspace, so the lane replays on any host
10
+ // with a usable `pwsh` — the lane mounts the pwsh stack through an overlay
11
+ // (the shipped tree keeps the bash stack).
12
+ import { spawnSync } from 'node:child_process'
13
+ import { readFile } from 'node:fs/promises'
14
+ import { join } from 'node:path'
15
+ import { fileURLToPath } from 'node:url'
16
+ import type { Browser, Page } from 'playwright'
17
+ import { chromium } from 'playwright'
18
+ import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
19
+ import { resolvePwshPath } from '@deepseek-ai/dsh-pwsh-local'
20
+ import {
21
+ assertFixtureInventory, captureStableAria, compareOrRefreshGolden,
22
+ fixtureUserPrompts, launchWebScaffold, seedSession, webSnapshotMode,
23
+ type WebScaffold,
24
+ } from './scaffold.ts'
25
+ import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts'
26
+
27
+ const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/pwsh-terminal', import.meta.url))
28
+ const SEED = join(SNAPSHOT_DIR, 'session.v3.jsonl')
29
+ const TERMINAL_EXPECTED = join(SNAPSHOT_DIR, 'terminal-card.expected.md')
30
+ const OVERLAY = fileURLToPath(new URL('./pwsh-terminal.overlay.yml', import.meta.url))
31
+ const PROMPT = 'Run a PowerShell command that fails, then stop.'
32
+ const SEED_ID = 'pwsh-terminal-web-e2e'
33
+ const MODE = webSnapshotMode()
34
+
35
+ // The overlay swaps the shipped bash executor for @deepseek-ai/dsh-pwsh-local;
36
+ // a host without a usable `pwsh` cannot boot it, so the lane self-skips,
37
+ // mirroring the pwshOnly ACP scenarios. The probe follows the executor's own
38
+ // resolution (Program Files installs on Windows are found even when bare
39
+ // `pwsh` is not on PATH), the same judgment the tool-pwsh tests reuse; record
40
+ // mode skips the lane anyway, so the probe stays inert there.
41
+ const HAS_PWSH = MODE === 'record' ? false : spawnSync(
42
+ resolvePwshPath(), ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', '$true'],
43
+ { encoding: 'utf8' },
44
+ ).status === 0
45
+
46
+ describe.skipIf(MODE === 'record' || !HAS_PWSH)('web e2e: pwsh calls use the bash terminal-card layout', () => {
47
+ let scaffold: WebScaffold
48
+ let browser: Browser
49
+ let page: Page
50
+
51
+ beforeAll(async () => {
52
+ const fixture = await readFile(SEED, 'utf8')
53
+ expect(fixtureUserPrompts(fixture), 'seed fixture must carry the single drive prompt').toEqual([PROMPT])
54
+ scaffold = await launchWebScaffold({ extraOverlayPath: OVERLAY })
55
+ await seedSession(scaffold, fixture, SEED_ID)
56
+ browser = await chromium.launch()
57
+ page = await newEnglishPage(browser)
58
+ await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
59
+ await connectFreshWorkspace(page, scaffold.workspaceCwd)
60
+ }, 120_000)
61
+
62
+ afterAll(async () => {
63
+ await browser?.close()
64
+ await scaffold?.close()
65
+ })
66
+
67
+ it('renders the seeded pwsh call as a terminal card with the parsed exit pill', async () => {
68
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-pwsh-terminal'))
69
+ // Open the seeded session through content search: the sidebar groups
70
+ // sessions by workspace and its row order is world-dependent, while the
71
+ // search index covers the seeded log deterministically. Search is a
72
+ // collapsed header action; expand it so the input is actionable.
73
+ const searchButton = page.getByRole('button', { name: 'Search sessions' })
74
+ if (await searchButton.getAttribute('aria-expanded') !== 'true') await searchButton.click()
75
+ const search = page.getByPlaceholder('Search sessions', { exact: false })
76
+ await search.fill('Run a PowerShell command')
77
+ const result = page.getByRole('tree', { name: 'Search results' }).getByRole('treeitem')
78
+ await expect.poll(() => result.count(), { timeout: 15_000 }).toBe(1)
79
+ await result.click()
80
+ await page.getByRole('tab', { name: 'Chat', exact: true }).waitFor({ timeout: 15_000 })
81
+ // The tool row is expand-gated: the settled row uses the bash layout and carries the
82
+ // shell-family variant, and the terminal card lives in the expanded body.
83
+ const row = page.locator('[data-tool="pwsh"]').first()
84
+ await row.waitFor({ timeout: 15_000 })
85
+ if (await row.getAttribute('aria-expanded') !== 'true') await row.click()
86
+ const card = page.locator('[data-terminal]').first()
87
+ await card.waitFor({ timeout: 15_000 })
88
+ // The parsed exit pill replaces the `[exit code: 1]` marker in the output
89
+ // body — the bash tool's terminal presentation, not the generic fence.
90
+ const text = await card.textContent()
91
+ expect(text).toContain('exit code 1')
92
+ expect(text).toContain('Get-Item : Cannot find path')
93
+ expect(text).not.toContain('[exit code: 1]')
94
+ const snapshot = (await captureStableAria(page, '[data-terminal]', scaffold.workspaceCwd))
95
+ // normalizeAria collapses the workspace basename with a '/' split, which
96
+ // misses Windows temp paths; collapse it here too (a no-op on POSIX) so
97
+ // the golden is platform-independent.
98
+ .split(scaffold.workspaceCwd.split(/[\\/]/).pop()!).join('{{workspace}}')
99
+ .split(SEED_ID).join('{{seededId}}')
100
+ await compareOrRefreshGolden(TERMINAL_EXPECTED, snapshot, MODE)
101
+ }, 60_000)
102
+
103
+ it('guards the lane fixture inventory', async () => {
104
+ await assertFixtureInventory(SNAPSHOT_DIR, ['session.v3.jsonl', 'terminal-card.expected.md'])
105
+ })
106
+ })
apps/web/tests/rail-search-expand.e2e.ts ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Web e2e scenario: the collapsed rail's search control in the real event
2
+ // order. The rail click flips the sidebar wide and mounts WorkspaceBrowser's
3
+ // outside-click dismissal listener during its own React dispatch; the same
4
+ // click then keeps bubbling to document with the unmounted rail button as its
5
+ // target — outside searchRoot. The package-level jsdom test cannot replay
6
+ // that continuation (fireEvent does not re-bubble through listeners mounted
7
+ // mid-dispatch), so the guard that keeps the gesture alive
8
+ // (.agents/notes/archived/bug-fix/2026-08-18-rail-search-outside-click-self-dismissal.md)
9
+ // is pinned here, in the assembled application under a real browser click.
10
+ //
11
+ // Zero model calls: collapsing the sidebar and expanding the search are pure
12
+ // client layout gestures; the scenario needs no session content at all.
13
+ import type { Browser, Page } from 'playwright'
14
+ import { chromium } from 'playwright'
15
+ import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
16
+ import { launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts'
17
+ import { newEnglishPage, saveFailureShot } from './support.ts'
18
+
19
+ /** WorkspaceBrowser's rail-search focus delay (EXPAND_SLIDE_MS) plus flush headroom. */
20
+ const FOCUS_SETTLE_MS = 600
21
+
22
+ describe('web e2e: rail search click survives its own document-level bubble', () => {
23
+ let scaffold: WebScaffold
24
+ let browser: Browser
25
+ let page: Page
26
+ let tripwire: ReturnType<typeof watchConsole>
27
+
28
+ beforeAll(async () => {
29
+ scaffold = await launchWebScaffold({})
30
+ browser = await chromium.launch()
31
+ page = await newEnglishPage(browser)
32
+ tripwire = watchConsole(page)
33
+ await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
34
+ await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
35
+ }, 120_000)
36
+
37
+ afterAll(async () => {
38
+ await browser?.close()
39
+ await scaffold?.close()
40
+ })
41
+
42
+ it('expands the search and lands focus in the input from one rail click', async () => {
43
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-rail-search-expand'))
44
+ await page.getByRole('button', { name: 'Collapse sidebar' }).click()
45
+ const railSearch = page.getByRole('button', { name: 'Search sessions' })
46
+ // The wide chrome stays mounted through the 150ms collapse crossfade; the
47
+ // rail control (no aria-expanded) replaces it at settle.
48
+ await expect.poll(async () => railSearch.getAttribute('aria-expanded'), { timeout: 10_000 }).toBeNull()
49
+
50
+ // The one real click under test: it must expand the sidebar AND leave the
51
+ // search expanded after its own bubble reaches document.
52
+ await railSearch.click()
53
+
54
+ const wideSearch = page.getByRole('button', { name: 'Search sessions' })
55
+ await expect.poll(async () => wideSearch.getAttribute('aria-expanded'), { timeout: 10_000 }).toBe('true')
56
+ const input = page.getByPlaceholder('Search sessions...')
57
+ await expect.poll(
58
+ async () => input.evaluate(el => document.activeElement === el),
59
+ { timeout: FOCUS_SETTLE_MS + 10_000 },
60
+ ).toBe(true)
61
+
62
+ // The guard ends with the gesture: a genuine outside click on an empty
63
+ // query dismisses the expanded search as before.
64
+ await page.getByRole('button', { name: 'New session' }).first().click()
65
+ await expect.poll(async () => wideSearch.getAttribute('aria-expanded'), { timeout: 10_000 }).toBe('false')
66
+ expect(tripwire.pageErrors).toEqual([])
67
+ }, 60_000)
68
+ })
apps/web/tests/schedule-after.e2e.ts ADDED
@@ -0,0 +1,826 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** Keyless assembled-Web evidence for conversational Schedule delivery. */
2
+
3
+ import { mkdir, readFile, writeFile } from 'node:fs/promises'
4
+ import { join } from 'node:path'
5
+ import { fileURLToPath } from 'node:url'
6
+ import type { Browser, Page } from 'playwright'
7
+ import { chromium } from 'playwright'
8
+ import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
9
+ import type { Agent, AgentHandle } from '@deepseek-ai/dsh-agent'
10
+ import { composeEntries, loadOverlayPatches } from '@deepseek-ai/dsh-app-boot'
11
+ import { ToolCallId, createUserMessage, LlmAdapter } from '@deepseek-ai/dsh-llm'
12
+ import type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm'
13
+ import { SessionId, type SessionEvent } from '@deepseek-ai/dsh-session'
14
+ import {
15
+ ScheduleId,
16
+ createEveryScheduleRecord,
17
+ foldScheduleEvents,
18
+ resolveEveryOccurrence,
19
+ type EveryScheduleRecord,
20
+ } from '@deepseek-ai/dsh-schedule'
21
+ import {
22
+ assertFixtureInventory,
23
+ captureStableAria,
24
+ compareOrRefreshGolden,
25
+ launchWebScaffold,
26
+ seedSession,
27
+ watchConsole,
28
+ webSnapshotMode,
29
+ type WebScaffold,
30
+ } from './scaffold.ts'
31
+ import {
32
+ REPO_ROOT,
33
+ connectFreshWorkspace,
34
+ conversationContextKey,
35
+ saveFailureShot,
36
+ } from './support.ts'
37
+
38
+ const MODE = webSnapshotMode()
39
+ const OVERLAY = fileURLToPath(new URL('../../cli/config/examples/schedule/cordis.yml', import.meta.url))
40
+ const SNAPSHOT_DIR = fileURLToPath(new URL('./expected/schedule-after', import.meta.url))
41
+ const AFTER_EXPECTED = join(SNAPSHOT_DIR, 'conversation.expected.md')
42
+ const AT_EXPECTED = join(SNAPSHOT_DIR, 'at-conversation.expected.md')
43
+ const EVERY_EXPECTED = join(SNAPSHOT_DIR, 'every-conversation.expected.md')
44
+ const AFTER_PROVIDER = 'schedule-after-web-test'
45
+ const AT_PROVIDER = 'schedule-at-web-test'
46
+ const EVERY_PROVIDER = 'schedule-every-web-test'
47
+ const MODEL = 'reply'
48
+ const AFTER_PROMPT = 'Check the deployment log'
49
+ const AFTER_REPLY = 'Reminder: Check the deployment log.'
50
+ const AT_BROWSER_ZONE = 'Asia/Shanghai'
51
+ const AT_USER_PROMPT = 'Remind me to review the release window in a few seconds in my local time.'
52
+ const AT_PROMPT = 'Review the release window'
53
+ const AT_READY = 'Ready for a browser-local reminder request.'
54
+ const AT_ACK = 'Scheduled in your browser time zone.'
55
+ const AT_REPLY = 'Reminder: Review the release window.'
56
+ const EVERY_PROMPTS = ['Check primary metrics', 'Check secondary metrics'] as const
57
+ const EVERY_REPLY = 'Reminders: Check primary metrics; Check secondary metrics.'
58
+ const EVERY_INTERVAL_SECONDS = 60 * 60
59
+ const EVERY_FIXTURE_AGE_MS = 90 * 60 * 1_000
60
+ const CATALOG_SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/schedule-catalog', import.meta.url))
61
+ const CATALOG_FIXTURE = join(CATALOG_SNAPSHOT_DIR, 'session.v3.jsonl')
62
+ const CATALOG_EXPECTED = join(CATALOG_SNAPSHOT_DIR, 'catalog.expected.md')
63
+ const BASE_PATCH = fileURLToPath(new URL('../../../packages/bundle/base/cordis.patch.yml', import.meta.url))
64
+ const WEB_PATCH = fileURLToPath(new URL('../../../packages/bundle/web-app/cordis.patch.yml', import.meta.url))
65
+ const CATALOG_NOW = Date.parse('2099-08-25T12:00:00.000Z')
66
+ const CATALOG_SESSION_ID = SessionId('schedule-catalog-web-e2e')
67
+ const CATALOG_TITLE = 'Active schedule catalog'
68
+ const REMINDER_TRIGGER_NAME = /^\d+ reminders?$/
69
+ const ACTIVE_SCHEDULE_LABEL = 'Has active scheduled task'
70
+ const CATALOG_IDS = {
71
+ after: ScheduleId('catalog-after'),
72
+ at: ScheduleId('catalog-at'),
73
+ every: ScheduleId('catalog-every'),
74
+ } as const
75
+
76
+ /** Emit one complete assistant text response. */
77
+ function textResponse(text: string): StreamChunk[] {
78
+ return [
79
+ { type: 'block-start', index: 0, blockType: 'text' },
80
+ { type: 'block-end', index: 0, block: { type: 'text', text } },
81
+ { type: 'finish', reason: { kind: 'stop' } },
82
+ ]
83
+ }
84
+
85
+ /** Deterministic model seam that turns one due reminder into ordinary assistant prose. */
86
+ class ReminderAdapter extends LlmAdapter {
87
+ readonly requests: GenerateOptions[] = []
88
+
89
+ override async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
90
+ this.requests.push(options)
91
+ yield * textResponse(AFTER_REPLY)
92
+ }
93
+ }
94
+
95
+ /** Deterministic model seam for one multi-record fixed-rate batch. */
96
+ class EveryReminderAdapter extends LlmAdapter {
97
+ readonly requests: GenerateOptions[] = []
98
+
99
+ override async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
100
+ this.requests.push(options)
101
+ yield * textResponse(EVERY_REPLY)
102
+ }
103
+ }
104
+
105
+ interface LocalAt {
106
+ readonly date: string
107
+ readonly time: string
108
+ readonly time_zone: string
109
+ }
110
+
111
+ /** Render one future epoch as exact local calendar fields in an explicit zone. */
112
+ function localAt(epoch: number, timeZone: string): LocalAt {
113
+ const parts = Object.fromEntries(new Intl.DateTimeFormat('en-CA', {
114
+ timeZone,
115
+ year: 'numeric',
116
+ month: '2-digit',
117
+ day: '2-digit',
118
+ hour: '2-digit',
119
+ minute: '2-digit',
120
+ second: '2-digit',
121
+ hourCycle: 'h23',
122
+ }).formatToParts(epoch).map(part => [part.type, part.value])) as Record<string, string>
123
+ return {
124
+ date: `${parts['year']}-${parts['month']}-${parts['day']}`,
125
+ time: `${parts['hour']}:${parts['minute']}:${parts['second']}`,
126
+ time_zone: timeZone,
127
+ }
128
+ }
129
+
130
+ /** Dynamic model seam proving request-local browser context becomes an explicit At selector. */
131
+ class BrowserZoneAtAdapter extends LlmAdapter {
132
+ readonly requests: GenerateOptions[] = []
133
+ selectedAt: LocalAt | undefined
134
+ scheduledAt: string | undefined
135
+
136
+ override async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
137
+ this.requests.push(options)
138
+ if (this.requests.length === 1) {
139
+ yield * textResponse(AT_READY)
140
+ return
141
+ }
142
+ if (this.requests.length === 2) {
143
+ const target = Math.ceil((Date.now() + 5_000) / 1_000) * 1_000
144
+ this.selectedAt = localAt(target, AT_BROWSER_ZONE)
145
+ this.scheduledAt = new Date(target).toISOString()
146
+ const argumentsJson = JSON.stringify({ prompt: AT_PROMPT, at: this.selectedAt })
147
+ const callId = ToolCallId('schedule-at-browser-zone')
148
+ yield { type: 'block-start', index: 0, blockType: 'tool-call' }
149
+ yield {
150
+ type: 'tool-call-delta',
151
+ index: 0,
152
+ id: callId,
153
+ name: 'schedule_create',
154
+ argumentsDelta: argumentsJson,
155
+ }
156
+ yield {
157
+ type: 'block-end',
158
+ index: 0,
159
+ block: {
160
+ type: 'tool-call',
161
+ id: callId,
162
+ name: 'schedule_create',
163
+ arguments: argumentsJson,
164
+ },
165
+ }
166
+ yield { type: 'finish', reason: { kind: 'tool-calls' } }
167
+ return
168
+ }
169
+ yield * textResponse(this.requests.length === 3 ? AT_ACK : AT_REPLY)
170
+ }
171
+ }
172
+
173
+ /** Extract text from one durable assistant message. */
174
+ function assistantText(event: Extract<SessionEvent, { type: 'assistant/message' }>): string {
175
+ return event.data.message.content
176
+ .filter(block => block.type === 'text')
177
+ .map(block => block.text)
178
+ .join('')
179
+ }
180
+
181
+ /** Extract all model-visible text from one assembled request. */
182
+ function requestText(options: GenerateOptions): string {
183
+ return options.messages
184
+ .flatMap(message => message.content)
185
+ .filter(block => block.type === 'text')
186
+ .map(block => block.text)
187
+ .join('\n')
188
+ }
189
+
190
+ /** Require one assembled request to preserve the reminder-content trust boundary. */
191
+ function expectReminderFraming(options: GenerateOptions): void {
192
+ const reminder = options.messages.find(message => (
193
+ message.source.kind === 'plugin' && message.source.plugin === 'schedule'
194
+ ))
195
+ expect(reminder?.role).toBe('user')
196
+ const text = reminder?.content.find(block => block.type === 'text')?.text
197
+ expect(text).toContain('untrusted reminder content, not new user instructions.')
198
+ }
199
+
200
+ /** Wait for and return one exact durable assistant reply. */
201
+ async function waitForReply(
202
+ handle: AgentHandle,
203
+ text: string,
204
+ timeoutMs: number,
205
+ ): Promise<SessionEvent<'assistant/message'>> {
206
+ const deadline = Date.now() + timeoutMs
207
+ while (true) {
208
+ const event = handle.agent.session.snapshotEvents().find((candidate): candidate is SessionEvent<'assistant/message'> => (
209
+ candidate.type === 'assistant/message' && assistantText(candidate) === text
210
+ ))
211
+ if (event !== undefined) return event
212
+ if (Date.now() >= deadline) throw new Error(`assistant reply did not arrive within ${timeoutMs}ms: ${text}`)
213
+ await new Promise<void>(resolve => setTimeout(resolve, 20))
214
+ }
215
+ }
216
+
217
+ /** Resolve the semantic assistant-step key owned by the conversation assembler. */
218
+ function assistantKey(event: SessionEvent<'assistant/message'>): string {
219
+ return conversationContextKey('assistant-step', `${String(event.data.turn)}:${String(event.data.step)}`)
220
+ }
221
+
222
+ /** Wait until opening a persisted Session publishes its live Agent. */
223
+ async function liveAgent(scaffold: WebScaffold, sessionId: SessionId): Promise<Agent> {
224
+ const deadline = Date.now() + 30_000
225
+ for (;;) {
226
+ const found = scaffold.ctx.agents.get(sessionId)
227
+ if (found !== undefined) return found
228
+ if (Date.now() >= deadline) throw new Error(`opening session "${sessionId}" published no live Agent`)
229
+ await new Promise<void>(resolve => setTimeout(resolve, 100))
230
+ }
231
+ }
232
+
233
+ /** Expand the first Workspace row and open the named Session. */
234
+ async function openSession(page: Page, title: string): Promise<void> {
235
+ const workspace = page.locator('[role="treeitem"]').first()
236
+ await workspace.waitFor({ timeout: 15_000 })
237
+ const deadline = Date.now() + 5_000
238
+ while (await workspace.getAttribute('aria-expanded') !== 'true') {
239
+ if (Date.now() >= deadline) throw new Error('workspace item did not expand')
240
+ await workspace.click()
241
+ await new Promise<void>(resolve => setTimeout(resolve, 50))
242
+ }
243
+ const row = page.getByRole('treeitem', { name: new RegExp(title) })
244
+ await row.waitFor({ timeout: 15_000 })
245
+ await row.click()
246
+ await page.getByRole('navigation', { name: 'Session hierarchy' })
247
+ .getByRole('button', { name: title, exact: true })
248
+ .waitFor({ timeout: 15_000 })
249
+ }
250
+
251
+ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => {
252
+ let scaffold: WebScaffold
253
+ let afterHandle: AgentHandle
254
+ let atHandle: AgentHandle
255
+ let everyHandle: AgentHandle
256
+ let browser: Browser
257
+ let page: Page
258
+ let afterAssistantReply: SessionEvent<'assistant/message'> | undefined
259
+ let atAssistantReply: SessionEvent<'assistant/message'> | undefined
260
+ let everyAssistantReply: SessionEvent<'assistant/message'> | undefined
261
+ let everyRecords: readonly [EveryScheduleRecord, EveryScheduleRecord]
262
+ let tripwire: ReturnType<typeof watchConsole>
263
+ const afterAdapter = new ReminderAdapter()
264
+ const atAdapter = new BrowserZoneAtAdapter()
265
+ const everyAdapter = new EveryReminderAdapter()
266
+
267
+ beforeAll(async () => {
268
+ scaffold = await launchWebScaffold({ extraOverlayPath: OVERLAY })
269
+ scaffold.ctx.effect(
270
+ () => scaffold.ctx.llm.registerAdapter([AFTER_PROVIDER], afterAdapter),
271
+ 'Schedule Web After adapter',
272
+ )
273
+ scaffold.ctx.effect(
274
+ () => scaffold.ctx.llm.registerAdapter([AT_PROVIDER], atAdapter),
275
+ 'Schedule Web At adapter',
276
+ )
277
+ scaffold.ctx.effect(
278
+ () => scaffold.ctx.llm.registerAdapter([EVERY_PROVIDER], everyAdapter),
279
+ 'Schedule Web Every adapter',
280
+ )
281
+
282
+ browser = await chromium.launch()
283
+ page = await browser.newPage({
284
+ viewport: { width: 1680, height: 1000 },
285
+ locale: 'en-US',
286
+ timezoneId: AT_BROWSER_ZONE,
287
+ })
288
+ await page.addInitScript(() => { localStorage.setItem('dsh.locale', 'en') })
289
+ tripwire = watchConsole(page)
290
+ await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
291
+ await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
292
+ await connectFreshWorkspace(page, scaffold.workspaceCwd)
293
+ expect(await page.evaluate(() => Intl.DateTimeFormat().resolvedOptions().timeZone))
294
+ .toBe(AT_BROWSER_ZONE)
295
+
296
+ const cwd = join(scaffold.workspaceCwd, 'workspace')
297
+ const workspace = await scaffold.ctx.workspaceRegistry.resolveByPath(cwd)
298
+ if (workspace === undefined) throw new Error('connected Web workspace was not registered')
299
+
300
+ afterHandle = await scaffold.ctx.agents.create({
301
+ sessionId: SessionId('schedule-after-web-e2e'),
302
+ meta: { cwd },
303
+ agentOptions: { provider: AFTER_PROVIDER, model: MODEL },
304
+ })
305
+ afterHandle.agent.session.append('session/title', {
306
+ title: 'Scheduled After follow-up',
307
+ messageSeqs: [],
308
+ source: { kind: 'user' },
309
+ })
310
+ await workspace.attachSession(afterHandle.agent.id)
311
+ const afterCreated = await scaffold.ctx.tools.execute({
312
+ signal: AbortSignal.timeout(10_000),
313
+ callId: ToolCallId('schedule-after-create'),
314
+ name: 'schedule_create',
315
+ arguments: { prompt: AFTER_PROMPT, after_seconds: 1 },
316
+ agent: afterHandle.agent,
317
+ })
318
+ if (afterCreated.isError) {
319
+ throw new Error(`Schedule After create failed: ${JSON.stringify(afterCreated.value)}`)
320
+ }
321
+ expect(afterCreated.value).toMatchObject({
322
+ id: 'schedule-1',
323
+ kind: 'after',
324
+ prompt: AFTER_PROMPT,
325
+ afterSeconds: 1,
326
+ state: 'scheduled',
327
+ deliveryMode: 'session-local',
328
+ })
329
+ afterAssistantReply = await waitForReply(afterHandle, AFTER_REPLY, 15_000)
330
+ await afterHandle.agent.whenIdle()
331
+ await expect(scaffold.ctx.sessions.flush(afterHandle.agent.session)).resolves.toBe(true)
332
+
333
+ everyHandle = await scaffold.ctx.agents.create({
334
+ sessionId: SessionId('schedule-every-web-e2e'),
335
+ meta: { cwd },
336
+ agentOptions: { provider: EVERY_PROVIDER, model: MODEL },
337
+ })
338
+ everyHandle.agent.session.append('session/title', {
339
+ title: 'Fixed-rate reminder batch',
340
+ messageSeqs: [],
341
+ source: { kind: 'user' },
342
+ })
343
+ const seededAt = Date.now()
344
+ everyRecords = [
345
+ createEveryScheduleRecord(
346
+ ScheduleId('schedule-every-primary'),
347
+ EVERY_PROMPTS[0],
348
+ EVERY_INTERVAL_SECONDS,
349
+ seededAt - EVERY_FIXTURE_AGE_MS,
350
+ ),
351
+ createEveryScheduleRecord(
352
+ ScheduleId('schedule-every-secondary'),
353
+ EVERY_PROMPTS[1],
354
+ EVERY_INTERVAL_SECONDS,
355
+ seededAt - EVERY_FIXTURE_AGE_MS,
356
+ ),
357
+ ]
358
+ for (const record of everyRecords) {
359
+ everyHandle.agent.session.append('schedule/change', {
360
+ version: 1,
361
+ operation: 'create',
362
+ schedule: record,
363
+ })
364
+ }
365
+ await expect(scaffold.ctx.sessions.flush(everyHandle.agent.session)).resolves.toBe(true)
366
+ await workspace.attachSession(everyHandle.agent.id)
367
+ const everyListed = await scaffold.ctx.tools.execute({
368
+ signal: AbortSignal.timeout(10_000),
369
+ callId: ToolCallId('schedule-every-list'),
370
+ name: 'schedule_list',
371
+ arguments: {},
372
+ agent: everyHandle.agent,
373
+ })
374
+ expect(everyListed.isError).toBe(false)
375
+ everyAssistantReply = await waitForReply(everyHandle, EVERY_REPLY, 15_000)
376
+ await everyHandle.agent.whenIdle()
377
+ await expect(scaffold.ctx.sessions.flush(everyHandle.agent.session)).resolves.toBe(true)
378
+
379
+ atHandle = await scaffold.ctx.agents.create({
380
+ sessionId: SessionId('schedule-at-web-e2e'),
381
+ meta: { cwd },
382
+ agentOptions: { provider: AT_PROVIDER, model: MODEL },
383
+ })
384
+ atHandle.agent.session.append('session/title', {
385
+ title: 'Explicit local-time reminder',
386
+ messageSeqs: [],
387
+ source: { kind: 'user' },
388
+ })
389
+ atHandle.agent.followup(createUserMessage({
390
+ content: [{ type: 'text', text: 'Prepare the reminder test session.' }],
391
+ source: { kind: 'plugin', plugin: 'schedule-web-e2e' },
392
+ }))
393
+ await atHandle.agent.whenIdle()
394
+ expect(atAdapter.requests).toHaveLength(1)
395
+ await expect(scaffold.ctx.sessions.flush(atHandle.agent.session)).resolves.toBe(true)
396
+ await workspace.attachSession(atHandle.agent.id)
397
+ await page.reload({ waitUntil: 'load' })
398
+ await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
399
+ const workspaceItem = page.locator('[role="treeitem"]').first()
400
+ await workspaceItem.waitFor({ timeout: 15_000 })
401
+ const expansionDeadline = Date.now() + 5_000
402
+ while (await workspaceItem.getAttribute('aria-expanded') !== 'true') {
403
+ if (Date.now() >= expansionDeadline) throw new Error('workspace item did not expand')
404
+ if (await workspaceItem.getAttribute('aria-expanded') !== 'true') {
405
+ await workspaceItem.click()
406
+ }
407
+ await new Promise<void>(resolve => setTimeout(resolve, 50))
408
+ }
409
+ const atSession = page.getByRole('treeitem', { name: /Explicit local-time reminder/ })
410
+ await atSession.waitFor({ timeout: 15_000 })
411
+ await atSession.click()
412
+ const composer = page.locator('[data-composer-input][contenteditable="true"]').last()
413
+ await composer.fill(AT_USER_PROMPT)
414
+ const settled = scaffold.whenTurnSettled(60_000)
415
+ await page.getByRole('button', { name: 'Send message', exact: true }).click()
416
+ expect(await settled).toBe(atHandle.agent.id)
417
+ await page.getByText(AT_ACK, { exact: true }).waitFor({ timeout: 15_000 })
418
+ atAssistantReply = await waitForReply(atHandle, AT_REPLY, 20_000)
419
+ await atHandle.agent.whenIdle()
420
+ await expect(scaffold.ctx.sessions.flush(atHandle.agent.session)).resolves.toBe(true)
421
+ }, 120_000)
422
+
423
+ afterAll(async () => {
424
+ const failures: unknown[] = []
425
+ await browser?.close().catch((error: unknown) => failures.push(error))
426
+ await atHandle?.dispose().catch((error: unknown) => failures.push(error))
427
+ await everyHandle?.dispose().catch((error: unknown) => failures.push(error))
428
+ await afterHandle?.dispose().catch((error: unknown) => failures.push(error))
429
+ await scaffold?.close().catch((error: unknown) => failures.push(error))
430
+ if (failures.length === 1) throw failures[0]
431
+ if (failures.length > 1) throw new AggregateError(failures, 'Schedule Web evidence teardown failed')
432
+ })
433
+
434
+ it('renders After as an ordinary assistant follow-up', async () => {
435
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-schedule-after'))
436
+ const reminderRequest = afterAdapter.requests[0]
437
+ if (reminderRequest === undefined) throw new Error('model did not receive the After reminder')
438
+ expectReminderFraming(reminderRequest)
439
+ const session = page.getByRole('treeitem', { name: /Scheduled After follow-up/ })
440
+ await session.click()
441
+ if (afterAssistantReply === undefined) throw new Error('After assistant reply was not captured')
442
+ const selector = `[data-chat-anchor-key="${assistantKey(afterAssistantReply)}"]`
443
+ const row = page.locator(selector)
444
+ await row.waitFor({ timeout: 15_000 })
445
+ expect(await row.getAttribute('data-chat-flow-kind')).toBe('assistant-step')
446
+ expect(await row.textContent()).toContain(AFTER_REPLY)
447
+ await compareOrRefreshGolden(
448
+ AFTER_EXPECTED,
449
+ await captureStableAria(page, selector, scaffold.workspaceCwd),
450
+ MODE,
451
+ )
452
+ expect(await page.getByRole('button', { name: REMINDER_TRIGGER_NAME }).count()).toBe(0)
453
+ }, 60_000)
454
+
455
+ it('batches one latest occurrence per overdue Every record into an ordinary follow-up', async () => {
456
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-schedule-every'))
457
+ const ids = new Set(everyRecords.map(record => record.id))
458
+ const dispatches = everyHandle.agent.session.snapshotEvents().filter(event => (
459
+ event.type === 'schedule/change'
460
+ && event.data.operation === 'dispatch'
461
+ && ids.has(event.data.id)
462
+ ))
463
+ expect(dispatches).toHaveLength(2)
464
+ const acceptedAt = dispatches.map((event) => {
465
+ if (event.type !== 'schedule/change' || event.data.operation !== 'dispatch'
466
+ || !('acceptedAt' in event.data)) throw new Error('expected Every dispatch')
467
+ return event.data.acceptedAt
468
+ })
469
+ expect(new Set(acceptedAt).size).toBe(1)
470
+ const decision = acceptedAt[0]
471
+ if (decision === undefined) throw new Error('missing Every decision time')
472
+
473
+ const batch = everyHandle.agent.session.snapshotEvents().find(event => (
474
+ event.type === 'user/message'
475
+ && event.data.source.kind === 'plugin'
476
+ && event.data.source.plugin === 'schedule'
477
+ && event.data.content.some(block => block.type === 'text'
478
+ && block.text.startsWith('[SCHEDULE REMINDER BATCH]'))
479
+ ))
480
+ if (batch?.type !== 'user/message') throw new Error('missing Every batch message')
481
+ const batchBlock = batch.data.content.find(block => block.type === 'text')
482
+ if (batchBlock?.type !== 'text') throw new Error('missing Every batch text')
483
+ for (const record of everyRecords) {
484
+ const occurrenceAt = resolveEveryOccurrence(record, Date.parse(decision)).occurrenceAt
485
+ expect(batchBlock.text).toContain(JSON.stringify({
486
+ schedule_id: record.id,
487
+ occurrence_at: occurrenceAt,
488
+ reminder_prompt: record.prompt,
489
+ }).slice(1, -1))
490
+ }
491
+ expect(everyAdapter.requests).toHaveLength(1)
492
+ const reminderRequest = everyAdapter.requests[0]
493
+ if (reminderRequest === undefined) throw new Error('model did not receive the Every batch')
494
+ expect(requestText(reminderRequest)).toContain(batchBlock.text)
495
+ expectReminderFraming(reminderRequest)
496
+ const active = foldScheduleEvents(everyHandle.agent.session.snapshotEvents()).active
497
+ expect(active).toHaveLength(2)
498
+ expect(active.every(record => Date.parse(record.scheduledAt) > Date.parse(decision))).toBe(true)
499
+
500
+ const session = page.getByRole('treeitem', { name: /Fixed-rate reminder batch/ })
501
+ await session.click()
502
+ if (everyAssistantReply === undefined) throw new Error('Every assistant reply was not captured')
503
+ const selector = `[data-chat-anchor-key="${assistantKey(everyAssistantReply)}"]`
504
+ const row = page.locator(selector)
505
+ await row.waitFor({ timeout: 15_000 })
506
+ expect(await row.getAttribute('data-chat-flow-kind')).toBe('assistant-step')
507
+ expect(await row.textContent()).toContain(EVERY_REPLY)
508
+ await compareOrRefreshGolden(
509
+ EVERY_EXPECTED,
510
+ await captureStableAria(page, selector, scaffold.workspaceCwd),
511
+ MODE,
512
+ )
513
+ await page.getByRole('button', { name: '2 reminders', exact: true }).waitFor({ timeout: 15_000 })
514
+ expect(await page.getByRole('list', { name: 'Active reminders' }).count()).toBe(0)
515
+ }, 60_000)
516
+
517
+ it('uses request-local browser context to create an explicit local At reminder', async () => {
518
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-schedule-at'))
519
+ const user = atHandle.agent.session.snapshotEvents().find(event => (
520
+ event.type === 'user/message'
521
+ && event.data.source.kind === 'user'
522
+ && event.data.content.some(block => block.type === 'text' && block.text === AT_USER_PROMPT)
523
+ ))
524
+ if (user?.type !== 'user/message' || user.data.source.kind !== 'user') {
525
+ throw new Error('missing browser user-rpc message')
526
+ }
527
+ expect(user.data.source).toMatchObject({ kind: 'user', clientTimeZone: AT_BROWSER_ZONE })
528
+ expect(typeof (user.data.source as { rpcId?: unknown }).rpcId).toBe('string')
529
+
530
+ const firstRequest = atAdapter.requests[1]
531
+ if (firstRequest === undefined) throw new Error('model did not receive the browser prompt')
532
+ expect(requestText(firstRequest)).toContain(
533
+ `Browser time zone for this request: ${AT_BROWSER_ZONE}. `
534
+ + 'Interpret otherwise-unqualified dates and times in this zone.',
535
+ )
536
+ expect(firstRequest.tools?.some(tool => tool.name === 'schedule_create')).toBe(true)
537
+ const selectedAt = atAdapter.selectedAt
538
+ const scheduledAt = atAdapter.scheduledAt
539
+ if (selectedAt === undefined || scheduledAt === undefined) {
540
+ throw new Error('model did not choose an explicit local At target')
541
+ }
542
+ expect(selectedAt.time_zone).toBe(AT_BROWSER_ZONE)
543
+
544
+ const toolCall = atHandle.agent.session.snapshotEvents().find(event => (
545
+ event.type === 'tool/call' && event.data.name === 'schedule_create'
546
+ ))
547
+ if (toolCall?.type !== 'tool/call') throw new Error('missing schedule_create tool call')
548
+ expect(JSON.parse(toolCall.data.arguments)).toEqual({ prompt: AT_PROMPT, at: selectedAt })
549
+ const created = atHandle.agent.session.snapshotEvents().find(event => (
550
+ event.type === 'schedule/change'
551
+ && event.data.operation === 'create'
552
+ && event.data.schedule.kind === 'at'
553
+ ))
554
+ if (created?.type !== 'schedule/change' || created.data.operation !== 'create') {
555
+ throw new Error('explicit local At call did not create a durable record')
556
+ }
557
+ const schedule = created.data.schedule
558
+ expect(schedule).toMatchObject({
559
+ kind: 'at',
560
+ prompt: AT_PROMPT,
561
+ scheduledAt,
562
+ })
563
+ expect(atHandle.agent.session.snapshotEvents().filter(event => (
564
+ event.type === 'schedule/change'
565
+ && event.data.operation === 'dispatch'
566
+ && event.data.id === schedule.id
567
+ ))).toHaveLength(1)
568
+ expect(atAdapter.requests).toHaveLength(4)
569
+ const reminderRequest = atAdapter.requests[3]
570
+ if (reminderRequest === undefined) throw new Error('model did not receive the At reminder')
571
+ expectReminderFraming(reminderRequest)
572
+
573
+ const session = page.getByRole('treeitem', { name: /Explicit local-time reminder/ })
574
+ await session.click()
575
+ if (atAssistantReply === undefined) throw new Error('At assistant reply was not captured')
576
+ const selector = `[data-chat-anchor-key="${assistantKey(atAssistantReply)}"]`
577
+ const row = page.locator(selector)
578
+ await row.waitFor({ timeout: 15_000 })
579
+ expect(await row.getAttribute('data-chat-flow-kind')).toBe('assistant-step')
580
+ expect(await row.textContent()).toContain(AT_REPLY)
581
+ await compareOrRefreshGolden(
582
+ AT_EXPECTED,
583
+ await captureStableAria(page, selector, scaffold.workspaceCwd),
584
+ MODE,
585
+ )
586
+ expect(await page.getByRole('button', { name: REMINDER_TRIGGER_NAME }).count()).toBe(0)
587
+ expect(tripwire.pageErrors).toEqual([])
588
+ expect(tripwire.warnings).toEqual([])
589
+ }, 60_000)
590
+
591
+ it('keeps the fixture inventory closed', async () => {
592
+ await assertFixtureInventory(SNAPSHOT_DIR, [
593
+ 'at-conversation.expected.md',
594
+ 'conversation.expected.md',
595
+ 'every-conversation.expected.md',
596
+ ])
597
+ })
598
+ })
599
+
600
+ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => {
601
+ let scaffold: WebScaffold
602
+ let browser: Browser
603
+ let page: Page
604
+ let tripwire: ReturnType<typeof watchConsole>
605
+
606
+ beforeAll(async () => {
607
+ const fixture = await readFile(CATALOG_FIXTURE, 'utf8')
608
+ scaffold = await launchWebScaffold({
609
+ extraOverlayPath: OVERLAY,
610
+ })
611
+ await seedSession(scaffold, fixture, CATALOG_SESSION_ID, 'standard')
612
+ const workspace = await scaffold.ctx.workspaceRegistry.create(scaffold.workspaceCwd)
613
+ await workspace.attachSession(CATALOG_SESSION_ID)
614
+
615
+ // Seed the zero-I/O list view before the Session is opened.
616
+ const catalogReader = await scaffold.ctx.sessionPersistence.open(CATALOG_SESSION_ID, 'read')
617
+ try {
618
+ const catalogEvents = [...(await catalogReader.read()).events]
619
+ scaffold.ctx.sessionProjectionCache.coldSnapshot(catalogReader.header, catalogReader.inheritedEventCount, catalogEvents)
620
+ } finally {
621
+ await catalogReader.close()
622
+ }
623
+
624
+ browser = await chromium.launch()
625
+ page = await browser.newPage({
626
+ viewport: { width: 900, height: 900 },
627
+ locale: 'en-US',
628
+ timezoneId: AT_BROWSER_ZONE,
629
+ })
630
+ await page.clock.setFixedTime(new Date(CATALOG_NOW))
631
+ await page.addInitScript(() => { localStorage.setItem('dsh.locale', 'en') })
632
+ tripwire = watchConsole(page)
633
+ await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
634
+ await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
635
+ await page.evaluate(() => { document.body.removeAttribute('data-ds-dark-theme') })
636
+ const openSidebar = page.getByRole('button', { name: 'Open sidebar' })
637
+ if (await openSidebar.isVisible()) {
638
+ await openSidebar.click()
639
+ await page.getByRole('button', { name: 'Collapse sidebar' }).waitFor({ timeout: 10_000 })
640
+ }
641
+ const workspaceRow = page.locator('[role="treeitem"]').first()
642
+ await workspaceRow.waitFor({ timeout: 15_000 })
643
+ const expansionDeadline = Date.now() + 5_000
644
+ while (await workspaceRow.getAttribute('aria-expanded') !== 'true') {
645
+ if (Date.now() >= expansionDeadline) throw new Error('workspace item did not expand')
646
+ await workspaceRow.click()
647
+ await new Promise<void>(resolve => setTimeout(resolve, 50))
648
+ }
649
+ await page.getByRole('treeitem', { name: new RegExp(CATALOG_TITLE) }).waitFor({ timeout: 15_000 })
650
+ }, 120_000)
651
+
652
+ afterAll(async () => {
653
+ const failures: unknown[] = []
654
+ await browser?.close().catch((error: unknown) => failures.push(error))
655
+ await scaffold?.close().catch((error: unknown) => failures.push(error))
656
+ if (failures.length === 1) throw failures[0]
657
+ if (failures.length > 1) throw new AggregateError(failures, 'Schedule catalog teardown failed')
658
+ })
659
+
660
+ it('replays the overlay-only catalog and sidebar marker, then removes both live', async () => {
661
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-schedule-catalog'))
662
+ const base = composeEntries([
663
+ loadOverlayPatches('Schedule catalog base roster', BASE_PATCH),
664
+ loadOverlayPatches('Schedule catalog base roster', WEB_PATCH),
665
+ ])
666
+ const scheduled = composeEntries([
667
+ loadOverlayPatches('Schedule catalog overlay roster', BASE_PATCH),
668
+ loadOverlayPatches('Schedule catalog overlay roster', WEB_PATCH),
669
+ loadOverlayPatches('Schedule catalog overlay roster', OVERLAY),
670
+ ])
671
+ expect(base.find(entry => entry.id === 'ui-schedule')).toMatchObject({
672
+ name: '@deepseek-ai/dsh-client-ui-schedule',
673
+ disabled: true,
674
+ })
675
+ expect(scheduled.find(entry => entry.id === 'ui-schedule')).toMatchObject({
676
+ name: '@deepseek-ai/dsh-client-ui-schedule',
677
+ disabled: false,
678
+ })
679
+
680
+ const catalogRow = page.getByRole('treeitem', { name: new RegExp(CATALOG_TITLE) })
681
+ expect(await catalogRow.getByRole('img', { name: ACTIVE_SCHEDULE_LABEL }).count()).toBe(1)
682
+
683
+ await page.getByRole('button', { name: 'Search sessions' }).click()
684
+ const search = page.getByPlaceholder('Search sessions', { exact: false })
685
+ await search.fill(CATALOG_TITLE)
686
+ const result = page.getByRole('tree', { name: 'Search results' })
687
+ .getByRole('treeitem', { name: new RegExp(CATALOG_TITLE) })
688
+ await result.waitFor({ timeout: 15_000 })
689
+ expect(await result.getByRole('img', { name: ACTIVE_SCHEDULE_LABEL }).count()).toBe(1)
690
+ expect(await result.getByRole('button').count()).toBe(0)
691
+
692
+ await page.getByRole('button', { name: 'Clear search' }).click()
693
+ await catalogRow.waitFor({ timeout: 15_000 })
694
+
695
+ await page.getByRole('button', { name: 'View options' }).click()
696
+ await page.getByRole('menuitem', { name: 'In one list' }).click()
697
+ const flatRow = page.getByRole('treeitem', { name: new RegExp(CATALOG_TITLE) })
698
+ await flatRow.waitFor({ timeout: 15_000 })
699
+ expect(await flatRow.getByRole('img', { name: ACTIVE_SCHEDULE_LABEL }).count()).toBe(1)
700
+
701
+ await page.getByRole('button', { name: 'View options' }).click()
702
+ await page.getByRole('menuitem', { name: 'WorkSpace' }).click()
703
+ await catalogRow.waitFor({ timeout: 15_000 })
704
+ expect(await catalogRow.getByRole('img', { name: ACTIVE_SCHEDULE_LABEL }).count()).toBe(1)
705
+
706
+ await openSession(page, CATALOG_TITLE)
707
+ const parentAgent = await liveAgent(scaffold, CATALOG_SESSION_ID)
708
+
709
+ const trigger = page.getByRole('button', { name: '3 reminders' })
710
+ await trigger.waitFor({ timeout: 15_000 })
711
+ await trigger.click()
712
+ const catalog = page.getByRole('list', { name: 'Active reminders' })
713
+ await catalog.waitFor({ timeout: 10_000 })
714
+ expect(await catalog.getByRole('listitem').count()).toBe(3)
715
+ const lightLayout = await page.evaluate(() => {
716
+ const triggerElement = document.querySelector('button[aria-label="3 reminders"]')
717
+ const catalogElement = document.querySelector('[aria-label="Active reminders"]')
718
+ if (!(triggerElement instanceof HTMLElement) || !(catalogElement instanceof HTMLElement)) {
719
+ throw new Error('active reminder trigger or catalog is not mounted')
720
+ }
721
+ const triggerBox = triggerElement.getBoundingClientRect()
722
+ const catalogBox = catalogElement.getBoundingClientRect()
723
+ const viewport = window.innerWidth
724
+ return {
725
+ bodyPortal: catalogElement.parentElement === document.body,
726
+ position: getComputedStyle(catalogElement).position,
727
+ triggerLeft: triggerBox.left,
728
+ catalogLeft: catalogBox.left,
729
+ catalogRight: catalogBox.right,
730
+ width: catalogBox.width,
731
+ viewport,
732
+ expectedLeft: Math.min(Math.max(16, triggerBox.left), viewport - catalogBox.width - 16),
733
+ scrollWidth: document.documentElement.scrollWidth,
734
+ background: getComputedStyle(catalogElement).backgroundColor,
735
+ }
736
+ })
737
+ expect(lightLayout.bodyPortal).toBe(true)
738
+ expect(lightLayout.position).toBe('fixed')
739
+ expect(lightLayout.width).toBe(336)
740
+ expect(lightLayout.catalogLeft).toBe(lightLayout.expectedLeft)
741
+ expect(lightLayout.catalogLeft).toBeLessThan(lightLayout.triggerLeft)
742
+ expect(lightLayout.catalogRight).toBeLessThanOrEqual(lightLayout.viewport - 16)
743
+ expect(lightLayout.scrollWidth).toBeLessThanOrEqual(lightLayout.viewport)
744
+ expect(lightLayout.background).not.toBe('rgba(0, 0, 0, 0)')
745
+ const longRow = catalog.getByRole('listitem').filter({ hasText: 'Join release review' })
746
+ const cadenceRow = catalog.getByRole('listitem').filter({ hasText: 'Check exact cadence' })
747
+ const longPrompt = longRow.locator(':scope > span').nth(1)
748
+ const promptLayout = await longPrompt.evaluate(element => ({
749
+ height: element.getBoundingClientRect().height,
750
+ clientWidth: element.clientWidth,
751
+ scrollWidth: element.scrollWidth,
752
+ }))
753
+ expect(promptLayout.height).toBeGreaterThan(18)
754
+ expect(promptLayout.scrollWidth).toBeLessThanOrEqual(promptLayout.clientWidth)
755
+ const [longRowLayout, cadenceRowLayout] = await Promise.all([
756
+ longRow.evaluate((element) => {
757
+ const box = element.getBoundingClientRect()
758
+ return {
759
+ bottom: box.bottom,
760
+ clientHeight: element.clientHeight,
761
+ scrollHeight: element.scrollHeight,
762
+ childBottoms: [...element.children].map(child => child.getBoundingClientRect().bottom),
763
+ }
764
+ }),
765
+ cadenceRow.evaluate((element) => {
766
+ const box = element.getBoundingClientRect()
767
+ return { top: box.top, bottom: box.bottom }
768
+ }),
769
+ ])
770
+ expect(longRowLayout.scrollHeight).toBeLessThanOrEqual(longRowLayout.clientHeight)
771
+ expect(longRowLayout.childBottoms).not.toHaveLength(0)
772
+ for (const childBottom of longRowLayout.childBottoms) {
773
+ expect(childBottom).toBeLessThanOrEqual(longRowLayout.bottom)
774
+ }
775
+ expect(longRowLayout.bottom).toBeLessThanOrEqual(cadenceRowLayout.top)
776
+ expect(cadenceRowLayout.bottom).toBeGreaterThan(cadenceRowLayout.top)
777
+ const scrollLayout = await catalog.evaluate(element => ({
778
+ clientHeight: element.clientHeight,
779
+ scrollHeight: element.scrollHeight,
780
+ }))
781
+ expect(scrollLayout.scrollHeight).toBeGreaterThan(scrollLayout.clientHeight)
782
+
783
+ const evidenceDir = join(REPO_ROOT, '.artifacts')
784
+ await mkdir(evidenceDir, { recursive: true })
785
+ await writeFile(
786
+ join(evidenceDir, 'web-e2e-schedule-catalog-left-alignment.json'),
787
+ `${JSON.stringify(lightLayout, null, 2)}\n`,
788
+ )
789
+ await page.screenshot({
790
+ path: join(evidenceDir, 'web-e2e-schedule-catalog-left-alignment.png'),
791
+ fullPage: true,
792
+ })
793
+
794
+ await page.evaluate(() => { document.body.setAttribute('data-ds-dark-theme', '') })
795
+ const darkBackground = await catalog.evaluate(element => getComputedStyle(element).backgroundColor)
796
+ expect(darkBackground).not.toBe('rgba(0, 0, 0, 0)')
797
+ expect(darkBackground).not.toBe(lightLayout.background)
798
+ await compareOrRefreshGolden(
799
+ CATALOG_EXPECTED,
800
+ await captureStableAria(page, '[aria-label="Active reminders"]', scaffold.workspaceCwd),
801
+ MODE,
802
+ )
803
+
804
+ const sessionRow = page.getByRole('treeitem', { name: new RegExp(CATALOG_TITLE) })
805
+ expect(await sessionRow.getByRole('img', { name: ACTIVE_SCHEDULE_LABEL }).count()).toBe(1)
806
+ for (const id of Object.values(CATALOG_IDS)) {
807
+ parentAgent.session.append('schedule/change', { version: 1, operation: 'delete', id })
808
+ }
809
+ await expect(scaffold.ctx.sessions.flush(parentAgent.session)).resolves.toBe(true)
810
+ await expect.poll(() => page.getByRole('button', { name: REMINDER_TRIGGER_NAME }).count(), {
811
+ timeout: 15_000,
812
+ }).toBe(0)
813
+ expect(await page.getByRole('list', { name: 'Active reminders' }).count()).toBe(0)
814
+ await expect.poll(() => sessionRow.getByRole('img', { name: ACTIVE_SCHEDULE_LABEL }).count(), {
815
+ timeout: 15_000,
816
+ }).toBe(0)
817
+ await assertFixtureInventory(CATALOG_SNAPSHOT_DIR, [
818
+ 'catalog.expected.md',
819
+ 'session.v3.jsonl',
820
+ 'system-prompt.expected.md',
821
+ 'tool-schemas.expected.json',
822
+ ])
823
+ expect(tripwire.pageErrors).toEqual([])
824
+ expect(tripwire.warnings).toEqual([])
825
+ }, 60_000)
826
+ })
apps/web/tests/session-unarchive.e2e.ts ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Web e2e scenario: the archived-session Settings page restores a Session
2
+ // through the real wire, from its row menu through the archive set, the page,
3
+ // and the reload that rebuilds state from the host baseline. Zero model calls:
4
+ // both verbs are host RPCs and the page reads already-loaded Session summaries,
5
+ // so no replay fixture mounts and a stray model stream fails loud.
6
+ import { readFile } from 'node:fs/promises'
7
+ import { fileURLToPath } from 'node:url'
8
+ import type { Browser, Locator, Page } from 'playwright'
9
+ import { chromium } from 'playwright'
10
+ import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
11
+ import { SessionId } from '@deepseek-ai/dsh-session'
12
+ import {
13
+ acknowledgeReloadConnectionLoss, launchWebScaffold, seedSession, watchConsole, type WebScaffold,
14
+ } from './scaffold.ts'
15
+ import { newEnglishPage, saveFailureShot } from './support.ts'
16
+
17
+ // The seed is another scenario's committed fixture, reused read-only: this
18
+ // spec needs any one cold Session row, not new recorded content.
19
+ const SEED = fileURLToPath(new URL('../../../snapshots/web/seeded-history/session.v3.jsonl', import.meta.url))
20
+ const SEED_ID = 'session-unarchive-web-e2e'
21
+
22
+ describe('web e2e: archived sessions are restored from the Settings page', () => {
23
+ let scaffold: WebScaffold
24
+ let browser: Browser
25
+ let page: Page
26
+ let tripwire: ReturnType<typeof watchConsole>
27
+
28
+ /**
29
+ * Expand the Ungrouped group when it renders collapsed so its rows are
30
+ * addressable, then return the section holding them.
31
+ * @returns the expanded Ungrouped section locator.
32
+ */
33
+ async function ungroupedSection(): Promise<Locator> {
34
+ const header = page.getByText('Ungrouped', { exact: true })
35
+ const groupRow = header.locator('..').locator('..')
36
+ await expect.poll(async () => {
37
+ if (await groupRow.count() === 0) return 'absent'
38
+ if (await groupRow.getAttribute('aria-expanded') !== 'true') {
39
+ await header.click()
40
+ return 'collapsed'
41
+ }
42
+ return 'expanded'
43
+ }, { timeout: 15_000 }).toBe('expanded')
44
+ return groupRow.locator('..')
45
+ }
46
+
47
+ /**
48
+ * Reveal and click a row action, re-hovering if a projection update replaces
49
+ * the row before its hover-only button becomes visible.
50
+ * @param row - the row owning the action.
51
+ * @param name - accessible name of the action button.
52
+ */
53
+ async function clickHoverAction(row: Locator, name: string): Promise<void> {
54
+ const button = row.getByRole('button', { name })
55
+ await expect.poll(async () => {
56
+ await row.hover()
57
+ return await button.isVisible()
58
+ }, { timeout: 10_000 }).toBe(true)
59
+ await button.click()
60
+ }
61
+
62
+ beforeAll(async () => {
63
+ scaffold = await launchWebScaffold({})
64
+ // Seed one cold session; with no Workspace registered it is the sidebar's
65
+ // only row, in the Ungrouped bucket.
66
+ await seedSession(scaffold, await readFile(SEED, 'utf8'), SEED_ID)
67
+ browser = await chromium.launch()
68
+ page = await newEnglishPage(browser)
69
+ tripwire = watchConsole(page)
70
+ await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
71
+ await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
72
+ }, 120_000)
73
+
74
+ afterAll(async () => {
75
+ await browser?.close()
76
+ await scaffold?.close()
77
+ })
78
+
79
+ it('archives the seed, unarchives it from Settings, and keeps it restored across reload', async () => {
80
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-session-unarchive'))
81
+ // Select the only visible Session, then give it a user-owned title: the
82
+ // locator binds to the seed's own copy on both sides of the round trip.
83
+ const seededRow = (await ungroupedSection()).locator('[role="treeitem"]')
84
+ .filter({ has: page.locator('button[aria-label^="Session actions for "]') })
85
+ await expect.poll(() => seededRow.count(), { timeout: 10_000 }).toBe(1)
86
+ await seededRow.click()
87
+ await expect.poll(() => seededRow.getAttribute('aria-selected'), { timeout: 10_000 }).toBe('true')
88
+ const { title } = await scaffold.ctx.sessionController.rename({
89
+ sessionId: SessionId(SEED_ID), title: `Unarchive target ${SEED_ID}`,
90
+ })
91
+ const sessionRow = page.getByRole('treeitem').filter({ has: page.getByText(title, { exact: true }) })
92
+ await expect.poll(() => sessionRow.count(), { timeout: 10_000 }).toBe(1)
93
+ await expect.poll(() => sessionRow.getAttribute('aria-selected'), { timeout: 10_000 }).toBe('true')
94
+
95
+ // Archive from the row menu: no confirmation dialog, and losing the last
96
+ // visible Session withdraws the whole Ungrouped bucket.
97
+ await clickHoverAction(sessionRow, `Session actions for ${title}`)
98
+ await page.getByRole('menuitem', { name: 'Archive session' }).click()
99
+ await expect.poll(() => sessionRow.count(), { timeout: 10_000 }).toBe(0)
100
+ await expect.poll(() => page.getByText('Ungrouped', { exact: true }).count(), { timeout: 10_000 }).toBe(0)
101
+ // Durable on the host: the registry-global set carries the id while the
102
+ // Session log itself stays in persistence untouched.
103
+ expect([...scaffold.ctx.workspaceRegistry.archivedSessionIds]).toEqual([SessionId(SEED_ID)])
104
+ expect((await scaffold.ctx.sessionPersistence.list()).map(snapshot => snapshot.header.id))
105
+ .toContain(SessionId(SEED_ID))
106
+
107
+ // The Settings page lists the archived Session behind its own search box.
108
+ await page.getByRole('button', { name: 'Settings', exact: true }).click()
109
+ const dialog = page.getByRole('dialog', { name: 'Settings' })
110
+ await dialog.waitFor({ timeout: 10_000 })
111
+ await dialog.getByRole('button', { name: 'Archived sessions' }).click()
112
+ const search = dialog.getByRole('searchbox', { name: 'Search archived sessions' })
113
+ await search.waitFor({ timeout: 10_000 })
114
+ const unarchiveRow = dialog.getByRole('button', { name: `Unarchive ${title}` })
115
+ await expect.poll(() => unarchiveRow.count(), { timeout: 10_000 }).toBe(1)
116
+ expect(await dialog.getByText(title, { exact: true }).count()).toBe(1)
117
+ expect(await dialog.getByText(/^Ungrouped · /).count()).toBe(1)
118
+ expect(await dialog.getByText('No archived sessions.', { exact: true }).count()).toBe(0)
119
+ // The search box filters these rows in both directions.
120
+ await search.fill('zzz-no-such-archived-session')
121
+ await expect.poll(
122
+ () => dialog.getByText('No matching sessions.', { exact: true }).count(),
123
+ { timeout: 5_000 },
124
+ ).toBe(1)
125
+ expect(await unarchiveRow.count()).toBe(0)
126
+ await search.fill(title)
127
+ await expect.poll(() => unarchiveRow.count(), { timeout: 5_000 }).toBe(1)
128
+ expect(await dialog.getByText('No matching sessions.', { exact: true }).count()).toBe(0)
129
+ await search.fill('')
130
+ await expect.poll(() => unarchiveRow.count(), { timeout: 5_000 }).toBe(1)
131
+
132
+ // Unarchive: the durable set empties (the row's own RPC), the page row
133
+ // leaves with the empty status, and the Session row is back in the sidebar.
134
+ await unarchiveRow.click()
135
+ await expect.poll(
136
+ () => [...scaffold.ctx.workspaceRegistry.archivedSessionIds],
137
+ { timeout: 10_000 },
138
+ ).toEqual([])
139
+ await expect.poll(() => unarchiveRow.count(), { timeout: 10_000 }).toBe(0)
140
+ expect(await dialog.getByText(title, { exact: true }).count()).toBe(0)
141
+ await expect.poll(
142
+ () => dialog.getByText('No archived sessions.', { exact: true }).count(),
143
+ { timeout: 10_000 },
144
+ ).toBe(1)
145
+ await dialog.getByRole('button', { name: 'Close' }).last().click()
146
+ await dialog.waitFor({ state: 'hidden', timeout: 10_000 })
147
+ await ungroupedSection()
148
+ await expect.poll(() => sessionRow.count(), { timeout: 15_000 }).toBe(1)
149
+
150
+ // Reload: the restored row is rebuilt from the host baseline, so the
151
+ // unarchive was durable and not merely client state.
152
+ const warningStart = tripwire.warnings.length
153
+ await page.reload({ waitUntil: 'load' })
154
+ await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
155
+ acknowledgeReloadConnectionLoss(tripwire, warningStart)
156
+ await ungroupedSection()
157
+ await expect.poll(() => sessionRow.count(), { timeout: 15_000 }).toBe(1)
158
+ expect(tripwire.pageErrors).toEqual([])
159
+ expect(tripwire.warnings).toEqual([])
160
+ }, 120_000)
161
+ })
apps/web/tests/skill-user-invoke.e2e.ts ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Web e2e scenario: a user invokes a disable-model-invocation skill through
2
+ // the composer (issue #1470). The entered `/name args` line claims into
3
+ // skill.invoke: the real host forwards the gesture as an ordinary user
4
+ // prompt, injects the rendered body as instructions context named after the
5
+ // skill, and starts a turn answered by the replay adapter. The transcript shows
6
+ // the gesture bubble, the collapsed context-injection row, and the reply.
7
+ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
8
+ import { tmpdir } from 'node:os'
9
+ import { fileURLToPath } from 'node:url'
10
+ import { join } from 'node:path'
11
+ import type { Browser, Page } from 'playwright'
12
+ import { chromium } from 'playwright'
13
+ import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
14
+ import type { ReplayOverrideDoc } from '@deepseek-ai/dsh-llm-replay'
15
+ import {
16
+ assertFixtureInventory,
17
+ captureExpandedTurnProcessAria,
18
+ captureStableAria,
19
+ compareOrRefreshGolden,
20
+ launchWebScaffold,
21
+ watchConsole,
22
+ webSnapshotMode,
23
+ type WebScaffold,
24
+ } from './scaffold.ts'
25
+ import { connectFreshWorkspace, expandOwningTurnProcess, newEnglishPage, saveFailureShot } from './support.ts'
26
+
27
+ const SNAPSHOT_DIR = fileURLToPath(new URL('./expected/skill-user-invoke', import.meta.url))
28
+ const UI_EXPECTED = join(SNAPSHOT_DIR, 'ui.expected.md')
29
+ const UI_EXPANDED_EXPECTED = join(SNAPSHOT_DIR, 'ui-expanded.expected.md')
30
+ const MODE = webSnapshotMode()
31
+
32
+ const SKILL_NAME = 'user-invoke-demo'
33
+ const ARGS_TEXT = '@"meeting notes.md" and confirm the fixture wiring'
34
+ const REPLY = 'USER_INVOKE_REPLY acknowledged; following the injected skill.'
35
+
36
+ async function seedUserOnlySkill(workspaceCwd: string): Promise<void> {
37
+ const directory = join(workspaceCwd, 'workspace', '.agents', 'skills', SKILL_NAME)
38
+ await mkdir(directory, { recursive: true })
39
+ await writeFile(join(directory, 'SKILL.md'), [
40
+ '---',
41
+ `name: ${SKILL_NAME}`,
42
+ 'description: Prove user-explicit invocation of a model-hidden skill',
43
+ 'disable-model-invocation: true',
44
+ '---',
45
+ '',
46
+ 'Reply with the fixture acknowledgement line.',
47
+ '',
48
+ ].join('\n'))
49
+ }
50
+
51
+ const REPLAY: ReplayOverrideDoc = [{
52
+ kind: 'chunks',
53
+ chunks: [
54
+ { type: 'block-start', index: 0, blockType: 'text' },
55
+ { type: 'text-delta', index: 0, text: REPLY },
56
+ { type: 'block-end', index: 0, block: { type: 'text', text: REPLY } },
57
+ { type: 'usage', usage: { inputTokens: 256, outputTokens: 16 } },
58
+ { type: 'finish', reason: { kind: 'stop' } },
59
+ ],
60
+ }]
61
+
62
+ describe.skipIf(MODE === 'record')('web e2e: user-explicit skill invocation through the composer', () => {
63
+ let scaffold: WebScaffold
64
+ let browser: Browser
65
+ let page: Page
66
+ let replayDir: string
67
+ let tripwire: ReturnType<typeof watchConsole>
68
+
69
+ beforeAll(async () => {
70
+ replayDir = await mkdtemp(join(tmpdir(), 'dsh-skill-user-invoke-replay-'))
71
+ const replayOverride = join(replayDir, 'replay.override.json')
72
+ await writeFile(replayOverride, JSON.stringify(REPLAY))
73
+ scaffold = await launchWebScaffold({
74
+ replayFixture: join(replayDir, 'override-only.jsonl'),
75
+ replayOverride,
76
+ // Paced replay keeps the timing-derived chrome (TTFT / tok/s) present
77
+ // deterministically; instant playback races it in and out of the golden.
78
+ paceMs: 10,
79
+ })
80
+ await seedUserOnlySkill(scaffold.workspaceCwd)
81
+ await writeFile(join(scaffold.workspaceCwd, 'workspace', 'meeting notes.md'), '# Meeting notes\n\nSent reference preview.\n')
82
+ browser = await chromium.launch()
83
+ page = await newEnglishPage(browser)
84
+ tripwire = watchConsole(page)
85
+ await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
86
+ await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
87
+ await connectFreshWorkspace(page, scaffold.workspaceCwd)
88
+ }, 120_000)
89
+
90
+ afterAll(async () => {
91
+ const failures: unknown[] = []
92
+ await browser?.close().catch((error: unknown) => failures.push(error))
93
+ await scaffold?.close().catch((error: unknown) => failures.push(error))
94
+ if (replayDir !== undefined) {
95
+ await rm(replayDir, { recursive: true, force: true })
96
+ .catch((error: unknown) => failures.push(error))
97
+ }
98
+ if (failures.length === 1) throw failures[0]
99
+ if (failures.length > 1) throw new AggregateError(failures, 'skill-user-invoke e2e cleanup failed')
100
+ })
101
+
102
+ it('claims /name args into a gesture bubble, an injection row, and a replayed answer', async () => {
103
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-skill-user-invoke'))
104
+ const composer = page.locator('[data-composer-input][contenteditable="true"]').last()
105
+ await composer.waitFor({ timeout: 15_000 })
106
+
107
+ // The menu lists the user-only skill (its only entry point) before enter.
108
+ await composer.fill(`/${SKILL_NAME}`)
109
+ const menu = page.getByRole('listbox', { name: 'Trigger suggestions' })
110
+ await expect.poll(
111
+ () => menu.getByRole('option', { name: new RegExp(SKILL_NAME) }).count(),
112
+ { timeout: 10_000 },
113
+ ).toBe(1)
114
+
115
+ const settled = scaffold.whenTurnSettled()
116
+ await composer.fill(`/${SKILL_NAME} ${ARGS_TEXT}`)
117
+ await composer.press('Enter')
118
+
119
+ // The gesture stays an ordinary user bubble (decorated /name token plus
120
+ // the trailing text), ahead of the injected context.
121
+ const bubble = page.locator('[data-ref-chip="skill"]').first()
122
+ await bubble.waitFor({ timeout: 15_000 })
123
+ expect(await bubble.textContent()).toBe(`/${SKILL_NAME}`)
124
+
125
+ // The rendered body arrives as a context-injection row named after the
126
+ // skill. Context plus the final answer contributes no summary count, so
127
+ // the Turn uses the fallback title while the row's own disclosure remains usable.
128
+ const injectionFlow = page.locator('[data-chat-flow-kind="context"]').filter({ hasText: SKILL_NAME })
129
+ await injectionFlow.waitFor({ state: 'attached', timeout: 15_000 })
130
+ await page.getByText('USER_INVOKE_REPLY', { exact: false }).first().waitFor({ timeout: 20_000 })
131
+ await settled
132
+ const process = page.getByRole('button', { name: 'Thought for a while', exact: true })
133
+ await process.waitFor({ state: 'visible', timeout: 10_000 })
134
+ // The chip derives from the step's logged injection, so it must survive
135
+ // every later Node rebuild of the Turn (process publication, turn close).
136
+ expect(await bubble.count()).toBe(1)
137
+ expect(await bubble.textContent()).toBe(`/${SKILL_NAME}`)
138
+ await expandOwningTurnProcess(page, injectionFlow)
139
+ const injectionRow = page.getByRole('button', { name: `Context injection ${SKILL_NAME}` })
140
+ await injectionRow.click()
141
+ const injectionBody = page
142
+ .locator('[data-context-injection-body]')
143
+ .filter({ hasText: `<skill_content name="${SKILL_NAME}">` })
144
+ await injectionBody.waitFor({ timeout: 10_000 })
145
+ const injected = await injectionBody.textContent()
146
+ expect(injected).toContain('Reply with the fixture acknowledgement line.')
147
+ expect(injected).not.toContain(ARGS_TEXT)
148
+ await injectionRow.click()
149
+ await process.click()
150
+
151
+ const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
152
+ await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE)
153
+ const expanded = await captureExpandedTurnProcessAria(
154
+ page,
155
+ '[class*="centerCol"]',
156
+ scaffold.workspaceCwd,
157
+ )
158
+ await compareOrRefreshGolden(UI_EXPANDED_EXPECTED, expanded, MODE)
159
+ expect(tripwire.pageErrors).toEqual([])
160
+ expect(tripwire.warnings).toEqual([])
161
+ }, 60_000)
162
+
163
+ it('previews sent skill and quoted file references with prose-link hover styling after reloading history', async () => {
164
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-sent-reference-preview'))
165
+ await page.reload({ waitUntil: 'load' })
166
+ const skill = page.locator('[data-chat-flow-kind="user"] [data-ref-chip="skill"]').first()
167
+ await skill.waitFor({ timeout: 15_000 })
168
+ const preview = page.locator('[data-document-markdown]')
169
+ await skill.hover()
170
+ await expect.poll(() => skill.evaluate(el => getComputedStyle(el).textDecorationStyle)).toBe('dotted')
171
+ await skill.click()
172
+ await expect.poll(() => preview.textContent(), { timeout: 10_000 }).toContain('Reply with the fixture acknowledgement line.')
173
+ const file = page.locator('[data-chat-flow-kind="user"] [data-ref-chip="file"]').first()
174
+ await file.hover()
175
+ expect(await file.evaluate(el => getComputedStyle(el).textDecorationStyle)).toBe('dotted')
176
+ await file.click()
177
+ await expect.poll(() => preview.textContent()).toContain('Sent reference preview.')
178
+ await skill.click()
179
+ await expect.poll(() => preview.textContent()).toContain('Reply with the fixture acknowledgement line.')
180
+ expect(await page.locator('[data-chat-flow-kind="user"]').first().textContent()).toContain('and confirm the fixture wiring')
181
+ expect(tripwire.pageErrors).toEqual([])
182
+ expect(tripwire.warnings).toEqual([])
183
+ })
184
+
185
+ it('keeps its snapshot inventory closed', async () => {
186
+ await assertFixtureInventory(SNAPSHOT_DIR, ['ui.expected.md', 'ui-expanded.expected.md'])
187
+ })
188
+ })
apps/web/tests/stats-paged-history.e2e.ts ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Web e2e scenario: full-session stats over paged history. A deterministic
2
+ // 28-turn log (56 chat messages — more than one 50-message history page)
3
+ // seeded cold through the REAL persistence API must render whole-log turn/step
4
+ // counts from the sessionStats projection on first open, and loading the
5
+ // older page must NOT change them. This pins the bug the projection fixed:
6
+ // the pre-projection window fold recounted per loaded page, so 加载更早 grew
7
+ // the counter. Zero model calls; the seed is generated, not recorded, because
8
+ // no line of it is model output.
9
+ import { fileURLToPath } from 'node:url'
10
+ import type { Browser, Page } from 'playwright'
11
+ import { chromium } from 'playwright'
12
+ import { createSystemMessage } from '@deepseek-ai/dsh-llm'
13
+ import { SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session'
14
+ import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
15
+ import {
16
+ assertFixtureInventory, captureStableAria, compareOrRefreshGolden,
17
+ launchWebScaffold, seedSession, watchConsole, webSnapshotMode, type WebScaffold,
18
+ } from './scaffold.ts'
19
+ import { newEnglishPage, saveFailureShot } from './support.ts'
20
+
21
+ const SNAPSHOT_DIR = fileURLToPath(new URL('./expected/stats-paged-history', import.meta.url))
22
+ const UI_EXPECTED = fileURLToPath(new URL('./expected/stats-paged-history/ui.expected.md', import.meta.url))
23
+ const MODE = webSnapshotMode()
24
+ const SEED_ID = 'stats-paged-history-web-e2e'
25
+
26
+ /** Turn count: 2 chat messages per turn, so 28 turns overflow one 50-message page. */
27
+ const TURNS = 28
28
+ const FULL_COUNTS = `${TURNS} turns ${TURNS} steps`
29
+
30
+ /**
31
+ * Generate the seed: TURNS closed single-step turns of one short user prompt
32
+ * and one short assistant reply each. Fixed times pin displayed dates;
33
+ * the empty system head precedes every user message in the current format.
34
+ * @param turns - closed turns to generate.
35
+ * @returns session.jsonl text for {@link seedSession}.
36
+ */
37
+ function buildSeed(turns: number): string {
38
+ const lines = [JSON.stringify({
39
+ type: 'session', version: SESSION_FORMAT_VERSION, id: '{{sessionId}}',
40
+ createdAt: 1784974100000, cwd: '{{cwd}}/workspace', isSeeded: false, delegationDepth: 0,
41
+ })]
42
+ let seq = 0
43
+ let time = 1784974100000
44
+ const at = (event: Record<string, unknown>): void => {
45
+ lines.push(JSON.stringify({ ...event, seq: seq++, time: time++ }))
46
+ }
47
+ for (let turn = 1; turn <= turns; turn++) {
48
+ at({ type: 'turn/start', data: { turn } })
49
+ at({ type: 'step/start', data: { turn, step: 1 } })
50
+ if (turn === 1) {
51
+ at({
52
+ type: 'system/message',
53
+ data: { turn, step: 1, message: createSystemMessage('', '@deepseek-ai/dsh-system-prompt') },
54
+ surfaceOp: 'append',
55
+ })
56
+ }
57
+ at({
58
+ type: 'user/message',
59
+ data: {
60
+ id: `00000000-0000-4000-9000-${String(turn).padStart(12, '0')}`,
61
+ role: 'user',
62
+ content: [{ type: 'text', text: `m${turn}` }],
63
+ source: { kind: 'user' },
64
+ },
65
+ surfaceOp: 'append',
66
+ })
67
+ at({
68
+ type: 'assistant/message',
69
+ data: {
70
+ stream: [],
71
+ turn,
72
+ step: 1,
73
+ message: {
74
+ id: `00000000-0000-4000-8000-${String(turn).padStart(12, '0')}`,
75
+ role: 'assistant',
76
+ content: [{ type: 'text', text: `r${turn}` }],
77
+ source: { kind: 'model', provider: 'snapshot', model: 'snapshot-replier' },
78
+ },
79
+ },
80
+ surfaceOp: 'append',
81
+ })
82
+ at({ type: 'step/end', data: { turn, step: 1 } })
83
+ at({ type: 'turn/end', data: { turn, reason: { kind: 'completed' } } })
84
+ }
85
+ return `${lines.join('\n')}\n`
86
+ }
87
+
88
+ describe('web e2e: whole-session stats survive history paging', () => {
89
+ let scaffold: WebScaffold
90
+ let browser: Browser
91
+ let page: Page
92
+ let tripwire: ReturnType<typeof watchConsole>
93
+
94
+ beforeAll(async () => {
95
+ if (MODE === 'record') throw new Error('stats-paged-history is a keyless assembled snapshot')
96
+ scaffold = await launchWebScaffold({})
97
+ await seedSession(scaffold, buildSeed(TURNS), SEED_ID)
98
+ browser = await chromium.launch()
99
+ page = await newEnglishPage(browser)
100
+ tripwire = watchConsole(page)
101
+ await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
102
+ await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
103
+ }, 120_000)
104
+
105
+ afterAll(async () => {
106
+ await browser?.close()
107
+ await scaffold?.close()
108
+ })
109
+
110
+ it('renders full-session counts on the partial tail page and keeps them across load-older', async () => {
111
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-stats-paged'))
112
+ const groupRow = page.locator('[role="treeitem"]').first()
113
+ await groupRow.waitFor({ timeout: 15_000 })
114
+ await groupRow.click()
115
+ const sessionRow = page.locator('[role="treeitem"]').nth(1)
116
+ await sessionRow.waitFor({ timeout: 10_000 })
117
+ await sessionRow.click()
118
+ // Settled barrier: the newest recorded reply renders from the tail page.
119
+ await expect.poll(() => page.getByText(`r${TURNS}`, { exact: true }).count(), { timeout: 15_000 }).toBe(1)
120
+ // The tail page is partial (56 messages > one 50-message page): the first
121
+ // turns are NOT loaded, yet the strip already reports the whole log —
122
+ // the sessionStats projection, not the window fold.
123
+ expect(await page.getByText('m1', { exact: true }).count()).toBe(0)
124
+ await expect.poll(() => page.getByText(FULL_COUNTS, { exact: false }).count(), { timeout: 10_000 }).toBe(1)
125
+ const strip = page.getByText(FULL_COUNTS, { exact: false }).locator('..')
126
+ const stripBeforePaging = await strip.textContent()
127
+
128
+ // 加载更早: prepending the older page must not move ANY strip figure —
129
+ // counts, wall times, or token groups.
130
+ await page.getByRole('button', { name: 'Load earlier' }).click()
131
+ await expect.poll(() => page.getByText('m1', { exact: true }).count(), { timeout: 10_000 }).toBe(1)
132
+ expect(await strip.textContent()).toBe(stripBeforePaging)
133
+ // With the whole log loaded, the window mounts one turn-tail footer per
134
+ // settled turn — the loaded-window probe the scroll/perf lanes count now
135
+ // that the strip is whole-log-scoped.
136
+ expect(await page.locator('[data-chat-flow-key^="9:turn-tail"]').count()).toBe(TURNS)
137
+ }, 60_000)
138
+
139
+ it('matches the paged-stats aria golden', async () => {
140
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-stats-paged-aria'))
141
+ const snapshot = (await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd))
142
+ .split(SEED_ID).join('{{seededId}}')
143
+ await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE)
144
+ })
145
+
146
+ it('issued zero model calls and stayed clean', async () => {
147
+ expect(tripwire.pageErrors).toEqual([])
148
+ expect(tripwire.warnings).toEqual([])
149
+ await assertFixtureInventory(SNAPSHOT_DIR, ['ui.expected.md'])
150
+ })
151
+ })
apps/web/tests/subagent-conversation.e2e.ts ADDED
@@ -0,0 +1,606 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
2
+ import { tmpdir } from 'node:os'
3
+ import { fileURLToPath } from 'node:url'
4
+ import { join } from 'node:path'
5
+ import type { Browser, Page } from 'playwright'
6
+ import { chromium } from 'playwright'
7
+ import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
8
+ import { prepareSessionSnapshotFixtureForComparison } from '@deepseek-ai/dsh-llm-replay'
9
+ import {
10
+ SESSION_FORMAT_VERSION, SessionId as sessionId, SessionLogOffset, type SessionEvent, type SessionHeader, type SessionId,
11
+ } from '@deepseek-ai/dsh-session'
12
+ import type {} from '@deepseek-ai/dsh-agent'
13
+ import { snapshotSubagentDescriptor } from '@deepseek-ai/dsh-subagent'
14
+ import {
15
+ acknowledgeReloadConnectionLoss, captureExpandedTurnProcessAria, captureStableAria,
16
+ compareOrRefreshGolden,
17
+ launchWebScaffold, readPersistedEvents, selectedSessionFixture, watchConsole,
18
+ webSnapshotMode, type WebScaffold,
19
+ } from './scaffold.ts'
20
+ import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts'
21
+
22
+ const BASE_FIXTURE = fileURLToPath(new URL('../../../snapshots/web/live-interactions/session.v3.jsonl', import.meta.url))
23
+ const AVAILABLE_CHILD_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/subagent-conversation/ui.expected.md', import.meta.url))
24
+ const AVAILABLE_CHILD_EXPANDED_EXPECTED = fileURLToPath(
25
+ new URL('../../../snapshots/web/subagent-conversation/ui-expanded.expected.md', import.meta.url),
26
+ )
27
+ const TREE_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/subagent-conversation/tree.expected.md', import.meta.url))
28
+ const BRANCHLESS_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/subagent-conversation/branchless.expected.md', import.meta.url))
29
+ const STALE_CATALOG_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/subagent-conversation/stale-catalog.expected.md', import.meta.url))
30
+ const SIDEBAR_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/subagent-conversation/sidebar.expected.md', import.meta.url))
31
+ const UNAVAILABLE_GRANDCHILD_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/subagent-conversation/nested.expected.md', import.meta.url))
32
+ const FORK_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/subagent-conversation/fork.expected.md', import.meta.url))
33
+ const MODE = webSnapshotMode()
34
+ const LABEL = 'event-sourcing researcher'
35
+ const ONE_SHOT_LABEL = 'event-sourcing reviewer'
36
+ const NESTED_LABEL = 'example editor'
37
+ const PARENT_PROMPT = 'Ask a research subagent to explain event sourcing.'
38
+ const INITIAL_PROMPT = 'Explain event sourcing in one sentence.'
39
+ /** The grandchild's own first message; its arrival is what says its history finished loading. */
40
+ const NESTED_PROMPT = 'Give one concrete event sourcing example.'
41
+ const FOLLOWUP = 'Now give the same explanation to a human reader.'
42
+ const POST_FORK_FOLLOWUP = 'Continue the original conversation after the fork.'
43
+
44
+ function childFixture(source: string, fixtureId: string, withContinuation: boolean): string {
45
+ const [header, ...eventLines] = source.trimEnd().split('\n')
46
+ if (header === undefined) throw new Error('base replay fixture has no header')
47
+ const childHeaderValue = JSON.parse(header) as Record<string, unknown>
48
+ childHeaderValue.id = fixtureId
49
+ childHeaderValue.createdAt = 1784998084442
50
+ const childHeader = JSON.stringify(childHeaderValue)
51
+ if (!withContinuation) return [childHeader, ...eventLines, ''].join('\n')
52
+ const seqOffset = eventLines.length
53
+ const continued = eventLines.map((line) => {
54
+ const event = JSON.parse(line) as {
55
+ type: string
56
+ seq: number
57
+ data: Record<string, unknown>
58
+ }
59
+ const data = { ...event.data }
60
+ if (data.turn === 1) data.turn = 2
61
+ if (event.type === 'session/title' && Array.isArray(data.messageSeqs)) {
62
+ data.messageSeqs = data.messageSeqs.map((seq: unknown) => {
63
+ if (typeof seq !== 'number') throw new Error('base replay fixture title has a non-numeric message seq')
64
+ return seq + seqOffset
65
+ })
66
+ }
67
+ return JSON.stringify({ ...event, seq: event.seq + seqOffset, data })
68
+ })
69
+ return [childHeader, ...eventLines, ...continued, ''].join('\n')
70
+ }
71
+
72
+ async function waitForAgentToSettle(scaffold: WebScaffold, id: SessionId): Promise<void> {
73
+ const deadline = Date.now() + 30_000
74
+ while (scaffold.ctx.agents.get(id) !== undefined) {
75
+ if (Date.now() >= deadline) throw new Error(`subagent ${id} did not settle`)
76
+ await new Promise<void>(resolve => setTimeout(resolve, 10))
77
+ }
78
+ }
79
+
80
+ /** Poll until the cold-read write-back of {@link coldSnapshot} lands a visible row. */
81
+ async function waitForCacheRow(
82
+ scaffold: WebScaffold,
83
+ header: SessionHeader,
84
+ ): Promise<void> {
85
+ const deadline = Date.now() + 10_000
86
+ while (scaffold.ctx.sessionProjectionCache.cachedSnapshot(header, SessionLogOffset(0)) === undefined) {
87
+ if (Date.now() >= deadline) throw new Error(`cache row for "${header.id}" did not land`)
88
+ await new Promise<void>(resolve => setTimeout(resolve, 10))
89
+ }
90
+ }
91
+
92
+ describe('web e2e: persisted subagent conversation and human continuation', () => {
93
+ let scaffold: WebScaffold
94
+ let browser: Browser
95
+ let page: Page
96
+ let sidecarRoot: string
97
+ let childId: SessionId
98
+ let oneShotId: SessionId
99
+ let grandchildId: SessionId
100
+ let tripwire: ReturnType<typeof watchConsole>
101
+ const apiCalls: string[] = []
102
+
103
+ beforeAll(async () => {
104
+ if (MODE === 'record') throw new Error('subagent conversation is a keyless assembled snapshot')
105
+ const selectedBaseFixture = await selectedSessionFixture(BASE_FIXTURE)
106
+ const baseFixture = prepareSessionSnapshotFixtureForComparison(
107
+ await readFile(selectedBaseFixture, 'utf8'),
108
+ )
109
+ sidecarRoot = await mkdtemp(join(tmpdir(), 'dsh-web-subagent-'))
110
+ const childFixturePath = join(sidecarRoot, 'child.jsonl')
111
+ await writeFile(childFixturePath, childFixture(baseFixture, 'recorded-subagent', true))
112
+ scaffold = await launchWebScaffold({
113
+ replayFixture: selectedBaseFixture,
114
+ compareReplaySession: false,
115
+ replayChildFixtures: [childFixturePath],
116
+ paceMs: 25,
117
+ })
118
+ browser = await chromium.launch()
119
+ page = await newEnglishPage(browser)
120
+ page.on('request', (request) => {
121
+ const path = new URL(request.url()).pathname
122
+ if (path.startsWith('/api/')) apiCalls.push(path)
123
+ })
124
+ tripwire = watchConsole(page)
125
+ await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
126
+ await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
127
+ await connectFreshWorkspace(page, scaffold.workspaceCwd)
128
+
129
+ const parent = scaffold.ctx.agents.roots()[0]
130
+ if (parent === undefined) throw new Error('fresh workspace did not publish its parent Agent')
131
+ const parentSettled = scaffold.whenTurnSettled()
132
+ const parentInput = page.locator('[data-composer-input][contenteditable="true"]').first()
133
+ await parentInput.fill(PARENT_PROMPT)
134
+ await parentInput.press('Enter')
135
+ expect(await parentSettled).toBe(parent.id)
136
+
137
+ const started = await scaffold.ctx.subagents.startContinuable({
138
+ provider: 'spawn',
139
+ label: LABEL,
140
+ signal: new AbortController().signal,
141
+ request: {
142
+ prompt: [{ type: 'text', text: INITIAL_PROMPT }],
143
+ parent,
144
+ },
145
+ })
146
+ childId = started.childId
147
+ await waitForAgentToSettle(scaffold, childId)
148
+ oneShotId = sessionId('recorded-one-shot')
149
+ const oneShotDurationMs = 192 * 24 * 60 * 60 * 1_000
150
+ const oneShotAt = Date.now() - oneShotDurationMs
151
+ const oneShotHeader: SessionHeader = {
152
+ version: SESSION_FORMAT_VERSION,
153
+ id: oneShotId,
154
+ createdAt: oneShotAt,
155
+ isSeeded: false,
156
+ cwd: scaffold.workspaceCwd,
157
+ parentSession: parent.id,
158
+ origin: 'subagent',
159
+ delegationDepth: 1,
160
+ }
161
+ const oneShotHandle = await scaffold.ctx.sessionPersistence.create(oneShotHeader)
162
+ const oneShotEvents = [
163
+ {
164
+ type: 'turn/start',
165
+ seq: 0,
166
+ time: oneShotAt,
167
+ data: { turn: 1 },
168
+ },
169
+ {
170
+ type: 'user/message',
171
+ seq: 1,
172
+ time: oneShotAt + 1,
173
+ data: {
174
+ id: '00000000-0000-4000-9000-000000000101',
175
+ role: 'user',
176
+ content: [{ type: 'text', text: 'Review the event sourcing explanation.' }],
177
+ source: { kind: 'user' },
178
+ },
179
+ surfaceOp: 'append',
180
+ },
181
+ {
182
+ type: 'subagent/descriptor',
183
+ seq: 2,
184
+ time: oneShotAt + 2,
185
+ data: snapshotSubagentDescriptor({
186
+ mode: 'one-shot', provider: 'spawn', label: ONE_SHOT_LABEL,
187
+ }),
188
+ },
189
+ {
190
+ type: 'turn/end',
191
+ seq: 3,
192
+ time: oneShotAt + oneShotDurationMs,
193
+ data: { turn: 1, reason: { kind: 'completed' } },
194
+ },
195
+ ] as SessionEvent[]
196
+ await oneShotHandle.append(oneShotEvents)
197
+ await oneShotHandle.close()
198
+ scaffold.ctx.sessionProjectionCache.coldSnapshot(oneShotHeader, SessionLogOffset(0), oneShotEvents)
199
+ await waitForCacheRow(scaffold, oneShotHeader)
200
+ grandchildId = sessionId('recorded-grandchild')
201
+ const authoredAt = Date.now()
202
+ const grandchildHeader: SessionHeader = {
203
+ version: SESSION_FORMAT_VERSION,
204
+ id: grandchildId,
205
+ createdAt: authoredAt,
206
+ isSeeded: false,
207
+ cwd: scaffold.workspaceCwd,
208
+ parentSession: childId,
209
+ origin: 'subagent',
210
+ delegationDepth: 2,
211
+ }
212
+ const grandchildHandle = await scaffold.ctx.sessionPersistence.create(grandchildHeader)
213
+ const grandchildEvents = [
214
+ {
215
+ type: 'turn/start',
216
+ seq: 0,
217
+ time: authoredAt,
218
+ data: { turn: 1 },
219
+ },
220
+ {
221
+ type: 'user/message',
222
+ seq: 1,
223
+ time: authoredAt + 1,
224
+ data: {
225
+ id: '00000000-0000-4000-9000-000000000102',
226
+ role: 'user',
227
+ content: [{ type: 'text', text: NESTED_PROMPT }],
228
+ source: { kind: 'user' },
229
+ },
230
+ surfaceOp: 'append',
231
+ },
232
+ {
233
+ type: 'subagent/descriptor',
234
+ seq: 2,
235
+ time: authoredAt + 2,
236
+ data: snapshotSubagentDescriptor({
237
+ mode: 'continuable', provider: 'spawn', label: NESTED_LABEL,
238
+ }),
239
+ },
240
+ {
241
+ type: 'turn/end',
242
+ seq: 3,
243
+ time: authoredAt + 3,
244
+ data: { turn: 1, reason: { kind: 'completed' } },
245
+ },
246
+ ] as SessionEvent[]
247
+ await grandchildHandle.append(grandchildEvents)
248
+ await grandchildHandle.close()
249
+ scaffold.ctx.sessionProjectionCache.coldSnapshot(grandchildHeader, SessionLogOffset(0), grandchildEvents)
250
+ await waitForCacheRow(scaffold, grandchildHeader)
251
+ expect(scaffold.ctx.agents.get(childId)).toBeUndefined()
252
+ expect(scaffold.ctx.agents.get(oneShotId)).toBeUndefined()
253
+ expect(scaffold.ctx.agents.get(grandchildId)).toBeUndefined()
254
+ await expect(scaffold.ctx.subagents.listChildren(parent.id)).resolves.toMatchObject([
255
+ {
256
+ kind: 'child', id: oneShotId, mode: 'one-shot',
257
+ label: ONE_SHOT_LABEL, activity: 'inactive', hasChildren: false,
258
+ },
259
+ {
260
+ kind: 'child', id: childId, mode: 'continuable', label: LABEL,
261
+ activity: 'inactive', hasChildren: true,
262
+ },
263
+ ])
264
+ await expect(scaffold.ctx.subagents.listChildren(childId)).resolves.toMatchObject([
265
+ {
266
+ kind: 'child', id: grandchildId, mode: 'continuable',
267
+ label: NESTED_LABEL, activity: 'inactive', hasChildren: false,
268
+ },
269
+ ])
270
+ // These two cold fixtures were authored after the page's initial
271
+ // session.list and intentionally emitted no api-session/added event. Reload
272
+ // to exercise the restart baseline that discovers their full lineage.
273
+ const warningStart = tripwire.warnings.length
274
+ await page.reload({ waitUntil: 'load' })
275
+ await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
276
+ const catalogButton = page.getByRole('button', { name: '3 subagents', exact: true })
277
+ await catalogButton.waitFor({ timeout: 15_000 })
278
+ await catalogButton.hover()
279
+ const catalogTree = page.getByRole('tree', { name: 'Subagent sessions' })
280
+ await catalogTree.getByRole('treeitem').nth(1).waitFor({ timeout: 15_000 })
281
+ await catalogTree.press('Escape')
282
+ await page.getByRole('button', { name: '3 subagents' }).waitFor({ timeout: 15_000 })
283
+ acknowledgeReloadConnectionLoss(tripwire, warningStart)
284
+ }, 120_000)
285
+
286
+ afterAll(async () => {
287
+ const failures: unknown[] = []
288
+ await browser?.close().catch((error: unknown) => failures.push(error))
289
+ await scaffold?.close().catch((error: unknown) => failures.push(error))
290
+ if (sidecarRoot !== undefined) {
291
+ await rm(sidecarRoot, { recursive: true, force: true })
292
+ .catch((error: unknown) => failures.push(error))
293
+ }
294
+ if (failures.length === 1) throw failures[0]
295
+ if (failures.length > 1) throw new AggregateError(failures, 'subagent Web teardown failed')
296
+ })
297
+
298
+ it('keeps known descendants reachable across a stale empty catalog response', async () => {
299
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-stale-catalog'))
300
+ const pattern = '**/api/subagents/list'
301
+ let firstClaimed = false
302
+ let emptyDelivered = false
303
+ let trailingRequested = false
304
+ let releaseCatalog = (): void => {}
305
+ const catalogHeld = new Promise<void>((resolve) => { releaseCatalog = resolve })
306
+ await page.route(pattern, async (route) => {
307
+ if (firstClaimed) {
308
+ const response = await route.fetch()
309
+ trailingRequested = true
310
+ await catalogHeld
311
+ await route.fulfill({ response })
312
+ return
313
+ }
314
+ firstClaimed = true
315
+ const response = await route.fetch()
316
+ const body = await response.json() as {
317
+ result: { ok: true; value: { entries: unknown[] } } | { ok: false }
318
+ }
319
+ if (body.result.ok) body.result.value.entries = []
320
+ await route.fulfill({ response, json: body })
321
+ emptyDelivered = true
322
+ })
323
+
324
+ const warningStart = tripwire.warnings.length
325
+ try {
326
+ await page.reload({ waitUntil: 'load' })
327
+ await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
328
+ await expect.poll(() => emptyDelivered, { timeout: 15_000 }).toBe(true)
329
+ await page.getByRole('button', { name: '3 subagents' }).waitFor({ timeout: 15_000 })
330
+ acknowledgeReloadConnectionLoss(tripwire, warningStart)
331
+
332
+ await page.getByRole('button', { name: '3 subagents' }).hover()
333
+ await expect.poll(() => trailingRequested, { timeout: 15_000 }).toBe(true)
334
+ const tree = page.getByRole('tree', { name: 'Subagent sessions' })
335
+ await tree.getByRole('treeitem', { name: 'Loading subagents' }).first().waitFor()
336
+ expect(await tree.getByRole('treeitem', { name: 'Loading subagents' }).count()).toBe(2)
337
+ await compareOrRefreshGolden(
338
+ STALE_CATALOG_EXPECTED,
339
+ await captureStableAria(page, '[role="tree"][aria-label="Subagent sessions"]', scaffold.workspaceCwd),
340
+ MODE,
341
+ )
342
+ releaseCatalog()
343
+ await tree.getByRole('treeitem', { name: new RegExp(LABEL) }).waitFor({ timeout: 15_000 })
344
+ await tree.press('Escape')
345
+ } finally {
346
+ releaseCatalog()
347
+ await page.unroute(pattern)
348
+ }
349
+ })
350
+
351
+ it('expands a persisted grandchild progressively without activating either level', async () => {
352
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-tree'))
353
+ await page.getByRole('button', { name: '3 subagents' }).hover()
354
+ const catalogTree = page.getByRole('tree', { name: 'Subagent sessions' })
355
+ expect(await catalogTree.evaluate((element) => {
356
+ const rect = element.getBoundingClientRect()
357
+ const hit = document.elementFromPoint(rect.left + 8, rect.top + 8)
358
+ return hit !== null && element.contains(hit)
359
+ })).toBe(true)
360
+ expect(await page.getByRole('button', {
361
+ name: `Expand ${ONE_SHOT_LABEL} descendants`,
362
+ }).count()).toBe(0)
363
+ const oneShotRow = page.getByRole('treeitem', { name: new RegExp(ONE_SHOT_LABEL) })
364
+ expect(await oneShotRow.getByText('~6mo 12d', { exact: true }).count()).toBe(1)
365
+ expect(await oneShotRow.getAttribute('aria-label')).toContain('192d 00h 00m 00s')
366
+ await page.getByRole('button', { name: `Expand ${LABEL} descendants` }).click()
367
+ const childRow = page.getByRole('treeitem', { name: new RegExp(LABEL) })
368
+ const childLabel = await childRow.getAttribute('aria-label')
369
+ await page.waitForTimeout(1_100)
370
+ expect(await childRow.getAttribute('aria-label')).toBe(childLabel)
371
+ await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).waitFor({ timeout: 15_000 })
372
+ expect(scaffold.ctx.agents.get(childId)).toBeUndefined()
373
+ expect(scaffold.ctx.agents.get(grandchildId)).toBeUndefined()
374
+ const snapshot = await captureStableAria(
375
+ page,
376
+ '[role="tree"][aria-label="Subagent sessions"]',
377
+ scaffold.workspaceCwd,
378
+ )
379
+ await compareOrRefreshGolden(TREE_EXPECTED, snapshot, MODE)
380
+ await page.getByRole('tree', { name: 'Subagent sessions' }).press('Escape')
381
+ })
382
+
383
+ it('opens the completed child from persistence without activating it', async () => {
384
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-open'))
385
+ await page.getByRole('button', { name: '3 subagents' }).hover()
386
+ await page.getByRole('treeitem', { name: new RegExp(LABEL) }).click()
387
+ await expect.poll(
388
+ () => page.getByText(/^Explain event sourcing in one sentence\.Your parent agent id is /).count(),
389
+ { timeout: 15_000 },
390
+ ).toBe(1)
391
+ if (scaffold.ctx.agents.get(childId) !== undefined) {
392
+ throw new Error(`viewing the child activated it; API calls: ${apiCalls.join(', ')}`)
393
+ }
394
+ const hierarchy = page.getByRole('navigation', { name: 'Session hierarchy' })
395
+ await hierarchy.getByRole('button', { name: `Switch subagent: ${LABEL}` }).waitFor()
396
+ const sidebar = await captureStableAria(
397
+ page,
398
+ '[role="tree"][aria-label="Sessions"]',
399
+ scaffold.workspaceCwd,
400
+ )
401
+ await compareOrRefreshGolden(SIDEBAR_EXPECTED, sidebar, MODE)
402
+ })
403
+
404
+ it('keeps a restored child neutral until its parent availability arrives', async () => {
405
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-restore'))
406
+ const pattern = '**/api/subagents/list'
407
+ let requested = false
408
+ let releaseCatalog = (): void => {}
409
+ const catalogHeld = new Promise<void>((resolve) => { releaseCatalog = resolve })
410
+ await page.route(pattern, async (route) => {
411
+ const response = await route.fetch()
412
+ requested = true
413
+ await catalogHeld
414
+ await route.fulfill({ response })
415
+ })
416
+
417
+ const warningStart = tripwire.warnings.length
418
+ try {
419
+ await page.reload({ waitUntil: 'load' })
420
+ await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
421
+ await expect.poll(() => requested, { timeout: 15_000 }).toBe(true)
422
+ expect(await page.getByText('This subagent is read-only for now', { exact: true }).count()).toBe(0)
423
+ expect(await page.locator('[data-composer-seat]').evaluate(element =>
424
+ getComputedStyle(element).visibility)).toBe('hidden')
425
+ releaseCatalog()
426
+ const input = page.getByRole('textbox', { name: 'Message or run a task, / commands, @ files or sessions' })
427
+ await input.waitFor({ timeout: 15_000 })
428
+ await expect.poll(() => input.isEnabled(), { timeout: 15_000 }).toBe(true)
429
+ acknowledgeReloadConnectionLoss(tripwire, warningStart)
430
+ } finally {
431
+ releaseCatalog()
432
+ await page.unroute(pattern)
433
+ }
434
+ })
435
+
436
+ it('continues through FIFO follow-up admission and receives the child follow events', async () => {
437
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-followup'))
438
+ const ended = new Promise<void>((resolveEnded, reject) => {
439
+ const timer = setTimeout(() => {
440
+ off()
441
+ reject(new Error('subagent follow-up did not reach turn/end'))
442
+ }, 30_000)
443
+ const off = scaffold.ctx.on('session/event', (session: { id: SessionId }, event: SessionEvent) => {
444
+ if (session.id !== childId || event.type !== 'turn/end') return
445
+ clearTimeout(timer)
446
+ off()
447
+ resolveEnded()
448
+ })
449
+ })
450
+ const input = page.getByRole('textbox', { name: 'Message or run a task, / commands, @ files or sessions' })
451
+ await input.fill(FOLLOWUP)
452
+ await input.press('Enter')
453
+ await expect.poll(
454
+ () => scaffold.ctx.agents.get(childId)?.status,
455
+ { timeout: 10_000 },
456
+ ).toBe('running')
457
+ await ended
458
+ await expect.poll(() => page.getByText(FOLLOWUP, { exact: true }).count(), { timeout: 10_000 }).toBe(1)
459
+ await expect.poll(() => scaffold.ctx.agents.get(childId), { timeout: 10_000 }).toBeUndefined()
460
+ expect(await page.getByRole('button', { name: 'Stop generating' }).count()).toBe(0)
461
+ })
462
+
463
+ it('matches the settled addressed-conversation aria golden and stays clean', async () => {
464
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-aria'))
465
+ const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
466
+ await compareOrRefreshGolden(AVAILABLE_CHILD_EXPECTED, snapshot, MODE)
467
+ const expanded = await captureExpandedTurnProcessAria(
468
+ page,
469
+ '[class*="centerCol"]',
470
+ scaffold.workspaceCwd,
471
+ { scrollToBottom: true },
472
+ )
473
+ await compareOrRefreshGolden(AVAILABLE_CHILD_EXPANDED_EXPECTED, expanded, MODE)
474
+ expect(tripwire.pageErrors).toEqual([])
475
+ expect(tripwire.warnings).toEqual([])
476
+ })
477
+
478
+ it('opens an unavailable persisted grandchild after recording the available child', async () => {
479
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-grandchild'))
480
+ await page.getByRole('button', { name: '1 subagent' }).hover()
481
+ const tree = page.getByRole('tree', { name: 'Subagent sessions' })
482
+ const nestedRow = tree.locator('[role="treeitem"]').filter({ hasText: NESTED_LABEL })
483
+ await nestedRow.waitFor({ timeout: 15_000 })
484
+ const clickArea = nestedRow.locator(':scope > div')
485
+ expect(await clickArea.count()).toBe(1)
486
+ const [treeBox, clickAreaBox] = await Promise.all([
487
+ tree.boundingBox(),
488
+ clickArea.boundingBox(),
489
+ ])
490
+ expect(treeBox).not.toBeNull()
491
+ expect(clickAreaBox).not.toBeNull()
492
+ expect([
493
+ Math.round(clickAreaBox!.x - treeBox!.x),
494
+ Math.round(treeBox!.x + treeBox!.width - clickAreaBox!.x - clickAreaBox!.width),
495
+ // Menu padding alone insets the rows now that the border is gone.
496
+ ]).toEqual([4, 4])
497
+ await compareOrRefreshGolden(
498
+ BRANCHLESS_EXPECTED,
499
+ await captureStableAria(page, '[role="tree"][aria-label="Subagent sessions"]', scaffold.workspaceCwd),
500
+ MODE,
501
+ )
502
+ await nestedRow.click()
503
+ await page.getByText('The parent session is offline; reopen it to continue sending messages.').waitFor()
504
+ // The offline banner renders from the descriptor alone, so it says nothing
505
+ // about the transcript below it. The golden pins that transcript, and
506
+ // `captureStableAria` calls two identical polls stable — including two of
507
+ // "Loading history…". Wait for the message the golden asserts.
508
+ await page.getByText(NESTED_PROMPT).waitFor()
509
+ const hierarchy = page.getByRole('navigation', { name: 'Session hierarchy' })
510
+ const crumbs = await hierarchy.getByRole('button').allTextContents()
511
+ expect(crumbs.slice(-2)).toEqual([LABEL, NESTED_LABEL])
512
+ expect(scaffold.ctx.agents.get(childId)).toBeUndefined()
513
+ expect(scaffold.ctx.agents.get(grandchildId)).toBeUndefined()
514
+ await compareOrRefreshGolden(
515
+ UNAVAILABLE_GRANDCHILD_EXPECTED,
516
+ await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd),
517
+ MODE,
518
+ )
519
+ })
520
+
521
+ it('opens a one-shot child as permanently read-only history', async () => {
522
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-one-shot'))
523
+ const parentSession = page.getByRole('tree', { name: 'Sessions' })
524
+ .getByRole('treeitem')
525
+ .last()
526
+ await parentSession.click()
527
+ await page.getByRole('button', { name: '3 subagents' }).hover()
528
+ await page.getByRole('treeitem', { name: new RegExp(ONE_SHOT_LABEL) }).click()
529
+ await page.getByText('One-shot tasks do not accept follow-ups; review the full execution record here.').waitFor()
530
+ expect(scaffold.ctx.agents.get(oneShotId)).toBeUndefined()
531
+ })
532
+
533
+ it('places an ordinary fork from a subagent beside its workspace-owning ancestor', async () => {
534
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-fork'))
535
+ await page.getByRole('tree', { name: 'Sessions' })
536
+ .getByRole('treeitem', { name: /Ask a research subagent to/ })
537
+ .click()
538
+ await page.getByRole('button', { name: '3 subagents' }).hover()
539
+ await page.getByRole('treeitem', { name: new RegExp(LABEL) }).click()
540
+ await page.getByRole('textbox', { name: 'Message or run a task, / commands, @ files or sessions' }).waitFor()
541
+ const forkResponse = page.waitForResponse(response =>
542
+ new URL(response.url()).pathname === '/api/session/fork')
543
+ await page.getByRole('button', { name: 'Branch into a new conversation' }).last().click()
544
+ const forkReceipt = await (await forkResponse).json() as { result: { ok: boolean } }
545
+ expect(forkReceipt.result).toMatchObject({ ok: true })
546
+ await expect.poll(
547
+ () => page.getByRole('tree', { name: 'Sessions' }).getByRole('treeitem').count(),
548
+ { timeout: 15_000 },
549
+ ).toBe(3)
550
+ expect(await page.getByText('Ungrouped', { exact: true }).count()).toBe(0)
551
+ const hierarchy = page.getByRole('navigation', { name: 'Session hierarchy' })
552
+ await expect.poll(() => hierarchy.getByRole('button').count()).toBe(1)
553
+ await compareOrRefreshGolden(
554
+ FORK_EXPECTED,
555
+ await captureStableAria(page, '[role="tree"][aria-label="Sessions"]', scaffold.workspaceCwd),
556
+ MODE,
557
+ )
558
+ })
559
+
560
+ it('cold-resumes the original subagent while its ordinary fork stays active', async () => {
561
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-post-fork-followup'))
562
+ const sessions = page.getByRole('tree', { name: 'Sessions' })
563
+ await sessions.getByRole('treeitem', { name: /Ask a research subagent to/ }).click()
564
+ await page.getByRole('button', { name: '3 subagents' }).hover()
565
+ await page.getByRole('treeitem', { name: new RegExp(LABEL) }).click()
566
+ await page.locator('[data-composer-input][contenteditable="true"]').first().waitFor()
567
+ expect(scaffold.ctx.agents.get(childId)).toBeUndefined()
568
+
569
+ const forkResponse = page.waitForResponse(response =>
570
+ new URL(response.url()).pathname === '/api/session/fork')
571
+ await page.getByRole('button', { name: 'Branch into a new conversation' }).last().click()
572
+ const forkReceipt = await (await forkResponse).json() as {
573
+ result: { ok: true; value: { sessionId: string } } | { ok: false }
574
+ }
575
+ expect(forkReceipt.result).toMatchObject({ ok: true })
576
+ if (!forkReceipt.result.ok) return
577
+ const forkId = sessionId(forkReceipt.result.value.sessionId)
578
+ await expect.poll(() => scaffold.ctx.agents.get(forkId)).not.toBeUndefined()
579
+
580
+ await sessions.getByRole('treeitem', { name: /Ask a research subagent to/ }).click()
581
+ await page.getByRole('button', { name: '3 subagents' }).press('ArrowDown')
582
+ await page.getByRole('treeitem', { name: new RegExp(LABEL) }).click()
583
+ const input = page.locator('[data-composer-input][contenteditable="true"]').first()
584
+ await input.waitFor()
585
+ const promptResponse = page.waitForResponse(response =>
586
+ new URL(response.url()).pathname === '/api/subagents/prompt')
587
+ await input.fill(POST_FORK_FOLLOWUP)
588
+ await input.press('Enter')
589
+ const promptReceipt = await (await promptResponse).json() as {
590
+ result: { ok: true } | { ok: false; error: { code: string; message: string } }
591
+ }
592
+ if (!promptReceipt.result.ok) {
593
+ throw new Error(`post-fork follow-up rejected: ${JSON.stringify(promptReceipt.result.error)}`)
594
+ }
595
+ await expect.poll(async () => {
596
+ // The resumed loop appends the follow-up turn's closing events durably,
597
+ // so the physical log alone answers whether the turn settled.
598
+ const events = await readPersistedEvents(scaffold, childId)
599
+ const messageIndex = events.findIndex(event => event.type === 'user/message'
600
+ && event.data.content.some(block => block.type === 'text' && block.text === POST_FORK_FOLLOWUP))
601
+ return messageIndex >= 0 && events.slice(messageIndex + 1).some(event => event.type === 'turn/end')
602
+ }, { timeout: 30_000 }).toBe(true)
603
+ expect(scaffold.ctx.agents.get(forkId)).not.toBeUndefined()
604
+ await expect.poll(() => scaffold.ctx.agents.get(childId), { timeout: 10_000 }).toBeUndefined()
605
+ })
606
+ })