Merge master and align scoped CUA replays with system input

This commit is contained in:
creatixchu committed 2026-11-20 10:43:24 +08:00
commit 6eb6625063
1822 files changed
+60377 -10491

No files matched your search

+2 -2
View File
@@ -15,8 +15,8 @@
en: 85171337ac2fb2ff
zh: 705a4eef97d9b519
/deepseek-ai-dsh/optional-overlays:
en: 3a40ddc44e55f79c
zh: 8d3949132e1ef93c
en: bedb55bd3a80599c
zh: a381da5cd5db885b
/deepseek-ai-dsh/installed-payload:
en: c19f3d56f611f173
zh: 5002a7a318414960
+1 -1
View File
@@ -51,7 +51,7 @@ The [CLI behavior reference](reference/README.md) owns exact layer precedence, f
## Optional overlays
`config/examples/` ships opt-in overlays for GitHub review webhooks, memory MCP servers, and runtime Cordis tools. They are never part of a default profile; the [user guides](../../docs/user/guide/index.md) and [developer practice guides](../../docs/user/develop/practice/index.md) own setup and safety instructions.
`config/examples/` ships opt-in overlays for GitHub review webhooks, memory MCP servers, [cross-Session messages](../../docs/user/session-control.md) in Web profiles, and runtime Cordis tools. They are never part of a default profile; the [user guides](../../docs/user/guide/index.md) and [developer practice guides](../../docs/user/develop/practice/index.md) own setup and safety instructions.
## Installed payload
+1 -1
View File
@@ -51,7 +51,7 @@ profile 目录包含一个 `package.json`,其中记录树外插件依赖,以
## 可选覆盖层
`config/examples/` 交付 GitHub 评审 webhook、记忆 MCP 服务器与运行时 Cordis 工具的可选覆盖层。它们绝不属于默认 profile;设置与安全说明由[用户指南](../../docs/user/guide/index.zh.md)和[开发实战指南](../../docs/user/develop/practice/index.zh.md)负责。
`config/examples/` 交付 GitHub 评审 webhook、记忆 MCP 服务器、Web profile 中的[跨 Session 消息](../../docs/user/session-control.zh.md)与运行时 Cordis 工具的可选覆盖层。它们绝不属于默认 profile;设置与安全说明由[用户指南](../../docs/user/guide/index.zh.md)和[开发实战指南](../../docs/user/develop/practice/index.zh.md)负责。
## 安装包内容
@@ -0,0 +1,6 @@
# Enables the disabled tool-session-control row of the dsh-web-app bundle, so
# Agents in a Web profile can message ordinary Sessions in any Workspace or
# directory. Profiles without that bundle (headless, sdk, sdk-minimal, acp)
# have no such row; the Loader warns and skips this patch there.
- id: tool-session-control
disabled: false
+3
View File
@@ -1,6 +1,9 @@
# Minimal keyless composition for loading example MCP overlays against the
# package-owned fixture server in memory-mcp-configs.spec.ts. Source builtins
# keep this unit test independent of prebuilt workspace artifacts.
- id: session-projection
name: cordis:memory-test-session-projection
- id: system-prompt
name: cordis:memory-test-system-prompt
@@ -11,6 +11,7 @@ import { afterEach, describe, expect, it } from 'vitest'
import type { Context } from '@deepseek-ai/cordis'
import type { PatchOptions } from '@deepseek-ai/cordis-plugin-include'
import { boot, loadOverlayPatches } from '@deepseek-ai/dsh-app-boot'
import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
import ToolRuntime from '@deepseek-ai/dsh-tools'
import * as McpClient from '@deepseek-ai/dsh-mcp-client/src/index.ts'
@@ -122,6 +123,7 @@ describe('third-party memory MCP example overlays', () => {
[...patches, fixturePatch],
(ctx) => {
liveContexts.add(ctx)
ctx.loader.builtins['memory-test-session-projection'] = SessionProjectionRegistry
ctx.loader.builtins['memory-test-system-prompt'] = SystemPrompt
ctx.loader.builtins['memory-test-tools'] = ToolRuntime
ctx.loader.builtins['memory-test-mcp-client'] = McpClient
@@ -6,7 +6,7 @@
{"type":"turn/start","data":{"turn":1}}
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
{"type":"step/start","data":{"turn":1,"step":1}}
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:apply_patch","order":1350,"state":"active","contentIndex":6},{"name":"tool:glob","order":1400,"state":"active","contentIndex":7},{"name":"tool:grep","order":1500,"state":"active","contentIndex":8},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":9},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":10},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":11},{"name":"tool:goal","order":2400,"state":"active","contentIndex":12},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":13},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":14}]},"id":"{{sessionId}}"}},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"Create a durable two-round goal for the ACP snapshot, inspect it, then report readiness."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}
@@ -6,7 +6,7 @@
{"type":"turn/start","data":{"turn":1}}
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
{"type":"step/start","data":{"turn":1,"step":1}}
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:apply_patch","order":1350,"state":"active","contentIndex":6},{"name":"tool:glob","order":1400,"state":"active","contentIndex":7},{"name":"tool:grep","order":1500,"state":"active","contentIndex":8},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":9},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":10},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":11},{"name":"tool:goal","order":2400,"state":"active","contentIndex":12},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":13},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":14}]},"id":"{{sessionId}}"}},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"Create a durable goal for the wrap-up snapshot, then report readiness."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}
@@ -55,8 +55,6 @@ Available at app or window level depending on the platform.
click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform.
Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name.
AX read defaults: maxElements=2000, maxDepth=25.
Maximum click holdMs: 5000 ms.
@@ -17,7 +17,7 @@
{
"name": "cua_run_code",
"title": "Computer use program",
"description": "Run a TypeScript program to observe and operate desktop applications. The global cua object is ready to use; retain application and window objects across calls. Only tools.cua is available inside the program. Call other session tools directly. Use inspect(...values) to display selected text and images. The program contains TypeScript REPL statements; only erasable syntax is accepted, with no enum or namespaces. Type annotations are advisory. Top-level declarations and await are supported; top-level return is not supported. Use inspect(...values) to display output. Do not use console. Use the raw form of a template literal only for short text whose backslashes must stay exactly as written, such as a regular expression; write other text, in particular file contents and commands, as ordinary strings. Write file contents as an array of quoted strings, one line each, joined with newlines; never as one template literal. The program runs in strict mode: assigning an undeclared name throws, so use globalThis for intentional globals; eval and new Function are unavailable. Variables, functions, and imported modules remain in memory for this Agent across calls. Each call runs one program in its own top-level scope. Its top-level let, const, var, class, and function declarations, and the names it received from earlier programs, are copied into the top-level scope of later programs: later programs receive copies of these variables, not references to them, so an object they hold is still shared. In one program, either use a copied name or declare it again; do not declare a name and also use its copied value. Assigning to a copied name, even one declared with const, changes only this program's copy, which later programs receive. Do not declare var inside blocks; a block-level var changes which value later programs copy. Functions and still-running code from earlier programs keep the values they captured, and assignments they make later are not copied; keep shared mutable state in objects. If a program fails before a declaration of an existing name finishes, later programs keep that name's earlier value. Use await import(...) for modules; require and module are unavailable. Relative import specifiers resolve from the working directory of this environment's first program, while process.cwd() and relative file paths follow each program's working directory. Direct filesystem access follows the environment's launch-time sandbox policy; process.env starts empty. Timeout and cancellation results say whether retained variables were preserved or cleared. Restart, sandbox changes, or process failure clears them. Recreate missing variables and resources; conversation history does not restore state. Earlier mutations and tool effects are not rolled back. Approved sandbox escalations use a fresh environment and discard its variables afterward. Await tools and cleanup before the program ends; unfinished tools reject. After completion, timeout, or cancellation, new tool calls are rejected and captured output is discarded; background work may still change state. Await child-process completion before the program ends; raw output belongs to the active evaluation. Each program starts in the Session's current directory. Running programs keep their initial directory. A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically.",
"description": "Run a TypeScript program to observe and operate desktop applications. The global cua object is ready to use; retain application and window objects across calls. Call other session tools directly outside cua_run_code. Use inspect(...values) to display selected text and images. The program contains TypeScript REPL statements; only erasable syntax is accepted, with no enum or namespaces. Type annotations are advisory. Top-level declarations and await are supported; top-level return is not supported. Use inspect(...values) to display output. Do not use console. Use the raw form of a template literal only for short text whose backslashes must stay exactly as written, such as a regular expression; write other text, in particular file contents and commands, as ordinary strings. Write file contents as an array of quoted strings, one line each, joined with newlines; never as one template literal. The program runs in strict mode: assigning an undeclared name throws, so use globalThis for intentional globals; eval and new Function are unavailable. Variables, functions, and imported modules remain in memory for this Agent across calls. Each call runs one program in its own top-level scope. Its top-level let, const, var, class, and function declarations, and the names it received from earlier programs, are copied into the top-level scope of later programs: later programs receive copies of these variables, not references to them, so an object they hold is still shared. In one program, either use a copied name or declare it again; do not declare a name and also use its copied value. Assigning to a copied name, even one declared with const, changes only this program's copy, which later programs receive. Do not declare var inside blocks; a block-level var changes which value later programs copy. Functions and still-running code from earlier programs keep the values they captured, and assignments they make later are not copied; keep shared mutable state in objects. If a program fails before a declaration of an existing name finishes, later programs keep that name's earlier value. Use await import(...) for modules; require and module are unavailable. Relative import specifiers resolve from the working directory of this environment's first program, while process.cwd() and relative file paths follow each program's working directory. Direct filesystem access follows the environment's launch-time sandbox policy; process.env starts empty. Timeout and cancellation results say whether retained variables were preserved or cleared. Restart, sandbox changes, or process failure clears them. Recreate missing variables and resources; conversation history does not restore state. Earlier mutations and tool effects are not rolled back. Approved sandbox escalations use a fresh environment and discard its variables afterward. Await tools and cleanup before the program ends; unfinished tools reject. After completion, timeout, or cancellation, new tool calls are rejected and captured output is discarded; background work may still change state. Await child-process completion before the program ends; raw output belongs to the active evaluation. Each program starts in the Session's current directory. Running programs keep their initial directory. A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically.",
"inputSchema": {
"type": "object",
"properties": {
@@ -50,6 +50,7 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)('compaction: a long session compa
},
persistenceRoot: join(workdir, '.sessions'),
})
expect(ctx.get('compaction'), 'the compaction service is active before model requests').toBeDefined()
const agent = await ctx.agentLoop.create(brandString<SessionId>('e2e-compaction'), { provider: 'deepseek-official', model: 'deepseek-v4-flash' }, { cwd: workdir })
// Completed read turns cannot collapse into one retained parallel tool group.
@@ -2,7 +2,7 @@
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"turn/start","seq":4,"time":0,"data":{"turn":1}}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"agent/inbox/spliced","seq":5,"time":0,"data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/start","seq":6,"time":0,"data":{"turn":1,"step":1}}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:glob","order":1400,"state":"active","contentIndex":6},{"name":"tool:grep","order":1500,"state":"active","contentIndex":7},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":8},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":9},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":10},{"name":"tool:goal","order":2400,"state":"active","contentIndex":11},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":12},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":13}]},"id":"{{sessionId}}"}},"surfaceOp":"append"}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":8,"time":0,"data":{"content":[{"type":"text","text":"Probe strict-schema fillers against missing-goal revision 1, then create a durable goal to finish the snapshot proof and inspect it."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/header","seq":10,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}}
@@ -6,7 +6,7 @@
{"type":"turn/start","data":{"turn":1}}
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
{"type":"step/start","data":{"turn":1,"step":1}}
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:glob","order":1400,"state":"active","contentIndex":6},{"name":"tool:grep","order":1500,"state":"active","contentIndex":7},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":8},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":9},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":10},{"name":"tool:goal","order":2400,"state":"active","contentIndex":11},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":12},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":13}]},"id":"{{sessionId}}"}},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"Prove the product headless profile path with one real tool round trip."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"request/header","data":{"header":{"config":{"provider":"cli-mock","model":"cli-mock","reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true},"tools":"{{tools}}"},"reason":"initial"}}
@@ -2,7 +2,7 @@
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"turn/start","seq":4,"time":0,"data":{"turn":1}}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"agent/inbox/spliced","seq":5,"time":0,"data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/start","seq":6,"time":0,"data":{"turn":1,"step":1}}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:glob","order":1400,"state":"active","contentIndex":6},{"name":"tool:grep","order":1500,"state":"active","contentIndex":7},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":8},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":9},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":10},{"name":"tool:goal","order":2400,"state":"active","contentIndex":11},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":12},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":13}]},"id":"{{sessionId}}"}},"surfaceOp":"append"}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":8,"time":0,"data":{"content":[{"type":"text","text":"say pong"}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/header","seq":10,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":"{{tools}}"},"reason":"initial"}}}
@@ -2,7 +2,7 @@
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"turn/start","seq":4,"time":0,"data":{"turn":1}}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"agent/inbox/spliced","seq":5,"time":0,"data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/start","seq":6,"time":0,"data":{"turn":1,"step":1}}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:glob","order":1400,"state":"active","contentIndex":6},{"name":"tool:grep","order":1500,"state":"active","contentIndex":7},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":8},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":9},{"name":"tool:goal","order":2400,"state":"active","contentIndex":10},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":11},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":12}]},"id":"{{sessionId}}"}},"surfaceOp":"append"}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":8,"time":0,"data":{"content":[{"type":"text","text":"say pong"}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/header","seq":10,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":"{{tools}}"},"reason":"initial"}}}
@@ -2,7 +2,7 @@
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"turn/start","seq":4,"time":0,"data":{"turn":1}}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"agent/inbox/spliced","seq":5,"time":0,"data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/start","seq":6,"time":0,"data":{"turn":1,"step":1}}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:glob","order":1400,"state":"active","contentIndex":6},{"name":"tool:grep","order":1500,"state":"active","contentIndex":7},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":8},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":9},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":10},{"name":"tool:goal","order":2400,"state":"active","contentIndex":11},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":12},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":13}]},"id":"{{sessionId}}"}},"surfaceOp":"append"}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":8,"time":0,"data":{"content":[{"type":"text","text":"retry the transient provider failure"}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/header","seq":10,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}}
@@ -16,7 +16,7 @@
{"type":"turn/start","data":{"turn":2}}
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
{"type":"step/start","data":{"turn":2,"step":1}}
{"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}}
{"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:glob","order":1400,"state":"active","contentIndex":6},{"name":"tool:grep","order":1500,"state":"active","contentIndex":7},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":8},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":9},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":10},{"name":"tool:goal","order":2400,"state":"active","contentIndex":11},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":12},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":13}],"reset":true},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}}
{"type":"user/message","data":{"content":[{"type":"text","text":"Continue safely from the interrupted operation."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial","startsSeries":true}}
@@ -14,7 +14,7 @@
{"type":"turn/start","data":{"turn":2}}
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
{"type":"step/start","data":{"turn":2,"step":1}}
{"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}}
{"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:glob","order":1400,"state":"active","contentIndex":6},{"name":"tool:grep","order":1500,"state":"active","contentIndex":7},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":8},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":9},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":10},{"name":"tool:goal","order":2400,"state":"active","contentIndex":11},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":12},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":13}],"reset":true},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}}
{"type":"user/message","data":{"content":[{"type":"text","text":"Call list_agents once and report what it shows."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial","startsSeries":true}}
@@ -22,7 +22,7 @@
{"type":"session/title","data":{"title":"Start a background job.","messageSeqs":[3],"source":{"kind":"fallback"}}}
{"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"list-once","name":"list_agents","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"list-once","name":"list_agents","args":["{}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"list-once","name":"list_agents","arguments":"{}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"}
{"type":"tool/call","data":{"turn":2,"step":1,"callId":"list-once","name":"list_agents","arguments":"{}"}}
{"type":"tool/result","data":{"turn":2,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"list-once"},"toolCallId":"list-once","content":[{"type":"text","text":"lead [running] — root agent\n{{sessionId}} [inactive] — descriptorless child"}],"isError":false,"id":"{{sessionId}}"}},"sourceEventSeqs":[22],"surfaceOp":"append"}
{"type":"tool/result","data":{"turn":2,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"list-once"},"toolCallId":"list-once","content":[{"type":"text","text":"Subagent capacity: running=0, limit=8\nlead [running] — root agent\n{{sessionId}} [inactive] — descriptorless child"}],"isError":false,"id":"{{sessionId}}"}},"sourceEventSeqs":[22],"surfaceOp":"append"}
{"type":"step/end","data":{"turn":2,"step":1}}
{"type":"step/start","data":{"turn":2,"step":2}}
{"type":"assistant/message","data":{"turn":2,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"The catalogued subagent is ready. PARENT_DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["The catalogued subagent is ready. PARENT_DONE"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"The catalogued subagent is ready. PARENT_DONE"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"}
@@ -6,7 +6,7 @@
{"type":"turn/start","data":{"turn":1}}
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
{"type":"step/start","data":{"turn":1,"step":1}}
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:apply_patch","order":1350,"state":"active","contentIndex":6},{"name":"tool:glob","order":1400,"state":"active","contentIndex":7},{"name":"tool:grep","order":1500,"state":"active","contentIndex":8},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":9},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":10},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":11},{"name":"tool:goal","order":2400,"state":"active","contentIndex":12},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":13},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":14}]},"id":"{{sessionId}}"}},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{sessionId}}"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it. Messages from other agents begin with \"Agent <name> sent a message:\". Other user messages come from the human user, who reads this conversation directly. You can still message other agents to coordinate, but answer the human user in your reply.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it. Messages from other agents begin with \"Agent <name> sent a message:\". Other user messages come from the human user, who reads this conversation directly. You can still message other agents to coordinate, but answer the human user in your reply."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","reasoningEffort":"low"},"tools":"{{tools}}"},"reason":"initial"}}
@@ -14,7 +14,7 @@
{"type":"turn/start","data":{"turn":2}}
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
{"type":"step/start","data":{"turn":2,"step":1}}
{"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}}
{"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:apply_patch","order":1350,"state":"active","contentIndex":6},{"name":"tool:glob","order":1400,"state":"active","contentIndex":7},{"name":"tool:grep","order":1500,"state":"active","contentIndex":8},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":9},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":10},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":11},{"name":"tool:goal","order":2400,"state":"active","contentIndex":12},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":13},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":14}],"reset":true},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}}
{"type":"user/message","data":{"content":[{"type":"text","text":"Delegate the write probe to a subagent."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","reasoningEffort":"low"},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","write"]},"reason":"resume","startsSeries":true}}
@@ -6,7 +6,7 @@
{"type":"turn/start","data":{"turn":1}}
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
{"type":"step/start","data":{"turn":1,"step":1}}
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:glob","order":1400,"state":"active","contentIndex":6},{"name":"tool:grep","order":1500,"state":"active","contentIndex":7},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":8},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":9},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":10},{"name":"tool:goal","order":2400,"state":"active","contentIndex":11},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":12},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":13}]},"id":"{{sessionId}}"}},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly CHILD_RESULT and nothing else. Do not call send_message."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{sessionId}}"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it. Messages from other agents begin with \"Agent <name> sent a message:\". Other user messages come from the human user, who reads this conversation directly. You can still message other agents to coordinate, but answer the human user in your reply.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it. Messages from other agents begin with \"Agent <name> sent a message:\". Other user messages come from the human user, who reads this conversation directly. You can still message other agents to coordinate, but answer the human user in your reply."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}
@@ -2,7 +2,7 @@
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"turn/start","seq":4,"time":0,"data":{"turn":1}}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"agent/inbox/spliced","seq":5,"time":0,"data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/start","seq":6,"time":0,"data":{"turn":1,"step":1}}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:glob","order":1400,"state":"active","contentIndex":6},{"name":"tool:grep","order":1500,"state":"active","contentIndex":7},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":8},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":9},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":10},{"name":"tool:goal","order":2400,"state":"active","contentIndex":11},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":12},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":13}]},"id":"{{sessionId}}"}},"surfaceOp":"append"}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":8,"time":0,"data":{"content":[{"type":"text","text":"Start one continuable subagent and acknowledge its completion notice. Do not call list_agents or send_message."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/header","seq":10,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}}
@@ -14,7 +14,7 @@
{"type":"turn/start","data":{"turn":2}}
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
{"type":"step/start","data":{"turn":2,"step":1}}
{"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}}
{"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:glob","order":1400,"state":"active","contentIndex":6},{"name":"tool:grep","order":1500,"state":"active","contentIndex":7},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":8},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":9},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":10},{"name":"tool:goal","order":2400,"state":"active","contentIndex":11},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":12},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":13}],"reset":true},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}}
{"type":"user/message","data":{"content":[{"type":"text","text":"Acknowledge the current workspace instruction."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nUpdated instructions from: AGENTS.md\n\nThis file changed after it was loaded. Use the following content instead of the previously loaded instructions from this file.\n\nNew workspace instruction after offline edit.\n\n</system-reminder>"}],"source":{"kind":"agent-instructions","form":"instructions","changes":[{"action":"replace","scope":".\u0000AGENTS.md","path":"AGENTS.md","digest":"d8375b516f158718bd3463bc8eb7ed42c011b29f"}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
@@ -14,7 +14,7 @@
{"type":"turn/start","data":{"turn":2}}
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
{"type":"step/start","data":{"turn":2,"step":1}}
{"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}}
{"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:glob","order":1400,"state":"active","contentIndex":6},{"name":"tool:grep","order":1500,"state":"active","contentIndex":7},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":8},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":9},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":10},{"name":"tool:goal","order":2400,"state":"active","contentIndex":11},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":12},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":13}],"reset":true},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}}
{"type":"user/message","data":{"content":[{"type":"text","text":"Acknowledge the current workspace instruction."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThis complete workspace instruction baseline replaces all earlier workspace instruction baselines. The following workspace instructions may be relevant to your work. Use them as guidance when applicable. More specific instructions take precedence over broader ones. They do not override system, developer, or direct user instructions.\n\nInstructions from: AGENTS.md\n\nCurrent AGENTS rule.\n\n\nInstructions from: CLAUDE.md\n\nCurrent CLAUDE rule.\n\n</system-reminder>"}],"source":{"kind":"agent-instructions","form":"instructions","baseline":true,"baselineIdentity":"{\"projectRoot\":\"\",\"projectRootMarkers\":[\".git\"],\"maxBytes\":65536,\"maxSourceBytes\":1048576,\"instructionFileCandidates\":[\"AGENTS.md\",\"CLAUDE.md\"],\"localInstructionFileCandidates\":[\"AGENTS.local.md\",\"CLAUDE.local.md\"]}","changes":[{"action":"set","scope":".\u0000AGENTS.md","path":"AGENTS.md","digest":"7f53d2327837129750aef117f9754a001c46cf68"},{"action":"set","scope":".\u0000CLAUDE.md","path":"CLAUDE.md","digest":"5b1e9e3fd759eee6b43ceff899e47fb10c64701a"}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
@@ -8,6 +8,7 @@ import {
normalizeSessionLog,
normalizeSessionSnapshot,
normalizeSessionSnapshots,
REPLAY_CREDENTIAL_ENV,
normalizeStdout,
scrubModelRequestBulk,
type NormalizeContext,
@@ -394,6 +395,7 @@ describe('headless stream-json snapshots', () => {
binArgs: ['headless', '--patch', headlessOverlayPath, task],
tsconfigPath,
env: {
...REPLAY_CREDENTIAL_ENV,
DSH_PERMISSION_MODE: 'danger-full-access',
DSH_TELEMETRY_DISABLED: '1',
NODE_OPTIONS: [process.env.NODE_OPTIONS, '--disable-warning=ExperimentalWarning'].filter(Boolean).join(' '),
@@ -692,6 +694,7 @@ describe('headless stream-json snapshots', () => {
binArgs: [retryConfigPath, prompt],
tsconfigPath,
env: {
...REPLAY_CREDENTIAL_ENV,
DSH_SNAPSHOT: 'replay',
NODE_OPTIONS: [process.env.NODE_OPTIONS, '--disable-warning=ExperimentalWarning'].filter(Boolean).join(' '),
},
@@ -1318,6 +1321,7 @@ describe('headless stream-json snapshots', () => {
binArgs: [goalConfigPath, prompt],
tsconfigPath,
env: {
...REPLAY_CREDENTIAL_ENV,
DSH_SNAPSHOT: 'replay',
DSH_SNAPSHOT_FILE: join(goalScenarioDir, 'session.jsonl'),
DSH_SNAPSHOT_OVERRIDE: join(goalScenarioDir, 'replay.override.json'),
@@ -1378,6 +1382,7 @@ describe('headless stream-json snapshots', () => {
binArgs: [settlementConfigPath, task],
tsconfigPath,
env: {
...REPLAY_CREDENTIAL_ENV,
// The override fully supplies the parent script; the child fixture
// remains separate so replay binds it to the fresh child Session.
DSH_SNAPSHOT_FILE: parentReplay,
@@ -21,7 +21,7 @@ import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local'
import * as ToolBash from '@deepseek-ai/dsh-tool-bash'
import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key'
import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import NodeRuntime from '@deepseek-ai/dsh-ptc-runtime-node'
import NodeRuntime, { type Config as NodeRuntimeConfig } from '@deepseek-ai/dsh-ptc-runtime-node'
import Sandbox from '@deepseek-ai/dsh-sandbox-local'
import SandboxPolicy from '@deepseek-ai/dsh-sandbox-policy'
import LocalFileSystem from '@deepseek-ai/dsh-fs-local'
@@ -43,6 +43,15 @@ const PERSONA = 'You are a coding agent. You work by writing TypeScript programs
+ 'batch related tool work into one program and inspect ONLY the findings that matter.'
const WORKSPACE_PROBE = 'dragonfruit-8675309'
/** Node runtime program formats the keyless cases run under; their programs end with inspect, so both formats accept them unchanged. */
const PTC_MODES = [
{ mode: 'per-call', config: { executionMode: 'per-call' } },
{ mode: 'scoped REPL', config: { executionMode: 'persistent-in-memory', replScoped: true } },
] as const satisfies readonly { mode: string; config: NodeRuntimeConfig }[]
type PtcMode = typeof PTC_MODES[number]
/** The with-key model cases keep function-body programs. */
const PER_CALL: PtcMode = PTC_MODES[0]
let ctx: Context | undefined
let workdir: string | undefined
@@ -70,7 +79,7 @@ async function ptcModeHarness(cwd: string): Promise<Context> {
await harness.plugin(BashEnvPlugin)
await harness.plugin(LocalBashExecutor, { cwd, timeoutMs: 30_000 })
await harness.plugin(ToolBash)
await mountRuntime(harness)
await mountRuntime(harness, PER_CALL)
return harness
}
@@ -87,7 +96,7 @@ async function workspacePtcModeHarness(): Promise<Context> {
await harness.plugin(AgentLoop, { agents: [] })
await harness.plugin(DeepSeekAuth)
await harness.plugin(LlmDeepSeek, { models: [{ id: 'deepseek-v4-flash' }] })
await mountRuntime(harness)
await mountRuntime(harness, PER_CALL)
return harness
}
@@ -123,7 +132,7 @@ function completion(result: ToolExecutionResult): unknown {
return JSON.parse(text)
}
async function mountRuntime(harness: Context): Promise<void> {
async function mountRuntime(harness: Context, mode: PtcMode): Promise<void> {
onTestFinished(async () => { await harness.fiber.dispose() })
if (!harness.get('sessions')) await harness.plugin(SessionStore)
if (!harness.get('fs')) await harness.plugin(LocalFileSystem)
@@ -131,20 +140,20 @@ async function mountRuntime(harness: Context): Promise<void> {
if (!harness.get('sandbox')) await harness.plugin(Sandbox, {})
if (!harness.get('sessionProjections')) await harness.plugin(SessionProjectionRegistry)
if (!harness.get('sandboxPolicy')) await harness.plugin(SandboxPolicy, { mode: 'danger-full-access' })
await harness.plugin(NodeRuntime, {})
await harness.plugin(NodeRuntime, mode.config)
}
/** Keyless real-process harness for direct typed-binding acceptance tests. */
async function typedPtcModeHarness(): Promise<Context> {
async function typedPtcModeHarness(mode: PtcMode): Promise<Context> {
const harness = new Context()
await mountAgentLoopTestDependencies(harness, { workingDirectory: true, tools: { mode: 'ptc' } })
await mountRuntime(harness)
await mountRuntime(harness, mode)
return harness
}
/** Keyless real-process harness with the task-owned bash lifecycle. */
async function backgroundPtcModeHarness(cwd: string): Promise<Context> {
const harness = await typedPtcModeHarness()
async function backgroundPtcModeHarness(mode: PtcMode, cwd: string): Promise<Context> {
const harness = await typedPtcModeHarness(mode)
await harness.plugin(LocalJobRegistry)
await harness.plugin(ToolJobs, {})
if (harness.get('subprocess') === undefined) await harness.plugin(LocalSubprocessRuntime)
@@ -154,12 +163,12 @@ async function backgroundPtcModeHarness(cwd: string): Promise<Context> {
return harness
}
describe('PTC mode typed values: keyless real-process contracts', () => {
describe.each(PTC_MODES)('PTC mode typed values ($mode): keyless real-process contracts', (mode) => {
it('returns formatted read content from inspect through the real outer run_code result', async () => {
workdir = await realpath(await mkdtemp(join(tmpdir(), 'dsh-ptc-inspect-read-')))
const path = join(workdir, 'a.txt')
await writeFile(path, 'alpha\nbeta\n')
ctx = await typedPtcModeHarness()
ctx = await typedPtcModeHarness(mode)
await ctx.plugin(ToolFs)
const formatted = `<path>${path}</path>\n<type>file</type>\n<content>\n1: alpha\n2: beta\n\n(End of file - total 2 lines)\n</content>`
@@ -179,7 +188,7 @@ describe('PTC mode typed values: keyless real-process contracts', () => {
})
it.each(['renderer', 'policy'])('keeps an empty %s output silent while preserving program data', async (source) => {
ctx = await typedPtcModeHarness()
ctx = await typedPtcModeHarness(mode)
ctx.tools.register(defineTool({
name: 'silent_result', description: 'Return data without display text.', parameters: {},
output: {
@@ -200,7 +209,7 @@ describe('PTC mode typed values: keyless real-process contracts', () => {
})
it('crosses a large intermediate value intact and exposes only typed tool failure fields', async () => {
ctx = await typedPtcModeHarness()
ctx = await typedPtcModeHarness(mode)
ctx.tools.register(defineTool({
name: 'large_value',
description: 'Return a large canonical string.',
@@ -254,7 +263,7 @@ describe('PTC mode typed values: keyless real-process contracts', () => {
it('returns a background job id, settles the outer run, and polls that id to completion', async () => {
workdir = await mkdtemp(join(tmpdir(), 'dsh-ptc-background-'))
ctx = await backgroundPtcModeHarness(workdir)
ctx = await backgroundPtcModeHarness(mode, workdir)
const jobId = completion(await runCode(ctx, `
const started = await tools.bash({
@@ -277,7 +286,7 @@ describe('PTC mode typed values: keyless real-process contracts', () => {
it('pre-abort spawns nothing; post-publication abort leaves job_kill as the cancellation owner', { timeout: 15_000, retry: 0 }, async () => {
workdir = await mkdtemp(join(tmpdir(), 'dsh-ptc-task-cancel-'))
ctx = await backgroundPtcModeHarness(workdir)
ctx = await backgroundPtcModeHarness(mode, workdir)
const pre = new AbortController()
pre.abort('pre-aborted')
@@ -327,7 +336,7 @@ describe('PTC mode typed values: keyless real-process contracts', () => {
it('keeps foreground bash coupled to the outer signal', async () => {
workdir = await mkdtemp(join(tmpdir(), 'dsh-ptc-foreground-cancel-'))
ctx = await backgroundPtcModeHarness(workdir)
ctx = await backgroundPtcModeHarness(mode, workdir)
const controller = new AbortController()
const startedAt = Date.now()
const pending = runCode(ctx, `
@@ -341,7 +350,7 @@ describe('PTC mode typed values: keyless real-process contracts', () => {
}, 15_000)
it('uses runtime inspection results directly through PTC', async () => {
ctx = await typedPtcModeHarness()
ctx = await typedPtcModeHarness(mode)
await ctx.plugin(CordisHostRunner)
await ctx.plugin(CordisInspectProviders)
await ctx.plugin(ToolCordis)
@@ -6,6 +6,7 @@ import {
fixtureContext,
normalizeSessionSnapshot,
normalizeSessionSnapshots,
REPLAY_CREDENTIAL_ENV,
type NormalizeContext,
} from '@deepseek-ai/dsh-session-snapshot'
import { LOADER_SMOKE_TEST_TIMEOUT_MS, runLoaderSmoke } from '@deepseek-ai/dsh-loader-smoke'
@@ -114,6 +115,7 @@ describe('semantic checkpoint recovery snapshot', () => {
binArgs: [configPath, task],
tsconfigPath,
env: {
...REPLAY_CREDENTIAL_ENV,
DSH_SNAPSHOT_FILE: replayFixture,
DSH_SNAPSHOT_OVERRIDE: replayOverride,
},
@@ -11,6 +11,7 @@ import {
fixtureContext,
normalizeSessionSnapshot,
normalizeSessionSnapshots,
REPLAY_CREDENTIAL_ENV,
type NormalizeContext,
} from '@deepseek-ai/dsh-session-snapshot'
import { LOADER_SMOKE_TEST_TIMEOUT_MS, runLoaderSmoke } from '@deepseek-ai/dsh-loader-smoke'
@@ -118,6 +119,7 @@ describe('parent-owned cold child catalog snapshot', () => {
binArgs: [configPath, task],
tsconfigPath,
env: {
...REPLAY_CREDENTIAL_ENV,
DSH_SNAPSHOT_FILE: replayOverride,
DSH_SNAPSHOT_OVERRIDE: replayOverride,
},
@@ -129,7 +131,10 @@ describe('parent-owned cold child catalog snapshot', () => {
const sessionsDir = join(runCwd, '.sessions')
const files = (await readdir(sessionsDir, { recursive: true })).filter(file => file.endsWith('.jsonl'))
const logs = await Promise.all(files.map(async file => readFile(join(sessionsDir, file), 'utf8')))
const parent = logs.find(content => content.includes('"subagent-diagnostic-parent"'))
const parent = logs.find((content) => {
const header = JSON.parse(content.split('\n')[0]!) as SessionHeader
return header.id === parentId
})
if (parent === undefined) throw new Error('missing persisted parent log')
// Discovery reads child catalogs without requiring activation descriptors.
@@ -128,7 +128,7 @@ describe('parent-only override inheritance snapshot', () => {
const logs = await Promise.all(files.map(async file => readFile(join(sessionsDir, file), 'utf8')))
const headerOf = (content: string): Record<string, unknown> =>
JSON.parse(content.split('\n')[0] ?? '{}') as Record<string, unknown>
const parent = logs.find(content => content.includes('"subagent-inheritance-parent"'))
const parent = logs.find(content => headerOf(content).id === sessionId)
const child = logs.find(content => typeof headerOf(content).parentSession === 'string')
if (parent === undefined || child === undefined) throw new Error('missing persisted parent or child log')
@@ -12,6 +12,7 @@ import {
fixtureContext,
normalizeSessionSnapshot,
normalizeSessionSnapshots,
REPLAY_CREDENTIAL_ENV,
type NormalizeContext,
} from '@deepseek-ai/dsh-session-snapshot'
import { LOADER_SMOKE_TEST_TIMEOUT_MS, runLoaderSmoke } from '@deepseek-ai/dsh-loader-smoke'
@@ -147,6 +148,7 @@ describe('agent-instructions resume snapshot', () => {
binArgs: [configPath, 'Acknowledge the current workspace instruction.'],
tsconfigPath,
env: {
...REPLAY_CREDENTIAL_ENV,
DSH_SNAPSHOT_FILE: replayFixture,
DSH_SNAPSHOT_OVERRIDE: replayOverride,
},
@@ -204,6 +206,7 @@ describe('agent-instructions resume snapshot', () => {
binArgs: [configPath, 'Acknowledge the current workspace instruction.'],
tsconfigPath,
env: {
...REPLAY_CREDENTIAL_ENV,
DSH_SNAPSHOT_FILE: replayFixture,
DSH_SNAPSHOT_OVERRIDE: replayOverride,
},
@@ -23,7 +23,7 @@ it.each([
requests.push(JSON.parse(body) as Record<string, unknown>)
const tool = mode === 'ptc' ? {
type: 'tool_use', id: 'question-call', name: 'run_code', input: {
code: `return await tools.ask_user_question(${JSON.stringify({ questions })});`, description: 'Ask which output format to use',
code: `await tools.ask_user_question(${JSON.stringify({ questions })});`, description: 'Ask which output format to use',
},
} : { type: 'tool_use', id: 'question-call', name: 'ask_user_question', input: { questions } }
response.writeHead(200, { 'content-type': 'text/event-stream' })
+1 -1
View File
@@ -469,7 +469,7 @@ describe('the shipped Web composition', () => {
try {
const assembly = await ctx.systemPrompt.assemble({ scope: handle.agent })
expect(assembly.sections).toEqual([
{ name: 'deployment:persona-prefix', text: MINIMAL_PROMPT },
{ name: 'deployment:persona-prefix', order: 0, text: MINIMAL_PROMPT, complete: true },
])
expect(assembly.tools.map(tool => tool.name)).toEqual(['bash', 'read_image', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update'])
expect(assembly.tools.find(tool => tool.name === 'bash')?.description).toBe(MINIMAL_BASH_DESCRIPTION)
+4 -4
View File
@@ -15,8 +15,8 @@
en: 37d76f8473b967b7
zh: d211cc54af96672d
/desktop-ci-publication/setup-sequence:
en: 2be541ef35a092a4
zh: 77d87c00deb45758
en: 4a7458326bb10b10
zh: e48c2345ebd54aac
/desktop-ci-publication/runner-labels-and-queue-diagnosis:
en: d2195ee7581b74ec
zh: 0b9847afe9a2a373
@@ -24,8 +24,8 @@
en: 0f43f2e193e95043
zh: 1c1efb062c06f7b8
/desktop-ci-publication/package-and-publish:
en: 6325c71df74a9915
zh: edaa8a4502ed80a1
en: 2b75de75308c7729
zh: 1b09a6edd8c7e9b0
/desktop-ci-publication/rollout-and-website-publication:
en: b6c39cec0946d5f4
zh: 3a6014ffbbec81f1
+3 -1
View File
@@ -28,7 +28,7 @@ Use this sequence when onboarding a dedicated machine. The deployment operator o
1. Prepare a runner-owned checkout and an external configuration directory. Follow [Windows machine setup and signing](../../windows-signing/README.md#machine-setup) or [macOS runner and signing setup](../../packaging/README.md#macos-actions) for tools, templates and platform credentials.
2. Register the runner using GitHub **Settings → Actions → Runners**, or the organization's runner administration page. Record its exact registered name, grant this repository access to its runner group, and assign the [required labels](#runner-labels). Keep the default labels during registration.
3. Install and start the platform supervisor described in the platform guide. Windows Task Scheduler and the macOS LaunchAgent require the configured user's login; they do not provide unattended startup before login. Confirm both GitHub connectivity and `Listening for Jobs`, then check the runner is online in GitHub.
3. Install and start the platform supervisor described in the platform guide. Windows supports optional Boot tasks for startup before login; its default Interactive task and the macOS LaunchAgent require the configured user's desktop login. Confirm both GitHub connectivity and `Listening for Jobs`, then check the runner is online in GitHub.
4. Complete [machine publication configuration](#machine-setup), the repository's `DESKTOP_PUBLISH_RUNNERS` variable, and the two deployment Environments. The repository administrator owns routing and reviewers; the COS administrator owns bucket configuration and object read/write permissions; production also needs the configured GitHub App.
5. Run a signed Windows or notarized macOS **test** package using [Package and publish](#package-and-publish). Confirm the packaging job used the intended registered runner and retained its files. Dispatch publication from `master` with that run ID and attempt; confirm `prepare` actually starts on the same machine and produces the approval summary.
6. Inspect the summary's environment, version, channel and URLs before approving the test upload. Verify the publication record, public installer download and update feed. Test acceptance does not establish production permissions: provision and approve production separately. Keep the run/attempt and acceptance results for recovery.
@@ -69,6 +69,8 @@ Environment approval gates this workflow, not arbitrary code running under the s
## Package and publish
The Windows packaging run shows a Chinese parameter summary with the requested source, environment, channel, version mode, signing mode, compression, test release ID and cache namespace, plus the workflow identity, checked-out commit, resolved version and runner. Once workflow helpers are staged, earlier failures still produce the summary with unavailable results labeled explicitly. The summary reads no machine configuration; a blank test release ID is shown as machine-default selection, not its resolved value. It does not establish build, signature or publication success.
The publication form accepts an optional `staging_percentage` integer from 0 to 100. It applies to the retained package’s channel (nightly or stable), appears in the approval summary, and is included in the published YAML and audit record without modifying retained artifacts. Leave it blank for the packaged default (normally full rollout). Completed publications cannot change this percentage through a retry; same-version feed conflicts remain errors.
For publication to either test or production, choose Windows `signing=signed` or leave macOS **Skip notarization** unchecked. Unsigned and unnotarized packages are only for internal debugging; they cannot publish or provide automatic updates. Before installing dependencies, the hosted routing job rejects debugging artifacts identified by the selected run and attempt. An archive-only rerun retains the original build attempt in artifact names, so this early check can miss it; local manifest qualification still rejects debugging builds before publication. Missing artifact metadata does not establish eligibility: the original machine still validates its retained manifest and signatures. A debugging-package rejection requires a new signed/notarized package and its run ID / attempt; retrying publication cannot qualify the existing bytes.
+3 -1
View File
@@ -28,7 +28,7 @@ description: "在专用 macOS 和 Windows runner 上发布留存的 Desktop 安
1. 准备 runner 专用 checkout 和仓库外的配置目录。按 [Windows 机器与签名配置](../../windows-signing/README.zh.md#machine-setup)或 [macOS runner 与签名配置](../../packaging/README.zh.md#macos-actions)准备工具、模板和平台凭据。
2. 通过 GitHub **Settings → Actions → Runners** 或组织的 runner 管理页面注册 runner。记录准确的注册名称,允许本仓库访问其 runner group,并分配[必需标签](#runner-labels)。注册时保留默认标签。
3. 按平台指南安装并启动守护任务。Windows 计划任务和 macOS LaunchAgent 都要求配置的用户登录,不能在登录前无人值守启动。确认已连接 GitHub 且出现 `Listening for Jobs`,再检查 GitHub 中 runner 在线。
3. 按平台指南安装并启动守护任务。Windows 可选 Boot 任务支持登录前启动;默认 Interactive 任务和 macOS LaunchAgent 仍要求配置的用户登录桌面。确认已连接 GitHub 且出现 `Listening for Jobs`,再检查 GitHub 中 runner 在线。
4. 完成[本机发布配置](#machine-setup)、仓库变量 `DESKTOP_PUBLISH_RUNNERS` 和两个部署 Environment。仓库管理员负责路由与审批人;COS 管理员负责桶配置及对象读写权限;production 还需要配置 GitHub App。
5. 按[打包与发布](#package-and-publish)完成一次 Windows 已签名或 macOS 已公证的 **test** 打包。确认打包 job 使用预期的注册 runner 并留存文件。从 `master` 发起发布,填写该 run ID 和 attempt;确认 `prepare` 确实在同一台机器上启动并生成审批摘要。
6. 审核摘要中的环境、版本、频道和 URL 后,再批准测试上传。验证发布记录、公开安装包下载和升级 feed。test 验收不能证明 production 权限可用:production 需独立配置与审批。保留 run/attempt 和验收结果,供故障恢复使用。
@@ -69,6 +69,8 @@ Environment 审批限制此工作流,不限制同一机器账户运行的任
## 打包与发布
Windows 打包运行会展示中文参数摘要,列出请求的源码、环境、通道、版本模式、签名方式、压缩等级、测试 release ID 和缓存命名空间,以及工作流标识、检出提交、解析版本和 runner。工作流辅助脚本暂存成功后,即使前序步骤失败仍会生成摘要,并明确标记尚未取得的结果。摘要不读取机器配置;测试 release ID 留空时仅显示选择了机器默认值,不展示其解析值。摘要不代表构建、签名或发布成功。
发布表单支持可选的 `staging_percentage`,取值为 0 到 100 的整数。该值作用于保留包所属的 nightly 或 stable 渠道,显示在审批摘要中,并写入发布的 YAML 和审计记录,不修改保留产物。留空沿用包内默认值(通常为全量)。已完成的发布不能通过重试修改比例;同版本清单内容冲突仍会报错。
发布到 test 或 production 都必须在 Windows 选择 `signing=signed`,或在 macOS 不勾选**跳过公证**。无签名、无公证的包仅限内部调试,不能发布或用于自动更新。托管路由 job 会在安装依赖前,依据所选 run 和 attempt 对应的 artifact 名称拒绝已标明的调试包。仅重跑归档时,artifact 名称保留原构建 attempt,早期检查可能未识别该包;本地清单资格校验仍会在发布前拒绝调试包。缺少 artifact 元数据不代表允许发布:原机器仍会验证留存清单和签名。遇到调试包拒绝提示时,需重新完成签名或公证,再使用新包的 run ID / attempt 发布;重跑发布不能使现有产物获得发布资格。
@@ -14,6 +14,8 @@ import { tmpdir } from 'node:os'
import { basename, dirname, join } from 'node:path'
import { promisify } from 'node:util'
import { scrubWindowsSigningEnvironment } from './windows-sign.mjs'
const run = promisify(execFile)
/** One tool the packaging run requires, and what went wrong with it. */
@@ -45,6 +47,14 @@ async function probeTar(): Promise<string | undefined> {
async function probeWindowsInstallerToolchain(environment: NodeJS.ProcessEnv): Promise<DesktopToolchainProbeFailure[]> {
const failures: DesktopToolchainProbeFailure[] = []
try {
await run('pwsh', ['-NoProfile', '-NonInteractive', '-Command',
'$ErrorActionPreference="Stop"; if ($PSVersionTable.PSVersion.Major -lt 7) { throw "PowerShell 7 or newer is required" }; Import-Module "$PSHOME/Modules/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1" -ErrorAction Stop; Get-Command Get-AuthenticodeSignature -ErrorAction Stop | Out-Null'],
{ env: scrubWindowsSigningEnvironment(environment), windowsHide: true, timeout: 20_000 })
}
catch (error) {
failures.push({ tool: 'pwsh', detail: `PowerShell 7 with Authenticode support must be available on PATH: ${error instanceof Error ? error.message : String(error)}` })
}
const programFiles = environment['ProgramFiles(x86)']
const vswhere = programFiles === undefined
? undefined
@@ -4,17 +4,17 @@ $runnerRoot = [IO.Path]::GetFullPath((Split-Path -Parent $PSScriptRoot)).TrimEnd
$digest = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($runnerRoot.ToUpperInvariant())))
$taskName = 'DSH-Packaging-' + $digest.Substring(0,16)
$log = Join-Path $PSScriptRoot ('run-' + [DateTime]::UtcNow.ToString('yyyyMMddTHHmmssfffZ') + '-' + $PID + '.log')
$attemptReserved = $false
try {
$config = Get-Content -LiteralPath (Join-Path $PSScriptRoot 'config.json') -Raw | ConvertFrom-Json
$attemptFile = Join-Path $PSScriptRoot 'attempts.txt'
$attempts = [int](Get-Content -LiteralPath $attemptFile -Raw)
if ($attempts -lt 0 -or $config.RestartCount -lt 1 -or $config.RestartCount -gt 999) { throw 'Invalid restart budget; reinstall the task.' }
if ($attempts -gt $config.RestartCount) {
$null = Disable-ScheduledTask -TaskName $config.TaskName -TaskPath '\'
Set-Content -LiteralPath $log -Value 'Restart budget exhausted. Task disabled; inspect runner logs, fix the cause and run start.'
exit 1
throw 'Restart budget exhausted; inspect runner logs, fix the cause and run start.'
}
Set-Content -LiteralPath $attemptFile -Value ($attempts + 1)
$attemptReserved = $true
$startup = Join-Path $PSScriptRoot 'start.ps1'
if ($config.NetworkRoot) {
if (-not (Test-Path -LiteralPath (Join-Path $config.ConfigRoot 'runner-network.json') -PathType Leaf)) { throw 'Owned network supervision requires runner-network.json.' }
@@ -27,10 +27,25 @@ try {
# An unexpected exit is a task failure even when run.cmd hides the listener's nonzero status; the log retains its code.
exit 1
} catch {
# A missing or unwritable counter cannot bound retries; the task name must not depend on readable configuration.
$null = Disable-ScheduledTask -TaskName $taskName -TaskPath '\'
$message = 'Runner task failed: ' + $_.Exception.Message
$failure = $_.Exception.Message
$disposition = 'Scheduled recovery remains bounded by the persisted attempt budget.'
# Stop triggers when the budget is exhausted or an attempt could not be persisted.
if (-not $attemptReserved) {
try {
$scheduler = New-Object -ComObject 'Schedule.Service'
$scheduler.Connect()
$scheduler.GetFolder('\').GetTask($taskName).Enabled = $false
$disposition = 'Task disabled; inspect configuration and attempt storage before starting.'
} catch {
# A limited task account may lack permission to change its scheduler registration.
$disposition = 'Task disable failed; an administrator must disable its triggers. No runner was launched.'
}
}
$message = 'Runner task failed: ' + $failure + ' ' + $disposition
[Console]::Error.WriteLine($message)
Add-Content -LiteralPath $log -Value $message
try { Add-Content -LiteralPath $log -Value $message } catch {
# The launcher captures stderr independently when the runner log is unavailable.
[Console]::Error.WriteLine('Runner log unavailable: ' + $_.Exception.Message)
}
exit 1
}
@@ -0,0 +1,7 @@
/** Windows packaging parameter summary without machine configuration access. */
/**
* Summarize allowlisted workflow inputs and resolved build identity.
* @param environment Workflow inputs and GitHub run identity.
* @returns Markdown tables without a build or signature success claim.
*/
export function windowsPackagingSummary(environment: NodeJS.ProcessEnv): string
@@ -0,0 +1,45 @@
/** Render Windows packaging inputs and resolved build identity without loading machine configuration. */
import { appendFile } from 'node:fs/promises'
import { realpathSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
function text(value) {
return value.replace(/[&<>"'|`\r\n\\*_\[\]()!~:]/gu, character => `&#${character.charCodeAt(0)};`)
}
/**
* Summarize allowlisted workflow inputs separately from resolved checkout and version values.
* @param {NodeJS.ProcessEnv} environment Workflow inputs and GitHub run identity.
* @returns {string} Markdown parameter tables; no signature or publication success claim.
*/
export function windowsPackagingSummary(environment) {
const row = (label, value, fallback = '未提供') => `| ${label} | ${value ? `<code>${text(value)}</code>` : fallback} |`
return [
'## Windows 打包参数', '',
'以下记录输入参数与已解析结果,不代表构建、签名或发布成功;执行结果以各步骤状态为准。', '',
'### 输入参数', '', '| 项目 | 选择值 |', '| --- | --- |',
row('源码 ref', environment.PACKAGE_SOURCE_REF),
row('环境', environment.DSH_PACKAGING_PRESET),
row('升级通道', environment.DSH_DESKTOP_UPDATE_CHANNEL),
row('版本模式', environment.PACKAGE_INPUT_VERSION_MODE),
row('手动版本号', environment.PACKAGE_BUILD_VERSION, '未填写'),
row('签名方式(请求)', environment.PACKAGE_SIGNING),
row('安装器压缩等级', environment.PACKAGE_WINDOWS_COMPRESSION_LEVEL),
row('测试 release ID(输入)', environment.PACKAGE_TEST_RELEASE_ID, '使用机器默认值(本摘要不读取)'),
row('缓存命名空间', environment.PACKAGE_CACHE_NAMESPACE, '共享缓存'), '',
'### 执行信息', '', '| 项目 | 已知值 |', '| --- | --- |',
row('平台', 'win-x64'),
row('工作流 ref', environment.GITHUB_WORKFLOW_REF),
row('工作流 SHA', environment.GITHUB_WORKFLOW_SHA),
row('检出源码 SHA', environment.PACKAGE_SOURCE_SHA, '尚未取得'),
row('解析后的版本号', environment.PACKAGE_VERSION, '尚未解析成功'),
row('Runner', environment.RUNNER_NAME),
row('运行 ID', environment.GITHUB_RUN_ID),
row('尝试次数', environment.GITHUB_RUN_ATTEMPT), '',
].join('\n')
}
if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
if (!process.env.GITHUB_STEP_SUMMARY) throw new Error('Windows packaging summary requires GITHUB_STEP_SUMMARY')
await appendFile(process.env.GITHUB_STEP_SUMMARY, windowsPackagingSummary(process.env))
}
@@ -48,7 +48,7 @@ function Wait-RunnerNetwork($Config) {
$info.Environment['DSH_NETWORK_PROBE_TIMEOUT'] = [string]($Config.timeoutSeconds * 1000)
$info.ArgumentList.Add('--input-type=module')
$info.ArgumentList.Add('-e')
$info.ArgumentList.Add('try { const r = await fetch(process.env.DSH_NETWORK_PROBE_URL, { method: "HEAD", redirect: "error", signal: AbortSignal.timeout(Number(process.env.DSH_NETWORK_PROBE_TIMEOUT)) }); await r.body?.cancel(); process.exit(r.ok ? 0 : 1); } catch { process.exit(1); }')
$info.ArgumentList.Add('try { const r = await fetch(process.env.DSH_NETWORK_PROBE_URL, { method: "HEAD", redirect: "error", signal: AbortSignal.timeout(Number(process.env.DSH_NETWORK_PROBE_TIMEOUT)) }); await r.body?.cancel(); process.exitCode = r.ok ? 0 : 1; } catch { process.exitCode = 1; }')
for ($attempt = 1; $attempt -le $Config.attempts; $attempt++) {
$ready = $true
if ($Config.serviceName) {
@@ -0,0 +1,50 @@
// Toolhelp snapshots expose parent IDs without the WMI namespace permissions required by CIM.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
public static class DshRunnerProcesses
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct Entry
{
public uint Size, Usage, ProcessId;
public UIntPtr DefaultHeapId;
public uint ModuleId, Threads, ParentProcessId;
public int Priority;
public uint Flags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string Name;
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr CreateToolhelp32Snapshot(uint flags, uint processId);
[DllImport("kernel32.dll", EntryPoint = "Process32FirstW", SetLastError = true)]
private static extern bool First(IntPtr snapshot, ref Entry entry);
[DllImport("kernel32.dll", EntryPoint = "Process32NextW", SetLastError = true)]
private static extern bool Next(IntPtr snapshot, ref Entry entry);
[DllImport("kernel32.dll")]
private static extern bool CloseHandle(IntPtr handle);
// These parent IDs select handles to await; taskkill retains termination authority over the live tree.
public static Dictionary<int, int> ReadParents()
{
IntPtr snapshot = CreateToolhelp32Snapshot(2, 0);
if (snapshot == new IntPtr(-1)) throw new Win32Exception(Marshal.GetLastWin32Error());
try
{
var result = new Dictionary<int, int>();
var entry = new Entry { Size = (uint)Marshal.SizeOf(typeof(Entry)) };
bool found = First(snapshot, ref entry);
while (found)
{
result.Add((int)entry.ProcessId, (int)entry.ParentProcessId);
found = Next(snapshot, ref entry);
}
int error = Marshal.GetLastWin32Error();
if (error != 18) throw new Win32Exception(error);
return result;
}
finally { CloseHandle(snapshot); }
}
}
@@ -0,0 +1,72 @@
# Build an unregistered runner task. Credentials are supplied only to the scheduler at installation.
function New-WindowsRunnerTaskDefinition($Scheduler, [string]$Sid, [string]$RunnerRoot, [string]$PowerShell, [int]$RestartMinutes, [ValidateSet('Interactive','Boot')][string]$StartupMode = 'Interactive') {
$definition = $Scheduler.NewTask(0)
$definition.RegistrationInfo.Description = "DSH packaging runner: $RunnerRoot; owner: $Sid"
$definition.Principal.UserId = $Sid
$definition.Principal.LogonType = if ($StartupMode -eq 'Boot') { 1 } else { 3 } # Password or InteractiveToken.
$definition.Principal.RunLevel = 0 # TASK_RUNLEVEL_LUA: the job does not inherit installer elevation.
$definition.Settings.Priority = 4
$definition.Settings.Enabled = $false
$definition.Settings.MultipleInstances = 2 # TASK_INSTANCES_IGNORE_NEW
$definition.Settings.ExecutionTimeLimit = 'PT0S'
$definition.Settings.DisallowStartIfOnBatteries = $false
$definition.Settings.StopIfGoingOnBatteries = $false
if ($StartupMode -eq 'Boot') {
$null = $definition.Triggers.Create(8) # TASK_TRIGGER_BOOT
} else {
$logon = $definition.Triggers.Create(9) # TASK_TRIGGER_LOGON
$logon.UserId = $Sid
}
$recovery = $definition.Triggers.Create(1) # TASK_TRIGGER_TIME
$recovery.StartBoundary = (Get-Date).AddMinutes($RestartMinutes).ToString('yyyy-MM-ddTHH:mm:ss')
$recovery.Repetition.Interval = "PT${RestartMinutes}M"
$execution = $definition.Actions.Create(0) # TASK_ACTION_EXEC
$execution.Path = Join-Path $RunnerRoot 'dsh-task/launcher.exe'
$execution.Arguments = '"' + $PowerShell + '"'
$execution.WorkingDirectory = $RunnerRoot
return $definition
}
# Prompt locally and submit once; credential-bearing COM failures must not reach diagnostics.
function Register-WindowsRunnerBootTask($Scheduler, [string]$TaskName, $Definition, [string]$Sid, [string]$RunAs) {
$credential = Get-Credential -UserName $RunAs -Message 'Windows account password for unattended runner startup (not the signing Token PIN)'
if (-not $credential -or $credential.UserName -ne $RunAs -or $credential.Password.Length -eq 0) {
throw 'Credential entry cancelled or account changed; no task was registered.'
}
try {
# COM avoids putting a plaintext password in command arguments or cmdlet parameter logging.
$null = $Scheduler.GetFolder('\').RegisterTaskDefinition($TaskName, $Definition, 2, $RunAs, $credential.GetNetworkCredential().Password, 1, "D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;$Sid)")
} catch {
# Registration may have committed before an error reached this caller.
$code = '0x{0:X8}' -f $_.Exception.GetBaseException().HResult
throw "Boot task registration failed ($code); registration outcome is unconfirmed. Inspect Task Scheduler, batch-logon policy and account credentials locally before retrying."
} finally {
$credential = $null
}
}
# Validate machine-owned preparation data before credentials or scheduler registration.
function Assert-WindowsRunnerBootConfiguration($Config, [string]$Sid, [string]$RunnerRoot, [string]$TaskName) {
if ($Config.StartupMode -ne 'Boot' -or $Config.AccountSid -ne $Sid -or $Config.RunnerRoot -ne $RunnerRoot -or $Config.TaskName -ne $TaskName) {
throw 'Prepared Boot configuration does not match RunAs and RunnerRoot; prepare again as the runner account.'
}
if (($Config.RestartMinutes -isnot [int] -and $Config.RestartMinutes -isnot [long]) -or $Config.RestartMinutes -lt 1 -or $Config.RestartMinutes -gt 1440 -or $Config.PowerShell -isnot [string] -or $Config.PowerShell -notmatch '^[A-Za-z]:[\\/]' -or -not (Test-Path -LiteralPath $Config.PowerShell -PathType Leaf) -or -not (Test-Path -LiteralPath (Join-Path $RunnerRoot 'dsh-task/launcher.exe') -PathType Leaf)) {
throw 'Prepared Boot startup files or restart interval are invalid; prepare again as the runner account.'
}
}
# Missing tasks are distinct from denied or unavailable scheduler access.
function Get-WindowsRunnerTask($Scheduler, [string]$TaskName) {
try { return $Scheduler.GetFolder('\').GetTask($TaskName) } catch {
if ($_.Exception.GetBaseException().HResult -eq -2147024894) { return $null }
throw
}
}
# Unreadable process locations must reject maintenance just like missing locations.
function Get-WindowsRunnerProcessPath($Process) {
try { return $Process.Path } catch {
# Access-denied and exited-process errors cannot establish an unrelated location.
return $null
}
}
+76 -36
View File
@@ -1,18 +1,21 @@
# Manage a registered packaging runner in the current user's interactive Windows session.
# Prepare startup files and manage runner tasks; Boot registration requires an administrator.
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)][ValidateSet('install','start','stop','status','uninstall')][string]$Action,
[Parameter(Mandatory=$true)][ValidateSet('install','register-boot','start','stop','status','uninstall')][string]$Action,
[Parameter(Mandatory=$true)][string]$RunnerRoot,
[string]$ConfigRoot,
[string]$NetworkRoot,
[ValidateSet('Interactive','Boot')][string]$StartupMode = 'Interactive',
[string]$RunAs,
[ValidateRange(1,1440)][int]$RestartMinutes = 1,
[ValidateRange(1,999)][int]$RestartCount = 10
)
$ErrorActionPreference = 'Stop'
if (-not $IsWindows) { throw 'This command requires PowerShell 7 on Windows.' }
if ($Action -ne 'install' -and @('ConfigRoot','NetworkRoot','RestartMinutes','RestartCount').Where({ $PSBoundParameters.ContainsKey($_) }).Count) {
throw 'ConfigRoot, NetworkRoot, RestartMinutes and RestartCount apply only to install; reinstall to change them.'
if ($Action -ne 'install' -and @('ConfigRoot','NetworkRoot','StartupMode','RestartMinutes','RestartCount').Where({ $PSBoundParameters.ContainsKey($_) }).Count) {
throw 'Configuration and retry options apply only to install; reinstall to change them.'
}
if ($Action -ne 'register-boot' -and $PSBoundParameters.ContainsKey('RunAs')) { throw 'RunAs applies only to register-boot.' }
if ($RunnerRoot -notmatch '^[A-Za-z]:[\\/]') { throw 'RunnerRoot must be an absolute local directory.' }
$RunnerRoot = [IO.Path]::GetFullPath($RunnerRoot).TrimEnd('\','/')
if (-not (Test-Path -LiteralPath (Join-Path $RunnerRoot '.runner') -PathType Leaf)) { throw 'Register the runner before managing its task.' }
@@ -23,11 +26,46 @@ $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
$digest = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($RunnerRoot.ToUpperInvariant())))
$taskName = 'DSH-Packaging-' + $digest.Substring(0,16)
$serviceDir = Join-Path $RunnerRoot 'dsh-task'
$task = Get-ScheduledTask -TaskPath '\' | Where-Object TaskName -eq $taskName
if ($task -and $task.Description -ne "DSH packaging runner: $RunnerRoot; owner: $sid") { throw 'Task ownership differs; inspect it in Task Scheduler.' }
if ($Action -eq 'register-boot') {
if (-not $RunAs) { throw 'Boot registration requires -RunAs with the prepared runner account.' }
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
if (-not ([Security.Principal.WindowsPrincipal]::new($identity)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
throw 'Boot registration requires an elevated PowerShell; the runner account remains limited.'
}
$sid = ([Security.Principal.NTAccount]::new($RunAs)).Translate([Security.Principal.SecurityIdentifier]).Value
if ($sid -in @('S-1-5-18','S-1-5-19','S-1-5-20') -or $sid.EndsWith('-500')) { throw 'Use a dedicated runner account, not a built-in service or Administrator account.' }
}
. (Join-Path $PSScriptRoot 'windows-runner-scheduler.ps1')
$scheduler = New-Object -ComObject 'Schedule.Service'
$scheduler.Connect()
$task = Get-WindowsRunnerTask $scheduler $taskName
if ($task -and $task.Definition.RegistrationInfo.Description -ne "DSH packaging runner: $RunnerRoot; owner: $sid") { throw 'Task ownership differs; inspect it in Task Scheduler.' }
if ($Action -in @('install','register-boot')) {
if ($task) { throw 'Task already installed; stop and uninstall before reinstalling.' }
# Pause dispatch before migration; never overwrite a live startup snapshot.
foreach ($process in @(Get-Process | Where-Object { $_.ProcessName -in @('Runner.Listener','Runner.Worker') })) {
$path = Get-WindowsRunnerProcessPath $process
if (-not $path -or $path.StartsWith($RunnerRoot + '\', [StringComparison]::OrdinalIgnoreCase)) {
throw 'A runner process is active or its location is unreadable. Pause dispatch and stop its supervisor before installing.'
}
}
if (Test-Path -LiteralPath (Join-Path $RunnerRoot '.service')) { throw 'A native runner service is configured; inspect and remove it before task migration.' }
if ((Test-Path -LiteralPath $serviceDir) -and ((Get-Item -LiteralPath $serviceDir).Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw 'Task directory cannot be a link.' }
}
if ($Action -eq 'register-boot') {
# This elevated path only registers a limited task; it never executes runner-owned files.
$configFile = Join-Path $serviceDir 'config.json'
if ((Get-Item -LiteralPath $configFile).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Task configuration cannot be a link.' }
$config = Get-Content -LiteralPath $configFile -Raw | ConvertFrom-Json
Assert-WindowsRunnerBootConfiguration $config $sid $RunnerRoot $taskName
$definition = New-WindowsRunnerTaskDefinition $scheduler $sid $RunnerRoot $config.PowerShell $config.RestartMinutes 'Boot'
Register-WindowsRunnerBootTask $scheduler $taskName $definition $sid $RunAs
Write-Output "Registered disabled Boot task $taskName. Run start as the runner account. Logs: $serviceDir"
exit 0
}
if ($Action -eq 'install') {
if ($task) { throw 'Task already installed; stop and uninstall before reinstalling.' }
if (-not $ConfigRoot -or $ConfigRoot -notmatch '^[A-Za-z]:[\\/]') { throw 'Install requires an absolute ConfigRoot.' }
$ConfigRoot = [IO.Path]::GetFullPath($ConfigRoot)
$pwsh = Join-Path $PSHOME 'pwsh.exe'
@@ -56,46 +94,47 @@ if ($Action -eq 'install') {
foreach ($helper in @('windows-runner-network.ps1','run-windows-runner-network-process.ps1')) {
Copy-Item -LiteralPath (Join-Path $PSScriptRoot $helper) -Destination (Join-Path $serviceDir $helper)
}
@{ RunnerRoot = $RunnerRoot; ConfigRoot = $ConfigRoot; NetworkRoot = $NetworkRoot; TaskName = $taskName; RestartCount = $RestartCount } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $serviceDir 'config.json') -Encoding utf8
@{ RunnerRoot = $RunnerRoot; ConfigRoot = $ConfigRoot; NetworkRoot = $NetworkRoot; TaskName = $taskName; RestartCount = $RestartCount; StartupMode = $StartupMode; AccountSid = $sid; PowerShell = $pwsh; RestartMinutes = $RestartMinutes } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $serviceDir 'config.json') -Encoding utf8
Set-Content -LiteralPath (Join-Path $serviceDir 'attempts.txt') -Value '0'
$execution = New-ScheduledTaskAction -Execute $launcher -Argument ('"' + $pwsh + '"') -WorkingDirectory $RunnerRoot
$principal = New-ScheduledTaskPrincipal -UserId $sid -LogonType Interactive -RunLevel Limited
$trigger = @(
(New-ScheduledTaskTrigger -AtLogOn -User $sid),
(New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes($RestartMinutes) -RepetitionInterval (New-TimeSpan -Minutes $RestartMinutes))
)
$settings = New-ScheduledTaskSettingsSet -Priority 4 -MultipleInstances IgnoreNew -ExecutionTimeLimit ([TimeSpan]::Zero) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
$settings.Enabled = $false
$null = Register-ScheduledTask -TaskName $taskName -TaskPath '\' -Action $execution -Principal $principal -Trigger $trigger -Settings $settings -Description "DSH packaging runner: $RunnerRoot; owner: $sid"
if ($StartupMode -eq 'Boot') {
Write-Output "Prepared Boot startup for account $sid. An administrator must run register-boot with RunnerRoot and RunAs; no task was registered."
exit 0
}
$definition = New-WindowsRunnerTaskDefinition $scheduler $sid $RunnerRoot $pwsh $RestartMinutes 'Interactive'
$null = $scheduler.GetFolder('\').RegisterTaskDefinition($taskName, $definition, 2, $sid, $null, 3, $null)
Write-Output "Installed disabled task $taskName. Run start while logged in; reboot requires desktop login. Logs: $serviceDir"
exit 0
}
if (-not $task) { throw 'Task is not installed for this runner directory.' }
switch ($Action) {
'status' {
$info = Get-ScheduledTaskInfo -InputObject $task
$bootTrigger = $false
for ($index = 1; $index -le $task.Definition.Triggers.Count; $index++) {
if ($task.Definition.Triggers.Item($index).Type -eq 8) { $bootTrigger = $true }
}
$launches = [int](Get-Content -LiteralPath (Join-Path $serviceDir 'attempts.txt') -Raw)
$config = Get-Content -LiteralPath (Join-Path $serviceDir 'config.json') -Raw | ConvertFrom-Json
[pscustomobject]@{ TaskName = $taskName; State = $task.State; LastRunTime = $info.LastRunTime; LastTaskResult = $info.LastTaskResult; Launches = $launches; RemainingLaunches = [Math]::Max(0, 1 + $config.RestartCount - $launches); Logs = $serviceDir }
[pscustomobject]@{ TaskName = $taskName; State = @('Unknown','Disabled','Queued','Ready','Running')[[int]$task.State]; Account = $task.Definition.Principal.UserId; LogonType = @('None','Password','S4U','Interactive','Group','ServiceAccount','InteractiveOrPassword')[[int]$task.Definition.Principal.LogonType]; BootTrigger = $bootTrigger; LastRunTime = $task.LastRunTime; LastTaskResult = $task.LastTaskResult; Launches = $launches; RemainingLaunches = [Math]::Max(0, 1 + $config.RestartCount - $launches); Logs = $serviceDir }
}
'start' {
if ($task.State -eq 'Running') { Write-Output "$taskName is already running."; break }
if ($task.State -eq 4) { Write-Output "$taskName is already running."; break }
Set-Content -LiteralPath (Join-Path $serviceDir 'attempts.txt') -Value '0'
$null = Enable-ScheduledTask -InputObject $task
Start-ScheduledTask -InputObject $task
$task.Enabled = $true
$null = $task.Run($null)
Write-Output "Start requested for $taskName. Verify Connected to GitHub and Listening for Jobs in $serviceDir."
}
'stop' {
# Operators pause workflow dispatch first; this local check cannot reserve an idle GitHub runner.
$workers = Get-CimInstance Win32_Process -Filter "Name = 'Runner.Worker.exe'"
$workers = Get-Process | Where-Object ProcessName -eq 'Runner.Worker'
foreach ($worker in $workers) {
if (-not $worker.ExecutablePath -or $worker.ExecutablePath.StartsWith($RunnerRoot + '\', [StringComparison]::OrdinalIgnoreCase)) {
$path = Get-WindowsRunnerProcessPath $worker
if (-not $path -or $path.StartsWith($RunnerRoot + '\', [StringComparison]::OrdinalIgnoreCase)) {
throw 'A runner job is active or its location is unreadable. Wait for completion before stopping.'
}
}
$null = Disable-ScheduledTask -InputObject $task
$task = Get-ScheduledTask -TaskName $taskName -TaskPath '\'
if ($task.State -eq 'Running') {
$task.Enabled = $false
$task = Get-WindowsRunnerTask $scheduler $taskName
if ($task.State -eq 4) {
$recordFile = Join-Path $serviceDir 'process.json'
if (-not (Test-Path -LiteralPath $recordFile)) { throw 'Running task process identity is unavailable. Automatic starts are disabled; inspect the task before stopping it.' }
$record = Get-Content -LiteralPath $recordFile -Raw | ConvertFrom-Json
@@ -104,13 +143,14 @@ switch ($Action) {
throw 'Running task process identity is unavailable. Automatic starts are disabled; inspect the task before stopping it.'
}
# Parent IDs can be reused; this snapshot supplies wait handles, not termination authority.
$processes = @(Get-CimInstance Win32_Process)
if (-not ('DshRunnerProcesses' -as [type])) { Add-Type -Path (Join-Path $PSScriptRoot 'windows-runner-processes.cs') }
$processes = [DshRunnerProcesses]::ReadParents()
$ownedIds = [Collections.Generic.HashSet[int]]::new()
$null = $ownedIds.Add($owner.Id)
do {
$added = $false
foreach ($process in $processes) {
if ($ownedIds.Contains([int]$process.ParentProcessId) -and $ownedIds.Add([int]$process.ProcessId)) { $added = $true }
foreach ($process in $processes.GetEnumerator()) {
if ($ownedIds.Contains([int]$process.Value) -and $ownedIds.Add([int]$process.Key)) { $added = $true }
}
} while ($added)
$owned = @(foreach ($ownedId in $ownedIds) { Get-Process -Id $ownedId -ErrorAction SilentlyContinue })
@@ -120,19 +160,19 @@ switch ($Action) {
if (-not $process.WaitForExit(30000)) { throw 'Runner task child remains alive; inspect it before restarting.' }
}
}
Stop-ScheduledTask -InputObject $task
$task.Stop(0)
$deadline = [DateTime]::UtcNow.AddSeconds(30)
do {
$state = (Get-ScheduledTask -TaskName $taskName -TaskPath '\').State
if ($state -ne 'Running') { break }
$state = (Get-WindowsRunnerTask $scheduler $taskName).State
if ($state -ne 4) { break }
Start-Sleep -Milliseconds 200
} while ([DateTime]::UtcNow -lt $deadline)
if ($state -eq 'Running') { throw 'Task remains running; inspect its processes before further maintenance.' }
if ($state -eq 4) { throw 'Task remains running; inspect its processes before further maintenance.' }
Write-Output "Stopped and disabled $taskName. Run start to enable automatic starts again."
}
'uninstall' {
if ($task.State -ne 'Disabled') { throw 'Stop the task before uninstalling.' }
Unregister-ScheduledTask -InputObject $task -Confirm:$false
if ($task.State -ne 1) { throw 'Stop the task before uninstalling.' }
$scheduler.GetFolder('\').DeleteTask($taskName, 0)
Write-Output "Uninstalled $taskName. Registration, configuration and logs remain in $RunnerRoot."
}
}
@@ -9,13 +9,12 @@ import { inspectSignaturesBatched } from './windows-signature-batch.mjs'
import { packagingStep } from './packaging-step.mjs'
/**
* Read Windows trust, timestamp and signer identity using the engine's bundled modules, without accessing the private key.
* Read Windows trust, timestamp and signer identity using PowerShell 7's bundled modules, without accessing the private key.
* @param {string} path File to inspect.
* @returns {Promise<{status: string, timestamped: boolean, thumbprint: string | null}>} Authenticode verification result.
*/
export async function inspectWindowsRuntimeSignature(path) {
// Node can inherit PowerShell 7's module search path while launching Windows PowerShell 5.
const { stdout, stderr } = await promisify(execFile)('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
const { stdout, stderr } = await promisify(execFile)('pwsh', ['-NoProfile', '-NonInteractive', '-Command',
'$ErrorActionPreference="Stop"; [Console]::OutputEncoding=[System.Text.UTF8Encoding]::new(); Import-Module "$PSHOME/Modules/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1" -ErrorAction Stop; Import-Module "$PSHOME/Modules/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1" -ErrorAction Stop; $s=Get-AuthenticodeSignature -LiteralPath $env:DSH_RUNTIME_VERIFY_FILE; [pscustomobject]@{status=[string]$s.Status;timestamped=($null -ne $s.TimeStamperCertificate);thumbprint=$s.SignerCertificate.Thumbprint}|ConvertTo-Json -Compress'], {
env: { ...scrubWindowsSigningEnvironment(process.env), DSH_RUNTIME_VERIFY_FILE: path },
encoding: 'utf8', windowsHide: true, timeout: 60_000, maxBuffer: 64 * 1024,
@@ -1,4 +1,4 @@
/** Bounded public-key verification batches; every output row must match its requested file. */
/** Bounded PowerShell 7 public-key verification batches; every output row must match its requested file. */
import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
import { scrubWindowsSigningEnvironment } from './windows-sign.mjs'
@@ -27,7 +27,7 @@ export function parseSignatureRows(stdout, stderr, files) {
}
async function inspectBatch(files) {
const pending = promisify(execFile)('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', command], {
const pending = promisify(execFile)('pwsh', ['-NoProfile', '-NonInteractive', '-Command', command], {
env: scrubWindowsSigningEnvironment(process.env), encoding: 'utf8', windowsHide: true,
timeout: 60_000, maxBuffer: 64 * 1024 * files.length,
})
@@ -73,6 +73,18 @@ describe('desktop toolchain preflight', () => {
expect(failures.find(failure => failure.tool === 'vswhere')?.detail).toContain('ProgramFiles(x86)')
})
it('reports missing PowerShell before Windows packaging', async () => {
const empty = await mkdtemp(join(tmpdir(), 'dsh-no-pwsh-'))
directories.push(empty)
const failures = await probeDesktopToolchain('win32', { PATH: empty })
expect(failures.find(failure => failure.tool === 'pwsh')?.detail).toContain('PowerShell 7')
})
it.skipIf(process.platform !== 'win32')('accepts the Windows Authenticode toolchain', async () => {
const failures = await probeDesktopToolchain('win32', process.env)
expect(failures.filter(failure => failure.tool === 'pwsh')).toEqual([])
})
it('writes nothing into the working directory while probing', async () => {
const directory = await mkdtemp(join(tmpdir(), 'dsh-probe-cwd-'))
directories.push(directory)
@@ -0,0 +1,58 @@
/** Workflow summaries distinguish requested options from completed build evidence. */
import { execFile } from 'node:child_process'
import { copyFile, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { promisify } from 'node:util'
import { expect, it } from 'vitest'
import { windowsPackagingSummary } from '../scripts/windows-packaging-summary.mjs'
it('separates workflow identity, requested source, and resolved build version', () => {
const summary = windowsPackagingSummary({
PACKAGE_SOURCE_REF: 'feature/windows', PACKAGE_SOURCE_SHA: 'source-sha',
GITHUB_WORKFLOW_REF: 'repo/.github/workflows/windows-package.yml@refs/heads/master',
GITHUB_WORKFLOW_SHA: 'workflow-sha', PACKAGE_INPUT_VERSION_MODE: 'default',
PACKAGE_VERSION: '0.2.2-rc.1.20261110.1.1', PACKAGE_SIGNING: 'signed',
DSH_PACKAGING_PRESET: 'test', DSH_DESKTOP_UPDATE_CHANNEL: 'nightly',
})
expect(summary).toContain('| 源码 ref | <code>feature/windows</code> |')
expect(summary).toContain('| 检出源码 SHA | <code>source-sha</code> |')
expect(summary).toContain('| 工作流 SHA | <code>workflow-sha</code> |')
expect(summary).toContain('| 版本模式 | <code>default</code> |')
expect(summary).toContain('| 解析后的版本号 | <code>0.2.2-rc.1.20261110.1.1</code> |')
expect(summary).toContain('不代表构建、签名或发布成功')
})
it('retains unresolved and machine-default labels after an earlier failure', () => {
const summary = windowsPackagingSummary({ PACKAGE_SOURCE_REF: 'bad-source' })
expect(summary).toContain('| 检出源码 SHA | 尚未取得 |')
expect(summary).toContain('| 解析后的版本号 | 尚未解析成功 |')
expect(summary).toContain('使用机器默认值(本摘要不读取)')
expect(summary).toContain('| 缓存命名空间 | 共享缓存 |')
})
it('escapes input markup and excludes unrelated environment and private configuration', () => {
const summary = windowsPackagingSummary({
PACKAGE_SOURCE_REF: '<script>|\n[link](url)`',
DSH_DESKTOP_WINDOWS_TOKEN_PIN: 'private-pin-sentinel',
DSH_PACKAGING_CONFIG_DIR: 'private-directory-sentinel',
})
expect(summary).toContain('&#60;script&#62;&#124;&#10;&#91;link&#93;&#40;url&#41;&#96;')
expect(summary).not.toContain('<script>')
expect(summary).not.toContain('sentinel')
})
it('appends a summary using the standalone workflow helper without project dependencies', async (t) => {
const root = await mkdtemp(join(tmpdir(), 'windows-summary-'))
t.onTestFinished(() => rm(root, { recursive: true, force: true }))
const output = join(root, 'summary.md')
const helper = join(root, 'windows-packaging-summary.mjs')
await copyFile(join(import.meta.dirname, '../scripts/windows-packaging-summary.mjs'), helper)
await writeFile(output, 'Previous summary\n')
await promisify(execFile)(process.execPath, [helper], {
env: { GITHUB_STEP_SUMMARY: output, PACKAGE_SOURCE_REF: 'test-ref', PACKAGE_SIGNING: 'unsigned' },
timeout: 20_000,
})
expect(await readFile(output, 'utf8')).toMatch(/^Previous summary\n/u)
expect(await readFile(output, 'utf8')).toContain('| 签名方式(请求) | <code>unsigned</code> |')
})
+265
View File
@@ -0,0 +1,265 @@
# Inspect real Task Scheduler definitions without registering tasks, passwords, GitHub or signing hardware.
$ErrorActionPreference = 'Stop'
if (-not $IsWindows) { throw 'Requires PowerShell 7 on Windows.' }
. (Join-Path $PSScriptRoot '../scripts/windows-runner-scheduler.ps1')
$scheduler = New-Object -ComObject 'Schedule.Service'
$scheduler.Connect()
$sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
$root = Join-Path ([IO.Path]::GetTempPath()) ('dsh-boot-definition-' + [guid]::NewGuid().ToString('N'))
$null = New-Item -ItemType Directory -Path $root
try {
$runner = Join-Path $root 'runner with spaces'
$null = New-Item -ItemType Directory -Path $runner
Set-Content -LiteralPath (Join-Path $runner '.runner') -Value '{}'
$pwsh = Join-Path $PSHOME 'pwsh.exe'
foreach ($minutes in @(1, 7, 1440)) {
$definition = New-WindowsRunnerTaskDefinition $scheduler $sid $runner $pwsh $minutes 'Boot'
[xml]$xml = $definition.XmlText
$ns = [Xml.XmlNamespaceManager]::new($xml.NameTable)
$ns.AddNamespace('t', 'http://schemas.microsoft.com/windows/2004/02/mit/task')
function Read-Value([string]$Path) { return $xml.SelectSingleNode('/t:Task/' + $Path, $ns).InnerText }
if ((Read-Value 't:Principals/t:Principal/t:UserId') -ne $sid -or
(Read-Value 't:Principals/t:Principal/t:LogonType') -ne 'Password' -or
(Read-Value 't:Principals/t:Principal/t:RunLevel') -ne 'LeastPrivilege') { throw 'Boot account or logon configuration differs.' }
if ($xml.SelectNodes('/t:Task/t:Triggers/t:BootTrigger', $ns).Count -ne 1 -or
$xml.SelectNodes('/t:Task/t:Triggers/t:LogonTrigger', $ns).Count -ne 0 -or
(Read-Value 't:Triggers/t:TimeTrigger/t:Repetition/t:Interval') -ne "PT${minutes}M") { throw 'Boot or recovery trigger differs.' }
if ((Read-Value 't:Settings/t:Priority') -ne '4' -or
(Read-Value 't:Settings/t:Enabled') -ne 'false' -or
(Read-Value 't:Settings/t:MultipleInstancesPolicy') -ne 'IgnoreNew' -or
(Read-Value 't:Settings/t:ExecutionTimeLimit') -ne 'PT0S' -or
(Read-Value 't:Settings/t:DisallowStartIfOnBatteries') -ne 'false' -or
(Read-Value 't:Settings/t:StopIfGoingOnBatteries') -ne 'false') { throw 'Boot task lifetime settings differ.' }
if ((Read-Value 't:Actions/t:Exec/t:Command') -ne (Join-Path $runner 'dsh-task/launcher.exe') -or
(Read-Value 't:Actions/t:Exec/t:Arguments') -ne ('"' + $pwsh + '"') -or
(Read-Value 't:Actions/t:Exec/t:WorkingDirectory') -ne $runner) { throw 'Boot task bypasses the existing launcher.' }
# Round-trip through the scheduler's parser, without storing or enabling a task.
$parsed = $scheduler.NewTask(0)
$parsed.XmlText = $definition.XmlText
$parsedSid = ([Security.Principal.NTAccount]::new($parsed.Principal.UserId)).Translate([Security.Principal.SecurityIdentifier]).Value
if ($parsedSid -ne $sid -or $parsed.Settings.Enabled) { throw 'Definition did not round-trip.' }
}
$interactive = New-WindowsRunnerTaskDefinition $scheduler $sid $runner $pwsh 1
[xml]$interactiveXml = $interactive.XmlText
$interactiveNs = [Xml.XmlNamespaceManager]::new($interactiveXml.NameTable)
$interactiveNs.AddNamespace('t', 'http://schemas.microsoft.com/windows/2004/02/mit/task')
if ($interactive.Principal.LogonType -ne 3 -or $interactive.Principal.RunLevel -ne 0 -or $interactive.Settings.Priority -ne 4 -or $interactive.Settings.Enabled -or $interactiveXml.SelectNodes('/t:Task/t:Triggers/t:LogonTrigger/t:UserId', $interactiveNs).Count -ne 1 -or $interactiveXml.SelectSingleNode('/t:Task/t:Triggers/t:LogonTrigger/t:UserId', $interactiveNs).InnerText -ne $sid -or $interactiveXml.SelectNodes('/t:Task/t:Triggers/t:BootTrigger', $interactiveNs).Count -ne 0) { throw 'Interactive task defaults changed.' }
if (Get-WindowsRunnerTask $scheduler ('DSH-absent-' + [guid]::NewGuid().ToString('N'))) { throw 'Missing task lookup returned a task.' }
$deniedFolder = [pscustomobject]@{}
$deniedFolder | Add-Member ScriptMethod GetTask { param($Name); throw [Runtime.InteropServices.COMException]::new('Injected scheduler access denied', -2147024891) }
$deniedScheduler = [pscustomobject]@{ Folder=$deniedFolder }
$deniedScheduler | Add-Member ScriptMethod GetFolder { param($Path); return $this.Folder }
$denied = $false
try { $null = Get-WindowsRunnerTask $deniedScheduler 'fixture' } catch { $denied = $true }
if (-not $denied) { throw 'Denied task lookup was treated as a missing task.' }
$manager = Join-Path $PSScriptRoot '../scripts/windows-runner-task.ps1'
function Reject-Options([string[]]$Options, [string]$Message) {
$output = & $pwsh -NoProfile -NonInteractive -File $manager -RunnerRoot $runner @Options 2>&1 | Out-String
if ($LASTEXITCODE -eq 0 -or -not $output.Contains($Message)) { throw "Expected rejection: $Message`n$output" }
if (Test-Path -LiteralPath (Join-Path $runner 'dsh-task')) { throw 'Rejected options wrote a startup snapshot.' }
}
Reject-Options @('-Action','register-boot') 'requires -RunAs'
Reject-Options @('-Action','install','-StartupMode','Boot','-RunAs','NT AUTHORITY\SYSTEM') 'RunAs applies only to register-boot'
Reject-Options @('-Action','install','-RunAs','unused') 'RunAs applies only to register-boot'
Reject-Options @('-Action','start','-StartupMode','Boot') 'apply only to install'
$processProbe = Join-Path $root 'process-probe.ps1'
@'
param([string]$Manager, [string]$Runner, [switch]$Unreadable, [switch]$ThrowPath)
$ErrorActionPreference = 'Stop'
function Get-Process {
param($Name,$ErrorAction)
if ($ThrowPath) {
$process = [pscustomobject]@{ ProcessName = 'Runner.Worker' }
$process | Add-Member ScriptProperty Path { throw [ComponentModel.Win32Exception]::new(5) }
return $process
}
[pscustomobject]@{ ProcessName = 'Runner.Worker'; Path = if ($Unreadable) { $null } else { Join-Path $Runner 'bin/Runner.Worker.exe' } }
}
& $Manager -Action install -RunnerRoot $Runner
'@ | Set-Content -LiteralPath $processProbe
foreach ($mode in @('readable','missing','throwing')) {
$probeOptions = switch ($mode) { 'missing' { @('-Unreadable') }; 'throwing' { @('-ThrowPath') }; default { @() } }
$output = & $pwsh -NoProfile -NonInteractive -File $processProbe -Manager $manager -Runner $runner @probeOptions 2>&1 | Out-String
if ($LASTEXITCODE -eq 0 -or -not $output.Contains('A runner process is active or its location is unreadable')) { throw "Live-process installation guard failed: $output" }
if (Test-Path -LiteralPath (Join-Path $runner 'dsh-task')) { throw 'Live-process rejection wrote a startup snapshot.' }
}
Set-Content -LiteralPath (Join-Path $runner '.service') -Value 'fixture'
Reject-Options @('-Action','install','-ConfigRoot',$root) 'native runner service is configured'
Remove-Item -LiteralPath (Join-Path $runner '.service')
# Exercise preparation with isolated toolchain/network and process-inventory fixtures.
$fixture = Join-Path $root 'scripts'
$null = New-Item -ItemType Directory -Path $fixture
foreach ($name in @('windows-runner-task.ps1','windows-runner-scheduler.ps1','run-windows-runner-task.ps1','windows-runner-launcher.cs','windows-runner-network.ps1','run-windows-runner-network-process.ps1')) {
Copy-Item -LiteralPath (Join-Path $PSScriptRoot "../scripts/$name") -Destination $fixture
}
Set-Content -LiteralPath (Join-Path $fixture 'start-windows-packaging-runner.ps1') -Value 'param($RunnerRoot,$ConfigRoot,[switch]$CheckOnly); if (-not $CheckOnly) { throw "Unexpected runner launch" }; exit 0'
$prepareProbe = Join-Path $root 'prepare-probe.ps1'
@'
param($Manager,$Runner,$ConfigRoot)
$ErrorActionPreference = 'Stop'
function Get-Process { param($Name,$ErrorAction); return @() }
& $Manager -Action install -StartupMode Boot -RunnerRoot $Runner -ConfigRoot $ConfigRoot -RestartMinutes 7 -RestartCount 3
'@ | Set-Content -LiteralPath $prepareProbe
& $pwsh -NoProfile -NonInteractive -File $prepareProbe -Manager (Join-Path $fixture 'windows-runner-task.ps1') -Runner $runner -ConfigRoot $root
if ($LASTEXITCODE -ne 0) { throw 'Boot preparation failed.' }
$configFile = Join-Path $runner 'dsh-task/config.json'
$config = Get-Content -LiteralPath $configFile -Raw | ConvertFrom-Json
if ($config.StartupMode -ne 'Boot' -or $config.AccountSid -ne $sid -or $config.RestartMinutes -ne 7 -or $config.RestartCount -ne 3) { throw 'Preparation lost account or recovery settings.' }
if (Get-WindowsRunnerTask $scheduler $config.TaskName) { throw 'Preparation registered a task.' }
Assert-WindowsRunnerBootConfiguration $config $sid $runner $config.TaskName
$expectedTaskName = $config.TaskName
foreach ($field in @('StartupMode','AccountSid','RunnerRoot','TaskName','PowerShell','RestartMinutes')) {
$saved = $config.$field
try {
foreach ($invalid in @($null, 'invalid')) {
$config.$field = $invalid
$failure = $null
try { Assert-WindowsRunnerBootConfiguration $config $sid $runner $expectedTaskName } catch { $failure = $_ }
if (-not $failure) { throw "Invalid $field was accepted." }
}
} finally { $config.$field = $saved }
}
foreach ($invalid in @(0, 1441, 1.5, '7')) {
$config.RestartMinutes = $invalid
$failure = $null
try { Assert-WindowsRunnerBootConfiguration $config $sid $runner $config.TaskName } catch { $failure = $_ }
if (-not $failure) { throw 'Invalid restart interval was accepted.' }
}
$config.RestartMinutes = 7
$registrationProbe = Join-Path $root 'register-probe.ps1'
@'
param($Manager,$Runner,$RunAs,$Result)
$ErrorActionPreference = 'Stop'
function Get-Process { param($Name,$ErrorAction); return @() }
$nativeScheduler = New-Object -ComObject 'Schedule.Service'
$nativeScheduler.Connect()
$folder = [pscustomobject]@{}
$folder | Add-Member ScriptMethod GetTask { param($Name); return $null }
$folder | Add-Member ScriptMethod RegisterTaskDefinition {
param($Name,$Definition,$Flags,$User,$Password,$Logon,$Sddl)
if ($Password -ne 'fake-only-never-authenticated' -or $Flags -ne 2 -or $Logon -ne 1) { throw 'Invalid registration transport.' }
@{ Name=$Name; User=$User; Sddl=$Sddl; Xml=$Definition.XmlText } | ConvertTo-Json | Set-Content -LiteralPath $Result
}
$fake = [pscustomobject]@{ Native=$nativeScheduler; Folder=$folder }
$fake | Add-Member ScriptMethod Connect {}
$fake | Add-Member ScriptMethod NewTask { param($Flags); return $this.Native.NewTask($Flags) }
$fake | Add-Member ScriptMethod GetFolder { param($Path); return $this.Folder }
function New-Object { param($ComObject); if ($ComObject -ne 'Schedule.Service') { throw 'Unexpected COM object.' }; return $fake }
function Get-Credential { param($UserName,$Message); return [Management.Automation.PSCredential]::new($UserName,(ConvertTo-SecureString 'fake-only-never-authenticated' -AsPlainText -Force)) }
& $Manager -Action register-boot -RunnerRoot $Runner -RunAs $RunAs
'@ | Set-Content -LiteralPath $registrationProbe
$registrationResult = Join-Path $root 'registration.json'
$account = [Security.Principal.WindowsIdentity]::GetCurrent().Name
$elevated = ([Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
$registrationOutput = & $pwsh -NoProfile -NonInteractive -File $registrationProbe -Manager (Join-Path $fixture 'windows-runner-task.ps1') -Runner $runner -RunAs $account -Result $registrationResult 2>&1 | Out-String
if ($elevated -and -not $sid.EndsWith('-500')) {
if ($LASTEXITCODE -ne 0) { throw "Boot registration entry failed: $registrationOutput" }
$submitted = Get-Content -LiteralPath $registrationResult -Raw | ConvertFrom-Json
if ($submitted.User -ne $account -or $submitted.Name -ne $config.TaskName -or $submitted.Sddl -notlike "*(A;;GA;;;$sid)*") { throw 'Registration lost prepared account or management access.' }
} else {
Write-Output 'SKIP: elevated registration entry with substitute transport; unsupported installer context. Real cross-account registration is not tested.'
if ($LASTEXITCODE -eq 0 -or (Test-Path -LiteralPath $registrationResult)) { throw 'Boot registration accepted an unsupported installer context.' }
}
if (Get-WindowsRunnerTask $scheduler $config.TaskName) { throw 'Isolated registration created a real task.' }
# Exercise management against a registered-task substitute, without CIM or real scheduler mutation.
$managementProbe = Join-Path $root 'manage-probe.ps1'
@'
param($Manager,$Runner,$Operation,$Result)
$ErrorActionPreference = 'Stop'
. (Join-Path (Split-Path $Manager) 'windows-runner-scheduler.ps1')
$native = New-Object -ComObject 'Schedule.Service'
$native.Connect()
$sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
$definition = New-WindowsRunnerTaskDefinition $native $sid $Runner (Join-Path $PSHOME 'pwsh.exe') 1 'Boot'
$script:enabled = $Operation -ne 'uninstall'
$task = [pscustomobject]@{ Definition=$definition; State=$(if ($script:enabled) { 3 } else { 1 }); LastRunTime=[DateTime]::MinValue; LastTaskResult=0 }
$task | Add-Member ScriptProperty Enabled { return $script:enabled } {
param($Value)
$script:enabled = $Value
Add-Content -LiteralPath $Result -Value "enabled=$Value"
if (-not $Value -and $this.State -ne 4) { $this.State = 1 }
}
$task | Add-Member ScriptMethod Run { param($Parameters); Add-Content -LiteralPath $Result -Value 'run'; $this.State=4 }
$task | Add-Member ScriptMethod Stop { param($Flags); Add-Content -LiteralPath $Result -Value 'stop'; $this.State=1 }
$folder = [pscustomobject]@{ Task=$task }
$folder | Add-Member ScriptMethod GetTask { param($Name); return $this.Task }
$folder | Add-Member ScriptMethod DeleteTask { param($Name,$Flags); Add-Content -LiteralPath $Result -Value 'delete' }
$fake = [pscustomobject]@{ Folder=$folder }
$fake | Add-Member ScriptMethod Connect {}
$fake | Add-Member ScriptMethod GetFolder { param($Path); return $this.Folder }
function New-Object { param($ComObject); if ($ComObject -ne 'Schedule.Service') { throw 'Unexpected COM object.' }; return $fake }
function Get-Process { param($Name,$ErrorAction); return @() }
$status = & $Manager -Action $Operation -RunnerRoot $Runner
if ($Operation -eq 'status') { $status | ConvertTo-Json | Set-Content -LiteralPath $Result }
'@ | Set-Content -LiteralPath $managementProbe
foreach ($operation in @('status','start','stop','uninstall')) {
$resultFile = Join-Path $root "manage-$operation.txt"
& $pwsh -NoProfile -NonInteractive -File $managementProbe -Manager (Join-Path $fixture 'windows-runner-task.ps1') -Runner $runner -Operation $operation -Result $resultFile
if ($LASTEXITCODE -ne 0) { throw "Management failed: $operation" }
$result = Get-Content -LiteralPath $resultFile -Raw
if ($operation -eq 'status') {
$status = $result | ConvertFrom-Json
if (-not $status.BootTrigger -or $status.LogonType -ne 'Password' -or $status.State -ne 'Ready' -or $status.RemainingLaunches -ne 4) { throw 'Status lost startup mode or recovery budget.' }
} else {
$expected = switch ($operation) { 'start' { "enabled=True`nrun" }; 'stop' { "enabled=False`nstop" }; 'uninstall' { 'delete' } }
if ($result.Replace("`r`n","`n").Trim() -ne $expected) { throw "Unexpected management effects: $operation" }
}
}
Remove-Item -LiteralPath (Join-Path $runner 'dsh-task/launcher.exe')
$failure = $null
try { Assert-WindowsRunnerBootConfiguration $config $sid $runner $config.TaskName } catch { $failure = $_ }
if (-not $failure) { throw 'Missing launcher was accepted.' }
# Only the credential dialog and registration transport are replaced; no account authentication occurs.
$script:credentialResult = $null
$script:credentialThrows = $false
$script:registrationCalls = 0
$script:registrationFails = $false
$script:registrationMismatch = $false
function Get-Credential { param($UserName, $Message); if ($script:credentialThrows) { throw 'Prompt unavailable' }; return $script:credentialResult }
$fakeFolder = [pscustomobject]@{}
$fakeFolder | Add-Member ScriptMethod RegisterTaskDefinition {
param($Name, $Definition, $Flags, $User, $Password, $Logon, $Sddl)
$script:registrationCalls++
if ($Name -ne 'fixture' -or $Flags -ne 2 -or $User -ne 'fixture-user' -or $Logon -ne 1 -or $Sddl -ne "D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;$sid)" -or $Password -ne 'fake-only-never-authenticated') {
$script:registrationMismatch = $true; throw 'Unexpected registration request.'
}
if ($script:registrationFails) { throw [Runtime.InteropServices.COMException]::new('fake-only-never-authenticated', -2147023570) }
}
$fakeScheduler = [pscustomobject]@{ Folder = $fakeFolder }
$fakeScheduler | Add-Member ScriptMethod GetFolder { param($Path); if ($Path -ne '\') { throw 'Unexpected task folder.' }; return $this.Folder }
function Reject-Registration([string]$Message) {
$failure = $null
try { Register-WindowsRunnerBootTask $fakeScheduler 'fixture' $definition $sid 'fixture-user' } catch { $failure = $_ }
if (-not $failure -or -not $failure.Exception.Message.Contains($Message) -or $failure.ToString().Contains('fake-only-never-authenticated')) {
throw 'Registration failure was not contained or exposed the fake credential.'
}
}
try {
$script:credentialThrows = $true
Reject-Registration 'Prompt unavailable'
$script:credentialThrows = $false
Reject-Registration 'Credential entry cancelled'
$script:credentialResult = [Management.Automation.PSCredential]::new('other-user', (ConvertTo-SecureString 'fake-only-never-authenticated' -AsPlainText -Force))
Reject-Registration 'Credential entry cancelled'
$script:credentialResult = [Management.Automation.PSCredential]::new('fixture-user', [Security.SecureString]::new())
Reject-Registration 'Credential entry cancelled'
if ($script:registrationCalls -ne 0) { throw 'Invalid credential input reached registration.' }
$script:credentialResult = [Management.Automation.PSCredential]::new('fixture-user', (ConvertTo-SecureString 'fake-only-never-authenticated' -AsPlainText -Force))
Register-WindowsRunnerBootTask $fakeScheduler 'fixture' $definition $sid 'fixture-user'
if ($script:registrationCalls -ne 1) { throw 'Registration was not submitted once.' }
$script:registrationFails = $true
Reject-Registration '0x8007052E'
if ($script:registrationMismatch) { throw 'Unexpected registration request.' }
if ($script:registrationCalls -ne 2) { throw 'Failed registration retried authentication.' }
} finally {
Remove-Item Function:Get-Credential
$script:credentialResult = $null
}
} finally {
Remove-Item -LiteralPath $root -Recurse -Force
}
Write-Output "PASS: boot/password/least-privilege definition, recovery settings, duplicate policy, launcher reuse, XML round-trip, invalid options, credential substitutes and single-attempt registration failure containment. No task registered."
exit 0
+26 -3
View File
@@ -9,7 +9,7 @@ $pwshLink = Join-Path $root 'tools/pwsh-7.6.6'
if ($CheckStartup) { $null = New-Item -ItemType Junction -Path $pwshLink -Target $PSHOME }
$server = $null
$saved = @{}
foreach ($name in @('HTTP_PROXY','HTTPS_PROXY','NO_PROXY','NODE_USE_ENV_PROXY')) { $saved[$name] = [Environment]::GetEnvironmentVariable($name,'Process') }
foreach ($name in @('HTTP_PROXY','HTTPS_PROXY','NO_PROXY','NODE_USE_ENV_PROXY','NODE_OPTIONS')) { $saved[$name] = [Environment]::GetEnvironmentVariable($name,'Process') }
try {
if ($null -ne (Read-RunnerNetwork $root)) { throw 'Absent configuration changed behavior.' }
$fixture = Join-Path $root 'proxy.cjs'
@@ -41,6 +41,16 @@ server.listen(0, '127.0.0.1', () => fs.writeFileSync(path.join(root, 'port'), St
if ($server.HasExited -or [DateTime]::UtcNow -gt $deadline) { throw 'Proxy fixture did not become ready.' }
Start-Sleep -Milliseconds 50
}
# Observe natural event-loop drain in the real redirected probe, without replacing fetch.
$lifecycle = Join-Path $root 'probe-lifecycle.cjs'
@'
const fs = require('node:fs');
const path = require('node:path');
if (process.env.DSH_NETWORK_PROBE_URL) {
process.once('beforeExit', () => fs.appendFileSync(path.join(__dirname, 'drained'), 'drained\n'));
}
'@ | Set-Content -LiteralPath $lifecycle
$env:NODE_OPTIONS = '--require "' + $lifecycle.Replace('\', '/') + '"'
$port = Get-Content (Join-Path $root 'port') -Raw
$config = @{proxyUrl="http://127.0.0.1:$port";noProxy='';serviceName='';probeUrl='http://runner-probe.invalid/ready';attempts=2;timeoutSeconds=2;retrySeconds=1}
function Write-Config { $config | ConvertTo-Json | Set-Content (Join-Path $root 'runner-network.json') }
@@ -48,6 +58,7 @@ server.listen(0, '127.0.0.1', () => fs.writeFileSync(path.join(root, 'port'), St
$parsed = Read-RunnerNetwork $root
Set-RunnerNetwork $parsed
Wait-RunnerNetwork $parsed
if (-not (Test-Path (Join-Path $root 'drained')) -or (Get-Content (Join-Path $root 'drained')).Count -ne 1) { throw 'Successful probe bypassed normal Node event-loop drain.' }
if ($env:NODE_USE_ENV_PROXY -ne '1' -or $env:HTTP_PROXY -ne $config.proxyUrl -or $env:HTTPS_PROXY -ne $config.proxyUrl) { throw 'Proxy environment was not applied.' }
# Full startup requires the operator's installed packaging toolchain and persistent PATH.
if ($CheckStartup) {
@@ -90,7 +101,19 @@ server.listen(0, '127.0.0.1', () => fs.writeFileSync(path.join(root, 'port'), St
$config.timeoutSeconds = 1
$failure = $null
try { Wait-RunnerNetwork $config } catch { $failure = $_ }
if (-not $failure -or (Get-Content (Join-Path $root 'requests')).Count -ne 6) { throw 'Unresponsive endpoint did not terminate its probe.' }
if (-not $failure -or -not $failure.Exception.Message.StartsWith('Runner network dependency unavailable;') -or (Get-Content (Join-Path $root 'requests')).Count -ne 6) { throw 'Unresponsive endpoint did not terminate its probe.' }
# Retain a bound non-listening socket so no concurrent fixture can claim the refused port.
$refused = [Net.Sockets.Socket]::new([Net.Sockets.AddressFamily]::InterNetwork, [Net.Sockets.SocketType]::Stream, [Net.Sockets.ProtocolType]::Tcp)
try {
$refused.Bind([Net.IPEndPoint]::new([Net.IPAddress]::Loopback, 0))
$config.proxyUrl = "http://127.0.0.1:$($refused.LocalEndPoint.Port)"
$config.noProxy = ''
$config.probeUrl = 'http://runner-probe.invalid/ready'
Set-RunnerNetwork $config
$failure = $null
try { Wait-RunnerNetwork $config } catch { $failure = $_ }
if (-not $failure -or -not $failure.Exception.Message.StartsWith('Runner network dependency unavailable;') -or (Get-Content (Join-Path $root 'requests')).Count -ne 6) { throw 'Refused proxy connection admitted startup or reached the HTTP fixture.' }
} finally { $refused.Dispose() }
foreach ($invalid in @('extra','credential','budget','type','wildcard','malformed')) {
$bad = $config.Clone()
switch ($invalid) {
@@ -106,7 +129,7 @@ server.listen(0, '127.0.0.1', () => fs.writeFileSync(path.join(root, 'port'), St
try { $null = Read-RunnerNetwork $root } catch { $failure = $_ }
if (-not $failure -or $failure.ToString().Contains('fake-secret')) { throw 'Invalid configuration accepted or disclosed.' }
}
Write-Output "PASS: absent config, proxy routing, Node proxy opt-in, service readiness, bounded failure and redacted invalid config; startup integration=$CheckStartup."
Write-Output "PASS: absent config, redirected native Node HTTP success, non-2xx, refused proxy, request timeout, proxy routing, Node proxy opt-in, service readiness, bounded failure and redacted invalid config; startup integration=$CheckStartup."
} finally {
foreach ($name in $saved.Keys) { [Environment]::SetEnvironmentVariable($name,$saved[$name],'Process') }
if ($server) { if (-not $server.HasExited) { $server.Kill($true); $server.WaitForExit() }; $server.Dispose() }
@@ -0,0 +1,22 @@
# Verify native parent IDs with an owned process and await its exit; no scheduler or runner is used.
$ErrorActionPreference = 'Stop'
if (-not $IsWindows) { throw 'Requires PowerShell 7 on Windows.' }
Add-Type -Path (Join-Path $PSScriptRoot '../scripts/windows-runner-processes.cs')
$info = [Diagnostics.ProcessStartInfo]::new((Join-Path $PSHOME 'pwsh.exe'))
$info.UseShellExecute = $false
$info.CreateNoWindow = $true
foreach ($argument in @('-NoProfile','-NonInteractive','-Command','Start-Sleep -Seconds 120')) { $info.ArgumentList.Add($argument) }
$child = [Diagnostics.Process]::Start($info)
try {
$parents = [DshRunnerProcesses]::ReadParents()
if (-not $parents.ContainsKey($PID) -or -not $parents.ContainsKey($child.Id) -or $parents[$child.Id] -ne $PID) {
throw 'Native process snapshot did not identify the owned child and parent.'
}
} finally {
try {
if (-not $child.HasExited) { $child.Kill($true) }
if (-not $child.WaitForExit(30000)) { throw 'Owned process did not exit.' }
} finally { $child.Dispose() }
}
Write-Output 'PASS: native process ancestry and owned child teardown without CIM.'
exit 0
@@ -0,0 +1,49 @@
# Isolated supervisor failures; no scheduler registration, GitHub or signing hardware.
$ErrorActionPreference = 'Stop'
$root = Join-Path ([IO.Path]::GetTempPath()) ('runner-recovery-' + [guid]::NewGuid().ToString('N'))
$null = New-Item -ItemType Directory $root
$source = Get-Content (Join-Path $PSScriptRoot '../scripts/run-windows-runner-task.ps1') -Raw
try {
foreach ($case in @('log-failure','counter-failure','exhausted','child-failure','disable-failure')) {
$dir = Join-Path $root $case
$null = New-Item -ItemType Directory $dir
@{RestartCount=1;TaskName='fake';RunnerRoot=$dir;ConfigRoot=$dir} | ConvertTo-Json | Set-Content (Join-Path $dir 'config.json')
Set-Content (Join-Path $dir 'attempts.txt') $(if($case -in @('exhausted','disable-failure')){'2'}else{'0'})
Set-Content (Join-Path $dir 'start.ps1') 'Set-Content (Join-Path $PSScriptRoot "launched") yes; exit 7'
$mocks = @'
function New-Object {
param($ComObject)
if ($ComObject -ne 'Schedule.Service') { throw 'Unexpected COM object.' }
$task = [pscustomobject]@{}
$task | Add-Member ScriptProperty Enabled { return $true } { param($Value); [IO.File]::WriteAllText((Join-Path $PSScriptRoot 'disabled'),'yes') }
$folder = [pscustomobject]@{ Task = $task }
$folder | Add-Member ScriptMethod GetTask { param($Name); return $this.Task }
$scheduler = [pscustomobject]@{ Folder = $folder }
$scheduler | Add-Member ScriptMethod Connect {}
$scheduler | Add-Member ScriptMethod GetFolder { param($Path); return $this.Folder }
return $scheduler
}
'@
if ($case -eq 'log-failure') { $mocks += "`nfunction Add-Content { throw 'Injected log storage unavailable' }" }
if ($case -eq 'counter-failure') { $mocks += "`nfunction Set-Content { throw 'Injected counter storage unavailable' }" }
if ($case -eq 'disable-failure') { $mocks = "function New-Object { throw 'Injected access denied' }" }
Set-Content (Join-Path $dir 'run.ps1') ($mocks + "`n" + $source)
$output = & (Join-Path $PSHOME 'pwsh.exe') -NoProfile -File (Join-Path $dir 'run.ps1') 2>&1 | Out-String
if ($LASTEXITCODE -ne 1) { throw "$case must fail visibly" }
$disabled = Test-Path (Join-Path $dir 'disabled')
if ($disabled -ne ($case -in @('counter-failure','exhausted'))) { throw "$case unexpected task disposition" }
if ($case -in @('log-failure','child-failure') -and [int](Get-Content (Join-Path $dir 'attempts.txt')) -ne 1) { throw 'Attempt must be persisted before launch' }
if ($case -in @('log-failure','child-failure') -and -not (Test-Path (Join-Path $dir 'launched'))) { throw 'Allowed attempt did not execute the child.' }
if ($case -eq 'child-failure' -and -not ((Get-Content (Join-Path $dir 'run-*.log') -Raw) -match 'exited with code 7')) { throw 'Child failure code was not retained.' }
if ($case -eq 'log-failure' -and $output -notmatch 'Runner log unavailable') { throw 'Missing stderr fallback' }
if ($case -in @('exhausted','disable-failure','counter-failure') -and (Test-Path (Join-Path $dir 'launched'))) { throw 'A blocked attempt launched a runner' }
if ($case -eq 'disable-failure') {
if ($output -notmatch 'Restart budget exhausted' -or $output -notmatch 'Task disable failed') { throw 'Missing original failure or scheduler disposition' }
if ([int](Get-Content (Join-Path $dir 'attempts.txt')) -ne 2) { throw 'Exhausted budget changed' }
}
Write-Output "PASS: $case"
}
} finally {
if ([IO.Path]::GetFullPath($root).StartsWith([IO.Path]::GetTempPath(),[StringComparison]::OrdinalIgnoreCase)) { Remove-Item -LiteralPath $root -Recurse -Force }
}
exit 0
+1 -1
View File
@@ -7,7 +7,7 @@ $source = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../scripts'))
$runner = Join-Path $root 'runner with spaces'
$null = New-Item -ItemType Directory -Path $runner
Set-Content -LiteralPath (Join-Path $runner '.runner') -Value '{}'
foreach ($file in @('windows-runner-task.ps1','run-windows-runner-task.ps1','windows-runner-launcher.cs','windows-runner-network.ps1','run-windows-runner-network-process.ps1')) { Copy-Item -LiteralPath (Join-Path $source $file) -Destination $root }
foreach ($file in @('windows-runner-task.ps1','windows-runner-scheduler.ps1','run-windows-runner-task.ps1','windows-runner-launcher.cs','windows-runner-processes.cs','windows-runner-network.ps1','run-windows-runner-network-process.ps1')) { Copy-Item -LiteralPath (Join-Path $source $file) -Destination $root }
$manager = Join-Path $root 'windows-runner-task.ps1'
@'
param([string]$RunnerRoot, [string]$ConfigRoot, [switch]$CheckOnly)
+1 -1
View File
@@ -74,7 +74,7 @@ describe('Windows token signing', () => {
} else {
expect(options.env.DSH_DESKTOP_WINDOWS_TOKEN_PIN).toBeUndefined()
expect(options.env.DSH_DESKTOP_WINDOWS_KEY_CONTAINER).toBeUndefined()
if (command === 'powershell.exe') {
if (command === 'pwsh') {
const timestamped = readFileSync(options.env.DSH_RUNTIME_VERIFY_FILE!, 'utf8').endsWith(':timestamp')
if (!timestamped) expect(existsSync(join(stateDirectory, 'attempt.json'))).toBe(true)
callback(null, JSON.stringify({ status: mode === 'invalid-primary' ? 'NotTrusted' : 'Valid', timestamped, thumbprint: 'A'.repeat(40) }), '')
@@ -1,7 +1,7 @@
/** Parser fault checks; real-file equivalence is measured separately. */
import { it as test } from 'vitest'
import assert from 'node:assert/strict'
import { copyFile, mkdtemp, rm } from 'node:fs/promises'
import { copyFile, mkdir, mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { parseSignatureRows, inspectSignaturesBatched } from '../scripts/windows-signature-batch.mjs'
@@ -33,12 +33,18 @@ test('empty input launches no verifier and returns no rows', async () => {
assert.deepEqual(await inspectSignaturesBatched([]), [])
})
test.skipIf(process.platform !== 'win32')('Unicode paths retain the same Windows trust result as individual inspection', async (t) => {
test.skipIf(process.platform !== 'win32')('long Unicode paths retain the same Windows trust result as short paths', async (t) => {
const root = await mkdtemp(join(tmpdir(), 'signature-batch-'))
t.onTestFinished(() => rm(root, { recursive: true, force: true }))
const path = join(root, "验证 ' 文件.exe")
await copyFile(join(process.env.SystemRoot!, 'System32', 'cmd.exe'), path)
const expected = await inspectWindowsRuntimeSignature(path)
const shortPath = join(root, 'short.exe')
const directory = join(root, 'nested-'.repeat(15), 'nested-'.repeat(15))
await mkdir(directory, { recursive: true })
const path = join(directory, "验证 ' 文件.exe")
assert.ok(path.length > 260)
await copyFile(join(process.env.SystemRoot!, 'System32', 'cmd.exe'), shortPath)
await copyFile(shortPath, path)
const expected = await inspectWindowsRuntimeSignature(shortPath)
assert.deepEqual(await inspectWindowsRuntimeSignature(path), expected)
assert.equal(expected.status, 'Valid')
assert.deepEqual(await inspectSignaturesBatched([path]), [expected])
await signWindowsCode(root, {
@@ -21,14 +21,17 @@
en: bb889e9514678d1c
zh: 48cbec1e907d6a2b
/windows-signing-and-runner-operations/machine-setup-and-runner-startup/supervised-startup:
en: cada81c15a20ecc2
zh: 80b7a4af7b1e0e5d
en: f4fcb23be1f3df4a
zh: f3699f0a64a9b94b
/windows-signing-and-runner-operations/machine-setup-and-runner-startup/unattended-windows-startup:
en: 3b6ae5eb5177dba8
zh: 0e7a3edeca2286c6
/windows-signing-and-runner-operations/machine-setup-and-runner-startup/optional-network-dependency:
en: 60f34f8637b3c252
zh: 805435964ab20263
en: 31ffd631dd215fc6
zh: ebfe8a3a64ed6e02
/windows-signing-and-runner-operations/signing-configuration:
en: 4b5548818375eb9a
zh: 8c975adbb1dca9c8
en: b38f6fbfcfd73f7a
zh: f3afb7053af7480b
/windows-signing-and-runner-operations/signing-and-timestamp-completion:
en: a8d23c931cafc236
zh: 28fd4860549cdc7b
+23 -4
View File
@@ -38,28 +38,47 @@ Run `pwsh -NoProfile -File apps/desktop/scripts/setup-windows-packaging.ps1 -Roo
For the complete registration, label, routing and approval sequence, start with [CI publication setup](../publishing/ci/README.md#setup-sequence). The task installer requires the Windows .NET Framework 4.5+ compiler at `%SystemRoot%/Microsoft.NET/Framework64/v4.0.30319/csc.exe`. It compiles a GUI executable into `runner/dsh-task/launcher.exe`; this executable starts PowerShell with no console and waits for it to exit. The output and errors of `run.ps1` itself go to uniquely named `launcher-*.out.log` and `launcher-*.err.log`; filenames include UTC time, PID and a random identifier. Launcher failures disable periodic starts, including failures before the retry budget can be read. Task result `2` indicates launcher failure; `3` means its error log could not be written; `4` means disabling the task also failed and an operator must disable it in Task Scheduler. After the direct child exits, output draining is limited to five seconds. A timeout returns `5` with a `launcher-*.drain.log` diagnostic: output may be incomplete, but periodic recovery continues within the existing restart budget. Descendant processes may outlive the exited runner; draining logs does not terminate them. The recorded stop target is the launcher process, so stop includes the launcher and its descendants. Normal runner output remains in `run-*.log`.
Run `pwsh -NoProfile -File apps/desktop/scripts/windows-runner-task.ps1 -Action install -RunnerRoot <registered-runner-directory> -ConfigRoot <machine-root>/packaging` as the runner's Windows user, using its installed PowerShell 7. The installer checks the environment and copies startup scripts into `runner/dsh-task`; registration, tools and secrets remain separate. It registers a disabled, limited-permission interactive Task Scheduler task without storing an account password. Task priority 4 gives the runner and its children normal CPU, I/O and memory priority; the scheduler default 7 lowers all three and slows dependency installation. Existing tasks retain their settings: while the runner is idle, stop, uninstall and reinstall the task before starting it again. For `-Action start` or `-Action status`, pass only `-RunnerRoot`; configuration and retry options apply only to installation. The task starts after this user's desktop login, including after reboot, and stops on logout. It does not provide unattended boot or unlock a signing Token.
Run `pwsh -NoProfile -File apps/desktop/scripts/windows-runner-task.ps1 -Action install -RunnerRoot <registered-runner-directory> -ConfigRoot <machine-root>/packaging` as the runner's Windows user, using its installed PowerShell 7. The installer checks the environment and copies startup scripts into `runner/dsh-task`; registration, tools and secrets remain separate. It registers a disabled, limited-permission interactive Task Scheduler task without storing an account password. Task priority 4 gives the runner and its children normal CPU, I/O and memory priority; the scheduler default 7 lowers all three and slows dependency installation. Existing tasks retain their settings: while the runner is idle, stop, uninstall and reinstall the task before starting it again. For `-Action start` or `-Action status`, pass only `-RunnerRoot`; configuration and retry options apply only to installation. The task starts after this user's desktop login, including after reboot, and stops on logout. This default `Interactive` mode requires desktop login; neither startup mode unlocks a signing Token.
The task permits one instance and has no execution time limit. A repeating trigger checks every `-RestartMinutes` minutes (default `1`) and restarts an exited launcher, including an unexpected zero exit. The persisted budget permits the initial launch plus `-RestartCount` restarts (default `10`) between explicit starts. Every desktop login also consumes this budget; `status` shows the remaining launches. After the budget is exhausted, login alone cannot restart the runner. Starting an already running task does not reset the budget. Missing or invalid budget/configuration files disable automatic starts until repaired. GitHub's launcher owns runner updates; task recovery does not rerun a failed workflow or clear signing interlocks. After retries are exhausted, inspect `runner/dsh-task/run-*.log`, the runner's `_diag` logs and `status`, correct the cause, then run `start`. A running task alone does not prove connectivity: verify `Connected to GitHub` and `Listening for Jobs`, then verify assignment in Actions. Both `run-*.log` and `launcher-*.log` are retained for operator-managed cleanup.
The task permits one instance and has no execution time limit. A repeating trigger checks every `-RestartMinutes` minutes (default `1`) and restarts an exited launcher, including an unexpected zero exit. The persisted budget permits the initial launch plus `-RestartCount` restarts (default `10`) between explicit starts. Every trigger that launches the task also consumes this budget; `status` shows the remaining launches. After the budget is exhausted, login or reboot alone cannot restart the runner. Starting an already running task does not reset the budget. Missing or invalid budget/configuration files prevent runner launches and request task disabling. If scheduler access is denied, an administrator must disable the triggers. Failures after reserving an attempt retain bounded recovery; unavailable runner logs fall back to launcher stderr. GitHub's launcher owns runner updates; task recovery does not rerun a failed workflow or clear signing interlocks. After retries are exhausted, inspect `runner/dsh-task/run-*.log`, the runner's `_diag` logs and `status`, correct the cause, then run `start`. A running task alone does not prove connectivity: verify `Connected to GitHub` and `Listening for Jobs`, then verify assignment in Actions. Both `run-*.log` and `launcher-*.log` are retained for operator-managed cleanup.
Before maintenance, pause new workflow dispatch and wait for the runner to become idle. `-Action stop` refuses an active worker for this runner, disables future starts and stops its task process tree; the local check cannot prevent a concurrent GitHub assignment. `-Action uninstall` requires a stopped, disabled task and retains registration, configuration and logs. Pulling repository changes does not update the installed copy. To upgrade it, record the original -ConfigRoot, optional -NetworkRoot and retry settings, then run `stop`, `uninstall`, `install` with those settings, and `start` from the updated checkout. Confirm listening and job assignment again. When migrating a manually launched runner, stop its existing launcher only after it is idle, then start the task; never run both launchers together.
Before maintenance, pause new workflow dispatch and wait for the runner to become idle. `-Action stop` refuses an active worker for this runner, disables future starts and stops its task process tree; the local check cannot prevent a concurrent GitHub assignment. `-Action uninstall` requires a stopped, disabled task and retains registration, configuration and logs. Pulling repository changes does not update the installed copy. To upgrade it, record the startup mode, original -ConfigRoot, optional -NetworkRoot and retry settings, then run `stop`, `uninstall`, `install` with those settings, and `start` from the updated checkout; Boot mode also requires `register-boot` before `start`. Confirm listening and job assignment again. When migrating a manually launched runner, stop its existing launcher only after it is idle, then start the task; never run both launchers together.
Operators can run `pwsh -NoProfile -File apps/desktop/tests/windows-runner-task.ps1` on Windows to exercise installation, console-free initial launch and automatic recovery, duplicate-start prevention, stop, child-process teardown, containment of startup/logging failures and uninstall against an isolated fake runner. This opt-in test creates a temporary task and retains diagnostic files; it does not contact GitHub or access signing hardware. `pwsh -NoProfile -File apps/desktop/tests/windows-runner-launcher.ps1` checks the GUI executable, child console absence, exit status, diagnostic output and bounded draining with an inherited writer without Task Scheduler; Windows CI runs it. Real-machine acceptance additionally checks an idle runner coming online without a visible Terminal window, an Actions job being assigned, and login after an operator-approved reboot. Signed packaging and logout/reboot acceptance require separate operator verification.
### Unattended Windows startup
Use `Boot` mode when the runner must accept jobs before desktop login. Prepare files under the existing runner account, which may remain a standard user. Use a separate elevated administrator session only for registration. Run the administrator command from a verified, administrator-owned checkout whose scripts and parent directories are not writable by the runner account; never elevate scripts from its checkout; it reads prepared configuration but does not execute the runner-owned launcher or preflight. The task grants its runner account management access and always runs with limited privileges and priority 4. Management uses Task Scheduler COM and native process snapshots instead of requiring CIM namespace access.
1. Pause workflow dispatch, wait for idle and stop any existing launcher. For an installed task, run `stop` then `uninstall` as its owner; retain configuration, caches and signing interlocks. Installation rejects active or unreadable runner processes and a native runner `.service` registration.
2. As the runner account, run `pwsh -NoProfile -File apps/desktop/scripts/windows-runner-task.ps1 -Action install -StartupMode Boot -RunnerRoot <registered-runner-directory> -ConfigRoot <machine-root>/packaging`, retaining any `-NetworkRoot` and retry options. This checks tools/network, compiles the launcher and prepares the startup snapshot; it does not register a task.
3. In an elevated administrator PowerShell, run `pwsh -NoProfile -File <administrator-owned-checkout>/apps/desktop/scripts/windows-runner-task.ps1 -Action register-boot -RunnerRoot <registered-runner-directory> -RunAs <machine-or-domain\runner-account>`. The account must match preparation. Enter its Windows password in the local prompt, not a Hello PIN or signing PIN. Registration submits credentials once and creates a disabled Password/AtStartup task. On failure, inspect Task Scheduler before retrying because registration may have committed; no automatic authentication retry occurs.
4. As the runner account, run the same manager with `-Action start -RunnerRoot <registered-runner-directory>`, then `-Action status`. Check the account, `LogonType=Password`, `BootTrigger=True`, remaining launches and listener logs. To return to login-only startup, stop and uninstall the task, then install without `-StartupMode Boot` and start.
The administrator must ensure batch-logon permission, no overriding deny policy, and runner access to its tools, private configuration, caches and logs. After an account password change, pause dispatch, wait for idle, run `stop` and `uninstall` as the runner account, repeat administrator `register-boot`, then run `start`; retain the prepared files without repeating `install`. Network dependencies, disk access and signing hardware must be available before login; prevent sleep during service hours. There is no desktop auto-login configuration. Healthy reboots also consume the persisted launch budget; no healthy-runtime reset or exhaustion alert exists. Check `status` and `RemainingLaunches` during maintenance; while idle, `stop` then `start` resets the budget. Recovery cannot clear a signing interlock or retry failed hardware signing.
Windows CI checks task XML, preparation, invalid configuration, absent/mismatched credentials, prompt errors and single-attempt registration with isolated substitutes; it does not register a real Boot task. Interactive prompt cancellation may terminate through the PowerShell host; substituted credential tests do not qualify that host behavior. Deployment operators must validate registration with separate administrator/standard accounts, task management permissions and a reboot without desktop login, followed by actual job assignment and a signed package on each new machine. Existing machine results do not qualify a new startup snapshot.
### Optional network dependency
Choose the network owner before installing Boot startup. An external service is suitable only after its forwarding process and required destinations have been verified after reboot without desktop login. A service reporting `Running`, a saved restore setting or a successful probe after login does not establish this: desktop software may stop its forwarding process and clear recovery state during logout or shutdown. If networking depends on that software, use the dedicated child-process mode below or provision an independently managed pre-login service. `runner-network.json` configures checks and proxy variables; it does not launch the proxy. Omitting `-NetworkRoot` leaves network startup to the external owner.
Without `runner-network.json` in `ConfigRoot`, startup retains its scrubbed direct-network behavior. To configure a network dependency, create that operator-owned JSON file outside the checkout with exactly `proxyUrl`, `noProxy`, `serviceName`, `probeUrl`, `attempts`, `timeoutSeconds` and `retrySeconds`. The first four fields are strings; the three budgets are integers from 1 through 60. Use an empty `proxyUrl` for direct access and an empty `serviceName` when no Windows service owns the dependency. URLs must use HTTP(S) without credentials, queries or fragments; the proxy URL cannot include a path. Startup applies `HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY` and `NODE_USE_ENV_PROXY` after environment scrubbing, then requires a successful Node HEAD probe before admitting the runner. Service readiness checks never start or stop a Windows service.
For a dedicated child process, add `-NetworkRoot <absolute-private-network-directory>` to task installation. That directory must contain `launch.json` with exactly an absolute `executable` filename, an `arguments` string array and an integer `restartDelaySeconds` from 1 through 3600. This mode requires `runner-network.json`; set its `serviceName` to empty. Give the child its own data directory, listener bindings and executable identity, distinct from applications managed by desktop software; separate ports alone do not prevent another manager from terminating a process by executable name. The scripts do not alter desktop network settings. Keep actual provider names, paths, addresses, ports and arguments in machine configuration, never in repository files or shared logs. Restrict access to both configuration directories to the runner operator.
Installation starts the dependency for readiness checking and stops it before registering the task. While the runner lives, the supervisor restarts only an exited owned network process after the configured delay, including repeated launch failures; it does not restart the runner or retry jobs or signing. Exit, restart and launch-failure messages appear in `run-*.log`; provider output is discarded. Restart messages establish process creation, not network availability: confirm reconnection in runner logs. A live but unresponsive dependency requires operator diagnosis. The supervisor exclusively locks `NetworkRoot`, verifies PID, start time and executable before reclaiming a stale child, and stops its child when the runner exits. Unrecoverable supervision errors leave the active runner alive until it exits and report that recovery has stopped. Preserve `NetworkRoot` when reinstalling; pulling changes alone does not replace installed helpers.
Windows CI runs `pwsh -NoProfile -File apps/desktop/tests/windows-runner-network.ps1` and `pwsh -NoProfile -File apps/desktop/tests/windows-runner-network-process.ps1` with isolated local fixtures. On a configured packaging machine, add `-CheckStartup` to the first command to verify network configuration after the actual startup environment scrub. These tests use no signing hardware or external network endpoints.
Windows CI runs `pwsh -NoProfile -File apps/desktop/tests/windows-runner-network.ps1` and `pwsh -NoProfile -File apps/desktop/tests/windows-runner-network-process.ps1` with isolated local fixtures. On a configured packaging machine, add `-CheckStartup` to the first command to verify network configuration after the actual startup environment scrub. The readiness probe sets its exit status and lets Node drain normally; response cancellation, request timeout and the outer process deadline remain enforced. Tests cover HTTP success, non-2xx responses, refused proxy connections and request timeout through the real redirected child-process path, without signing hardware or external endpoints.
For a new machine, keep the runner disabled while preparing and testing network access. A disabled runner task does not launch its owned network child; test that child separately without starting the listener. After an operator-approved reboot, verify the selected proxy and required destinations before any desktop login or manual network-client launch. Record whether a desktop shell was present and which process supplied the proxy. If this fails, inspect the network owner's startup/shutdown logs before retrying. Only after network qualification should an operator enable the runner and validate Boot startup and job assignment; signing qualification remains separate.
<a id="signing-configuration"></a>
## Signing configuration
Windows packaging requires PowerShell 7 (`pwsh`) on `PATH`. The toolchain check verifies Authenticode support before building; runtime signature checks use this engine to handle paths longer than 260 characters.
The [machine preset configuration](../packaging/README.md#configuration-and-local-builds) selects public settings and the signing file. Without a preset, use the target dotenv file.
Fill in `.env.windows` with `DSH_DESKTOP_WINDOWS_CER_FILE` (public EV leaf certificate), `DSH_DESKTOP_WINDOWS_SIGNTOOL` (SafeNet-compatible SignTool), `DSH_DESKTOP_WINDOWS_KEY_CONTAINER` (matching private-key container), and `DSH_DESKTOP_WINDOWS_TOKEN_PIN` (Token Password). The private key stays on the USB token; keep the certificate and local credential file out of Git.
+23 -4
View File
@@ -38,28 +38,47 @@ description: "配置和维护 Windows 打包 runner、签名凭据、EV Token
完整的注册、标签、路由和审批配置顺序见 [CI 发布配置](../publishing/ci/README.zh.md#setup-sequence)。任务安装器需要 Windows .NET Framework 4.5+ 编译器,路径为 `%SystemRoot%/Microsoft.NET/Framework64/v4.0.30319/csc.exe`。它将 GUI 可执行文件编译到 `runner/dsh-task/launcher.exe`;该程序不分配控制台地启动 PowerShell,并等待其退出。`run.ps1` 自身的输出和错误分别写入名称唯一的 `launcher-*.out.log` 和 `launcher-*.err.log`,文件名包含 UTC 时间、PID 和随机标识。启动器失败时禁用周期启动,包括尚未读取重试预算时发生的失败。任务结果 `2` 表示启动器失败,`3` 表示无法写入错误日志,`4` 表示禁用任务也失败,需要操作者在计划任务中手动禁用。直接子进程退出后,最多等待五秒排空输出;超时返回 `5`,将诊断写入 `launcher-*.drain.log`:输出可能不完整,但周期恢复仍受原有重试预算约束。后代进程可能在 runner 退出后继续运行;日志排空不会终止它们。记录的停止目标是启动器进程,因此 stop 覆盖启动器及其后代。正常 runner 输出仍保存在 `run-*.log`。
以 runner 的 Windows 用户运行 `pwsh -NoProfile -File apps/desktop/scripts/windows-runner-task.ps1 -Action install -RunnerRoot <registered-runner-directory> -ConfigRoot <machine-root>/packaging`,使用该机器安装的 PowerShell 7。安装器检查环境,并将启动脚本复制到 `runner/dsh-task`;注册、工具和凭据仍单独管理。它注册一个初始禁用、权限受限的交互式计划任务,不保存账户密码。任务优先级 4 让 runner 及子进程使用普通 CPU、I/O 和内存优先级;计划任务默认值 7 会降低三者的优先级,使依赖安装变慢。已有任务保留原设置:在 runner 空闲时停止、卸载并重新安装任务,再启动。执行 `-Action start` 或 `-Action status` 时只传 `-RunnerRoot`;配置目录及重试选项仅适用于安装。任务在该用户登录桌面后启动,重启后也需要登录,注销时停止。它不提供无人值守开机,也不解锁签名 Token。
以 runner 的 Windows 用户运行 `pwsh -NoProfile -File apps/desktop/scripts/windows-runner-task.ps1 -Action install -RunnerRoot <registered-runner-directory> -ConfigRoot <machine-root>/packaging`,使用该机器安装的 PowerShell 7。安装器检查环境,并将启动脚本复制到 `runner/dsh-task`;注册、工具和凭据仍单独管理。它注册一个初始禁用、权限受限的交互式计划任务,不保存账户密码。任务优先级 4 让 runner 及子进程使用普通 CPU、I/O 和内存优先级;计划任务默认值 7 会降低三者的优先级,使依赖安装变慢。已有任务保留原设置:在 runner 空闲时停止、卸载并重新安装任务,再启动。执行 `-Action start` 或 `-Action status` 时只传 `-RunnerRoot`;配置目录及重试选项仅适用于安装。任务在该用户登录桌面后启动,重启后也需要登录,注销时停止。默认的 `Interactive` 模式需要桌面登录;两种启动模式都不会解锁签名 Token。
任务只允许一个实例,且没有执行时限。周期触发器每隔 `-RestartMinutes` 分钟(默认 `1`)检查一次,并恢复已退出的启动器,包括意外的零退出码。持久预算允许首次启动及 `-RestartCount` 次重启(默认 `10`),直到再次显式启动。每次桌面登录也会消耗预算,`status` 显示剩余启动次数;预算耗尽后,仅登录不能重启 runner。对正在运行的任务执行 start 不会重置预算。预算或配置文件缺失、无效时,自动启动会禁用,需修复后恢复。GitHub 启动器负责 runner 更新;任务恢复不会重跑失败的 workflow,也不会清除签名互锁。重试耗尽后,检查 `runner/dsh-task/run-*.log`、runner 的 `_diag` 日志和 `status`,修复原因后运行 `start`。任务运行不等于连接成功:确认出现 `Connected to GitHub` 和 `Listening for Jobs`,再到 Actions 确认任务分配。`run-*.log` 和 `launcher-*.log` 均保留,由操作者管理清理。
任务只允许一个实例,且没有执行时限。周期触发器每隔 `-RestartMinutes` 分钟(默认 `1`)检查一次,并恢复已退出的启动器,包括意外的零退出码。持久预算允许首次启动及 `-RestartCount` 次重启(默认 `10`),直到再次显式启动。每次触发器启动任务也会消耗预算,`status` 显示剩余启动次数;预算耗尽后,仅登录或重启机器不能重启 runner。对正在运行的任务执行 start 不会重置预算。预算或配置文件缺失、无效时阻止 runner 启动并请求禁用任务;若计划任务访问被拒绝,管理员需禁用触发器。预留启动次数后发生的失败保留有界恢复;runner 日志不可用时回退到启动器 stderr。GitHub 启动器负责 runner 更新;任务恢复不会重跑失败的 workflow,也不会清除签名互锁。重试耗尽后,检查 `runner/dsh-task/run-*.log`、runner 的 `_diag` 日志和 `status`,修复原因后运行 `start`。任务运行不等于连接成功:确认出现 `Connected to GitHub` 和 `Listening for Jobs`,再到 Actions 确认任务分配。`run-*.log` 和 `launcher-*.log` 均保留,由操作者管理清理。
维护前暂停新 workflow 的触发,等待 runner 空闲。`-Action stop` 在该 runner 存在活跃 worker 时拒绝停止,否则禁用后续启动并停止任务进程树;本地检查无法阻止 GitHub 同时分配任务。`-Action uninstall` 要求任务已停止并禁用,保留注册、配置和日志。拉取仓库更新不会更新已安装的副本。升级时先记录原来的 -ConfigRoot、可选的 -NetworkRoot 和重试设置,再从更新后的 checkout 依次执行 `stop`、`uninstall`、携带原设置的 `install` 和 `start`,最后重新确认监听与 job 分配。迁移手动启动的 runner 时,只在空闲后停止原启动器,再启动计划任务;不要同时运行两个启动器。
维护前暂停新 workflow 的触发,等待 runner 空闲。`-Action stop` 在该 runner 存在活跃 worker 时拒绝停止,否则禁用后续启动并停止任务进程树;本地检查无法阻止 GitHub 同时分配任务。`-Action uninstall` 要求任务已停止并禁用,保留注册、配置和日志。拉取仓库更新不会更新已安装的副本。升级时先记录启动模式、原来的 -ConfigRoot、可选的 -NetworkRoot 和重试设置,再从更新后的 checkout 依次执行 `stop`、`uninstall`、携带原设置的 `install` 和 `start`;Boot 模式还需在 `start` 前执行 `register-boot`,最后重新确认监听与 job 分配。迁移手动启动的 runner 时,只在空闲后停止原启动器,再启动计划任务;不要同时运行两个启动器。
操作者可在 Windows 上运行 `pwsh -NoProfile -File apps/desktop/tests/windows-runner-task.ps1`,使用隔离的假 runner 验证安装、无控制台的首次启动与自动恢复、防止重复启动、停止、子进程退出、启动/日志失败时的禁用处理和卸载。此显式运行的测试创建临时任务并保留诊断文件,不连接 GitHub 或访问签名硬件。`pwsh -NoProfile -File apps/desktop/tests/windows-runner-launcher.ps1` 无需计划任务,检查 GUI 可执行文件、子进程无控制台、退出状态、诊断输出以及存在继承管道写端时的有界排空;Windows CI 会执行该测试。真实机器验收还需检查空闲 runner 上线且不出现 Terminal 窗口、Actions job 分配,以及经操作者批准的重启后登录。签名打包和注销/重启验收需要操作者单独验证。
### Windows 无人值守启动
runner 需要在桌面登录前接单时使用 `Boot` 模式。由原 runner 账户准备文件,该账户可保持标准用户;仅注册步骤使用独立的管理员提权会话。管理员必须从已核验、归管理员所有且 runner 账户无法写入脚本及其父目录的 checkout 执行命令,不得提权执行 runner checkout 中的脚本;该步骤读取已准备的配置,不执行 runner 所属的启动器或预检。任务授予运行账户管理权限,始终以受限权限和优先级 4 运行。管理使用 Task Scheduler COM 和原生进程快照,不要求 CIM 命名空间访问权限。
1. 暂停 workflow 触发,等待空闲并停止现有启动器。已有任务由所属账户先执行 `stop` 再执行 `uninstall`,保留配置、缓存及签名互锁。安装会拒绝活跃或路径不可读的 runner 进程,以及原生 runner 的 `.service` 注册。
2. 以 runner 账户运行 `pwsh -NoProfile -File apps/desktop/scripts/windows-runner-task.ps1 -Action install -StartupMode Boot -RunnerRoot <registered-runner-directory> -ConfigRoot <machine-root>/packaging`,保留原有 `-NetworkRoot` 和重试选项。此步骤检查工具和网络、编译启动器并准备启动快照,不注册任务。
3. 在管理员提权 PowerShell 中运行 `pwsh -NoProfile -File <administrator-owned-checkout>/apps/desktop/scripts/windows-runner-task.ps1 -Action register-boot -RunnerRoot <registered-runner-directory> -RunAs <machine-or-domain\runner-account>`。账户必须与准备阶段一致。在本机提示中输入该账户的 Windows 密码,不是 Hello PIN 或签名 PIN。注册只提交一次凭据,创建初始禁用的 Password/AtStartup 任务。失败后先检查计划任务再重试,因为注册可能已经完成;不会自动重试认证。
4. 以 runner 账户运行同一管理脚本,传入 `-Action start -RunnerRoot <registered-runner-directory>`,再执行 `-Action status`。核对账户、`LogonType=Password`、`BootTrigger=True`、剩余启动次数和监听日志。恢复登录后启动时,停止并卸载任务,再不带 `-StartupMode Boot` 安装并启动。
管理员须确保批处理登录权限、没有覆盖它的拒绝策略,以及 runner 对工具、私有配置、缓存和日志的访问权限。账户密码变更后,暂停触发并等待空闲,由 runner 账户执行 `stop`、`uninstall`,管理员重新执行 `register-boot`,再由 runner 账户执行 `start`;保留准备文件,无需再次 `install`。网络依赖、磁盘和签名硬件须在登录前可用,服务时段应避免睡眠。脚本不配置桌面自动登录。正常重启也消耗持久启动预算,没有健康运行后自动重置或耗尽告警;维护时检查 `status` 的 `RemainingLaunches`,空闲时执行 `stop` 再 `start` 可重置预算。恢复不能清除签名互锁或重试失败的硬件签名。
Windows CI 使用隔离替身检查任务 XML、准备阶段、无效配置、凭据缺失/不匹配及提示抛错和单次注册,不注册真实 Boot 任务。交互式取消可能由 PowerShell 宿主直接终止,凭据替身测试不代表该宿主行为已经验收。部署操作者须在每台新机器验证独立管理员与标准账户的注册、任务管理权限,以及不登录桌面的重启、实际接单和签名打包。旧机器结果不能替代新启动快照的验收。
### 可选网络依赖
安装 Boot 启动前,先明确网络进程由谁管理。只有在重启后、不登录桌面的条件下验证转发进程及所需目标地址可用,才能依赖外部服务。服务显示 `Running`、已保存恢复设置或登录后探测成功都不足以证明这一点:桌面软件可能在注销或关机时停止转发进程并清除恢复状态。若网络依赖此类软件,请使用下述专用子进程模式,或部署独立管理的登录前服务。`runner-network.json` 只配置检查和代理变量,不会启动代理;省略 `-NetworkRoot` 就意味着由外部管理者负责网络启动。
`ConfigRoot` 中没有 `runner-network.json` 时,启动仍使用清理继承环境后的直连行为。要配置网络依赖,请在 checkout 外创建操作者管理的该 JSON 文件,且只包含 `proxyUrl`、`noProxy`、`serviceName`、`probeUrl`、`attempts`、`timeoutSeconds` 和 `retrySeconds`。前四个字段为字符串,后三个预算为 1 至 60 的整数。直连时将 `proxyUrl` 留空,没有 Windows 服务管理依赖时将 `serviceName` 留空。URL 必须使用 HTTP(S),不能包含凭据、查询参数或片段;代理 URL 不能包含路径。启动脚本在清理环境后设置 `HTTP_PROXY`、`HTTPS_PROXY`、`NO_PROXY` 和 `NODE_USE_ENV_PROXY`,并要求 Node HEAD 探测成功才允许启动 runner。服务就绪检查不会启动或停止 Windows 服务。
若使用专用子进程,在安装任务时添加 `-NetworkRoot <absolute-private-network-directory>`。该目录必须包含 `launch.json`,且只包含绝对路径的 `executable` 文件名、字符串数组 `arguments`,以及 1 至 3600 的整数 `restartDelaySeconds`。此模式要求存在 `runner-network.json`,其中 `serviceName` 应留空。为子进程分配独立的数据目录、监听绑定和可执行文件标识,与桌面软件管理的应用分离;仅使用不同端口无法防止其他管理器按可执行文件名终止进程。脚本不会修改桌面网络设置。实际服务商名称、路径、地址、端口和参数只保存在机器配置中,不得写入仓库文件或共享日志。将两个配置目录的访问权限限制为 runner 操作者。
安装时会启动依赖进行就绪检查,并在注册任务前停止它。runner 存活期间,守卫仅在自己拥有的网络进程退出后,按配置间隔重新启动它;启动连续失败时仍会重试,但不会重启 runner、重跑任务或重试签名。退出、重启和启动失败消息写入 `run-*.log`,依赖进程的输出会被丢弃。重启消息只表明进程已创建,不代表网络可用;请在 runner 日志中确认重新连接。进程仍存活但无响应时需要操作者排查。守卫独占锁定 `NetworkRoot`,回收残留子进程前核对 PID、启动时间和可执行文件,并在 runner 退出时停止子进程。不可恢复的守卫错误会保留活动 runner 直到其退出,并报告恢复已停止。重新安装时保留 `NetworkRoot`;仅拉取代码不会替换已安装的辅助脚本。
Windows CI 使用隔离的本地 fixture 运行 `pwsh -NoProfile -File apps/desktop/tests/windows-runner-network.ps1` 和 `pwsh -NoProfile -File apps/desktop/tests/windows-runner-network-process.ps1`。在已配置的打包机器上,给第一条命令添加 `-CheckStartup`,可验证实际启动环境清理后的网络配置。这些测试不会使用签名硬件或外部网络端点。
Windows CI 使用隔离的本地 fixture 运行 `pwsh -NoProfile -File apps/desktop/tests/windows-runner-network.ps1` 和 `pwsh -NoProfile -File apps/desktop/tests/windows-runner-network-process.ps1`。在已配置的打包机器上,给第一条命令添加 `-CheckStartup`,可验证实际启动环境清理后的网络配置。就绪探测设置退出状态并让 Node 正常完成清理,保留响应体取消、请求超时和外层进程期限保护。测试通过真实重定向子进程路径覆盖 HTTP 成功、非 2xx、代理连接拒绝和请求超时,不使用签名硬件或外部网络端点。
新机器准备和测试网络时,保持 runner 禁用。禁用的 runner 任务不会启动其托管的网络子进程;应单独测试该子进程,不启动 listener。经操作者批准重启后,在登录桌面或手动打开网络客户端之前,验证所选代理及所需目标地址,记录当时是否存在桌面 Shell,以及由哪个进程提供代理。若失败,先检查网络管理者的启动和关闭日志,再重试。网络验收通过后,才由操作者启用 runner,验证 Boot 启动与任务分配;签名另行验收。
<a id="signing-configuration"></a>
## 签名配置
Windows 打包要求 `PATH` 中提供 PowerShell 7(`pwsh`)。工具链检查在构建前验证 Authenticode 支持;运行时签名检查使用此引擎处理超过 260 个字符的路径。
通过[机器 preset 配置](../packaging/README.zh.md#configuration-and-local-builds)选择公开设置与签名文件;不选择 preset 时使用目标 dotenv 文件。
在 `.env.windows` 中填写 `DSH_DESKTOP_WINDOWS_CER_FILE`(公开 EV 叶证书)、`DSH_DESKTOP_WINDOWS_SIGNTOOL`(SafeNet 兼容的 SignTool)、`DSH_DESKTOP_WINDOWS_KEY_CONTAINER`(匹配的私钥容器)和 `DSH_DESKTOP_WINDOWS_TOKEN_PIN`(Token Password)。私钥仍保留在 USB Token;不要把证书或本地凭据文件提交到 Git。
Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 KiB

After

Width:  |  Height:  |  Size: 84 KiB

+39 -20
View File
@@ -2,17 +2,15 @@
* Render the install icons of the Web application from the official
* application tile.
*
* A browser installs a Web App only with a raster 192px and a 512px icon, masks
* the icon it puts on the home screen, and has no manifest support for iOS,
* which reads `apple-touch-icon` instead. The whale favicon is the bare mark
* drawn edge to edge: handed to a launcher directly it loses its fins to the
* mask, and it carries neither the tile nor a background of its own. This
* script rasterizes the official application tile (`apps/desktop/resources/icon.svg`,
* the artwork the desktop application ships) into the committed PNGs under
* `public/`. Every variant crops the tile's drop shadow, which belongs to a
* desktop window rather than a launcher; the maskable variant additionally
* scales the whale inside the safe zone a platform mask may crop, leaving the
* tile's own gradient to fill the icon so no mask meets a seam.
* This script rasterizes the official application tile
* (`apps/desktop/resources/icon.svg`) into the committed PNGs under `public/`.
* The bare favicon has no background, and its edge-to-edge fins can be cropped
* by a launcher mask. The tile's drop shadow belongs to a desktop window, so
* every install variant crops it. The generic 192px and 512px icons have
* transparent rounded corners matching the macOS tile. Safari prefers the
* linked Apple touch icon, which stays square for system masking. The maskable
* variant scales the whale inside the platform's safe zone while retaining
* the tile's own gradient to the edges, so no platform mask meets a seam.
*
* The committed PNGs are the output; rerun
* `pnpm --filter @deepseek-ai/dsh-web-frontend run render:app-icons` after the
@@ -34,6 +32,9 @@ export const ICON_OUTPUT_DIRECTORY = fileURLToPath(new URL('../public/', import.
/** Tile edge in source units; every render density is expressed against it. */
const TILE_EDGE = 1024
/** Corner radius in source units, matching `apps/desktop/resources/icon-macos.svg`. */
const TILE_CORNER_RADIUS = 230
/** Tile inset in the source canvas: the drop shadow occupies the surrounding band. */
const TILE_INSET = { x: 40, y: 32 } as const
@@ -60,6 +61,9 @@ export const MASKABLE_SAFE_RADIUS_RATIO = 0.4
/** Root element of the source document, rewritten to crop the canvas to the tile. */
const SOURCE_ROOT = /^<svg[^>]*>/u
/** Source definitions element, including attributes preserved during clip insertion. */
const SOURCE_DEFINITIONS = /<defs(?:\s[^>]*)?>/u
/** The tile group's drop shadow; stripped because a launcher icon has no window around it. */
const TILE_SHADOW_GROUP = '<g filter="url(#filter0_d_1637_371)">'
@@ -72,18 +76,18 @@ export interface AppIconVariant {
readonly file: string
/** Square edge in pixels. */
readonly size: number
/** Which rendering the platform receives. */
readonly kind: 'tile' | 'maskable'
/** Target rendering; `tile` is an opaque square for system masking. */
readonly kind: 'rounded' | 'tile' | 'maskable'
}
/**
* Install icons the Web application ships. Chrome requires the 192px and 512px
* raster pair to offer installation, prefers a maskable icon for the home
* screen, and iOS reads the touch icon alone.
* raster pair to offer installation. Platforms that apply their own masks
* receive a separate opaque maskable icon; Safari prefers the linked Apple touch icon.
*/
export const APP_ICON_VARIANTS: readonly AppIconVariant[] = [
{ file: 'icon-192.png', size: 192, kind: 'tile' },
{ file: 'icon-512.png', size: 512, kind: 'tile' },
{ file: 'icon-192.png', size: 192, kind: 'rounded' },
{ file: 'icon-512.png', size: 512, kind: 'rounded' },
{ file: 'icon-maskable-512.png', size: 512, kind: 'maskable' },
{ file: 'apple-touch-icon.png', size: 180, kind: 'tile' },
]
@@ -102,13 +106,14 @@ function aboutCenter(scale: number): string {
}
/** Replace the source root so the icon canvas is exactly the tile. */
function reparent(source: string): string {
function reparent(source: string, tileGroup = '<g>'): string {
const trimmed = source.trim()
const root = SOURCE_ROOT.exec(trimmed)
if (root === null) throw new Error('app icons: the tile source has no root element')
if (!trimmed.includes(TILE_SHADOW_GROUP)) throw new Error('app icons: the tile source has no shadowed tile group')
if (!trimmed.includes(TILE_ARTWORK_GROUP)) throw new Error('app icons: the tile source has no artwork group')
return `${croppedRoot()}${trimmed.slice(root[0].length).replace(TILE_SHADOW_GROUP, '<g>')}`
if (!SOURCE_DEFINITIONS.test(trimmed)) throw new Error('app icons: the tile source has no definitions element')
return `${croppedRoot()}${trimmed.slice(root[0].length).replace(TILE_SHADOW_GROUP, tileGroup)}`
}
/**
@@ -120,6 +125,19 @@ export function tileDocument(source: string): string {
return reparent(source)
}
/**
* Round the generic install tile for launchers that display it without a mask.
* @param source - complete `icon.svg` document.
* @returns an SVG document with transparent rounded corners and unscaled artwork.
*/
export function roundedDocument(source: string): string {
return reparent(source, '<g clip-path="url(#install-tile-clip)">')
.replace(SOURCE_DEFINITIONS, '$&<clipPath id="install-tile-clip"><rect'
+ ` x="${String(TILE_INSET.x)}" y="${String(TILE_INSET.y)}"`
+ ` width="${String(TILE_EDGE)}" height="${String(TILE_EDGE)}"`
+ ` rx="${String(TILE_CORNER_RADIUS)}"/></clipPath>`)
}
/**
* Rewrite the tile source into a maskable icon. The tile keeps its own gradient
* and extent, so the icon's border is the real tile rather than an extension;
@@ -137,7 +155,7 @@ export function maskableDocument(source: string): string {
/**
* Rasterize one rewritten document at a square edge.
* @param document - output of {@link tileDocument} or {@link maskableDocument}.
* @param document - output of {@link tileDocument}, {@link roundedDocument} or {@link maskableDocument}.
* @param size - square edge in pixels.
* @returns the PNG bytes.
*/
@@ -157,6 +175,7 @@ async function renderPng(document: string, size: number): Promise<Buffer> {
function documentForVariant(source: string, kind: AppIconVariant['kind']): string {
switch (kind) {
case 'rounded': return roundedDocument(source)
case 'tile': return tileDocument(source)
case 'maskable': return maskableDocument(source)
default: return assertNever(kind)
+5 -3
View File
@@ -627,7 +627,8 @@ describe('web e2e: agent teamwork panel', () => {
expect(await panel.count()).toBe(1)
await page.mouse.click(2, 2)
await panel.waitFor({ state: 'detached' })
await page.setViewportSize(viewport)
// A width whose transcript cannot move aside for the panel, so the toggle opens it over the conversation.
await page.setViewportSize({ width: 1100, height: viewport.height })
await trigger.focus()
await page.keyboard.press('Enter')
await tasksHeading.waitFor()
@@ -675,8 +676,9 @@ describe('web e2e: agent teamwork panel', () => {
const row = board.locator(`[data-team-task="${task.id}"]`)
const emptyRow = board.locator(`[data-team-task="${completed.id}"]`)
onTestFinished(() => page.setViewportSize(viewport))
// Constrain the panel so closed and expanded task rows both exercise its scrollbar.
await page.setViewportSize({ width: viewport.width, height: 500 })
// Constrain the panel so closed and expanded task rows both exercise its scrollbar, at a width whose transcript
// cannot move aside for it: the panel opens over the conversation and stays mounted as the window narrows below.
await page.setViewportSize({ width: 1100, height: 500 })
await showSharedTasksSection(page)
await row.waitFor()
expect(await board.locator('[data-team-task-details], article').count()).toBe(0)
+41 -1
View File
@@ -4,7 +4,7 @@ import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import {
APP_ICON_VARIANTS, ICON_OUTPUT_DIRECTORY, MASKABLE_ARTWORK_SCALE, TILE_SOURCE,
maskableDocument, tileDocument,
maskableDocument, roundedDocument, tileDocument,
} from '../scripts/render-app-icons.ts'
import { pngSize } from './png-size.ts'
@@ -29,6 +29,46 @@ describe('web install icons', () => {
expect(maskable).toContain(`transform="translate(552 544) scale(${MASKABLE_ARTWORK_SCALE}) translate(-552 -544)"`)
})
it('rounds the full tile with the macOS corner geometry and unscaled artwork', async () => {
const source = await readFile(TILE_SOURCE, 'utf8')
const rounded = roundedDocument(source)
const macos = await readFile(new URL('../../desktop/resources/icon-macos.svg', import.meta.url), 'utf8')
expect(rounded).toContain('viewBox="40 32 1024 1024"')
expect(rounded).toContain('<g clip-path="url(#install-tile-clip)">')
expect(rounded).toContain('<clipPath id="install-tile-clip"><rect x="40" y="32" width="1024" height="1024" rx="230"/></clipPath>')
expect(rounded).not.toContain('<g filter="url(#filter0_d_1637_371)">')
expect(rounded).not.toContain(`scale(${MASKABLE_ARTWORK_SCALE})`)
expect(rounded).toContain(source.match(/<path\b[^>]*>/u)![0])
expect(rounded).toContain('<g filter="url(#filter1_ddi_1637_371)">')
const corner = rounded.match(/<clipPath\b[^>]*><rect\b[^>]*\brx="([^"]+)"/u)![1]
const tileRects = [...macos.matchAll(/<rect\b[^>]*\bwidth="1024"[^>]*\bheight="1024"[^>]*>/gu)]
expect(tileRects).toHaveLength(3)
expect(tileRects.map(rect => rect[0].match(/\brx="([^"]+)"/u)?.[1]))
.toEqual([corner, corner, corner])
})
it('clips the tile when another group precedes it', async () => {
const source = await readFile(TILE_SOURCE, 'utf8')
const precedingGroup = '<g><rect width="1" height="1"/></g>'
const rounded = roundedDocument(source.replace(
'<g filter="url(#filter0_d_1637_371)">',
`${precedingGroup}<g filter="url(#filter0_d_1637_371)">`,
))
expect(rounded).toContain(`${precedingGroup}<g clip-path="url(#install-tile-clip)">`)
})
it('preserves attributes on the source definitions', async () => {
const source = await readFile(TILE_SOURCE, 'utf8')
expect(roundedDocument(source.replace('<defs>', '<defs id="tile-definitions">')))
.toContain('<defs id="tile-definitions"><clipPath id="install-tile-clip">')
})
it('rejects a source without the definitions needed by the rounded tile', async () => {
const source = await readFile(TILE_SOURCE, 'utf8')
expect(() => roundedDocument(source.replace(/<defs>[\s\S]*<\/defs>/u, '')))
.toThrow(/no definitions element/)
})
it('rejects non-PNG bytes and incomplete image headers', () => {
expect(() => pngSize(Buffer.from('<svg/>'))).toThrow(/PNG IHDR/)
expect(() => pngSize(Buffer.alloc(33))).toThrow(/PNG IHDR/)
+2 -1
View File
@@ -34,7 +34,8 @@ it('sends the Creator customization intent without taking actions for an ordinar
expect(agent.session.header.agentPreset).toBe('cordis')
const system = agent.session.deriveMessages().find(message => message.role === 'system')
if (system === undefined) throw new Error('Creator request has no system prompt')
const prompt = system.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('')
// Each section is its own text block; adapters join them with blank lines.
const prompt = system.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n\n')
expect(prompt).toMatch(/^You are a coding agent powered by the .+ model\. You help the user customize DeepSeek Harness itself\.$/mu)
expect(prompt.split(CUSTOMIZATION_INTENT)).toHaveLength(2)
const sharedPrompt = prompt.replace(` ${CUSTOMIZATION_INTENT}`, '')
+8 -7
View File
@@ -28,15 +28,16 @@ it.skipIf(process.platform !== 'darwin').each([
const patch = join(directory, 'native-fixture.yml')
// Permission inspection fails against this non-helper executable; activation still permits dismissing setup.
await writeFile(patch, JSON.stringify([{ id: 'cua-macos', config: { helperPath: process.execPath } }]))
const defaults = join(directory, 'script-defaults')
if (script) {
await mkdir(defaults)
await writeFile(join(defaults, 'package.json'), JSON.stringify({ name: 'cua-script-defaults', version: '1.0.0', dsh: { bundle: { patch: 'cordis.patch.yml' } } }))
await writeFile(join(defaults, 'cordis.patch.yml'), '- id: ptc-runtime\n config:\n executionMode: vm-script\n scriptPersistence: false\n')
}
// Both variants start without retained state so that the persistent-mode action has an effect.
const defaults = join(directory, 'ptc-defaults')
await mkdir(defaults)
await writeFile(join(defaults, 'package.json'), JSON.stringify({ name: 'cua-ptc-defaults', version: '1.0.0', dsh: { bundle: { patch: 'cordis.patch.yml' } } }))
await writeFile(join(defaults, 'cordis.patch.yml'), script
? '- id: ptc-runtime\n config:\n executionMode: vm-script\n scriptPersistence: false\n'
: '- id: ptc-runtime\n config:\n executionMode: per-call\n')
const harnessHome = join(directory, 'home')
const scaffold = ownedScaffold = await launchWebScaffold({
profile: { packages: script ? [{ dir: defaults, enabled: true }] : [] },
profile: { packages: [{ dir: defaults, enabled: true }] },
harnessHome, extraOverlayPath: [
fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), patch,
] })
+1 -1
View File
@@ -56,7 +56,7 @@ it.skipIf(process.platform !== 'darwin')('keeps system requests pending until fr
// Application consent remains independent of the session's tool-approval policy.
const grant = scaffold.ctx.tools.execute({ agent, signal: new AbortController().signal,
calls: [{ type: 'tool-call', id: brandString<ToolCallId>('cua-app-approval'), name: 'run_code',
arguments: JSON.stringify({ code: 'return await tools.cua({ method: "getApp", params: { selector: "Fixture" } })',
arguments: JSON.stringify({ code: 'await tools.cua({ method: "getApp", params: { selector: "Fixture" } })',
description: 'Request application access' }) }] })
const approval = page.locator('[data-approval-key]')
await Promise.race([approval.waitFor(), grant.then((result) => {
+2 -1
View File
@@ -8,7 +8,7 @@ import {
assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts,
launchWebScaffold, selectedSessionFixture, watchConsole, webSnapshotMode, type WebScaffold,
} from './scaffold.ts'
import { connectFreshWorkspaceZh, saveFailureShot, ZH_BROWSER_LOCALE } from './support.ts'
import { connectFreshWorkspaceZh, saveFailureShot, startWithSessionPanelHidden, ZH_BROWSER_LOCALE } from './support.ts'
const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/deepseek-messages-chat', import.meta.url))
const FIXTURE = join(SNAPSHOT_DIR, 'session.v3.jsonl')
@@ -38,6 +38,7 @@ describe.skipIf(MODE === 'record')('web e2e: DeepSeek Messages conversation', ()
await scaffold.ctx.agentDefaultModel.saveSelection({ provider: 'deepseek-messages', model: 'deepseek-v4-flash' })
browser = await chromium.launch()
page = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
await startWithSessionPanelHidden(page)
tripwire = watchConsole(page)
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await connectFreshWorkspaceZh(page, scaffold.workspaceCwd)
@@ -80,7 +80,7 @@ it.skipIf(webSnapshotMode() === 'record').each(['deepseek-official', 'google', '
await openSettings(page, 'zh')
const dialog = page.getByRole('dialog', { name: '设置' })
await dialog.getByRole('button', { name: '模型', exact: true }).click()
const edit = dialog.getByRole('button', { name: `编辑 ${messages ? 'DeepSeek (deepseek-official)' : provider}`, exact: true })
const edit = dialog.getByRole('button', { name: `编辑 ${messages ? 'DeepSeek API (deepseek-official)' : provider}`, exact: true })
await edit.click()
// This row's card alone. Between the credential delete and the profile
// write that restores native auth, google's row reports no usable
@@ -136,7 +136,7 @@ it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webki
await openSettings(page, 'zh')
const dialog = page.getByRole('dialog', { name: '设置' })
await dialog.getByRole('button', { name: '模型', exact: true }).click()
const edit = dialog.getByRole('button', { name: '编辑 DeepSeek (deepseek-official)', exact: true })
const edit = dialog.getByRole('button', { name: '编辑 DeepSeek API (deepseek-official)', exact: true })
await edit.click()
// This row's card alone: the dialog can show another provider's card,
// with its own key field, beside this row.
@@ -165,7 +165,7 @@ it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webki
// while the settings snapshot is loading is dropped. The saved notice is
// published by that reload's completion, so waiting for it also makes the
// reopen below deterministic.
await dialog.getByText('已保存 DeepSeek (deepseek-official)。', { exact: true }).waitFor()
await dialog.getByText('已保存 DeepSeek API (deepseek-official)。', { exact: true }).waitFor()
await expect.poll(() => key.count(), { timeout: 10_000 }).toBe(0)
await edit.click()
expect(await key.getAttribute('placeholder')).toBe('•'.repeat('fixture-new-key'.length))
@@ -193,7 +193,7 @@ it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webki
await openSettings(page, 'zh')
const dialog = page.getByRole('dialog', { name: '设置', exact: true })
await dialog.getByRole('button', { name: '模型', exact: true }).click()
const setup = dialog.getByText('DeepSeek', { exact: true }).locator('xpath=ancestor::li')
const setup = dialog.getByText('DeepSeek API', { exact: true }).locator('xpath=ancestor::li')
await setup.getByText('自定义设置', { exact: true }).click()
await dialog.getByRole('button', { name: '添加模型提供商' }).click()
await dialog.getByRole('tab', { name: '自定义模型 API' }).click()
@@ -242,7 +242,7 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett
it('offers one DeepSeek card and saves Messages settings using the existing credential reference', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-deepseek-messages-settings'))
expect(scaffold.ctx.llm.listProviders()).toContainEqual({ id: 'deepseek-official', name: 'DeepSeek' })
expect(scaffold.ctx.llm.listProviders()).toContainEqual({ id: 'deepseek-official', name: 'DeepSeek API' })
expect(scaffold.ctx.llm.listProviders().filter(provider => provider.id === 'deepseek-official')).toHaveLength(1)
expect(scaffold.ctx.agentDefaultModel.currentSelection()).toEqual({ provider: 'deepseek-official', model: 'deepseek-flash' })
await page.getByRole('dialog', { name: '开始使用', exact: true }).getByRole('button', { name: '添加 API Key', exact: true }).click()
@@ -253,9 +253,9 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett
await openSettings(page, 'zh')
const dialog = page.getByRole('dialog', { name: '设置', exact: true })
await dialog.getByRole('button', { name: '模型', exact: true }).click()
await dialog.getByText('DeepSeek', { exact: true }).waitFor()
expect(await dialog.getByText('DeepSeek', { exact: true }).count()).toBe(1)
await dialog.getByText('DeepSeek', { exact: true }).locator('xpath=ancestor::li').getByRole('button', { name: '编辑' }).click()
await dialog.getByText('DeepSeek API', { exact: true }).waitFor()
expect(await dialog.getByText('DeepSeek API', { exact: true }).count()).toBe(1)
await dialog.getByText('DeepSeek API', { exact: true }).locator('xpath=ancestor::li').getByRole('button', { name: '编辑' }).click()
const messages = dialog
const key = messages.getByLabel('API 密钥', { exact: true })
expect(await key.inputValue()).toBe('')
@@ -271,7 +271,7 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett
expect(await messages.getByLabel('模型 ID 1').inputValue()).toBe('deepseek-flash')
await messages.getByLabel('显示名称 1', { exact: true }).fill('Messages Flash')
await messages.getByRole('button', { name: '保存', exact: true }).click()
await dialog.getByText('已保存 DeepSeek (deepseek-official)。', { exact: true }).waitFor()
await dialog.getByText('已保存 DeepSeek API (deepseek-official)。', { exact: true }).waitFor()
const settings = await readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8')
expect(settings).toContain('https://messages.example/anthropic')
@@ -285,7 +285,7 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett
expect(credentials).toContain('DEEPSEEK_API_KEY: sk-e2e-messages')
expect(credentials).not.toContain('DEEPSEEK_MESSAGES_API_KEY')
expect(await page.locator('body').innerText()).not.toContain('sk-e2e-')
await dialog.getByRole('button', { name: '编辑 DeepSeek (deepseek-official)', exact: true }).click()
await dialog.getByRole('button', { name: '编辑 DeepSeek API (deepseek-official)', exact: true }).click()
expect(await key.inputValue()).toBe('')
await messages.getByText('使用已保存的 API key。', { exact: true }).waitFor()
expect(await key.getAttribute('type')).toBe('password')
+53 -3
View File
@@ -84,13 +84,63 @@ describe.skipIf(MODE === 'record')('web e2e: default Workspace', () => {
const trigger = page.getByRole('button', { name: 'Choose workspace', exact: true })
await trigger.getByText('Default workspace', { exact: true }).waitFor()
await trigger.tap()
const menu = page.getByRole('menu').filter({ has: page.getByRole('menuitem', { name: 'Default workspace', exact: true }) })
await menu.waitFor({ state: 'visible', timeout: 10_000 })
const defaultWorkspace = page.getByRole('menuitem', { name: 'Default workspace', exact: true })
const singleWorkspaceMenu = page.getByRole('menu').filter({ has: defaultWorkspace })
await singleWorkspaceMenu.getByRole('menuitem', { name: 'Add workspace…', exact: true }).waitFor()
const search = page.getByRole('searchbox', { name: 'Search workspaces', exact: true })
expect(await search.count()).toBe(0)
await page.keyboard.press('Escape')
await singleWorkspaceMenu.waitFor({ state: 'hidden' })
const secondWorkspacePath = join(scaffold.workspaceCwd, 'secondary-workspace')
await mkdir(secondWorkspacePath)
await scaffold.ctx.workspaceRegistry.create(secondWorkspacePath, 'Secondary workspace')
await trigger.tap()
await search.waitFor({ state: 'visible', timeout: 10_000 })
const card = page.locator('[data-menu-material]').filter({ has: search })
const menu = card.getByRole('menu')
expect(await trigger.getAttribute('aria-expanded')).toBe('true')
expect(await trigger.evaluate(node => node.style.anchorName)).toBe(await menu.evaluate(node => node.style.positionAnchor))
expect(await trigger.evaluate(node => node.style.anchorName)).toBe(await card.evaluate(node => node.style.positionAnchor))
const searchRow = card.locator('[data-search-field]').filter({ has: search })
const workspace = menu.getByRole('menuitem', { name: 'Default workspace', exact: true })
const add = menu.getByRole('menuitem', { name: 'Add workspace…', exact: true })
await expect.poll(async () => {
const searchBox = await searchRow.boundingBox()
const workspaceBox = await workspace.boundingBox()
const addBox = await add.boundingBox()
const searchContentHeight = await searchRow.evaluate((element) => {
const style = getComputedStyle(element)
return element.getBoundingClientRect().height
- Number.parseFloat(style.paddingTop) - Number.parseFloat(style.paddingBottom)
- Number.parseFloat(style.borderTopWidth) - Number.parseFloat(style.borderBottomWidth)
})
return searchBox !== null && workspaceBox !== null && addBox !== null
&& Math.abs(searchContentHeight - addBox.height) < 1
&& searchBox.y + searchBox.height < workspaceBox.y + 1
}).toBe(true)
expect(await search.evaluate(element => element === document.activeElement)).toBe(false)
await search.tap()
await expect.poll(() => search.evaluate(element => element === document.activeElement)).toBe(true)
await search.fill('default')
await workspace.waitFor()
expect(await menu.getByRole('menuitem').allTextContents()).toEqual(['Default workspace', 'Add workspace…'])
const workspaceHeight = await workspace.evaluate(element => element.getBoundingClientRect().height)
await search.fill('missing-workspace-name')
const empty = card.getByRole('status').filter({ hasText: 'No matching workspaces' })
await expect.poll(() => empty.evaluate(element => element.getBoundingClientRect().height))
.toBeCloseTo(workspaceHeight, 0)
await page.keyboard.press('Escape')
await menu.waitFor({ state: 'hidden' })
expect(await trigger.getAttribute('aria-expanded')).toBe('false')
await trigger.click()
await expect.poll(() => search.evaluate(element => element === document.activeElement)).toBe(true)
expect(await search.inputValue()).toBe('')
await search.press('Escape')
await menu.waitFor({ state: 'hidden' })
await trigger.press('Enter')
await expect.poll(() => search.evaluate(element => element === document.activeElement)).toBe(true)
},
)
+590
View File
@@ -0,0 +1,590 @@
/** An anonymous browser enters the shipped application only after settings approval. */
import { fileURLToPath } from 'node:url'
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
import { chromium, type Locator, type Page } from 'playwright'
import { expect, it, onTestFinished } from 'vitest'
import {
captureStableAria, compareOrRefreshGolden, launchWebScaffold, webSnapshotMode,
} from './scaffold.ts'
import { launchRemoteConnectionFixture } from './remote-connection-fixture.ts'
import { openSettings, ZH_BROWSER_LOCALE } from './support.ts'
const spoofedSourceIp = '198.51.100.42'
const spoofedSourceHeaders = {
forwarded: `for=${spoofedSourceIp}`,
'x-forwarded-for': spoofedSourceIp,
'x-real-ip': spoofedSourceIp,
}
async function expectObservedSource(requests: Locator, authority: string): Promise<void> {
const content = await requests.innerText()
expect(content).toContain('来源 IP')
expect(content).toContain('127.0.0.1')
expect(content).not.toContain(authority)
expect(content).not.toContain(spoofedSourceIp)
}
async function readPairingCodes(page: Page, baseUrl: string): Promise<{ status: number; codes: (string | undefined)[] | undefined }> {
const response = await page.request.post(new URL('api/remoteConnection/pairingRequests', baseUrl).href, {
data: { type: 'client-request', rpcId: 'pairing-list-observation', method: 'remoteConnection/pairingRequests', payload: { args: {} } },
})
try {
const list: unknown = await response.json()
const result: unknown = typeof list === 'object' && list !== null ? Reflect.get(list, 'result') : undefined
const value: unknown = typeof result === 'object' && result !== null ? Reflect.get(result, 'value') : undefined
const rows: unknown = typeof value === 'object' && value !== null ? Reflect.get(value, 'requests') : undefined
const codes = Array.isArray(rows) ? rows.map((row: unknown) => {
const code: unknown = typeof row === 'object' && row !== null ? Reflect.get(row, 'code') : undefined
return typeof code === 'string' ? code : undefined
}) : undefined
return { status: response.status(), codes }
} finally { await response.dispose() }
}
async function decideWithDelayedList(page: Page, requests: Locator, code: string, decision: 'allow' | 'deny'): Promise<string> {
const releaseStaleRead = Promise.withResolvers<undefined>()
const releaseFreshReads = Promise.withResolvers<undefined>()
let readCount = 0
let staleRead: { method: string; request: unknown; response: unknown } | undefined
let staleReadSettled = false
let freshReadStarted = false
const routeErrors: unknown[] = []
await page.route('**/api/remoteConnection/pairingRequests', async (route) => {
const stale = readCount++ === 0
let handlingStarted = false
try {
if (stale) {
const response = await route.fetch()
staleRead = {
method: route.request().method(), request: route.request().postDataJSON(), response: await response.json(),
}
await releaseStaleRead.promise
handlingStarted = true
if (route.request().failure()?.errorText === 'net::ERR_ABORTED') await route.abort('aborted')
else await route.fulfill({ response })
} else {
freshReadStarted = true
await releaseFreshReads.promise
handlingStarted = true
if (route.request().failure()?.errorText === 'net::ERR_ABORTED') await route.abort('aborted')
else await route.continue()
}
} catch (error) {
if (route.request().failure()?.errorText !== 'net::ERR_ABORTED') routeErrors.push(error)
if (!handlingStarted) {
try { await route.abort('failed') } catch (abortError) { routeErrors.push(abortError) }
}
} finally {
if (stale) staleReadSettled = true
}
})
try {
await expect.poll(() => staleRead !== undefined || routeErrors.length > 0, { timeout: 15_000 }).toBe(true)
expect(routeErrors).toEqual([])
expect(staleRead?.method).toBe('POST')
expect(staleRead?.request).toMatchObject({ payload: { args: {} } })
expect(staleRead?.response).toMatchObject({ result: {
ok: true, value: { requests: [{ code: code.replace(' ', '') }] },
} })
await requests.getByRole('button', { name: decision === 'allow' ? '批准' : '拒绝', exact: true }).click()
const notice = page.getByRole('alert').filter({ hasText: decision === 'allow' ? '已批准申请' : '已拒绝申请' })
await notice.waitFor()
expect(await requests.getByText(code, { exact: true }).count()).toBe(0)
const snapshot = (await Promise.all([requests.ariaSnapshot(), notice.ariaSnapshot()])).join('\n')
releaseStaleRead.resolve(undefined)
await expect.poll(() => staleReadSettled, { timeout: 15_000 }).toBe(true)
await expect.poll(() => freshReadStarted, { timeout: 15_000 }).toBe(true)
expect(await requests.getByText(code, { exact: true }).count()).toBe(0)
return snapshot
} finally {
releaseStaleRead.resolve(undefined)
releaseFreshReads.resolve(undefined)
await page.unrouteAll({ behavior: 'wait' })
expect(routeErrors).toEqual([])
}
}
it('lets a paired mobile browser approve another device and keeps denied or cancelled applicants signed out behind a public mount', async () => {
const scaffold = await launchWebScaffold({
publicMount: { prefix: '/tools/dsh/' },
extraOverlayPath: fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)),
})
onTestFinished(() => scaffold.close())
const browser = await chromium.launch()
try {
const owner = await browser.newPage({ locale: ZH_BROWSER_LOCALE, viewport: { width: 1440, height: 1000 } })
await owner.goto(scaffold.authenticatedUrl)
await owner.waitForFunction(() => '__DSH_BOOT__' in window)
expect((await owner.context().cookies()).some(cookie => cookie.name.startsWith('dsh-auth-') && cookie.httpOnly)).toBe(true)
await openSettings(owner, 'zh')
const navigation = owner.getByRole('dialog', { name: '设置', exact: true })
.getByRole('button', { name: '远程连接', exact: true })
await expect.poll(() => navigation.count()).toBe(1)
await navigation.click()
const approvals = owner.getByRole('region', { name: '远程连接', exact: true })
.getByRole('region', { name: '配对申请', exact: true })
await approvals.waitFor()
const applicant = await browser.newPage({
locale: ZH_BROWSER_LOCALE, viewport: { width: 390, height: 844 },
extraHTTPHeaders: spoofedSourceHeaders,
})
const errors: string[] = []
applicant.on('pageerror', error => errors.push(error.message))
const anonymousScript = applicant.waitForResponse(response => response.url() === new URL('pairing/client.js', scaffold.baseUrl).href)
expect((await applicant.goto(scaffold.baseUrl))?.status()).toBe(401)
expect((await anonymousScript).status()).toBe(200)
expect(await applicant.evaluate(() => customElements.get('dsh-device-pairing') !== undefined)).toBe(true)
expect(await applicant.evaluate(() => '__ModuleLoader__' in window)).toBe(false)
await applicant.locator('#auth-pair-request').click()
await applicant.locator('#auth-pair-code').waitFor()
const previousCode = await applicant.locator('#auth-pair-code').innerText()
await approvals.getByText(previousCode, { exact: true }).waitFor()
const countdown = applicant.locator('#auth-pair-countdown')
const initialCountdown = await countdown.innerText()
expect(initialCountdown).toMatch(/\d+:\d{2}/u)
await expect.poll(() => countdown.innerText()).not.toBe(initialCountdown)
const [replacementResponse] = await Promise.all([
applicant.waitForResponse(response => new URL(response.url()).pathname.endsWith('/pairing/request')),
applicant.getByRole('button', { name: '重新申请', exact: true }).click(),
])
await expect.poll(() => applicant.locator('#auth-pair-code').innerText()).not.toBe(previousCode)
await applicant.locator('#auth-pair-panel[data-state="waiting"]').waitFor()
const code = await applicant.locator('#auth-pair-code').innerText()
expect(code).toMatch(/^[A-Z2-9]{4} [A-Z2-9]{4}$/u)
await approvals.getByText(previousCode, { exact: true }).waitFor({ state: 'detached' })
await approvals.getByText(code, { exact: true }).waitFor()
expect(await replacementResponse.request().allHeaders()).toMatchObject(spoofedSourceHeaders)
const ticket: unknown = await replacementResponse.json()
expect(ticket).toMatchObject({ code: code.replace(' ', ''), sourceIp: '127.0.0.1', authority: new URL(scaffold.baseUrl).origin })
await expectObservedSource(approvals, new URL(scaffold.baseUrl).host)
expect(await applicant.evaluate(() => '__DSH_BOOT__' in window)).toBe(false)
expect((await applicant.context().cookies()).filter(cookie => /^dsh-(?:auth|remote)-/u.test(cookie.name))).toEqual([])
expect(await applicant.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true)
const screenshotDirectory = process.env.DSH_PAIRING_SCREENSHOT_DIR
if (screenshotDirectory !== undefined) {
await applicant.emulateMedia({ colorScheme: 'light' })
await expect.poll(() => applicant.evaluate(() => getComputedStyle(document.documentElement).backgroundColor)).toBe('rgb(250, 250, 250)')
await applicant.screenshot({ path: join(screenshotDirectory, 'auth-request-light.png'), fullPage: true })
await applicant.emulateMedia({ colorScheme: 'dark' })
await expect.poll(() => applicant.evaluate(() => getComputedStyle(document.documentElement).backgroundColor)).toBe('rgb(23, 23, 23)')
await applicant.screenshot({ path: join(screenshotDirectory, 'auth-request-dark.png'), fullPage: true })
await applicant.emulateMedia({ colorScheme: null })
}
const mode = webSnapshotMode()
const applicationUrl = new URL(scaffold.authenticatedUrl)
const tokenPlaceholder = `${applicationUrl.origin}${applicationUrl.pathname}?token=xxx`
expect(await applicant.locator('#token').getAttribute('placeholder')).toBe(tokenPlaceholder)
await compareOrRefreshGolden(
fileURLToPath(new URL('./expected/device-pairing/request.expected.md', import.meta.url)),
(await captureStableAria(applicant, 'main', scaffold.workspaceCwd, {
replacements: [
[tokenPlaceholder, '{{application-url}}?token=xxx'],
[code, '{{pairing-code}}'], [new URL(scaffold.baseUrl).host, '{{authority}}'],
],
})).replace(/\d+:\d{2}/gu, '{{remaining}}'), mode,
)
await compareOrRefreshGolden(
fileURLToPath(new URL('./expected/device-pairing/approval.expected.md', import.meta.url)),
(await approvals.ariaSnapshot()).replaceAll(code, '{{pairing-code}}'), mode,
)
const approvedDecision = await decideWithDelayedList(owner, approvals, code, 'allow')
await applicant.waitForFunction(() => '__DSH_BOOT__' in window)
expect(applicant.url()).toBe(scaffold.baseUrl)
expect((await applicant.context().cookies()).some(cookie => cookie.name.startsWith('dsh-remote-') && cookie.httpOnly)).toBe(true)
expect((await applicant.reload())?.status()).toBe(200)
await applicant.waitForFunction(() => '__DSH_BOOT__' in window)
await openSettings(applicant, 'zh')
await applicant.getByRole('dialog', { name: '设置', exact: true })
.getByRole('button', { name: '远程连接', exact: true }).click()
const mobileSection = applicant.getByRole('region', { name: '远程连接', exact: true })
const mobileApprovals = mobileSection.getByRole('region', { name: '配对申请', exact: true })
await mobileApprovals.waitFor()
expect(await mobileSection.getByRole('img', { name: '一次性登录二维码', exact: true }).count()).toBe(0)
const third = await browser.newPage({ locale: ZH_BROWSER_LOCALE, viewport: { width: 390, height: 844 } })
third.on('pageerror', error => errors.push(error.message))
expect((await third.goto(scaffold.baseUrl))?.status()).toBe(401)
await third.getByRole('button', { name: '申请配对', exact: true }).click()
await third.locator('#auth-pair-code').waitFor()
const thirdCode = await third.locator('#auth-pair-code').innerText()
await mobileApprovals.getByText(thirdCode, { exact: true }).waitFor()
await expectObservedSource(mobileApprovals, new URL(scaffold.baseUrl).host)
expect(await third.evaluate(() => '__DSH_BOOT__' in window)).toBe(false)
expect((await third.context().cookies()).filter(cookie => /^dsh-(?:auth|remote)-/u.test(cookie.name))).toEqual([])
expect(await applicant.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true)
expect(await third.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true)
if (screenshotDirectory !== undefined) {
await applicant.emulateMedia({ colorScheme: 'light' })
await expect.poll(() => applicant.evaluate(() => getComputedStyle(document.documentElement).colorScheme)).toBe('light')
await applicant.screenshot({ path: join(screenshotDirectory, 'pairing-light.png'), fullPage: true })
await applicant.emulateMedia({ colorScheme: 'dark' })
await expect.poll(() => applicant.evaluate(() => getComputedStyle(document.documentElement).colorScheme)).toBe('dark')
await applicant.screenshot({ path: join(screenshotDirectory, 'pairing-dark.png'), fullPage: true })
await applicant.emulateMedia({ colorScheme: null })
}
await mobileApprovals.getByRole('button', { name: '批准', exact: true }).click()
await third.waitForFunction(() => '__DSH_BOOT__' in window)
expect(third.url()).toBe(scaffold.baseUrl)
expect((await third.context().cookies()).some(cookie => cookie.name.startsWith('dsh-remote-') && cookie.httpOnly)).toBe(true)
expect((await third.reload())?.status()).toBe(200)
await third.waitForFunction(() => '__DSH_BOOT__' in window)
await mobileApprovals.getByText(thirdCode, { exact: true }).waitFor({ state: 'detached' })
expect(await third.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true)
expect(errors).toEqual([])
const denied = await browser.newPage({ locale: ZH_BROWSER_LOCALE })
expect((await denied.goto(scaffold.baseUrl))?.status()).toBe(401)
await denied.locator('#auth-pair-request').click()
await denied.locator('#auth-pair-code').waitFor()
const deniedCode = await denied.locator('#auth-pair-code').innerText()
await approvals.getByText(deniedCode, { exact: true }).waitFor()
const deniedDecision = await decideWithDelayedList(owner, approvals, deniedCode, 'deny')
await compareOrRefreshGolden(
fileURLToPath(new URL('./expected/device-pairing/decision.expected.md', import.meta.url)),
[approvedDecision, deniedDecision].join('\n'), mode,
)
await denied.locator('#auth-pair-panel[data-state="denied"]').waitFor()
expect(await denied.evaluate(() => '__DSH_BOOT__' in window)).toBe(false)
expect((await denied.context().cookies()).filter(cookie => /^dsh-(?:auth|remote)-/u.test(cookie.name))).toEqual([])
await denied.getByRole('button', { name: '重新申请', exact: true }).click()
await denied.locator('#auth-pair-panel[data-state="waiting"]').waitFor()
const cancelledCode = await denied.locator('#auth-pair-code').innerText()
await approvals.getByText(cancelledCode, { exact: true }).waitFor()
await denied.locator('#auth-pair-cancel').click()
await denied.getByRole('button', { name: '申请配对', exact: true }).waitFor()
expect(await denied.locator('#auth-pair-panel').isHidden()).toBe(true)
await approvals.getByText(cancelledCode, { exact: true }).waitFor({ state: 'detached' })
expect((await denied.context().cookies()).filter(cookie => /^dsh-(?:auth|remote)-/u.test(cookie.name))).toEqual([])
expect((await denied.reload())?.status()).toBe(401)
for (const decision of ['allow', 'deny'] as const) {
const unconfirmed = await browser.newPage({ locale: ZH_BROWSER_LOCALE, viewport: { width: 390, height: 844 } })
unconfirmed.on('pageerror', error => errors.push(error.message))
expect((await unconfirmed.goto(scaffold.baseUrl))?.status()).toBe(401)
const creation = unconfirmed.waitForResponse(response => new URL(response.url()).pathname.endsWith('/pairing/request') && response.status() === 200)
await unconfirmed.getByRole('button', { name: '申请配对', exact: true }).click()
await unconfirmed.locator('#auth-pair-code').waitFor()
const unconfirmedCode = await unconfirmed.locator('#auth-pair-code').innerText()
const created = await creation
const ticket: unknown = await created.json()
const submitted: unknown = created.request().postDataJSON()
if (typeof ticket !== 'object' || ticket === null || typeof submitted !== 'object' || submitted === null) {
throw new Error('Pairing creation did not exchange credential records')
}
expect(Reflect.get(ticket, 'id') === Reflect.get(submitted, 'id') && Reflect.get(ticket, 'secret') === Reflect.get(submitted, 'secret')).toBe(true)
expect(Reflect.get(ticket, 'code')).toBe(unconfirmedCode.replace(' ', ''))
const observed = await readPairingCodes(owner, scaffold.baseUrl)
expect(observed.status).toBe(200)
expect(observed.codes).toContain(unconfirmedCode.replace(' ', ''))
try { await approvals.getByText(unconfirmedCode, { exact: true }).waitFor() }
catch (error) {
const current = await readPairingCodes(owner, scaffold.baseUrl)
console.info('pairing approval list before dropped decision', { decision, code: unconfirmedCode, ...current, content: await approvals.innerText(), errors })
throw error
}
expect((await unconfirmed.context().cookies()).filter(cookie => /^dsh-(?:auth|remote)-/u.test(cookie.name))).toEqual([])
const decisionDropped = Promise.withResolvers<undefined>()
const routeErrors: unknown[] = []
let committedResponse: unknown
await owner.route('**/api/remoteConnection/decidePairing', async (route) => {
try {
const response = await route.fetch()
committedResponse = await response.json()
expect(response.status()).toBe(200)
} catch (error) {
routeErrors.push(error)
} finally {
try { await route.abort('failed') } catch (error) { routeErrors.push(error) }
decisionDropped.resolve(undefined)
}
})
try {
await approvals.getByRole('button', { name: decision === 'allow' ? '批准' : '拒绝', exact: true }).click()
await decisionDropped.promise
expect(routeErrors).toEqual([])
expect(committedResponse).toMatchObject({ result: { ok: true, value: decision === 'allow' ? 'approved' : 'denied' } })
await owner.getByRole('alert').filter({ hasText: '无法确认审批结果,请刷新列表后再试' }).waitFor()
expect(await owner.getByRole('alert').filter({ hasText: '已批准申请' }).count()).toBe(0)
expect(await owner.getByRole('alert').filter({ hasText: '已拒绝申请' }).count()).toBe(0)
if (decision === 'allow') {
await unconfirmed.waitForFunction(() => '__DSH_BOOT__' in window)
expect(unconfirmed.url()).toBe(scaffold.baseUrl)
expect((await unconfirmed.context().cookies()).some(cookie => cookie.name.startsWith('dsh-remote-') && cookie.httpOnly)).toBe(true)
expect((await unconfirmed.reload())?.status()).toBe(200)
await unconfirmed.waitForFunction(() => '__DSH_BOOT__' in window)
} else {
await unconfirmed.locator('#auth-pair-panel[data-state="denied"]').waitFor()
expect(await unconfirmed.evaluate(() => '__DSH_BOOT__' in window)).toBe(false)
expect((await unconfirmed.context().cookies()).filter(cookie => /^dsh-(?:auth|remote)-/u.test(cookie.name))).toEqual([])
expect((await unconfirmed.reload())?.status()).toBe(401)
}
await approvals.getByText(unconfirmedCode, { exact: true }).waitFor({ state: 'detached' })
} finally {
await owner.unrouteAll({ behavior: 'wait' })
expect(routeErrors).toEqual([])
}
}
expect(errors).toEqual([])
} finally {
await browser.close()
}
})
it('keeps one Remote connection panel, its QR invitation, and login link while another browser requests approval', async () => {
const fixture = await launchRemoteConnectionFixture(false)
onTestFinished(() => fixture.close())
const browser = await chromium.launch({
proxy: { server: 'http://127.0.0.1:9', bypass: '*' },
args: ['--host-resolver-rules=MAP qr-login.test 127.0.0.1'],
})
try {
const owner = await browser.newPage({ locale: ZH_BROWSER_LOCALE, viewport: { width: 1440, height: 1000 } })
await owner.goto(fixture.authenticatedUrl)
await openSettings(owner, 'zh')
const navigation = owner.getByRole('dialog', { name: '设置', exact: true })
.getByRole('button', { name: '远程连接', exact: true })
await expect.poll(() => navigation.count()).toBe(1)
await navigation.click()
const section = owner.getByRole('region', { name: '远程连接', exact: true })
const loginLink = section.getByRole('region', { name: '访问地址', exact: true }).locator('code')
await expect.poll(() => loginLink.innerText()).toBe(fixture.authenticatedUrl)
const approvals = section.getByRole('region', { name: '配对申请', exact: true })
await approvals.waitFor()
const created = owner.waitForResponse(response => new URL(response.url()).pathname === '/api/remoteConnection/create')
await section.getByRole('button', { name: '生成二维码', exact: true }).click()
const invitation = await (await created).json() as { result: { ok: boolean; value: { url: string } } }
expect(invitation.result.ok).toBe(true)
const qr = section.getByRole('img', { name: '一次性登录二维码', exact: true })
await qr.waitFor()
const qrMarkup = await qr.innerHTML()
const applicant = await browser.newPage({
locale: ZH_BROWSER_LOCALE, viewport: { width: 390, height: 844 }, extraHTTPHeaders: spoofedSourceHeaders,
})
expect((await applicant.goto(fixture.url))?.status()).toBe(401)
await applicant.getByRole('button', { name: '申请配对', exact: true }).click()
await applicant.locator('#auth-pair-code').waitFor()
const previousCode = await applicant.locator('#auth-pair-code').innerText()
await approvals.getByText(previousCode, { exact: true }).waitFor()
const countdown = applicant.locator('#auth-pair-countdown')
const initialCountdown = await countdown.innerText()
await expect.poll(() => countdown.innerText()).not.toBe(initialCountdown)
const pairingListUrl = new URL('api/remoteConnection/pairingRequests', fixture.url).href
await owner.route(pairingListUrl, route => route.fulfill({ status: 503 }))
const readFailure = approvals.getByRole('alert')
await readFailure.waitFor()
expect(await approvals.getByText(previousCode, { exact: true }).count()).toBe(0)
expect(await approvals.getByRole('note').count()).toBe(0)
expect(await approvals.getByRole('status').count()).toBe(0)
const retry = approvals.getByRole('button', { name: '重试', exact: true })
expect(await retry.isEnabled()).toBe(true)
await compareOrRefreshGolden(
fileURLToPath(new URL('./expected/device-pairing/approval-refresh-failed.expected.md', import.meta.url)),
await approvals.ariaSnapshot(), webSnapshotMode(),
)
const [replacementResponse] = await Promise.all([
applicant.waitForResponse(response => new URL(response.url()).pathname.endsWith('/pairing/request')),
applicant.getByRole('button', { name: '重新申请', exact: true }).click(),
])
await applicant.locator('#auth-pair-panel[data-state="waiting"]').waitFor()
await expect.poll(() => applicant.locator('#auth-pair-code').innerText()).not.toBe(previousCode)
const code = await applicant.locator('#auth-pair-code').innerText()
await owner.unroute(pairingListUrl)
await retry.click()
await approvals.getByText(code, { exact: true }).waitFor()
expect(await approvals.getByText(previousCode, { exact: true }).count()).toBe(0)
expect(await readFailure.count()).toBe(0)
await approvals.getByRole('note').waitFor()
expect(await replacementResponse.request().allHeaders()).toMatchObject(spoofedSourceHeaders)
const ticket: unknown = await replacementResponse.json()
expect(ticket).toMatchObject({ code: code.replace(' ', ''), sourceIp: '127.0.0.1', authority: new URL(fixture.url).origin })
await expectObservedSource(approvals, new URL(fixture.url).host)
expect(await qr.innerHTML()).toBe(qrMarkup)
expect(await section.getByRole('button', { name: '重新生成', exact: true }).isEnabled()).toBe(true)
expect(await section.getByRole('button', { name: '取消', exact: true }).isEnabled()).toBe(true)
expect(await navigation.count()).toBe(1)
expect(await approvals.getByRole('button').allTextContents()).toEqual(['批准', '拒绝'])
for (const width of [1440, 390]) {
await owner.setViewportSize({ width, height: 1000 })
await approvals.scrollIntoViewIfNeeded()
const codeBounds = (await approvals.locator('code').boundingBox())!
const sourceIp = (await approvals.getByText('127.0.0.1', { exact: true }).boundingBox())!
const approve = (await approvals.getByRole('button', { name: '批准', exact: true }).boundingBox())!
const deny = (await approvals.getByRole('button', { name: '拒绝', exact: true }).boundingBox())!
expect(approve.height).toBe(28)
expect(deny.height).toBe(28)
if (width === 1440) {
expect(approve.x).toBeGreaterThan(codeBounds.x + codeBounds.width)
expect(deny.x).toBeGreaterThan(approve.x + approve.width)
expect(approve.y).toBe(deny.y)
const informationCenter = (codeBounds.y + sourceIp.y + sourceIp.height) / 2
expect(Math.abs(informationCenter - approve.y - approve.height / 2)).toBeLessThanOrEqual(1)
} else {
expect(approve.y).toBeGreaterThanOrEqual(sourceIp.y + sourceIp.height)
expect(deny.y).toBeGreaterThanOrEqual(approve.y + approve.height)
expect(approve.x).toBe(deny.x)
expect(approve.width).toBe(deny.width)
}
}
await owner.setViewportSize({ width: 1440, height: 1000 })
await compareOrRefreshGolden(
fileURLToPath(new URL('./expected/device-pairing/coexistence.expected.md', import.meta.url)),
(await captureStableAria(owner, 'section[aria-label="远程连接"]', fixture.root, {
replacements: [[fixture.authenticatedUrl, '{{access-address}}?token={{login-token}}'], [fixture.url, '{{access-address}}'], [code, '{{pairing-code}}']],
})).replace(/\d+ 秒后过期/gu, '{{seconds}} 秒后过期'), webSnapshotMode(),
)
await approvals.getByRole('button', { name: '批准', exact: true }).click()
await applicant.waitForFunction(() => '__DSH_BOOT__' in window)
expect(applicant.url()).toBe(fixture.url)
expect((await applicant.context().cookies()).some(cookie => cookie.name.startsWith('dsh-remote-') && cookie.httpOnly)).toBe(true)
expect(await qr.innerHTML()).toBe(qrMarkup)
expect(await loginLink.innerText()).toBe(fixture.authenticatedUrl)
const scanning = await browser.newPage({ locale: ZH_BROWSER_LOCALE, viewport: { width: 390, height: 844 } })
const exchanged = scanning.waitForResponse(response => new URL(response.url()).pathname === '/' && new URL(response.url()).searchParams.get('login') === 'qr'
&& response.request().method() === 'POST')
await scanning.goto(invitation.result.value.url)
expect((await exchanged).status()).toBe(204)
await scanning.waitForFunction(() => '__DSH_BOOT__' in window)
expect(scanning.url()).toBe(fixture.url)
expect((await scanning.context().cookies()).some(cookie => cookie.name.startsWith('dsh-remote-') && cookie.httpOnly)).toBe(true)
await section.getByText('二维码已使用,请在手机上确认是否已登录', { exact: true }).waitFor()
expect(await navigation.count()).toBe(1)
} finally { await browser.close() }
})
it('shows expiry and lets the applicant start a new request without signing in', async () => {
const root = await mkdtemp(join(tmpdir(), 'dsh-pairing-expiry-'))
onTestFinished(() => rm(root, { recursive: true, force: true }))
const overlay = join(root, 'pairing.yml')
await writeFile(overlay, '- id: remote-connection\n config:\n pairing:\n requestTtlMs: 3000\n pollIntervalMs: 500\n')
const scaffold = await launchWebScaffold({
extraOverlayPath: [fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), overlay],
})
onTestFinished(() => scaffold.close())
const browser = await chromium.launch()
try {
const applicant = await browser.newPage({ locale: ZH_BROWSER_LOCALE, viewport: { width: 390, height: 844 } })
expect((await applicant.goto(scaffold.baseUrl))?.status()).toBe(401)
await applicant.getByRole('button', { name: '申请配对', exact: true }).click()
await applicant.locator('#auth-pair-code').waitFor()
const expiredCode = await applicant.locator('#auth-pair-code').innerText()
await applicant.locator('#auth-pair-panel[data-state="expired"]').waitFor()
expect(await applicant.evaluate(() => '__DSH_BOOT__' in window)).toBe(false)
expect((await applicant.context().cookies()).filter(cookie => /^dsh-(?:auth|remote)-/u.test(cookie.name))).toEqual([])
await applicant.getByRole('button', { name: '重新申请', exact: true }).click()
await applicant.locator('#auth-pair-code').waitFor()
expect(await applicant.locator('#auth-pair-code').innerText()).not.toBe(expiredCode)
await applicant.locator('#auth-pair-cancel').click()
await applicant.getByRole('button', { name: '申请配对', exact: true }).waitFor()
expect(await applicant.locator('#auth-pair-panel').isHidden()).toBe(true)
} finally { await browser.close() }
})
it('keeps Token and pairing usable on the same page after a QR exchange fails', async () => {
const fixture = await launchRemoteConnectionFixture(false)
onTestFinished(() => fixture.close())
const browser = await chromium.launch({
proxy: { server: 'http://127.0.0.1:9', bypass: '*' },
args: ['--host-resolver-rules=MAP qr-login.test 127.0.0.1'],
})
try {
const applicant = await browser.newPage({ locale: ZH_BROWSER_LOCALE, viewport: { width: 390, height: 844 } })
const errors: string[] = []
applicant.on('pageerror', error => errors.push(error.message))
const target = new URL(fixture.url)
target.searchParams.set('login', 'qr')
target.hash = 'a'.repeat(43)
const exchanged = applicant.waitForResponse(response => response.request().method() === 'POST'
&& new URL(response.url()).pathname === '/' && new URL(response.url()).searchParams.get('login') === 'qr')
expect((await applicant.goto(target.href))?.status()).toBe(200)
expect((await exchanged).status()).toBe(410)
const failure = applicant.getByRole('alert').filter({ hasText: '二维码' })
await failure.waitFor()
expect(new URL(applicant.url()).hash).toBe('')
expect(await applicant.evaluate(() => '__DSH_BOOT__' in window)).toBe(false)
const token = applicant.locator('#token')
expect(await token.isEnabled()).toBe(true)
expect(await applicant.locator('#token-submit').isEnabled()).toBe(true)
expect(await applicant.getByRole('button', { name: '申请配对', exact: true }).isEnabled()).toBe(true)
const screenshotDirectory = process.env.DSH_PAIRING_SCREENSHOT_DIR
if (screenshotDirectory !== undefined) await mkdir(screenshotDirectory, { recursive: true })
for (const scene of [
{ name: 'mobile-light', width: 390, height: 844, colorScheme: 'light' },
{ name: 'mobile-dark', width: 390, height: 844, colorScheme: 'dark' },
{ name: 'desktop-light', width: 1440, height: 1000, colorScheme: 'light' },
] as const) {
await applicant.setViewportSize({ width: scene.width, height: scene.height })
await applicant.emulateMedia({ colorScheme: scene.colorScheme })
const layout = await applicant.evaluate(() => {
const form = document.querySelector<HTMLElement>('#token-form')!
const pairing = document.querySelector<HTMLElement>('dsh-device-pairing')!
const notice = document.querySelector<HTMLElement>('#qr-notice')!
const title = document.querySelector<HTMLElement>('#title')!
const formBox = form.getBoundingClientRect()
const pairBox = pairing.getBoundingClientRect()
return {
sameContainer: form.parentElement === pairing.parentElement,
feedbackOutside: notice.parentElement === form.parentElement?.parentElement,
headingAbove: title.getBoundingClientRect().bottom <= notice.getBoundingClientRect().top,
feedbackAbove: notice.getBoundingClientRect().bottom <= formBox.top,
gap: pairBox.top - formBox.bottom,
xDifference: pairBox.x - formBox.x,
widthDifference: pairBox.width - formBox.width,
borders: [form, pairing].map(card => Number.parseFloat(getComputedStyle(card).borderTopWidth)),
parentBorder: Number.parseFloat(getComputedStyle(form.parentElement!).borderTopWidth),
overflows: document.documentElement.scrollWidth > innerWidth,
}
})
expect(layout).toMatchObject({
sameContainer: true, feedbackOutside: true, headingAbove: true, feedbackAbove: true, overflows: false,
})
expect(Math.abs(layout.gap - 24)).toBeLessThanOrEqual(1)
expect(Math.abs(layout.xDifference)).toBeLessThanOrEqual(1)
expect(Math.abs(layout.widthDifference)).toBeLessThanOrEqual(1)
expect(layout.borders.every(border => border > 0)).toBe(true)
expect(layout.parentBorder).toBe(0)
if (screenshotDirectory !== undefined) {
await applicant.screenshot({
path: join(screenshotDirectory, `qr-rejected-options-${scene.name}.png`), fullPage: true,
})
}
}
await applicant.setViewportSize({ width: 390, height: 844 })
await applicant.getByRole('button', { name: '申请配对', exact: true }).click()
await applicant.locator('#auth-pair-code').waitFor()
expect(await applicant.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true)
if (screenshotDirectory !== undefined) {
for (const colorScheme of ['light', 'dark'] as const) {
await applicant.emulateMedia({ colorScheme })
await applicant.screenshot({
path: join(screenshotDirectory, `pairing-waiting-mobile-${colorScheme}.png`), fullPage: true,
})
}
}
expect(await token.isEnabled()).toBe(true)
const launchToken = new URL(fixture.authenticatedUrl).searchParams.get('token')
if (launchToken === null) throw new Error('Token entry did not publish a startup credential')
await token.fill(launchToken)
await applicant.locator('#token-submit').click()
await applicant.waitForFunction(() => '__DSH_BOOT__' in window)
expect(applicant.url()).toBe(fixture.url)
expect((await applicant.context().cookies()).some(cookie => cookie.name.startsWith('dsh-auth-') && cookie.httpOnly)).toBe(true)
expect(errors).toEqual([])
} finally {
await browser.close()
}
})
+153
View File
@@ -0,0 +1,153 @@
// DingTalk sign-in failures, recovery, and sign-out through the real Host/Remote/browser composition.
// A stand-in dws waits for each authorization page visit and keeps its sign-in on disk.
import { chmod, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import type { Browser, BrowserContext, Page } from 'playwright'
import { chromium } from 'playwright'
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
import { launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts'
import { ZH_BROWSER_LOCALE, saveFailureShot } from './support.ts'
const DINGTALK_DIR = fileURLToPath(new URL('../../../packages/connector/dingtalk', import.meta.url))
const AUTH_PAGE = 'https://login.dingtalk.com/oauth2/auth'
const authUrl = (attempt: number) => `${AUTH_PAGE}?e2e=${String(attempt)}&state=fixture-state`
// The stand-in keeps its sign-in in state.json beside itself. auth login prints a
// new authorization link alone on an indented stderr line for each attempt and
// waits until the test marks the page visited; its second successful sign-in
// makes a second organization's account current, as the stand-in's own rule;
// auth logout accepts only the current account's profile.
const DWS = `#!/usr/bin/env node
const { existsSync, readFileSync, writeFileSync } = require('node:fs')
const { join } = require('node:path')
const dir = __dirname
const statePath = join(dir, 'state.json')
const state = existsSync(statePath) ? JSON.parse(readFileSync(statePath, 'utf8')) : { signedIn: false, attempts: 0, logins: 0 }
const ACCOUNTS = [
{ corp_id: 'corp-e2e', corp_name: 'E2E 组织', user_id: 'user-e2e', user_name: 'E2E 用户' },
{ corp_id: 'corp-e2e-2', corp_name: '第二个 E2E 组织', user_id: 'user-e2e-2', user_name: '第二个 E2E 用户' },
]
const current = () => ACCOUNTS[Math.min(state.logins, ACCOUNTS.length) - 1]
const save = () => { writeFileSync(statePath, JSON.stringify(state)) }
const json = (value) => JSON.stringify(value, null, 2) + '\\n'
switch (process.argv.slice(2).join(' ')) {
case 'auth status --format json':
process.stdout.write(json(state.signedIn
? { success: true, authenticated: true, ...current() }
: { success: true, authenticated: false, message: '未登录' }))
break
case 'auth login --no-browser --format json': {
state.attempts += 1
save()
process.stderr.write('\\n🔐 登录钉钉\\n\\n请在浏览器中完成扫码授权。\\n如果浏览器未自动打开,请手动访问:\\n ${AUTH_PAGE}?e2e=' + state.attempts + '&state=fixture-state\\n\\n⏳ 等待授权中...\\n')
const poll = setInterval(() => {
if (!existsSync(join(dir, 'auth-visited'))) return
clearInterval(poll)
if (existsSync(join(dir, 'login-fails'))) {
process.stderr.write(json({ error: { category: 'auth', message: 'dingtalk login failed; state=fixture-state' } }))
process.exitCode = 2
} else {
state.signedIn = true
state.logins += 1
save()
process.stdout.write(json({ success: true, message: '登录成功' }))
}
}, 50)
break
}
case state.signedIn ? 'auth logout --profile ' + current().corp_id + ':' + current().user_id : 'auth logout':
state.signedIn = false
save()
process.stdout.write('[OK] 已清除认证信息\\n')
break
default:
process.stderr.write('unexpected dws arguments: ' + process.argv.slice(2).join(' ') + '\\n')
process.exitCode = 1
}
`
// The stand-in runs through its shebang, which Windows cannot execute.
describe.skipIf(process.platform === 'win32')('web e2e: DingTalk plugin account', () => {
let binDir: string
let scaffold: WebScaffold
let browser: Browser
let context: BrowserContext
let page: Page
let tripwire: ReturnType<typeof watchConsole>
beforeAll(async () => {
binDir = await mkdtemp(join(tmpdir(), 'dsh-dingtalk-e2e-'))
await writeFile(join(binDir, 'dws'), DWS)
await chmod(join(binDir, 'dws'), 0o755)
// Stand-in skills keep the row from downloading the release's skills archive.
const skillsDir = join(binDir, 'skills')
await mkdir(join(skillsDir, 'dingtalk-shared'), { recursive: true })
await writeFile(join(skillsDir, 'dingtalk-shared', 'SKILL.md'), '# DingTalk stand-in guide\n')
const overlay = join(binDir, 'dingtalk.overlay.yml')
await writeFile(overlay, `- id: dingtalk\n config:\n binDir: ${JSON.stringify(binDir)}\n skillsDir: ${JSON.stringify(skillsDir)}\n`)
scaffold = await launchWebScaffold({
extraOverlayPath: [fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), overlay],
profile: { packages: [{ dir: DINGTALK_DIR, enabled: true }] },
})
browser = await chromium.launch()
context = await browser.newContext({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
await context.route(url => url.href.startsWith(AUTH_PAGE), async (route) => {
await writeFile(join(binDir, 'auth-visited'), '')
await route.fulfill({ contentType: 'text/html; charset=utf-8', body: '<!doctype html><title>DingTalk</title><p>DingTalk stand-in page</p>' })
})
page = await context.newPage()
tripwire = watchConsole(page)
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
}, 120_000)
afterAll(async () => {
await browser?.close()
await scaffold?.close()
if (binDir !== undefined) await rm(binDir, { recursive: true, force: true })
})
it('reports a failed sign-in without its output, connects on retry, signs in to another organization, and signs out after confirmation', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-dingtalk-connection'))
await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click()
const panel = page.locator('[data-plugin-panel]')
await panel.getByRole('button', { name: '查看 钉钉插件', exact: true }).click({ timeout: 20_000 })
const section = panel.locator('[data-connector-account-key="@deepseek-ai/dsh-dingtalk"]')
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected')
expect(await panel.locator('[data-plugin-detail]').getByText('未连接', { exact: true }).count()).toBe(2)
const opened: Page[] = []
context.on('page', (popup) => { opened.push(popup) })
await writeFile(join(binDir, 'login-fails'), '')
await section.getByRole('button', { name: '连接钉钉', exact: true }).click()
await section.getByRole('alert').waitFor({ timeout: 20_000 })
expect(await section.getAttribute('data-connector-account')).toBe('disconnected')
expect(await section.getByRole('alert').innerText()).toContain('auth-login · exit 2')
expect(await section.innerText()).not.toContain('fixture-state')
await rm(join(binDir, 'login-fails'))
await rm(join(binDir, 'auth-visited'))
await section.getByRole('button', { name: '连接钉钉', exact: true }).click()
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('connected')
expect(opened.map(popup => popup.url())).toEqual([authUrl(1), authUrl(2)])
await section.getByText('已登录为 E2E 组织 的 E2E 用户。可以在对话中直接请 Agent 使用钉钉。', { exact: true }).waitFor({ timeout: 10_000 })
await page.getByText('钉钉已连接', { exact: true }).waitFor({ timeout: 10_000 })
// Signing in again while connected adds another organization's account; the section shows the account dws then reports.
await rm(join(binDir, 'auth-visited'))
await section.getByRole('button', { name: '登录其他组织', exact: true }).click()
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('connecting')
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('connected')
expect(opened.map(popup => popup.url())).toEqual([authUrl(1), authUrl(2), authUrl(3)])
await section.getByText('已登录为 第二个 E2E 组织 的 第二个 E2E 用户。可以在对话中直接请 Agent 使用钉钉。', { exact: true }).waitFor({ timeout: 10_000 })
await section.getByRole('button', { name: '退出登录', exact: true }).click()
const dialog = page.getByRole('dialog', { name: '退出钉钉登录?' })
await dialog.getByRole('button', { name: '退出登录', exact: true }).click()
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected')
await page.getByText('已退出钉钉登录', { exact: true }).waitFor({ timeout: 10_000 })
expect(tripwire.pageErrors).toEqual([])
})
})
+2 -2
View File
@@ -1061,7 +1061,7 @@ else process.exit(1);
sections.push('## PDF drag selection\n\n- Table selection: forward and backward drags exclude later sections\n- Line-break highlight: transparent\n- Text selection: translucent blue in light and dark themes; canvas text remains visible\n- Mouse release preserves the selected text')
const pngResponse = page.waitForResponse(response => new URL(response.url()).pathname === '/api/workspaceFiles/readBytes'
&& (response.request().postDataJSON() as { payload: { args: { path: string } } }).payload.args.path === 'tiny.png')
&& (response.request().postDataJSON() as { payload: { args: { path: string } } }).payload.args.path.endsWith('/tiny.png'))
await openFile('tiny.png')
const transferred = await pngResponse
expect(transferred.headers()['content-type']).toMatch(/^multipart\/form-data;/)
@@ -1214,7 +1214,7 @@ else process.exit(1);
let waitingForRead = false
const readPage = scaffold.ctx.workspaceFiles.read.bind(scaffold.ctx.workspaceFiles)
const heldRead = vi.spyOn(scaffold.ctx.workspaceFiles, 'read').mockImplementation(async (agent, path, range, signal) => {
if (path === 'pages.ts' && (range.offset ?? 1) === 1) {
if (path.endsWith('/pages.ts') && (range.offset ?? 1) === 1) {
waitingForRead = true
await releaseRead.promise
}
@@ -5,6 +5,7 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- heading "Agent 预设" [level=2]
@@ -5,16 +5,17 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
- paragraph: 填入各提供商的 API 密钥即可使用其模型。
- list:
- listitem:
- text: DeepSeek
- text: DeepSeek API
- img "API 密钥已配置"
- button "编辑 DeepSeek (deepseek-official)": 编辑
- text: DeepSeek deepseek-official API 密钥
- button "编辑 DeepSeek API (deepseek-official)": 编辑
- text: DeepSeek API deepseek-official API 密钥
- button "认证说明": "?"
- textbox "API 密钥":
- /placeholder: sk-messa••••••••••ding
@@ -5,16 +5,17 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
- paragraph: 填入各提供商的 API 密钥即可使用其模型。
- list:
- listitem:
- text: DeepSeek
- text: DeepSeek API
- img "API 密钥已配置"
- button "编辑 DeepSeek (deepseek-official)": 编辑
- text: DeepSeek deepseek-official API 密钥
- button "编辑 DeepSeek API (deepseek-official)": 编辑
- text: DeepSeek API deepseek-official API 密钥
- button "认证说明": "?"
- textbox "API 密钥":
- /placeholder: 留空使用环境认证(DEEPSEEK_API_KEY)
@@ -1,6 +1,6 @@
- group "模型与推理等级":
- menu "模型":
- group "DeepSeek":
- text: DeepSeek
- group "DeepSeek API":
- text: DeepSeek API
- menuitemradio "Messages Flash" [checked]
- menuitemradio "DeepSeek-V4-Pro"
@@ -5,6 +5,7 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- text: 权限 选择新会话的默认权限模式
@@ -5,6 +5,7 @@
- button "Models"
- button "Plugins"
- button "Agent presets"
- button "Remote connection"
- button "Open configuration file"
- button "Close"
- text: Permission Choose the default permission mode for new sessions
@@ -0,0 +1,5 @@
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
- alert: 无法加载申请,请重试以刷新列表
- button "重试"
@@ -0,0 +1,10 @@
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
- note:
- paragraph: 批准后,该浏览器将获得此应用的完整访问权限,也可以批准其他设备
- text: 配对码
- code: {{pairing-code}}
- paragraph: 来源 IP 127.0.0.1
- button "批准"
- button "拒绝"
@@ -0,0 +1,27 @@
- region "远程连接":
- heading "远程连接" [level=2]
- paragraph: 通过以下方式,在其他设备上登录并使用 DeepSeek Harness。
- region "访问地址":
- heading "访问地址" [level=3]
- code: {{access-address}}?token={{login-token}}
- button "复制链接"
- region "二维码登录":
- heading "二维码登录" [level=3]
- button "重新生成"
- button "取消"
- img "一次性登录二维码"
- paragraph:
- timer: {{seconds}} 秒后过期
- paragraph: 请勿分享登录二维码
- paragraph: 二维码使用或过期前,持有它的人都可以登录,请勿传播
- paragraph: HTTP 会明文传输登录凭据,请仅在可信网络中使用
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
- note:
- paragraph: 批准后,该浏览器将获得此应用的完整访问权限,也可以批准其他设备
- text: 配对码
- code: {{pairing-code}}
- paragraph: 来源 IP 127.0.0.1
- button "批准"
- button "拒绝"
@@ -0,0 +1,16 @@
- main:
- region "连接到此 Host":
- heading "连接到此 Host" [level=1]
- paragraph: 请用以下任意方式验证登录
- form "输入登录令牌或链接":
- heading "输入登录令牌或链接" [level=2]
- paragraph: 在已登录设备的「设置 → 远程连接」中复制链接,粘贴到此处
- textbox "输入登录令牌或链接":
- /placeholder: {{application-url}}?token=xxx
- button "继续"
- region "配对此设备":
- heading "配对此设备" [level=2]
- paragraph: 申请后,在另一台已登录设备的“设置 → 远程连接”核对配对码并批准,此设备将自动登录。
- code: {{pairing-code}}
- button "重新申请" [disabled]
- status: 正在确认登录状态…
@@ -0,0 +1,8 @@
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
- alert: 已批准申请
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
- alert: 已拒绝申请
@@ -0,0 +1,16 @@
- main:
- region "Connect to this Host":
- heading "Connect to this Host" [level=1]
- paragraph: Use one of the methods below to sign in.
- form "Enter a login token or link":
- heading "Enter a login token or link" [level=2]
- paragraph: On a signed-in device, copy the link from Settings → Remote connection and paste it here.
- textbox "Enter a login token or link":
- /placeholder: {{application-url}}?token=xxx
- button "Continue"
- region "Pair this device":
- heading "Pair this device" [level=2]
- paragraph: After requesting, open Settings → Remote connection on another signed-in device. Match the pairing code and approve to sign in here automatically.
- code: {{pairing-code}}
- button "Request again"
- alert: Could not complete pairing. Check your connection, then request again.
@@ -0,0 +1,16 @@
- main:
- region "连接到此 Host":
- heading "连接到此 Host" [level=1]
- paragraph: 请用以下任意方式验证登录
- form "输入登录令牌或链接":
- heading "输入登录令牌或链接" [level=2]
- paragraph: 在已登录设备的「设置 → 远程连接」中复制链接,粘贴到此处
- textbox "输入登录令牌或链接":
- /placeholder: {{application-url}}?token=xxx
- button "继续"
- region "配对此设备":
- heading "配对此设备" [level=2]
- paragraph: 申请后,在另一台已登录设备的“设置 → 远程连接”核对配对码并批准,此设备将自动登录。
- code: {{pairing-code}}
- button "重新申请"
- alert: 无法完成配对,请检查网络后重新申请
@@ -0,0 +1,18 @@
- main:
- region "连接到此 Host":
- heading "连接到此 Host" [level=1]
- paragraph: 请用以下任意方式验证登录
- form "输入登录令牌或链接":
- heading "输入登录令牌或链接" [level=2]
- paragraph: 在已登录设备的「设置 → 远程连接」中复制链接,粘贴到此处
- textbox "输入登录令牌或链接":
- /placeholder: {{application-url}}?token=xxx
- button "继续"
- region "配对此设备":
- heading "配对此设备" [level=2]
- paragraph: 申请后,在另一台已登录设备的“设置 → 远程连接”核对配对码并批准,此设备将自动登录。
- code: {{pairing-code}}
- button "重新申请"
- button "取消申请"
- status: 正在等待批准…
- timer: 剩余时间:{{remaining}}
@@ -1,4 +1,3 @@
- textbox "搜索分支"
- group "默认":
- menuitem "origin/main 默认"
- group "本地分支":
@@ -5,6 +5,7 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
@@ -5,6 +5,7 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
@@ -5,6 +5,7 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
@@ -5,6 +5,7 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
@@ -5,6 +5,7 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
@@ -5,6 +5,7 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
@@ -5,6 +5,7 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
@@ -5,6 +5,7 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
@@ -5,6 +5,7 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
@@ -5,6 +5,7 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
@@ -5,6 +5,7 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
@@ -5,16 +5,17 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
- paragraph: 填入各提供商的 API 密钥即可使用其模型。
- list:
- listitem:
- text: DeepSeek
- text: DeepSeek API
- img "API 密钥已配置"
- button "编辑 DeepSeek (deepseek-official)": 编辑
- text: DeepSeek deepseek-official API 密钥
- button "编辑 DeepSeek API (deepseek-official)": 编辑
- text: DeepSeek API deepseek-official API 密钥
- button "认证说明": "?"
- textbox "API 密钥":
- /placeholder: dsh_onboa•••••••••••••••••••••••••••••••test
@@ -5,16 +5,17 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
- paragraph: 填入各提供商的 API 密钥即可使用其模型。
- list:
- listitem:
- text: DeepSeek
- text: DeepSeek API
- img "API 密钥已配置"
- button "编辑 DeepSeek (deepseek-official)": 编辑
- text: DeepSeek deepseek-official API 密钥
- button "编辑 DeepSeek API (deepseek-official)": 编辑
- text: DeepSeek API deepseek-official API 密钥
- button "认证说明": "?"
- textbox "API 密钥":
- /placeholder: dsh_onboa•••••••••••••••••••••••••••••••test
@@ -5,13 +5,14 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
- paragraph: 填入各提供商的 API 密钥即可使用其模型。
- list:
- listitem:
- text: DeepSeek deepseek-official API 密钥
- text: DeepSeek API deepseek-official API 密钥
- button "认证说明": "?"
- textbox "API 密钥":
- /placeholder: 留空使用环境认证(DEEPSEEK_API_KEY)
Loaded 100 of 1822 files, more files were not shown because too many files have changed in this diff. Show more