Merge remote-tracking branch 'origin/master' into feat/cli-account

This commit is contained in:
gengruilin committed 2026-10-27 19:43:29 +08:00
commit ea28b3ab35
53 files changed
+979 -143

No files matched your search

@@ -13,6 +13,8 @@ Keep recoverable session facts in Projection and expose them through their ownin
2. Do not expose projection definitions or handles as production read APIs. Keep the ready handle private; consumers use the owning service's domain methods. A handle is a process-local reader, recreated during activation. Require `sessionProjections` when the service depends on it; optional registration is only for optional contributions. Do not hide a missing required dependency with another recovery path.
A runtime that needs several projected states receives one typed object of callbacks created with `handle.readerFor(session)`. Add properties instead of a constructor parameter or feature-specific reader for each state. Each callback has type `() => S`; single-purpose collaborators receive it directly. These host-state readers are separate from wire snapshots and live Cordis Context; they own no registration, disposal, cache or I/O. Registration, Session preparation and handle lifetimes stay with their owners. Rule 9 defines synchronous API compatibility.
3. State recovery through `init` and `apply` is synchronous and deterministic. Do not perform I/O or trigger Cordis hooks, models, or tools. Runtime hooks own those effects. Replay must not repeat them. Return the same state reference for unrelated events. Keep views synchronous and preserve their references when visible values do not change.
4. Persist JSON state that its schema accepts. Follow the README's state-version and checkpoint-watermark rules. Restoring a checkpoint and replaying its suffix must match full replay. Change the version when state fields or recovery semantics change.
@@ -0,0 +1,92 @@
/** A multi-select question opens with every option marked as recommended already chosen, wherever it sits in the list. */
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { chromium, type Browser, type Page } from 'playwright'
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
import type { SessionEvent } from '@deepseek-ai/dsh-session'
import {
assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts,
launchWebScaffold, recordFixture, watchConsole, webSnapshotMode, type WebScaffold,
} from './scaffold.ts'
import {
connectFreshWorkspace, newEnglishPage, pinBrowserClock, pinHostClock, saveFailureShot,
} from './support.ts'
const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/question-composer-recommended', import.meta.url))
const FIXTURE = join(SNAPSHOT_DIR, 'session.v4.jsonl')
const UI_EXPECTED = join(SNAPSHOT_DIR, 'ui.expected.md')
const MODE = webSnapshotMode()
const PROMPT = 'Use the ask_user_question tool to ask me exactly one multi-select question with id "checks", question "Which checks should run before merging?", header "Checks", and three options in this order: label "Unit tests (Recommended)", label "Full e2e suite", and label "Type check (Recommended)". Set multi_select to true. After I answer, reply with the single word DONE and stop.'
describe('web e2e: recommended multi-select options', () => {
let scaffold: WebScaffold
let browser: Browser
let page: Page
let tripwire: ReturnType<typeof watchConsole>
const sessionEvents: SessionEvent[] = []
let hostClock: ReturnType<typeof pinHostClock> | undefined
beforeAll(async () => {
if (MODE !== 'record') hostClock = pinHostClock()
scaffold = await launchWebScaffold(MODE === 'record' ? {} : { replayFixture: FIXTURE, paceMs: 15, compareReplaySession: true })
scaffold.ctx.on('session/event', (_session, event: SessionEvent) => { sessionEvents.push(event) })
browser = await chromium.launch()
page = await newEnglishPage(browser)
if (MODE !== 'record') await pinBrowserClock(page)
tripwire = watchConsole(page)
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
await connectFreshWorkspace(page, scaffold.workspaceCwd)
}, 120_000)
afterAll(async () => {
try {
await browser?.close()
} finally {
try { await scaffold?.close() }
finally { hostClock?.mockRestore() }
}
})
it('preselects every recommended option and submits them unchanged', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-question-recommended'))
if (MODE !== 'record') {
expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT])
}
const input = page.locator('[data-composer-input]').first()
await input.waitFor({ timeout: 10_000 })
const settled = scaffold.whenTurnSettled(MODE === 'record' ? 180_000 : 30_000)
await input.fill(PROMPT)
await input.press('Enter')
const composer = page.locator('[data-question-key]')
await composer.waitFor({ timeout: MODE === 'record' ? 120_000 : 30_000 })
await composer.getByRole('heading', { name: 'Which checks should run before merging?' }).waitFor({ timeout: 10_000 })
const checked = await composer.getByRole('checkbox').evaluateAll(nodes =>
nodes.map(node => node.getAttribute('aria-checked')))
expect(checked).toEqual(['true', 'false', 'true'])
if (MODE !== 'record') {
const snapshot = await captureStableAria(page, '[data-question-key]', scaffold.workspaceCwd)
await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE)
}
await composer.getByRole('button', { name: 'Submit', exact: true }).click()
const sessionId = await settled
if (MODE === 'record') {
await recordFixture(scaffold, sessionId, FIXTURE)
return
}
const answerText = sessionEvents.filter(event => event.type === 'tool/result')
.flatMap(event => event.data.message.content.filter(item => item.type === 'text').map(item => item.text))
.at(-1)
expect(JSON.parse(answerText ?? '')).toEqual({
answers: [{ id: 'checks', selected: ['Unit tests (Recommended)', 'Type check (Recommended)'] }],
})
await expect.poll(() => page.getByText('DONE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1)
expect(tripwire.pageErrors).toEqual([])
expect(tripwire.warnings).toEqual([])
await assertFixtureInventory(SNAPSHOT_DIR, ['session.v4.jsonl', 'ui.expected.md'])
}, 200_000)
})
+10 -25
View File
@@ -17,7 +17,7 @@
import type { ChildProcess } from 'node:child_process'
import { spawn } from 'node:child_process'
import { randomUUID } from 'node:crypto'
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { createServer } from 'node:http'
import { createRequire, SourceMap } from 'node:module'
import { tmpdir } from 'node:os'
@@ -27,7 +27,7 @@ import type { Browser, Page } from 'playwright'
import { chromium } from 'playwright'
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
import WebSocket from 'ws'
import { REPO_ROOT, connectFreshWorkspace, newEnglishPage, probeFreePort, requireDist, saveFailureShot } from './support.ts'
import { REPO_ROOT, newEnglishPage, probeFreePort, requireDist, saveFailureShot } from './support.ts'
const WEB_SURFACE_PROMPT = fileURLToPath(new URL('./expected/web-runtime-context/web-surface-prompt.expected.md', import.meta.url))
/** Framed user text that marks the auxiliary title request's own messages. */
@@ -284,31 +284,18 @@ async function screen(page: Page, name: string): Promise<void> {
/** First column track (px string) of the frame grid. */
async function firstTrack(page: Page): Promise<string> {
return (await page.locator('[class*="frame"]').evaluate(
return (await page.locator('[class*="frame"]').first().evaluate(
el => getComputedStyle(el).gridTemplateColumns)).split(' ')[0]!
}
/** Last column track (details) as a number of pixels. */
async function detailsTrack(page: Page): Promise<number> {
const cols = await page.locator('[class*="frame"]').evaluate(
const cols = await page.locator('[class*="frame"]').first().evaluate(
el => getComputedStyle(el).gridTemplateColumns)
return Number(cols.split(' ').pop()!.replace('px', ''))
}
// Readiness gate: `dsh web` serves every production manifest plugin; until every UI
// plugin's client bundle exists and exports apply, the loader fail-louds and
// the frame never appears.
const UI_PLUGIN_DIRS = [
'connection', 'ui-theme', 'locale', 'ui-layout', 'ui-renderer', 'ui-session', 'ui-sidebar',
'ui-settings', 'ui-settings-general', 'ui-settings-models', 'ui-conversation', 'ui-approval', 'ui-chat',
'ui-model-selection', 'ui-user-questions', 'ui-trajectory', '../session-query/session-log-export',
]
const ROUND_DONE_MARKER = 'WEB_ROUND_DONE'
const notReady = UI_PLUGIN_DIRS.filter((dir) => {
const bundle = join(REPO_ROOT, 'packages/client', dir, 'lib/client.js')
return !existsSync(bundle) || !readFileSync(bundle, 'utf8').includes('exports.apply')
})
if (notReady.length > 0) console.warn(`[smoke-real] skipped — client bundles not ready: ${notReady.join(', ')}`)
describe('dsh web keyless CLI smoke', () => {
it('serves a usable app from three immutable plugin batches', async () => {
@@ -686,7 +673,7 @@ describe('dsh web keyless CLI smoke', () => {
})
})
describe.skipIf(!process.env.DEEPSEEK_API_KEY || notReady.length > 0)('web smoke (real host, real key)', () => {
describe.skipIf(!process.env.DEEPSEEK_API_KEY)('web smoke (real host, real key)', () => {
let child: ChildProcess
let sessionsDir: string
let baseUrl: string
@@ -730,6 +717,9 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY || notReady.length > 0)('web smoke
page = await newEnglishPage(browser)
page.on('pageerror', e => pageErrors.push(String(e)))
await page.goto(baseUrl, { waitUntil: 'load' })
const welcome = page.getByRole('dialog', { name: 'Preview Notice' })
await welcome.getByRole('button', { name: 'Continue' }).click()
await welcome.waitFor({ state: 'detached' })
}, 120_000)
afterAll(async () => {
@@ -747,18 +737,13 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY || notReady.length > 0)('web smoke
onTestFailed(() => saveFailureShot(page, 'w5-cold-start'))
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
expect(await page.locator('text=Failed to load plugins').count()).toBe(0)
const template = await page.locator('[class*="frame"]').evaluate(el => getComputedStyle(el).gridTemplateColumns)
const template = await page.locator('[class*="frame"]').first().evaluate(el => getComputedStyle(el).gridTemplateColumns)
expect(template.split(' ').length).toBe(3)
await screen(page, '01-cold-start')
})
it('empty-state first send completes a real model round', async () => {
onTestFailed(() => saveFailureShot(page, 'w5-first-round'))
// This scenario spawns its own server against a fresh $DSH_HOME with the
// DeepSeek credential inherited from the environment, so no onboarding
// step mounts and the page is immediately interactive.
// Fresh world: connect a Workspace so the composer starts live.
await connectFreshWorkspace(page, sessionsDir)
const input = page.locator('[data-composer-input]').first()
await input.waitFor({ timeout: 10_000 })
const productTitle = await page.title()
@@ -839,7 +824,7 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY || notReady.length > 0)('web smoke
it('sidebar drag widens the column and resets across reload', async () => {
onTestFailed(() => saveFailureShot(page, 'w5-drag'))
const before = await firstTrack(page)
const handle = page.locator('[class*="handle"]').first()
const handle = page.locator('[data-side="sidebar"]')
const box = await handle.boundingBox()
expect(box).not.toBeNull()
await page.mouse.move(box!.x + box!.width / 2, box!.y + 300)
+52 -12
View File
@@ -1,6 +1,6 @@
// Cold boot may issue at most two settings/describe calls regardless of client
// plugin count. No model call or replay fixture is involved.
import type { Browser, Page } from 'playwright'
// Cold boot bounds shared settings reads and the Web Search credential reads
// caused by their publication waves. No model call or replay fixture is involved.
import type { Browser, Page, Request, Route } from 'playwright'
import { chromium } from 'playwright'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts'
@@ -8,6 +8,8 @@ import { newEnglishPage } from './support.ts'
/** One eager read plus one first-connection reset closes the pre-subscription commit window. */
const DESCRIBE_BUDGET = 2
/** One eager Web Search credential read plus one per settings publication wave. */
const WEB_SEARCH_CREDENTIAL_BUDGET = 3
let scaffold: WebScaffold
let browser: Browser
@@ -25,20 +27,58 @@ afterAll(async () => {
})
describe('startup RPC budget', () => {
it('keeps cold-boot settings.describe at the mirror count', async () => {
it('keeps settings and Web Search credential reads at their publication counts', async () => {
page = await newEnglishPage(browser)
watchConsole(page)
const calls: string[] = []
const credentials: string[][] = []
const pending = new Set<Request>()
const webSearchRequests = new Set<Request>()
const credentialStarted = Promise.withResolvers<undefined>()
let settingsFinished = 0
let webSearchFinished = 0
// Both settings answers must reach the card after it subscribes, regardless
// of plugin load order. The eager credential request proves that subscription.
const holdSettings = async (route: Route): Promise<void> => {
await credentialStarted.promise
await route.continue()
}
await page.route('**/api/settings/describe', holdSettings)
page.on('request', (request) => {
const url = new URL(request.url())
if (url.pathname.startsWith('/api/')) calls.push(url.pathname.slice('/api/'.length))
if (!url.pathname.startsWith('/api/')) return
const method = url.pathname.slice('/api/'.length)
calls.push(method)
pending.add(request)
if (method === 'credentials/describe') {
const body = request.postDataJSON() as { payload: { args: { refs: string[] } } }
const refs = body.payload.args.refs
credentials.push(refs)
// Models requests batch references; the Web Search card asks for this one key.
if (refs.length === 1 && refs[0] === 'DEEPSEEK_API_KEY') {
webSearchRequests.add(request)
credentialStarted.resolve(undefined)
}
}
})
await page.goto(scaffold.authenticatedUrl)
// Boot settles when the workspace picker is interactive; the trailing wait
// absorbs the first-connection reset wave the budget must include.
await page.getByRole('textbox', { name: 'Choose workspace' }).waitFor({ timeout: 30_000 })
await page.waitForTimeout(3000)
const describeCount = calls.filter(method => method === 'settings/describe').length
expect(describeCount, `startup /api calls:\n${calls.join('\n')}`).toBe(DESCRIBE_BUDGET)
page.on('requestfinished', (request) => {
pending.delete(request)
if (new URL(request.url()).pathname === '/api/settings/describe') settingsFinished++
if (webSearchRequests.has(request)) webSearchFinished++
})
page.on('requestfailed', request => pending.delete(request))
try {
await page.goto(scaffold.authenticatedUrl)
await page.getByRole('textbox', { name: 'Choose workspace' }).waitFor({ timeout: 30_000 })
await expect.poll(() => settingsFinished, { timeout: 30_000 }).toBeGreaterThanOrEqual(DESCRIBE_BUDGET)
await expect.poll(() => webSearchFinished, { timeout: 30_000 }).toBeGreaterThanOrEqual(WEB_SEARCH_CREDENTIAL_BUDGET)
await expect.poll(() => pending.size, { timeout: 30_000 }).toBe(0)
const describeCount = calls.filter(method => method === 'settings/describe').length
expect(describeCount, `startup /api calls:\n${calls.join('\n')}`).toBe(DESCRIBE_BUDGET)
expect(webSearchRequests.size, `startup credential references:\n${JSON.stringify(credentials)}`).toBe(WEB_SEARCH_CREDENTIAL_BUDGET)
} finally {
credentialStarted.resolve(undefined)
await page.unrouteAll({ behavior: 'wait' })
}
})
})
+1
View File
@@ -67,6 +67,7 @@
"tests/subagent-fork-schedule.snapshot.ts",
"tests/live-interactions.e2e.ts",
"tests/question-composer.e2e.ts",
"tests/question-composer-recommended.e2e.ts",
"tests/question-ptc.e2e.ts",
"tests/approval-composer.e2e.ts",
"tests/ptc-escalation.e2e.ts",
+2 -2
View File
@@ -27,8 +27,8 @@
en: 1a79a70b62c04cdb
zh: c86d765e21430405
/deepseek-harness-architecture/session-log:
en: 8a7f19b95d426c99
zh: d5bb0538404e20ea
en: b3b63d8fe7cab9fe
zh: 3703fcf30b1639d0
/deepseek-harness-architecture/capability-seams:
en: a5bc20c3f2a1b370
zh: 91773a281410b2f4
+1 -1
View File
@@ -127,7 +127,7 @@ Session consumers know only the current logical format. Header-only `stat` and `
**Model-visible means logged.** Every model request must be reconstructable from the log. New model-visible inputs require session events. Plugins changing existing message content register [pure message projections](subsystems/session.md#plugin-owned-message-projections); detached readers supply the same definitions explicitly. Tool changes are capability-independent; [Session tool history](../packages/core/session/README.md) supplies provider declarations.
**Projection seam.** `dsh-session-projection` owns `ctx.sessionProjections`: registered units fold committed events incrementally, and carriers batch cropped client views with `snapshot()`. Domain services await registration during activation, retain private handles, and expose business methods for other plugins. Releasing registration removes global participation; retained handles continue folding Session events. `AgentRegistry` owns turn and step state and exposes `turnBoundaryOf(session)` ([registration lifecycle](../packages/session/session-projection/README.md)). `AgentLoop` owns `modelSelection` and constructs each Agent’s `model` instance alongside its inbox.
**Projection seam.** `dsh-session-projection` owns `ctx.sessionProjections`: registered units fold committed events; carriers read selected client views through `snapshot()`. Domain services await registration, retain private handles, and expose business methods ([registration lifecycle](../packages/session/session-projection/README.md)). `AgentRegistry` exposes turn and step state through `turnBoundaryOf(session)`. `AgentLoop` owns `modelSelection` and inbox state ([loop lifecycle](../packages/core/agent-loop/README.md)).
[Working directories](subsystems/working-directory.md) supply user context and execution paths without changing original project identity, sandbox write roots, or existing process directories.
+1 -1
View File
@@ -131,7 +131,7 @@ Session 消费方只了解当前逻辑格式。仅 header 的 `stat` 与 `list`
**模型可见即已记录。** 每个模型请求都必须能从日志重建。新增模型可见输入需要会话事件。修改现有消息内容的插件注册[纯消息投影](subsystems/session.zh.md#plugin-owned-message-projections),独立读取器显式传入相同的处理器。 工具变更不依赖能力;[Session 工具历史](../packages/core/session/README.zh.md)提供提供方声明。
**投影 seam。** `dsh-session-projection` 提供 `ctx.sessionProjections`:已注册单元增量折叠已提交事件,载体通过 `snapshot()` 批量取得裁剪后的客户端视图。领域服务在激活时等待注册完成,在内部保留句柄,并向其他插件提供业务方法。释放注册会移除全局参与关系;已有句柄仍可继续折叠 Session 事件。`AgentRegistry` 持有轮次和步骤状态,并提供 `turnBoundaryOf(session)`([注册生命周期](../packages/session/session-projection/README.zh.md))。 `AgentLoop` 持有 `modelSelection`,并与 inbox 一起构建每个 Agent 的 `model` 实例。
**投影 seam。** `dsh-session-projection` 提供 `ctx.sessionProjections`:已注册单元折叠已提交事件,载体通过 `snapshot()` 读取选定的客户端视图。领域服务等待注册完成,在内部保留句柄,并提供业务方法([注册生命周期](../packages/session/session-projection/README.zh.md))。`AgentRegistry` 通过 `turnBoundaryOf(session)` 提供轮次和步骤状态。`AgentLoop` 持有 `modelSelection` 和 inbox 状态([Loop 生命周期](../packages/core/agent-loop/README.zh.md))。
[工作目录](subsystems/working-directory.zh.md) 提供用户上下文和执行路径,不改变原始项目标识、沙箱写入根目录或已有进程目录。
+2 -2
View File
@@ -3,8 +3,8 @@
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write docs/subsystems/session-projection.md
/session-projections:
en: 45e5f8cb8ca18d6b
zh: 4ecfad40ec9e221c
en: b2789f5257a935c5
zh: 12d430a9cd454592
/session-projections/the-unit:
en: d48814d3ab0e997f
zh: d0337d8eba097a63
+9
View File
@@ -18,6 +18,13 @@ interface ProjectionHandle<S> {
* @returns the projection state at the Session's current cursor.
*/
stateOf(session: Session): S
/**
* Create a reader for one exact Session without reading state or preparing it.
* The reader retains this unit after unregistration and owns no disposal.
* @param session - Session whose committed events the bound reader folds.
* @returns a synchronous callback with the same state and failures as `stateOf(session)`.
*/
readerFor(session: Session): () => S
/**
* Unregister from global drives and snapshots without invalidating this reader.
* @returns a promise that resolves when this registration is released.
@@ -28,6 +35,8 @@ interface ProjectionHandle<S> {
The [compatibility rules](../../packages/session/session-projection/README.md#deprecated-plugin-compatibility) define legacy disposal, keyed reads, and their once-per-key deprecation warnings.
`ProjectionHandle.readerFor(session)` returns a `() => S` callback for one exact Session. Calling it reads the original unit and preserves borrowed state, readiness requirements and synchronous failures. Owners can compose several readers in a typed object; domain services keep them private. See [binding several states](../../packages/session/session-projection/README.md#bind-several-states-to-one-session).
## The unit
`ProjectionDefinition<K, S>` carries each unit's host state type locally; registration infers `S` from `stateSchema` and returns `ProjectionHandle<S>`. Only client-visible keys merge into `SessionProjectionMap`, which types their whole values. A `wire` block makes a unit client-visible, and rendering belongs to the slot system, never this layer:
+9
View File
@@ -18,6 +18,13 @@ interface ProjectionHandle<S> {
* @returns the projection state at the Session's current cursor.
*/
stateOf(session: Session): S
/**
* Create a reader for one exact Session without reading state or preparing it.
* The reader retains this unit after unregistration and owns no disposal.
* @param session - Session whose committed events the bound reader folds.
* @returns a synchronous callback with the same state and failures as `stateOf(session)`.
*/
readerFor(session: Session): () => S
/**
* Unregister from global drives and snapshots without invalidating this reader.
* @returns a promise that resolves when this registration is released.
@@ -28,6 +35,8 @@ interface ProjectionHandle<S> {
[兼容规则](../../packages/session/session-projection/README.zh.md#deprecated-plugin-compatibility)规定旧释放操作、按键读取及其每个键一次的弃用警告。
`ProjectionHandle.readerFor(session)` 为一个确切的 Session 返回 `() => S` 回调。调用它会读取原有单元,保留借用状态、就绪要求和同步失败。所有者可将多个读取函数组合成一个类型化对象;领域服务将它们保留在内部。参见[绑定多个状态](../../packages/session/session-projection/README.zh.md#bind-several-states-to-one-session)。
## 投影单元
`ProjectionDefinition<K, S>` 在各单元内部携带宿主状态类型;注册从 `stateSchema` 推导 `S`,并返回 `ProjectionHandle<S>`。只有客户端可见的 key 合并到 `SessionProjectionMap`,由它约束对应的全量值。`wire` 块使单元对客户端可见,渲染归 slot 体系管,永远不归本层:
+1 -1
View File
@@ -85,7 +85,7 @@ A dynamic browser half either carries a module privately or requests the shared
3. **Silence means a private copy.** Third-party implementation libraries outside the baseline may be bundled independently. A value reached only through `import type` is erased and creates no request.
4. **A request has two possible suppliers.** A dynamic package supplies its own row; `PLATFORM_MODULES` supplies an exact static-table key. There is no `dsh.client.provide` alias protocol.
5. **Validate both sides.** The dynamic build preset externalizes the baseline and rejects undeclared workspace value imports; [`verify-client-packages`](../../scripts/verify-client-packages.ts) rejects malformed or redundant requests, missing suppliers, and synchronous request cycles.
6. **Package-local dynamic chunks are self-contained.** Source uses `import()` and the shared preset emits `require.async("./client.<name>.js")`; an entry or chunk must not retain a synchronous relative `require("./client*.js")`. Keep every static relative dependency inside its owning output chunk rather than relying on a sibling-chunk graph the runtime does not support.
6. **Package-local dynamic chunks are self-contained.** Source uses `import()` and the shared preset calls the factory loader's `.async` method with a literal `./client.<name>.js` path; an entry or chunk must not retain a synchronous relative `require("./client*.js")`. Keep every static relative dependency inside its owning output chunk rather than relying on a sibling-chunk graph the runtime does not support.
### The module graph sits below cordis DI
+4 -4
View File
@@ -24,8 +24,8 @@
en: 529af1eb8bf1acf2
zh: 7d891a5dfa90c625
/deepseek-ai-dsh-client-modules/use-this-package/what-the-browser-loads:
en: 1383d68472b3c057
zh: 94dd7d9abbdbccf3
en: 3c372e9d65e294a8
zh: 00f82efab7071258
/deepseek-ai-dsh-client-modules/use-this-package/live-plugin-composition:
en: 45740a56e931d094
zh: fa44cf77c86019af
@@ -36,8 +36,8 @@
en: 1778b5a63ecde5e8
zh: 537b4f8c755af8ad
/deepseek-ai-dsh-client-modules/use-this-package/build-requirements:
en: b6a4d3b901c89efe
zh: 615b5f3eec41f281
en: 15aa99a9df72e51e
zh: 3324596fb5d3588d
/deepseek-ai-dsh-client-modules/understand-the-implementation:
en: 7ab11d2c2bdc6eaa
zh: 54c3c9091cf59711
+3 -1
View File
@@ -40,7 +40,7 @@ The same `/plugins` route serves the images a client package publishes through i
### What the browser loads
The application combo scripts carry only each plugin's `client.js` entry and register those factories once during boot; module bodies remain lazy and run only at first import or materialization. A source `import()` split by tsdown compiles to `require.async("./client.<name>.js")`; its versioned sibling script arrives only when that expression runs. Rows that share a combo URL share one in-flight script task. A combo whose `<script>` fails to load is requested once more; a combo that loads without registering a row is never re-executed, because the batch script registers its packages in sequence and a replay would stop at the first duplicate registration. In both cases each still-missing row then loads its own one-resource combo URL, so one failed batch costs at most three requests per missing row and leaves the rows it did register untouched. The module system records the last import failure per row (transport, registration, dependency cascade, or factory execution); the Web boot audit reports that text per entry. HMR switches one changed row to its revisioned one-resource combo URL. `<id>/client` and the bare id resolve to the same exports, because a plugin bundle is its package's client half.
The application combo scripts carry only each plugin's `client.js` entry and register those factories once during boot; module bodies remain lazy and run only at first import or materialization. A source `import()` split by tsdown calls the factory loader's `.async` method with a literal `./client.<name>.js` path; its versioned sibling script arrives only when that expression runs. Rows that share a combo URL share one in-flight script task. A combo whose `<script>` fails to load is requested once more; a combo that loads without registering a row is never re-executed, because the batch script registers its packages in sequence and a replay would stop at the first duplicate registration. In both cases each still-missing row then loads its own one-resource combo URL, so one failed batch costs at most three requests per missing row and leaves the rows it did register untouched. The module system records the last import failure per row (transport, registration, dependency cascade, or factory execution); the Web boot audit reports that text per entry. HMR switches one changed row to its revisioned one-resource combo URL. `<id>/client` and the bare id resolve to the same exports, because a plugin bundle is its package's client half.
### Live plugin composition
@@ -58,6 +58,8 @@ The shell seeds a frozen module table ([`PLATFORM_MODULES`](../web/README.md#the
The host serves built client bundles, so `pnpm run build` must have produced each `lib/client.js` before launch; a missing bundle fails activation loudly with one build instruction and a package/path list. Source launch maps host imports to TypeScript source but still consumes the built client export. The package accepts no plugin config of its own.
The shared Client preset minifies browser factories and lazy chunks unless `NODE_ENV=development`. Minification preserves the function and class names produced by bundling, legal comments, full package license banners, and source maps with original source content. `pnpm run dev:web` and its HMR rebuilds inherit `NODE_ENV`; set it explicitly to `development` for unminified output. Host and Node Client output use separate presets.
-----
<a id="understand-the-implementation"></a>
+3 -1
View File
@@ -40,7 +40,7 @@ kind: "package-reference"
### 浏览器加载什么
application combo 脚本只携带每个插件的 `client.js` 入口,并在启动时仅注册一次这些 factory;模块主体仍保持惰性,只在首次 import 或物化时运行。经 tsdown 拆分的源码 `import()` 会编译为 `require.async("./client.<name>.js")`;只有执行该表达式时,对应的带版本同级脚本才会到达。共享 combo URL 的 row 共用一个进行中的脚本任务。`<script>` 加载失败的 combo 会再请求一次;加载成功但没有注册某条 row 的 combo 绝不会重新执行,因为批量脚本按顺序注册各个包,重放会在第一个重复注册处停止。两种情况下,每条仍缺失的 row 随后加载自己的单资源 combo URL,因此一个失败的 batch 对每条缺失 row 最多花费三次请求,且不影响它已经注册的 row。模块系统按 row 记录最后一次 import 失败(传输、注册、依赖级联或 factory 执行);Web 启动审计按条目报告该文本。HMR(热模块替换)会让一条发生变化的 row 改用带 revision 的单资源 combo URL。`<id>/client` 与裸 id 解析到同一组导出,因为插件 bundle 就是其包的客户端半侧。
application combo 脚本只携带每个插件的 `client.js` 入口,并在启动时仅注册一次这些 factory;模块主体仍保持惰性,只在首次 import 或物化时运行。经 tsdown 拆分的源码 `import()` 会以字面量 `./client.<name>.js` 路径调用 factory loader 的 `.async` 方法;只有执行该表达式时,对应的带版本同级脚本才会到达。共享 combo URL 的 row 共用一个进行中的脚本任务。`<script>` 加载失败的 combo 会再请求一次;加载成功但没有注册某条 row 的 combo 绝不会重新执行,因为批量脚本按顺序注册各个包,重放会在第一个重复注册处停止。两种情况下,每条仍缺失的 row 随后加载自己的单资源 combo URL,因此一个失败的 batch 对每条缺失 row 最多花费三次请求,且不影响它已经注册的 row。模块系统按 row 记录最后一次 import 失败(传输、注册、依赖级联或 factory 执行);Web 启动审计按条目报告该文本。HMR(热模块替换)会让一条发生变化的 row 改用带 revision 的单资源 combo URL。`<id>/client` 与裸 id 解析到同一组导出,因为插件 bundle 就是其包的客户端半侧。
### 插件动态组合
@@ -59,6 +59,8 @@ application combo 脚本只携带每个插件的 `client.js` 入口,并在启
宿主提供的是已构建的客户端 bundle,因此启动前 `pnpm run build` 必须已产出每个 `lib/client.js`;缺失 bundle 会明确导致激活失败,并给出一条构建说明及包/路径列表。源码启动会把宿主侧导入映射到 TypeScript 源码,但仍消费这一构建后的客户端导出。本包自身不接受任何插件配置。
除 `NODE_ENV=development` 外,共享 Client 预设会压缩浏览器 factory 和懒加载 chunk。压缩会保留打包生成的函数名和类名、法律声明注释、完整的包许可证声明,以及包含原始源码内容的 source map。`pnpm run dev:web` 及其 HMR 重建会继承 `NODE_ENV`;要获得未压缩产物,需显式将其设为 `development`。Host 和 Node Client 产物使用各自的预设。
-----
<a id="understand-the-implementation"></a>
+11 -5
View File
@@ -120,6 +120,8 @@ function browserSourcePath(source: string, sourcemapPath: string): string {
* the package without lib/index.js and the host Loader cannot import its node
* half. The Client build consumes `lib/types` and chains those tsc maps, with
* original source content, into the standalone plugin map.
* Browser factories and lazy chunks are minified unless NODE_ENV is development;
* minification retains bundled function/class names and legal notices.
* @param packageDir - the package's own directory, normally the config's
* `import.meta.dirname`. Its `package.json` name is the plugin id stamped into
* the __ModuleLoader__.load handoff and onto the injected style tags, and the
@@ -790,6 +792,12 @@ function clientConfig(
outDir: 'lib',
format: 'cjs',
platform: 'browser',
minify: process.env.NODE_ENV === 'development' ? false : {
// Cordis uses function/class names for plugin and callback labels.
compress: { keepNames: { function: true, class: true } },
mangle: { keepNames: true },
codegen: { legalComments: 'inline' },
},
// Types ship from lib/types (tsc); dts here would wrap the banner/footer into .d.cts and break parsing.
dts: false,
// Plugin code is fetched outside Vite's module graph, so its own bundle
@@ -927,11 +935,9 @@ function clientConfig(
isolation.sourcePath(source, mapPath)
return browserSourcePath(source, mapPath)
},
banner: (chunk) => {
const registration = `window.__ModuleLoader__.load({ id: ${JSON.stringify(id)}, ${chunk.isEntry ? '' : `chunk: ${JSON.stringify(chunk.fileName)}, `}factory: (require) => {`
const prefix = clientBanner?.(chunk.fileName)
return prefix === undefined ? registration : `${prefix}\n${registration}`
},
banner: chunk => `window.__ModuleLoader__.load({ id: ${JSON.stringify(id)}, ${chunk.isEntry ? '' : `chunk: ${JSON.stringify(chunk.fileName)}, `}factory: (require) => {`,
// Full license notices may include ordinary comments that minification removes.
postBanner: chunk => clientBanner?.(chunk.fileName) ?? '',
footer: 'return module.exports; } });',
intro: 'var module = { exports: {} }; var exports = module.exports;',
},
@@ -18,8 +18,8 @@
en: ba0053e60d4a5e9e
zh: 1e79aad162155e9c
/deepseek-ai-dsh-client-ui-settings-web-search/understand-the-implementation:
en: 4695da9b39a614a3
zh: 5ebe668df937e12e
en: d200933a35bf4972
zh: 2484eb9635102357
/deepseek-ai-dsh-client-ui-settings-web-search/further-exploration:
en: 72585c993e443510
zh: 90cf6894ccfe8588
@@ -37,7 +37,7 @@ The **Web search** card in the Official group opens the page. **API key** starts
<details>
<summary>Implementation internals — click to expand</summary>
The Host half is an empty `apply`, present only so the package holds a Loader row the client module system serves the browser half for. The browser half binds the `web`, `web-search-deepseek`, and `web-deepseek-api` namespaces through `ctx.configForms.get` and keeps one shared `SettingsFormModel` of `ui-primitives` per namespace in `WebSearchCardController`. The switch stages `searchProvider` and `fetchProvider` in `web`; a target equal to the composed value stages a reset instead. The key is the selection form's one secret control: its write goes to `remote.credentials.set` under the reference the selected API section's `apiKeyEnv` names (`DEEPSEEK_API_KEY` when it names none), and success is read back from `remote.credentials.describe`. The controller re-reads the credential when a scope changes, when the switch selects a section naming another reference, and when the Host reports `credentials/reference-updated` for the watched reference, since a key written on the Models page changes no settings section. The page registers `WebSearchCard` into the Plugins page's `plugins.item` slot through `ctx.configForms.whileServed`.
The Host half is an empty `apply`, present only so the package holds a Loader row the client module system serves the browser half for. The browser half binds the `web`, `web-search-deepseek`, and `web-deepseek-api` namespaces through `ctx.configForms.get` and keeps one shared `SettingsFormModel` of `ui-primitives` per namespace in `WebSearchCardController`. The switch stages `searchProvider` and `fetchProvider` in `web`; a target equal to the composed value stages a reset instead. The key is the selection form's one secret control: its write goes to `remote.credentials.set` under the reference the selected API section's `apiKeyEnv` names (`DEEPSEEK_API_KEY` when it names none), and success is read back from `remote.credentials.describe`. The controller combines synchronous scope publications and reference switches into one credential read in the next microtask; scope refreshes also resynchronize credentials after a connection reset. Reference changes clear the previous credential state immediately. Host `credentials/reference-updated` events for the watched reference and writes trigger independent reads, including while an earlier read is pending. Only the latest read for the selected reference updates the card; a save uses its own readback result. Disposal stops queued reads and suppresses late answers. The page registers `WebSearchCard` into the Plugins page's `plugins.item` slot through `ctx.configForms.whileServed`.
</details>
@@ -37,7 +37,7 @@ kind: "package-reference"
<details>
<summary>实现细节——点击展开</summary>
宿主半侧是一个空的 `apply`,只为让本包占一条 Loader 行,客户端模块系统据此送出浏览器半侧。浏览器半侧通过 `ctx.configForms.get` 绑定 `web`、`web-search-deepseek` 和 `web-deepseek-api` 命名空间,在 `WebSearchCardController` 里为每个命名空间维护一个 `ui-primitives` 共享的 `SettingsFormModel`。开关在 `web` 中暂存 `searchProvider` 和 `fetchProvider`;目标值等于组合值时改为暂存重置。密钥是选择表单里唯一的密文控件:写入走 `remote.credentials.set`,引用名取自当前所选 API 设置节的 `apiKeyEnv`(未指定时为 `DEEPSEEK_API_KEY`),是否成功由 `remote.credentials.describe` 回读判定。某个 scope 变化时、开关选中的设置节命名了另一个引用时、以及 Host 对所监视引用发出 `credentials/reference-updated` 时,控制器都会重读凭据,因为在模型页写入的密钥不会改变任何设置节。页面通过 `ctx.configForms.whileServed` 把 `WebSearchCard` 注册进插件页的 `plugins.item` slot。
宿主半侧是一个空的 `apply`,只为让本包占一条 Loader 行,客户端模块系统据此送出浏览器半侧。浏览器半侧通过 `ctx.configForms.get` 绑定 `web`、`web-search-deepseek` 和 `web-deepseek-api` 命名空间,在 `WebSearchCardController` 里为每个命名空间维护一个 `ui-primitives` 共享的 `SettingsFormModel`。开关在 `web` 中暂存 `searchProvider` 和 `fetchProvider`;目标值等于组合值时改为暂存重置。密钥是选择表单里唯一的密文控件:写入走 `remote.credentials.set`,引用名取自当前所选 API 设置节的 `apiKeyEnv`(未指定时为 `DEEPSEEK_API_KEY`),是否成功由 `remote.credentials.describe` 回读判定。控制器把同步发布的 scope 更新和引用切换合并成下一个微任务中的一次凭据读取;连接重置后的 scope 刷新也会重新同步凭据。引用变化会立即清除旧凭据状态。Host 对所监视引用发出 `credentials/reference-updated` 事件以及写入时,都会独立触发读取,即使此前的读取仍未完成。只有所选引用的最新读取会更新卡片;保存使用自身的回读结果。释放控制器后不再执行排队的读取,也不再发布迟到的响应。页面通过 `ctx.configForms.whileServed` 把 `WebSearchCard` 注册进插件页的 `plugins.item` slot。
</details>
@@ -133,6 +133,9 @@ export class WebSearchCardController {
private readonly store: SnapshotStore<WebSearchCardState>
private readonly unsubscribe: (() => void)[]
private credential: CredentialState = { ref: '', configured: false, writable: true }
private credentialReadQueued = false
private credentialReadSequence = 0
private disposed = false
/**
* @param scopes - the bound settings scopes for the page's namespaces.
@@ -164,12 +167,16 @@ export class WebSearchCardController {
// A staged switch can change which section names the key, without any
// scope publishing; a scope change can rename the reference itself.
const publish = () => {
const ref = this.ref()
if (ref !== this.credential.ref) {
this.resetCredentialReference(ref)
this.queueCredentialRead()
}
this.store.set(this.projection())
if (this.ref() !== this.credential.ref) void this.readCredential()
}
this.unsubscribe = [
...[this.selection, this.messages, this.api].map(form => form.bind(() => form.shell()).subscribe(publish)),
...[scopes.web, scopes.messages, scopes.api].map(scope => scope.subscribe(() => { void this.readCredential() })),
...[scopes.web, scopes.messages, scopes.api].map(scope => scope.subscribe(() => { this.queueCredentialRead() })),
]
void this.readCredential()
}
@@ -215,24 +222,42 @@ export class WebSearchCardController {
return refOf(this.searchApi() ? this.scopes.api.getSnapshot() : this.scopes.messages.getSnapshot())
}
/** Clear the old reference's answer and invalidate its pending reads. */
private resetCredentialReference(ref: string): void {
this.credential = { ref, configured: false, writable: true }
this.credentialReadSequence++
}
/** Combine settings publications, including connection-reset refreshes, into one credential read. */
private queueCredentialRead(): void {
if (this.credentialReadQueued) return
this.credentialReadQueued = true
queueMicrotask(() => {
this.credentialReadQueued = false
void this.readCredential()
})
}
/**
* Ask the credentials domain about the reference the selected section currently names.
*
* The answer is stored with the reference it describes: `apiKeyEnv` and the
* switch can change between the request and its response, and two reads can
* settle out of order, so a response is published only while it still
* answers for the reference in force.
* Only the latest read for the selected reference publishes its answer.
* A write's readback retains its own result even if another read starts.
* @returns the answer for this read, or undefined after failure, disposal, or a reference change.
*/
private async readCredential(): Promise<void> {
private async readCredential(): Promise<CredentialState | undefined> {
if (this.disposed) return
const ref = this.ref()
if (ref !== this.credential.ref) {
// A new reference knows nothing yet; keeping the old answer would claim
// the key is configured under a name nobody has checked.
this.credential = { ref, configured: false, writable: true }
this.resetCredentialReference(ref)
this.store.set(this.projection())
}
const sequence = ++this.credentialReadSequence
const response = await this.ctx.remote.credentials.describe([ref])
if (!response.ok || ref !== this.ref()) return
// oxlint-disable-next-line typescript/no-unnecessary-condition -- dispose() can run during the await.
if (this.disposed || !response.ok || ref !== this.ref()) return
const view = response.value[ref]
const next: CredentialState = {
ref,
@@ -241,9 +266,12 @@ export class WebSearchCardController {
// and the Host is what refuses, rather than the page guessing a refusal.
writable: view?.writable ?? true,
}
if (next.configured === this.credential.configured && next.writable === this.credential.writable) return
this.credential = next
this.store.set(this.projection())
if (sequence === this.credentialReadSequence
&& (next.configured !== this.credential.configured || next.writable !== this.credential.writable)) {
this.credential = next
this.store.set(this.projection())
}
return next
}
/**
@@ -325,12 +353,12 @@ export class WebSearchCardController {
// Refusals surface through the re-read below: the Host is the only
// authority on whether the key now exists.
await this.ctx.remote.credentials.set(this.ref(), value)
await this.readCredential()
return this.credential.configured
return (await this.readCredential())?.configured ?? false
}
/** Release configuration subscriptions. */
/** Release subscriptions and prevent queued reads or late answers from publishing. */
dispose(): void {
this.disposed = true
for (const off of this.unsubscribe) off()
for (const form of [this.selection, this.messages, this.api]) form.dispose()
}
@@ -78,6 +78,94 @@ function serve(b: ReturnType<typeof bench>, selection: SelectionLayers = {}): vo
}
describe('WebSearchCardController credential', () => {
it('reads once per settings publication wave after the eager read', async () => {
const b = bench()
try {
expect(b.credentials.describe).toHaveBeenCalledTimes(1)
serve(b)
await Promise.resolve()
expect(b.credentials.describe).toHaveBeenCalledTimes(2)
serve(b)
await Promise.resolve()
expect(b.credentials.describe).toHaveBeenCalledTimes(3)
for (const args of b.credentials.describe.mock.calls) expect(args).toEqual([['DEEPSEEK_API_KEY']])
} finally { b.controller.dispose() }
})
it('reads once when a settings publication wave renames the credential reference', async () => {
const b = bench()
try {
serve(b)
await vi.waitFor(() => { expect(b.state().apiKeyConfigured).toBe(true) })
const count = b.credentials.describe.mock.calls.length
b.messages.publish({ value: { apiKeyEnv: 'RENAMED_KEY' } })
expect(b.state().apiKeyConfigured).toBe(false)
await Promise.resolve()
expect(b.credentials.describe).toHaveBeenCalledTimes(count + 1)
expect(b.credentials.describe).toHaveBeenLastCalledWith(['RENAMED_KEY'])
} finally { b.controller.dispose() }
})
it.each(['before', 'after'])('keeps the credential update when the pending settings read finishes %s it', async (order) => {
const b = bench({ configured: false })
const pending = Promise.withResolvers<Awaited<ReturnType<typeof b.credentials.describe>>>()
const updated = Promise.withResolvers<Awaited<ReturnType<typeof b.credentials.describe>>>()
try {
await Promise.resolve()
b.credentials.describe.mockImplementationOnce(() => pending.promise)
serve(b)
await Promise.resolve()
const count = b.credentials.describe.mock.calls.length
b.credentials.describe.mockImplementationOnce(() => updated.promise)
b.controller.refreshCredential('DEEPSEEK_API_KEY')
expect(b.credentials.describe).toHaveBeenCalledTimes(count + 1)
if (order === 'before') {
pending.resolve({ ok: true, value: { DEEPSEEK_API_KEY: { configured: false, writable: true } } })
await Promise.resolve()
}
updated.resolve({ ok: true, value: { DEEPSEEK_API_KEY: { configured: true, writable: true } } })
await vi.waitFor(() => { expect(b.state().apiKeyConfigured).toBe(true) })
pending.resolve({ ok: true, value: { DEEPSEEK_API_KEY: { configured: false, writable: true } } })
await Promise.resolve()
expect(b.state().apiKeyConfigured).toBe(true)
} finally {
b.controller.dispose()
pending.resolve({ ok: true, value: {} })
updated.resolve({ ok: true, value: {} })
await Promise.all([pending.promise, updated.promise])
}
})
it('discards queued reads and late credential answers after disposal', async () => {
const b = bench({ configured: false })
const pending = Promise.withResolvers<Awaited<ReturnType<typeof b.credentials.describe>>>()
const publish = vi.fn()
const off = b.face.hooks.webSearchCard.subscribe(publish)
try {
await Promise.resolve()
b.credentials.describe.mockImplementationOnce(() => pending.promise)
b.controller.refreshCredential('DEEPSEEK_API_KEY')
serve(b)
b.controller.dispose()
const count = b.credentials.describe.mock.calls.length
publish.mockClear()
pending.resolve({ ok: true, value: { DEEPSEEK_API_KEY: { configured: true, writable: true } } })
await Promise.resolve()
expect(b.credentials.describe).toHaveBeenCalledTimes(count)
expect(publish).not.toHaveBeenCalled()
expect(b.state().apiKeyConfigured).toBe(false)
b.controller.refreshCredential('DEEPSEEK_API_KEY')
serve(b)
await Promise.resolve()
expect(b.credentials.describe).toHaveBeenCalledTimes(count)
} finally {
off()
b.controller.dispose()
pending.resolve({ ok: true, value: {} })
await pending.promise
}
})
it('reads the credential state for the reference the selected section names', async () => {
const b = bench()
await vi.waitFor(() => { expect(b.credentials.describe).toHaveBeenCalled() })
@@ -87,6 +175,16 @@ describe('WebSearchCardController credential', () => {
b.controller.dispose()
})
it('keeps an unknown credential reference writable and unconfigured', async () => {
const b = bench()
try {
await vi.waitFor(() => { expect(b.state().apiKeyConfigured).toBe(true) })
b.credentials.describe.mockResolvedValue({ ok: true, value: {} })
b.controller.refreshCredential('DEEPSEEK_API_KEY')
await vi.waitFor(() => { expect(b.state()).toMatchObject({ apiKeyConfigured: false, apiKeyWritable: true }) })
} finally { b.controller.dispose() }
})
it('writes the staged key through the credentials domain, never a settings section', async () => {
const b = bench({ configured: false })
serve(b)
@@ -103,6 +201,32 @@ describe('WebSearchCardController credential', () => {
b.controller.dispose()
})
it('accepts its successful key readback while a newer credential read is pending', async () => {
const b = bench({ configured: false })
const readback = Promise.withResolvers<Awaited<ReturnType<typeof b.credentials.describe>>>()
const newer = Promise.withResolvers<Awaited<ReturnType<typeof b.credentials.describe>>>()
try {
serve(b)
await vi.waitFor(() => { expect(b.credentials.describe).toHaveBeenCalledTimes(2) })
b.credentials.describe.mockImplementationOnce(() => readback.promise)
b.face.edit('apiKey', 'ds-secret')
b.face.save()
await vi.waitFor(() => { expect(b.credentials.describe).toHaveBeenCalledTimes(3) })
b.credentials.describe.mockImplementationOnce(() => newer.promise)
b.controller.refreshCredential('DEEPSEEK_API_KEY')
expect(b.credentials.describe).toHaveBeenCalledTimes(4)
readback.resolve({ ok: true, value: { DEEPSEEK_API_KEY: { configured: true, writable: true } } })
await vi.waitFor(() => { expect(b.state()).toMatchObject({ dirty: false, saving: false, failed: false }) })
newer.resolve({ ok: true, value: { DEEPSEEK_API_KEY: { configured: true, writable: true } } })
await vi.waitFor(() => { expect(b.state().apiKeyConfigured).toBe(true) })
} finally {
b.controller.dispose()
readback.resolve({ ok: true, value: {} })
newer.resolve({ ok: true, value: {} })
await Promise.all([readback.promise, newer.promise])
}
})
it('keeps the stored key when the draft is left blank', () => {
const b = bench()
serve(b)
@@ -168,17 +292,29 @@ describe('WebSearchCardController credential', () => {
b.controller.dispose()
})
it('drops a credential answer for a reference that changed while it was pending', async () => {
type Answer = { ok: true; value: Record<string, { configured: boolean; writable: boolean }> }
let answer: (value: Answer) => void = () => {}
const describe = vi.fn(() => new Promise<Answer>((resolve) => { answer = resolve }))
const b = bench({ ctx: ctxWith({ credentials: { describe, set: vi.fn() } }) })
serve(b)
b.messages.publish({ value: { apiKeyEnv: 'RENAMED_KEY' } })
answer({ ok: true, value: { DEEPSEEK_API_KEY: { configured: true, writable: true } } })
await Promise.resolve()
expect(b.state().apiKeyConfigured).toBe(false)
b.controller.dispose()
it('clears a changed reference immediately and drops its previous pending answer', async () => {
const b = bench()
const previous = Promise.withResolvers<Awaited<ReturnType<typeof b.credentials.describe>>>()
const renamed = Promise.withResolvers<Awaited<ReturnType<typeof b.credentials.describe>>>()
try {
serve(b)
await vi.waitFor(() => { expect(b.state().apiKeyConfigured).toBe(true) })
b.credentials.describe.mockImplementationOnce(() => previous.promise)
b.controller.refreshCredential('DEEPSEEK_API_KEY')
b.credentials.describe.mockImplementation(() => renamed.promise)
b.messages.publish({ value: { apiKeyEnv: 'RENAMED_KEY' } })
expect(b.state().apiKeyConfigured).toBe(false)
previous.resolve({ ok: true, value: { DEEPSEEK_API_KEY: { configured: true, writable: true } } })
await Promise.resolve()
expect(b.state().apiKeyConfigured).toBe(false)
renamed.resolve({ ok: true, value: { RENAMED_KEY: { configured: true, writable: false } } })
await vi.waitFor(() => { expect(b.state()).toMatchObject({ apiKeyConfigured: true, apiKeyWritable: false }) })
} finally {
b.controller.dispose()
previous.resolve({ ok: true, value: {} })
renamed.resolve({ ok: true, value: {} })
await Promise.all([previous.promise, renamed.promise])
}
})
})
@@ -10,6 +10,7 @@ import { describe, expect, it } from 'vitest'
const packageRoot = resolve(import.meta.dirname, '..')
const bundlePath = join(packageRoot, 'lib/client.js')
const pdfChunkPath = join(packageRoot, 'lib/client.pdf.js')
const syncChunkCall = /(?<![\w$.])[$A-Z_a-z][\w$]*\s*\(\s*(["'`])\.\/client[^"'`/]*\.js\1\s*\)/u
const require = createRequire(import.meta.url)
const licenseNames = [
'LICENSE',
@@ -58,16 +59,15 @@ describe('published document preview licenses', () => {
const client = run('tar', ['-xOf', resolve(packageRoot, packed.filename), 'package/lib/client.js'], packageRoot, task.timeout)
const pdf = run('tar', ['-xOf', resolve(packageRoot, packed.filename), 'package/lib/client.pdf.js'], packageRoot, task.timeout)
expect([...client.matchAll(/require\.async\("(\.\/client[^"/]*\.js)"\)/gu)].map(match => match[1]))
expect([...client.matchAll(/\.async\s*\(\s*(["'`])(\.\/client[^"'`/]*\.js)\1\s*\)/gu)].map(match => match[2]))
.toEqual(['./client.frontmatter-fields.js', './client.pdf.js', './client.excel.js'])
expect(client).not.toMatch(/\brequire\("\.\/client[^"/]*\.js"\)/u)
expect([...pdf.matchAll(/require\("(\.\/client[^"/]*\.js)"\)/gu)].map(match => match[1]))
.toEqual([])
expect(client).not.toMatch(syncChunkCall)
expect(pdf).not.toMatch(syncChunkCall)
expect(client).not.toContain('//! Bundled PDF.js license notices')
expect(client).not.toContain('/pdfjs-dist/')
expect(pdf).toContain('//! Bundled PDF.js license notices')
const excel = run('tar', ['-xOf', resolve(packageRoot, packed.filename), 'package/lib/client.excel.js'], packageRoot, task.timeout)
expect(excel).not.toMatch(/\brequire\("\.\/client[^"/]*\.js"\)/u)
expect(excel).not.toMatch(syncChunkCall)
expect(client).not.toContain('FortuneSheet')
expect(excel).toContain('//! Bundled spreadsheet license notices')
expect(excel).toContain('Copyright (c) 2022 Suzhou Ruilisi Technology Co., Ltd')
@@ -78,7 +78,7 @@ describe('published document preview licenses', () => {
expect(excel).toContain(license.split('\n').map(line => `// ${line}`).join('\n'))
}
const frontmatter = run('tar', ['-xOf', resolve(packageRoot, packed.filename), 'package/lib/client.frontmatter-fields.js'], packageRoot, task.timeout)
expect(frontmatter).not.toMatch(/\brequire\("\.\/client[^"/]*\.js"\)/u)
expect(frontmatter).not.toMatch(syncChunkCall)
let frontmatterInitialized = false
runInNewContext(frontmatter, { window: { __ModuleLoader__: { load: (registration: {
factory: (resolve: (specifier: string) => unknown) => { FrontmatterFields: unknown }
@@ -5,18 +5,20 @@ import { describe, expect, it } from 'vitest'
const packageRoot = resolve(import.meta.dirname, '..')
const entryPath = join(packageRoot, 'lib/client.js')
const terminalPath = join(packageRoot, 'lib/client.terminal.js')
const syncChunkCall = /(?<![\w$.])[$A-Z_a-z][\w$]*\s*\(\s*(["'`])\.\/client[^"'`/]*\.js\1\s*\)/u
describe('terminal client artifacts', () => {
it.skipIf(!existsSync(entryPath))('keeps xterm outside the startup bundle', () => {
expect(existsSync(terminalPath)).toBe(true)
const entry = readFileSync(entryPath, 'utf8')
const terminal = readFileSync(terminalPath, 'utf8')
expect([...entry.matchAll(/require\.async\("(\.\/client[^"/]*\.js)"\)/gu)].map(match => match[1]))
expect([...entry.matchAll(/\.async\s*\(\s*(["'`])(\.\/client[^"'`/]*\.js)\1\s*\)/gu)].map(match => match[2]))
.toEqual(['./client.terminal.js'])
expect(entry).not.toMatch(/\brequire\("\.\/client[^"/]*\.js"\)/u)
expect([...terminal.matchAll(/require\("(\.\/client[^"/]*\.js)"\)/gu)].map(match => match[1]))
.toEqual([])
expect(entry).not.toContain('/@xterm+xterm@')
expect(terminal).toContain('/@xterm+xterm@')
expect(entry).not.toMatch(syncChunkCall)
expect(terminal).not.toMatch(syncChunkCall)
const entryMap = JSON.parse(readFileSync(`${entryPath}.map`, 'utf8')) as { sources: string[] }
const terminalMap = JSON.parse(readFileSync(`${terminalPath}.map`, 'utf8')) as { sources: string[] }
expect(entryMap.sources.some(source => source.includes('/@xterm/xterm/'))).toBe(false)
expect(terminalMap.sources.some(source => source.includes('/@xterm/xterm/'))).toBe(true)
})
})
@@ -15,8 +15,8 @@
en: d152484eb41ac6b4
zh: 09388d293f9be9cb
/deepseek-ai-dsh-client-ui-user-questions/use-this-package:
en: 8d3815c19858ac85
zh: 94fc905fa202d334
en: f63c46f9fc2edb1f
zh: 82ad1b2e56a61a52
/deepseek-ai-dsh-client-ui-user-questions/use-this-package/answering:
en: 8900fbf9cbd72083
zh: 67a951d58a029a58
+1 -1
View File
@@ -25,7 +25,7 @@ The Web client shows an agent's question beside the chat input. Users choose opt
<a id="use-this-package"></a>
## Use this package
When the agent asks a question, the attached card temporarily occupies the composer seat: answer each question, navigate with the pager, or skip it. A first choice marked “Recommended” starts selected, but remains an unsubmitted draft and does not pause a timed countdown. Clicking a single-select choice advances immediately. Enter on a focused option attempts to submit the batch without selecting that option; missing answers return to the first incomplete question. Enter in a text answer continues the flow, while Shift+Enter breaks a line instead (during IME composition Enter only confirms the input candidate without advancing).
When the agent asks a question, the attached card temporarily occupies the composer seat: answer each question, navigate with the pager, or skip it. When a single-select question’s first choice is marked “Recommended”, it starts selected; in a multi-select question, every marked choice starts selected. These preselections remain unsubmitted drafts and do not pause a timed countdown. Clicking a single-select choice advances immediately. Enter on a focused option attempts to submit the batch without selecting that option; missing answers return to the first incomplete question. Enter in a text answer continues the flow, while Shift+Enter breaks a line instead (during IME composition Enter only confirms the input candidate without advancing).
### Answering
@@ -25,7 +25,7 @@ Web 客户端在聊天输入框旁显示 agent(智能体)的提问。用户
<a id="use-this-package"></a>
## 使用本包
当 agent 提问时,附着式卡片会暂时占用编辑器位置:回答每个问题、用翻页器导航,或跳过它。首个带推荐标记的选项会预先选中,但仍只是未提交的草稿,不会暂停计时倒计时。点击单选选项会立即前进。聚焦选项时按 Enter 会尝试提交整组答案,不会选中该选项;若有缺失答案,则回到第一道未完成的问题。文本答案中的 Enter 会继续流程,Shift+Enter 则换行(IME 组合输入期间按 Enter 只会确认输入候选,不会前进)。
当 agent 提问时,附着式卡片会暂时占用编辑器位置:回答每个问题、用翻页器导航,或跳过它。单选题的第一个选项带推荐标记时会预先选中;多选题中所有带推荐标记的选项都会预先选中。这些预选仍只是未提交的草稿,不会暂停计时倒计时。点击单选选项会立即前进。聚焦选项时按 Enter 会尝试提交整组答案,不会选中该选项;若有缺失答案,则回到第一道未完成的问题。文本答案中的 Enter 会继续流程,Shift+Enter 则换行(IME 组合输入期间按 Enter 只会确认输入候选,不会前进)。
### 作答
@@ -49,10 +49,14 @@ export function parseRecommendedLabel(label: string): { label: string; recommend
: { label, recommended: false }
}
/** Only a marked first choice is an implicit draft; the user still submits it. */
function recommendedFirstOption(question: PendingQuestion['questions'][number]): string | undefined {
const label = question.options?.[0]?.label
return label !== undefined && parseRecommendedLabel(label).recommended ? label : undefined
/**
* Implicit draft selection the user still submits: every marked choice of a
* multi-select question, or a marked first choice of a single-select question.
*/
function recommendedOptions(question: PendingQuestion['questions'][number]): string[] {
const labels = (question.options ?? []).map(option => option.label)
const candidates = question.multiSelect === true ? labels : labels.slice(0, 1)
return candidates.filter(label => parseRecommendedLabel(label).recommended)
}
/** Accept persisted progress only when it still describes this question batch. */
@@ -182,9 +186,8 @@ function QuestionFlow({ pending, t, useStore, useQuestionCard, actions }: Questi
return questions.map((item) => {
const answer = recorded.get(item.id)
const custom = answer?.custom ?? ''
const recommended = review === undefined ? recommendedFirstOption(item) : undefined
return {
selected: answer === undefined && recommended !== undefined ? [recommended] : [...answer?.selected ?? []],
selected: answer !== undefined ? [...answer.selected] : review === undefined ? recommendedOptions(item) : [],
custom,
// A recorded answer with no selection and no custom text was skipped.
skipped: answer !== undefined && answer.selected.length === 0 && custom === '',
@@ -240,6 +240,58 @@ describe('QuestionComposer', () => {
}
})
it('starts every recommended choice of a multi-select question selected', () => {
const { carrier, answer } = wait([{
id: 'checks', question: 'Which checks?', multiSelect: true,
options: [{ label: 'Unit (Recommended)' }, { label: 'Lint' }, { label: 'Types(推荐)' }],
}])
render(<QuestionComposer matched={carrier} {...kit} />)
expect(screen.getByRole('checkbox', { name: 'Unit' }).getAttribute('aria-checked')).toBe('true')
expect(screen.getByRole('checkbox', { name: 'Lint' }).getAttribute('aria-checked')).toBe('false')
expect(screen.getByRole('checkbox', { name: 'Types' }).getAttribute('aria-checked')).toBe('true')
fireEvent.keyDown(screen.getByRole('checkbox', { name: 'Lint' }), { key: 'Enter' })
expect(answer).toHaveBeenCalledWith(answerBatch([
{ id: 'checks', selected: ['Unit (Recommended)', 'Types(推荐)'] },
]))
})
it('keeps several recommended multi-select defaults without pausing a timed wait', () => {
const { carrier } = wait([
{
id: 'checks', question: 'Which checks?', multiSelect: true,
options: [{ label: 'Unit (Recommended)' }, { label: 'Lint' }, { label: 'Types (Recommended)' }],
},
{ id: 'note', question: 'Anything else?' },
], Date.now() + 30_000)
try {
const view = render(<QuestionComposer matched={carrier} {...kit} />)
fireEvent.click(screen.getByLabelText('下一题'))
view.unmount()
render(<QuestionComposer matched={carrier} {...kit} />)
expect(carrier.snapshot().countdown?.running).toBe(true)
fireEvent.click(screen.getByLabelText('上一题'))
expect(screen.getByRole('checkbox', { name: 'Unit' }).getAttribute('aria-checked')).toBe('true')
expect(screen.getByRole('checkbox', { name: 'Types' }).getAttribute('aria-checked')).toBe('true')
} finally {
carrier.timeout()
}
})
it('starts only a recommended first choice of a single-select question selected', () => {
const { carrier } = wait([
{ id: 'first', question: 'First?', options: [{ label: 'A (Recommended)' }, { label: 'B (Recommended)' }] },
{ id: 'later', question: 'Later?', options: [{ label: 'C' }, { label: 'D (Recommended)' }] },
])
render(<QuestionComposer matched={carrier} {...kit} />)
expect(screen.getByRole('radio', { name: 'A' }).getAttribute('aria-checked')).toBe('true')
expect(screen.getByRole('radio', { name: 'B' }).getAttribute('aria-checked')).toBe('false')
fireEvent.click(screen.getByLabelText('下一题'))
expect(screen.getByRole('radio', { name: 'C' }).getAttribute('aria-checked')).toBe('false')
expect(screen.getByRole('radio', { name: 'D' }).getAttribute('aria-checked')).toBe('false')
})
it('treats Enter on an unselected option as submit, without selecting it', () => {
const { carrier, answer } = wait([{
id: 'mode', question: 'Which mode?', options: [{ label: 'Alpha' }, { label: 'Beta' }],
@@ -993,6 +1045,28 @@ describe('review card', () => {
expect(screen.queryByPlaceholderText('输入你的答案')).toBeNull()
})
it('shows recorded multi-select answers without restoring recommended defaults', () => {
const questions: PendingQuestion['questions'] = [
{
id: 'checks', question: 'Which checks?', multiSelect: true,
options: [{ label: 'Unit (Recommended)' }, { label: 'Lint' }, { label: 'Types (Recommended)' }],
},
{
id: 'unrecorded', question: 'Which targets?', multiSelect: true,
options: [{ label: 'Web (Recommended)' }, { label: 'Desktop' }],
},
]
const carrier = new PendingQuestion(SID, questions, ToolCallId(REVIEWED_CALL), undefined, [{ id: 'checks', selected: ['Lint'] }])
carrier.attachSeat({ hide: vi.fn() })
render(<QuestionComposer matched={carrier} {...kit} />)
expect(screen.getByRole('checkbox', { name: 'Unit' }).getAttribute('aria-checked')).toBe('false')
expect(screen.getByRole('checkbox', { name: 'Lint' }).getAttribute('aria-checked')).toBe('true')
expect(screen.getByRole('checkbox', { name: 'Types' }).getAttribute('aria-checked')).toBe('false')
fireEvent.click(screen.getByLabelText('下一题'))
expect(screen.getByRole('checkbox', { name: 'Web' }).getAttribute('aria-checked')).toBe('false')
})
it('reads the record back instead of a draft the live card left under the same key', () => {
kit.actions.replace(PendingQuestion.keyOf(SID, REVIEWED_CALL), {
index: 2,
+2 -2
View File
@@ -39,8 +39,8 @@
en: ec2bf804bd1a5439
zh: 316e767507e859ef
/deepseek-ai-dsh-agent-loop/understand-the-implementation/creation-and-teardown:
en: 25be2920f1de4f6f
zh: 279c60a6e1b1767a
en: eaaed8cc22640221
zh: 557e2e67888ef7f6
/deepseek-ai-dsh-agent-loop/understand-the-implementation/persistence-integration:
en: 3b48a480036bd5df
zh: 28cea2036b0dccee
+1 -1
View File
@@ -109,7 +109,7 @@ The loop deep-freezes each derived message identity on its first request and reu
Fresh creation and resume share one rollback-covered initialization: construct the concrete agent and scoped context around the acquired Session; store constructor history, enter the SessionStore, and complete `session/created`; await optional setup and its commit; enter the AgentRegistry; await serial `agent/created` listeners; then release queued input. A caller creating a runtime child sets `options.parentAgent`; the caller Context separately owns the transaction and live handle. Setup, commit, or listener failure and owner disposal roll back the prepared resources. The Session is writable during setup, and every removal emits `session/disposed`, including setup failure before Agent creation is announced. Failed initialization preserves restored inbox input and any events already stored; it rejects only after releasing its scope and acquired write handle. Cancellation while persistence is still creating a write handle can reject earlier; that handle closes when creation settles. Announcements already delivered remain observable and receive matching disposal notifications. Teardown stops and drains the driver, unwinds the scope, closes the session's write path, detaches the agent, then detaches the session. Every detach binds the exact entered object, so a stale disposer cannot remove a later same-id replacement.
The loop awaits inbox and turn-boundary registration before publishing its factory and passes those handles into synchronous Agent construction. During factory unload, global registrations may disappear before teardown finishes; retained handles remain readable through scope cleanup, including cancellation from scoped abort listeners. Caller unload, factory unload, and handle disposal await the same teardown.
The loop awaits its required registrations before publishing its factory. It calls `readerFor(session)` on its model-selection and inbox handles and passes the callbacks to the driver in one typed object; the model and inbox collaborators receive their respective callbacks. During factory unload, global registrations may disappear before teardown finishes; retained handles remain readable through scope cleanup, including cancellation from scoped abort listeners. Caller unload, factory unload, and handle disposal await the same teardown.
### Persistence integration
+1 -1
View File
@@ -109,7 +109,7 @@ const handle = await ctx.agents.create({
新建和恢复共用一个受回滚保护的初始化流程:围绕已取得的 Session 构造具象 agent 与带作用域上下文;存储构造历史、进入 SessionStore 并完成 `session/created`;等待可选 setup 及其 commit;进入 AgentRegistry;等待串行 `agent/created` 监听器;随后释放已排队输入。创建运行时子 Agent 的调用方设置 `options.parentAgent`;调用方 Context 则单独拥有事务和存活句柄。Setup、commit、监听器失败或所有者 dispose 都会回滚已准备的资源。setup 期间 Session 可写;每次移除都会发出 `session/disposed`,包括 Agent 创建宣告前的 setup 失败。初始化失败保留恢复出的收件箱输入及已存储事件,并在释放自身作用域及已取得的写句柄后才拒绝。持久化层仍在创建写句柄时发生取消,可以更早拒绝;该句柄在创建完成后关闭。已送达的宣告仍可被观察,并有配对的销毁通知。Teardown 停止并排空驱动器、撤销作用域、关闭会话写路径、detach agent,再 detach 会话。每次 detach 都绑定到确切进入的对象,因此陈旧 disposer 无法移除之后出现的同 id 替代项。
loop 在发布工厂前等待 inbox 与轮次边界注册完成,并将句柄传入 Agent 的同步构造过程。工厂卸载时,全局注册可以先于 teardown 完成而消失;保留句柄在整个作用域清理期间仍可读取,包括作用域内 abort 监听器发起取消的时刻。调用方卸载、工厂卸载和句柄释放等待同一次 teardown。
loop 在发布工厂前等待必需的注册完成。它对模型选择和 inbox 句柄调用 `readerFor(session)`,将读取回调放入一个类型化对象传给驱动器;模型和 inbox 小组件接收各自的回调。工厂卸载时,全局注册可以先于 teardown 完成而消失;保留句柄在整个作用域清理期间仍可读取,包括作用域内 abort 监听器发起取消的时刻。调用方卸载、工厂卸载和句柄释放等待同一次 teardown。
### 持久化集成
+11 -4
View File
@@ -42,6 +42,14 @@ import { RuntimeContextProjection } from './runtime-context.ts'
import { AssistantStreamAttempt } from './assistant-stream.ts'
import { SystemPromptProjection } from './runtime-context.ts'
/** Projected facts consumed by this driver; registration stays with the factory. */
interface LoopProjections {
/** Current model selection, including pending changes. */
readonly modelSelection: () => ModelSelectionProjectionState
/** Current queued and claimed input. */
readonly inbox: () => InboxState
}
type Phase =
| { kind: 'idle'; lastTurn: number }
| {
@@ -131,16 +139,15 @@ export class ReactLoopAgent implements Agent {
public readonly id: SessionId,
public readonly options: AgentOptions,
public readonly session: Session,
readModel: () => ModelSelectionProjectionState,
readInbox: () => InboxState,
projections: LoopProjections,
lastTurn: number,
) {
this.requestSurfaceGeneration = session.surface.contentGeneration
this.dispatch = agentEvents(loopCtx, this)
this.scope = createScope(loopCtx, this)
this.ctx = this.scope.ctx
this.model = new AgentModel(readModel, session, options)
this.inbox = new ReactLoopInbox(readInbox, session, this.dispatch)
this.model = new AgentModel(projections.modelSelection, session, options)
this.inbox = new ReactLoopInbox(projections.inbox, session, this.dispatch)
this.phase = { kind: 'idle', lastTurn }
this.runtimeContext = new RuntimeContextProjection(this.ctx, session)
this.systemPrompt = new SystemPromptProjection(session)
+5 -4
View File
@@ -553,8 +553,6 @@ export class AgentLoop extends Service implements AgentFactory {
}
}
const untrack = this.ownership.track(dispose)
const modelProjectionHandle = this.modelProjectionHandle
const inboxProjectionHandle = this.inboxProjectionHandle
try {
assertAgentOptions(agentOptions)
ownerCtx.fiber.assertActive()
@@ -567,11 +565,14 @@ export class AgentLoop extends Service implements AgentFactory {
: new Error(`agent "${id}" creation aborted`, { cause: callerSignal.reason })
}
const lastTurn = loopCtx.agents.turnBoundaryOf(session).lastTurn
const projections = {
modelSelection: this.modelProjectionHandle.readerFor(session),
inbox: this.inboxProjectionHandle.readerFor(session),
}
unfollowOwner = ownerCtx.effect(function* () {
const created = machine = new ReactLoopAgent(
loopCtx, id, agentOptions, session,
() => modelProjectionHandle.stateOf(session),
() => inboxProjectionHandle.stateOf(session),
projections,
lastTurn,
)
machineReady.resolve()
@@ -79,7 +79,7 @@ describe('loop-owned request freezing', () => {
const inbox = await loopCtx.sessionProjections.register(inboxProjectionDefinition)
const model = await loopCtx.sessionProjections.register(modelSelectionProjectionDefinition)
const agent = new ReactLoopAgent(loopCtx, id, { provider: 'mock', model: 'mock' }, session,
() => model.stateOf(session), () => inbox.stateOf(session), ctx.agents.turnBoundaryOf(session).lastTurn)
{ modelSelection: model.readerFor(session), inbox: inbox.readerFor(session) }, ctx.agents.turnBoundaryOf(session).lastTurn)
cleanups.push(async () => {
agent.cancel({ kind: 'disposed' })
await agent.whenIdle()
@@ -129,7 +129,7 @@ describe('loop-owned request freezing', () => {
expect(freeze.mock.calls.filter(([value]) => value === userEvent.data)).toHaveLength(1)
expect(freeze.mock.calls.filter(([value]) => value === replacement.data)).toHaveLength(1)
const resumed = new ReactLoopAgent(loopCtx, id, { provider: 'mock', model: 'mock' }, session,
() => model.stateOf(session), () => inbox.stateOf(session), ctx.agents.turnBoundaryOf(session).lastTurn)
{ modelSelection: model.readerFor(session), inbox: inbox.readerFor(session) }, ctx.agents.turnBoundaryOf(session).lastTurn)
cleanups.push(async () => {
resumed.cancel({ kind: 'disposed' })
await resumed.whenIdle()
@@ -15,8 +15,8 @@
en: 4e53164159b5ce41
zh: 89582dc0294d0776
/deepseek-ai-dsh-experimental-webworker-packer/use-this-package:
en: 6a4ec925ea6681f5
zh: 4af12d1d3de38dbd
en: 2c7aff0894ebf4fa
zh: cce7ca3aa5eeac33
/deepseek-ai-dsh-experimental-webworker-packer/model-experience:
en: e16b355530dadc1c
zh: 8488e03b253b7b33
@@ -32,7 +32,7 @@ The pack is a three-layer standard stack:
1. **Roster** — the shipped profile template's bundles and every bundle in `OPTIONAL_BUNDLES` from [`dsh-official-bundles`](../../util/official-bundles/README.md), each resolved from the CLI manifest as the launcher resolves it, plus every package their patch files name (insert lists and grouped rows included), plus the rows of every config tree the CLI declares in its `package.json` `dsh.configTrees`, materialized as a Node-style dependency closure. External peer edges never bind the worker; workspace peers stay on the chain. The CLI manifest itself enters the image alone at `node_modules/@deepseek-ai/dsh/package.json`, as the worker's bundle resolution anchor; the manifest records its name and the profile.
2. **Publish view** — each workspace or vendored package contributes its built npm slice (`files` through picomatch) without source or workspace `dist/`. External packages retain published JavaScript under both `src/` and `dist/` because their `main` or `exports` may point there; only generic test, map, declaration, and archive exclusions apply.
3. **Reachability sweep** — the runtime loader's own resolution walks from every non-wildcard workspace runtime export plus the worker assembly's seeds (`IMAGE_ENTRY_SEEDS`), lowering each reached module to the wrapper contract at pack time. Declaration-only condition trees do not seed the sweep; runtime requests for those exports still fail. The transform reports statically named imports, re-exports, and dynamic imports; calls through `require`; and module-scope direct calls of the form `createRequire(import.meta.url)('pkg')` through a named import from `node:module` or `module`, including an import alias. Page assets (`lib/client.js` behind `./client` exports) ship verbatim; an unresolvable request from our own code fails the pack, third-party ones are tolerated to fail loud at require time.
4. **Lazy chunks** — every page chunk a page asset requests as a literal `require.async("./client.<name>.js")`, the only form the dynamic Client build emits, leaves the base image unless a `./client` export names it. Each becomes its own deterministic archive named `lazy/<sha256 of the archive>.tar.gz` beside the base image, and the manifest registers its path, size, and archive for the worker's lazy filesystem. A request for a chunk the package does not publish fails the pack.
4. **Lazy chunks** — every page chunk requested through the Client factory's injected loader `.async` method with a literal `./client.<name>.js` path leaves the base image unless a `./client` export names it. The scanner accepts the production build's renamed loader variable and single, double, or backtick quotes. Each chunk becomes its own deterministic archive named `lazy/<sha256 of the archive>.tar.gz` beside the base image, and the manifest registers its path, size, and archive for the worker's lazy filesystem. A request for a chunk the package does not publish fails the pack.
`repository.ts` owns the repo-shaped inputs (workspace scan of `vendor/`, `packages/`, `native/system/packages/`, and `apps/`; the profile roster through the shipped templates and optional-bundle list of `dsh-official-bundles` and app-boot's bundle patch readers; the CLI manifest as the installation; the home patch, which sets the runtime's `PLATFORM_ENTRY_CONFIG` fields over each named row's config composed from the template's bundle layers); `pack.ts` owns none of them, so the same library packs a different tree by being called differently. The native scan makes the Landlock entry package an ordinary published-view dependency while its executable remains a Worker platform implementation. The CLI is `dsh-pack-vfs-image --out <file> [--profile web]`; it writes the lazy archives beside the base image, and `apps/web`'s `build:preview` runs it after the preview shell build.
@@ -32,7 +32,7 @@ VFS 镜像打包器:把一份随附 profile 的 bundle 和安装提供的 opti
1. **Roster**——随附 profile 模板的 bundle 和 [`dsh-official-bundles`](../../util/official-bundles/README.zh.md) `OPTIONAL_BUNDLES` 中的每个 bundle(各自按启动器的方式从 CLI manifest 解析),加上它们 patch 文件点名的每个包(含 insert 列表与分组行),再加上 CLI(命令行界面)在 `package.json` `dsh.configTrees` 里声明的每棵配置树的行,按 Node 式依赖闭包物化。外部 peer 边绝不会绑定到 worker,workspace peer 保留在链上。CLI manifest 本身单独进入镜像,位于 `node_modules/@deepseek-ai/dsh/package.json`,作为 worker 解析 bundle 的锚点;manifest 记录它的名称和 profile。
2. **发布视图**——每个 workspace 或 vendored 包贡献其构建后的 npm 切片(`files` 走 picomatch),不带源码和 workspace `dist/`。外部包的 `main` 或 `exports` 可能指向 `src/` 或 `dist/`,因此两处发布 JavaScript 都会保留,只应用通用的测试、map、声明与归档排除规则。
3. **可达性 sweep**——用运行时加载器自己的解析, 从全部不含通配符的 workspace 运行时导出加 worker 装配种子 (`IMAGE_ENTRY_SEEDS`) 出发, 打包时把每个可达模块转换为符合包装层约定的形式. 仅含类型声明的条件树不作为扫描入口; 运行时代码请求这些导出仍会失败. 该转换会报告名称可静态确定的 import、re-export 与动态 import、经 `require` 发起的调用, 以及通过 `node:module` 或 `module` 具名导入 (含导入别名) 在模块作用域直接发起的 `createRequire(import.meta.url)('pkg')` 调用. 页面资产 (`./client` 导出背后的 `lib/client.js`) 原样直发; 自家代码的不可解析请求会让打包失败, 第三方不可解析请求则允许延后到 require 时明确失败.
4. **懒加载 chunk**——页面资产以字面量 `require.async("./client.<name>.js")`(动态 Client 构建产出的唯一形式)请求的每个页面 chunk,除非被 `./client` 导出点名,否则移出基础镜像。每个 chunk 成为基础镜像旁的一个独立确定性归档,命名为 `lazy/<归档的 sha256>.tar.gz`;manifest 为 worker 的懒加载文件系统登记其路径、大小和归档。请求包未发布的 chunk 会让打包失败。
4. **懒加载 chunk**——通过注入 Client factory 的 loader 的 `.async` 方法以字面量 `./client.<name>.js` 路径请求的每个页面 chunk,除非被 `./client` 导出点名,否则移出基础镜像。扫描器支持生产构建中改名后的 loader 变量,以及单引号、双引号或反引号。每个 chunk 成为基础镜像旁的一个独立确定性归档,命名为 `lazy/<归档的 sha256>.tar.gz`;manifest 为 worker 的懒加载文件系统登记其路径、大小和归档。请求包未发布的 chunk 会让打包失败。
`repository.ts` 拥有仓库形态输入(`vendor/`、`packages/`、`native/system/packages/` 与 `apps/` 的 workspace 扫描;经 `dsh-official-bundles` 的随附模板、optional bundle 列表和 app-boot 的 bundle patch 读取器得出 profile roster;以 CLI manifest 作为安装清单;home patch 在模板各 bundle 层合成出的行配置之上设置运行时 `PLATFORM_ENTRY_CONFIG` 字段);`pack.ts` 一概不拥有,同一库换参即可打另一棵树。Native 扫描使 Landlock 入口包成为普通发布视图依赖,其可执行文件仍由 Worker 平台实现。CLI 为 `dsh-pack-vfs-image --out <file> [--profile web]`;它把懒加载归档写在基础镜像旁,`apps/web` 的 `build:preview` 在预览壳构建后运行它。
@@ -580,10 +580,10 @@ function materialize(
}
/**
* Request form the dynamic Client build emits for a package-local chunk: a
* literal `require.async("./client.<name>.js")`, served by the Host on demand.
* Dynamic Client factories request package-local chunks through `.async` with
* a literal path. Minification can rename `require` and change the quote style.
*/
const CHUNK_REQUEST = /\brequire\.async\(\s*(["'])(\.\/client\.[A-Za-z0-9][A-Za-z0-9._-]*\.js)\1\s*\)/g
const CHUNK_REQUEST = /[A-Za-z_$][\w$]*\.async\(\s*(["'`])(\.\/client\.[A-Za-z0-9][A-Za-z0-9._-]*\.js)\1\s*\)/g
/**
* Image paths every materialized package's `./client` export names, under any
@@ -609,7 +609,7 @@ function clientEntriesOf(files: ImageFiles, packages: Iterable<string>): Set<str
}
/**
* Page chunks requested only through `require.async`, in path order.
* Page chunks matched by {@link CHUNK_REQUEST}, in path order.
* @param files - Image entries after the sweep.
* @param eager - Eager Client entry paths, never lazy.
* @returns Image paths to move into lazy archives.
@@ -664,7 +664,7 @@ function compressImage(archive: Uint8Array): Uint8Array {
* The manifest's claim is all-or-nothing: it names the one contract every packed body
* was emitted against. A module the transform cannot express therefore fails the pack
* rather than downgrading the image, because a mostly-transformed image boots into
* errors far from their cause. Page chunks requested through `require.async` leave
* errors far from their cause. Page chunks matched by {@link CHUNK_REQUEST} leave
* the base image for deterministic archives named by their content digest, which the manifest registers.
* @param options - Roster, installation, package index, and paths.
* @returns The compressed image, its lazy archives, and what went into them.
@@ -86,6 +86,28 @@ it('refuses a chunk request whose file the package does not publish', (test) =>
expect(() => packVfsImage(options)).toThrow(/client\.browser\.js requests chunk "\.\/client\.missing\.js"/)
})
it.for(['published', 'missing'] as const)('handles %s chunks with renamed loaders and backtick paths', (publication, test) => {
const options = fixture(test, {
...CHUNKS,
'client.browser.js': 'module.exports=e=>({load:()=>e.async(`./client.pdf.js`)})',
'client.pdf.js': 'module.exports=t=>({worker:()=>t.async(`./client.pdf-worker.js`)})',
})
if (publication === 'missing') {
rmSync(join(options.resolveFrom, 'lib/client.pdf-worker.js'))
expect(() => packVfsImage(options)).toThrow(/client\.pdf\.js requests chunk "\.\/client\.pdf-worker\.js"/)
} else {
const result = packVfsImage(options)
expect(Object.keys(result.files)).toContain(`${PREFIX}/client.browser.js`)
expect(Object.keys(result.files)).toContain(`${PREFIX}/client.orphan.js`)
expect(Object.keys(result.files)).not.toContain(`${PREFIX}/client.pdf.js`)
expect(Object.keys(result.files)).not.toContain(`${PREFIX}/client.pdf-worker.js`)
expect(result.lazyArchives.map(archive => archive.files)).toEqual([
[`${PREFIX}/client.pdf-worker.js`],
[`${PREFIX}/client.pdf.js`],
])
}
})
it('keeps a ./client export target in the base image even when a chunk requests it', (test) => {
const result = packVfsImage(fixture(test, {
'client.browser.js': 'module.exports = { load: () => require.async("./client.pdf.js") }',
@@ -38,7 +38,7 @@ export interface ImageManifest {
readonly visitedEntries: number
/** Visited entries the transform rewrote. */
readonly rewrittenEntries: number
/** Page chunks requested only through `require.async`, one archive each. */
/** Lazily requested page chunks, one archive each. */
readonly lazy: readonly ImageLazyArchive[]
}
@@ -7382,7 +7382,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [
},
{
name: 'ProjectionHandle',
declaration: 'export interface ProjectionHandle<S> {\n stateOf(session: Session): S;\n dispose(): Promise<void>;\n}',
declaration: 'export interface ProjectionHandle<S> {\n stateOf(session: Session): S;\n readerFor(session: Session): () => S;\n dispose(): Promise<void>;\n}',
},
{
name: 'ProjectionKeySelection',
@@ -24,8 +24,11 @@
en: 09758d1475fad86e
zh: 473637cb34aebe72
/deepseek-ai-dsh-session-projection/use-this-package/register-and-read:
en: 976fb019501a941b
zh: e15038a7205337c3
en: f64bc8038aecfcae
zh: fb5fb0999468fac0
/deepseek-ai-dsh-session-projection/use-this-package/bind-several-states-to-one-session:
en: dac4ea4d67ce057d
zh: 1cf3e5c7af5a5203
/deepseek-ai-dsh-session-projection/use-this-package/deprecated-plugin-compatibility:
en: eed1ad9d62755251
zh: 88a07c787528009a
@@ -63,6 +63,21 @@ const state = todoProjectionHandle.stateOf(session)
const { asOfSeq, values } = ctx.sessionProjections.snapshot(session)
```
<a id="bind-several-states-to-one-session"></a>
### Bind several states to one Session
Call `handle.readerFor(session)` on an awaited registration handle to obtain a `() => S` callback. Calling it reads the current state without a Session argument. An owner composing several states passes a typed object of these callbacks to its runtime. New states add properties instead of constructor arguments; ordinary plugins still use domain-service methods.
```text
const projections = {
todo: todoProjectionHandle.readerFor(session),
goal: goalProjectionHandle.readerFor(session),
}
const todo = projections.todo()
```
Each reader captures the exact Session and delegates to the original handle's `stateOf(session)`, preserving readiness requirements, null and undefined values, state references, and synchronous failures. Creating a reader does not read state, prepare the Session, perform storage I/O, or create a state cache. Readers own no registration or disposal. The original handle keeps its disposal responsibility; a reader keeps reading the original unit after deregistration or version replacement. One handle can create readers for several Sessions independently. Registration and Session preparation remain the owner's responsibility; client snapshots remain separate.
A domain that owns projected state declares `sessionProjections` as a Cordis service dependency and keeps its handle private. Consumers inject that domain service and use its methods, such as `ctx.agents.turnBoundaryOf(session)`, without importing definitions or retaining projection readers. Optional contributors may register under `ctx.inject(['sessionProjections'], …)`. Carriers use `ctx.get('sessionProjections')` and omit their block or frames when the registry is absent.
<a id="deprecated-plugin-compatibility"></a>
@@ -63,6 +63,21 @@ const state = todoProjectionHandle.stateOf(session)
const { asOfSeq, values } = ctx.sessionProjections.snapshot(session)
```
<a id="bind-several-states-to-one-session"></a>
### 将多个状态绑定到一个 Session
对已等待注册完成的句柄调用 `handle.readerFor(session)`,即可得到 `() => S` 回调。调用它时无需 Session 参数即可读取当前状态。组合多个状态的所有者将这些回调放入一个类型化对象,交给运行时。新增状态只增加属性,不增加构造参数;普通插件仍通过领域服务的方法读取。
```text
const projections = {
todo: todoProjectionHandle.readerFor(session),
goal: goalProjectionHandle.readerFor(session),
}
const todo = projections.todo()
```
每个读取函数保存确切的 Session,并将读取委托给原句柄的 `stateOf(session)`,保留就绪要求、null 和 undefined 值、状态引用及同步失败。创建读取函数不读取状态、不准备 Session、不执行存储 I/O,也不创建状态缓存。读取函数不拥有注册或释放职责。原句柄仍负责释放;注销或版本替换后,读取函数仍读取原有单元。同一句柄可为多个 Session 独立创建读取函数。注册和 Session 准备仍由原所有者完成;客户端快照保持独立。
持有投影状态的领域将 `sessionProjections` 声明为 Cordis 服务依赖,并在内部保留句柄。消费方注入该领域服务并使用其方法,例如 `ctx.agents.turnBoundaryOf(session)`,无需导入定义或保留投影读取句柄。可选贡献方可以在 `ctx.inject(['sessionProjections'], …)` 下注册。载体使用 `ctx.get('sessionProjections')`,注册表缺席时省略自己的块或帧。
<a id="deprecated-plugin-compatibility"></a>
@@ -56,6 +56,13 @@ export interface ProjectionHandle<S> {
* @returns the projection state at the Session's current cursor.
*/
stateOf(session: Session): S
/**
* Create a reader for one exact Session without reading state or preparing it.
* The reader retains this unit after unregistration and owns no disposal.
* @param session - Session whose committed events the bound reader folds.
* @returns a synchronous callback with the same state and failures as `stateOf(session)`.
*/
readerFor(session: Session): () => S
/**
* Unregister from global drives and snapshots without invalidating this reader.
* @returns a promise that resolves when this registration is released.
@@ -400,14 +407,16 @@ export class SessionProjectionRegistry extends Service {
// Observe disposal during the asynchronous registration handoff before exposing a reader.
await Promise.resolve()
this.ctx.fiber.assertActive()
return {
const handle: ProjectionHandle<S> = {
async dispose() {
await dispose()
},
stateOf: (session) => {
return this.cellFor(registration, session).state as S
},
readerFor: session => () => handle.stateOf(session),
}
return handle
}
/**
@@ -3,7 +3,7 @@ import { Context } from '@deepseek-ai/cordis'
import SessionStore from '@deepseek-ai/dsh-session'
import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection'
import { describe, expect, it, onTestFinished, vi } from 'vitest'
import { describe, expect, expectTypeOf, it, onTestFinished, vi } from 'vitest'
import { z } from 'zod'
declare module '@deepseek-ai/dsh-session-projection/types' {
@@ -32,10 +32,113 @@ async function setup() {
}
describe('retained projection readers', () => {
it('binds typed host states to the exact Session without reading unrelated units', async () => {
const { ctx, owner, session } = await setup()
const unrelatedInit = vi.fn(() => 0)
const unrelatedApply = vi.fn((state: number) => state)
await ctx.sessionProjections.register({
key: 'test/bound-unrelated', stateSchema: z.number(), stateVersion: 1,
init: unrelatedInit, apply: unrelatedApply,
})
const countInit = vi.fn(definition.init)
const countApply = vi.fn(definition.apply)
const count = await owner.ctx.sessionProjections.register({ ...definition, init: countInit, apply: countApply })
const hostInit = vi.fn((): { turn: number } | null => null)
const hostApply = vi.fn((state: { turn: number } | null, event: Parameters<ProjectionDefinition<'test/reader', number>['apply']>[1]) => (
event.type === 'turn/start' ? { turn: event.data.turn } : state
))
const host = await owner.ctx.sessionProjections.register({
key: 'test/bound-host', stateSchema: z.object({ turn: z.number() }).nullable(), stateVersion: 1,
init: hostInit, apply: hostApply,
})
const initialized = { count: countInit.mock.calls.length, host: hostInit.mock.calls.length, unrelated: unrelatedInit.mock.calls.length }
const applied = { count: countApply.mock.calls.length, host: hostApply.mock.calls.length, unrelated: unrelatedApply.mock.calls.length }
const reader = { count: count.readerFor(session), host: host.readerFor(session) }
expect({
count: countInit.mock.calls.length, host: hostInit.mock.calls.length, unrelated: unrelatedInit.mock.calls.length,
}).toEqual(initialized)
expect({
count: countApply.mock.calls.length, host: hostApply.mock.calls.length, unrelated: unrelatedApply.mock.calls.length,
}).toEqual(applied)
const initialCount = reader.count()
expectTypeOf(initialCount).toEqualTypeOf<number>()
expect(initialCount).toBe(0)
const initialHost = reader.host()
expectTypeOf(initialHost).toEqualTypeOf<{ turn: number } | null>()
expect(initialHost).toBeNull()
expect(unrelatedInit).toHaveBeenCalledTimes(initialized.unrelated)
expect(unrelatedApply).toHaveBeenCalledTimes(applied.unrelated)
const other = ctx.sessions.create()
const otherReader = count.readerFor(other)
other.append('turn/start', { turn: 1 })
expect(otherReader()).toBe(1)
expect(reader.count()).toBe(0)
session.append('turn/start', { turn: 2 })
expect(reader.count()).toBe(1)
expect(reader.host()).toEqual({ turn: 2 })
expect(reader.host()).toBe(host.stateOf(session))
const read = reader.host
expect(read()).toBe(host.stateOf(session))
})
it('retains the bound unit after owner disposal and version replacement', async () => {
const { ctx, owner, session } = await setup()
const original = await owner.ctx.sessionProjections.register(definition)
const reader = original.readerFor(session)
await owner.dispose()
expect(ctx.sessionProjections.checkpoint(session)).toEqual({})
const replacement = await ctx.sessionProjections.register({ ...definition, stateVersion: 2, apply: state => state + 10 })
const changed = vi.fn()
ctx.sessionProjections.onChanged(changed)
session.append('turn/start', { turn: 1 })
expect(reader()).toBe(1)
expect(original.readerFor(session)()).toBe(1)
expect(replacement.stateOf(session)).toBe(10)
expect(ctx.sessionProjections.snapshot(session).values).toEqual({ 'test/reader': 10 })
expect(changed).toHaveBeenCalledOnce()
expect(ctx.sessionProjections.checkpoint(session)['test/reader']?.ver).toBe(2)
})
it('does not read during binding and preserves the original synchronous failure', async () => {
const { owner, session } = await setup()
const failure = new Error('host state cannot initialize')
const init = vi.fn((): number => { throw failure })
const broken = await owner.ctx.sessionProjections.register({
key: 'test/bound-failure', stateSchema: z.number(), stateVersion: 1,
init, apply: state => state,
})
const initialized = init.mock.calls.length
const reader = broken.readerFor(session)
expect(init).toHaveBeenCalledTimes(initialized)
let caught: unknown
try {
reader()
} catch (error) {
caught = error
}
expect(caught).toBe(failure)
})
it('preserves undefined state without substituting a value', async () => {
const { owner, session } = await setup()
const handle = await owner.ctx.sessionProjections.register({
key: 'test/bound-undefined', stateSchema: z.number().optional(), stateVersion: 1,
init: () => undefined,
apply: (state, event) => event.type === 'turn/start' ? event.data.turn : state,
})
const read = handle.readerFor(session)
expectTypeOf(read()).toEqualTypeOf<number | undefined>()
expect(read()).toBeUndefined()
session.append('turn/start', { turn: 1 })
expect(read()).toBe(1)
})
it.each(['handle', 'fiber'] as const)('reads new events after %s disposal without rejoining snapshots or notifications', async (release) => {
const { ctx, owner, session } = await setup()
const apply = vi.fn(definition.apply)
const handle = await owner.ctx.sessionProjections.register({ ...definition, apply })
const read = handle.readerFor(session)
const changed = vi.fn()
ctx.sessionProjections.onChanged(changed)
expect(handle.stateOf(session)).toBe(0)
@@ -47,6 +150,7 @@ describe('retained projection readers', () => {
session.append('turn/start', { turn: 2 })
expect(apply).toHaveBeenCalledTimes(1)
expect(handle.stateOf(session)).toBe(2)
expect(read()).toBe(2)
expect(apply).toHaveBeenCalledTimes(2)
expect(changed).toHaveBeenCalledOnce()
expect(ctx.sessionProjections.snapshot(session).values).toEqual({})
@@ -28,6 +28,11 @@ export async function checkProjectionRegistrationTypes(registry: SessionProjecti
const host = await registry.register(counter)
expectTypeOf(host).toEqualTypeOf<ProjectionHandle<number>>()
expectTypeOf(host.stateOf(session)).toEqualTypeOf<number>()
const read = host.readerFor(session)
expectTypeOf(read).toEqualTypeOf<() => number>()
expectTypeOf(read()).toEqualTypeOf<number>()
// @ts-expect-error -- a bound reader cannot be retargeted at read time.
read(session)
const nullable = await registry.register({
key: 'type-test/nullable',
@@ -40,6 +45,7 @@ export async function checkProjectionRegistrationTypes(registry: SessionProjecti
},
})
expectTypeOf(nullable.stateOf(session)).toEqualTypeOf<string | null>()
expectTypeOf(nullable.readerFor(session)()).toEqualTypeOf<string | null>()
const visible = {
...counter,
+24 -4
View File
@@ -259,10 +259,30 @@ describe('client bundle package asset imports', () => {
write: false, clean: false, exports: false, report: false, logLevel: 'silent',
})
const output = builds.flatMap(bundle => bundle.chunks).find(chunk => chunk.type === 'chunk' && chunk.fileName === 'client.js')
const code = output?.type === 'chunk' ? output.code : ''
expect(code).toContain(`require.asset(${JSON.stringify(WHALE_URL)})`)
expect(code).not.toContain('__dshPackageAsset_')
expect(code).toContain('"__dshPackageAsset("')
if (output?.type !== 'chunk') throw new Error('asset fixture client output missing')
type AssetRequire = ((specifier: string) => never) & { asset(reference: string): string }
const requests: string[] = []
const require: AssetRequire = Object.assign((specifier: string): never => {
throw new Error(`Unexpected synchronous module request: ${specifier}`)
}, {
asset(reference: string): string {
requests.push(reference)
return `resolved:${reference}`
},
})
const registrations: { id: string; factory(require: AssetRequire): { url: string; text: string } }[] = []
runInNewContext(output.code, { window: { __ModuleLoader__: { load(value: typeof registrations[number]) {
registrations.push(value)
} } } })
expect(registrations).toHaveLength(1)
const registration = registrations[0]
if (registration === undefined) throw new Error('asset fixture factory registration missing')
expect(registration.id).toBe(PACKAGE_NAME)
expect(requests).toEqual([])
const exports = registration.factory(require)
expect(exports.url).toBe(`resolved:${WHALE_URL}`)
expect(exports.text).toBe('__dshPackageAsset(')
expect(requests).toEqual([WHALE_URL])
} finally {
for (const bundle of builds) await bundle[Symbol.asyncDispose]()
}
+199 -3
View File
@@ -3,9 +3,11 @@
* chaining, and physical watch dependencies hidden behind virtual CSS Modules.
*/
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { SourceMap } from 'node:module'
import { tmpdir } from 'node:os'
import { dirname, join, relative } from 'node:path'
import { fileURLToPath } from 'node:url'
import { runInNewContext } from 'node:vm'
import { build, type Rolldown, type TsdownBundle, type UserConfig } from 'tsdown'
import { describe, expect, it, onTestFinished, vi } from 'vitest'
import { clientBundle, requestedExternals, staticLinked } from '../packages/client/tsdown.client.ts'
@@ -120,6 +122,24 @@ function dynamicImportFixture(prefix: string): string {
return root
}
interface ClientFactoryRegistration<Value, Require> {
id: string
chunk?: string
factory(require: Require): Value
}
function registerClientFactory<Value, Require>(code: string): ClientFactoryRegistration<Value, Require> {
const registrations: ClientFactoryRegistration<Value, Require>[] = []
runInNewContext(code, { window: { __ModuleLoader__: { load(value: ClientFactoryRegistration<Value, Require>) {
registrations.push(value)
} } } })
expect(registrations).toHaveLength(1)
const registration = registrations[0]
if (registration === undefined) throw new Error('client factory registration missing')
expect(registration.id).toBe(REQUESTING_PACKAGE)
return registration
}
describe('client bundle dynamic imports', () => {
it('keeps a dual Client browser chunk disjoint from its Node output', async () => {
const root = dynamicImportFixture('dsh-dual-client-chunk-')
@@ -155,15 +175,191 @@ describe('client bundle dynamic imports', () => {
write: false, clean: false, exports: false, report: false, logLevel: 'silent',
})
const chunks = builds.flatMap(bundle => bundle.chunks).filter(chunk => chunk.type === 'chunk')
const output = chunks.find(chunk => chunk.fileName === 'client.js')?.code
expect(output).toContain('require.async("./client.terminal.js")')
expect(output).not.toContain('Promise.resolve().then(() => require("./client.terminal.js"))')
const entry = chunks.find(chunk => chunk.fileName === 'client.js')
const terminal = chunks.find(chunk => chunk.fileName === 'client.terminal.js')
if (entry === undefined || terminal === undefined) throw new Error('dynamic import fixture outputs missing')
type Terminal = { marker: string }
type Require = ((specifier: string) => never) & { async(specifier: string): Promise<Terminal> }
const requests: string[] = []
const require: Require = Object.assign((specifier: string): never => {
throw new Error(`Unexpected synchronous module request: ${specifier}`)
}, {
async(specifier: string): Promise<Terminal> {
requests.push(specifier)
expect(specifier).toBe('./client.terminal.js')
const registration = registerClientFactory<Terminal, Require>(terminal.code)
expect(registration.chunk).toBe('client.terminal.js')
return Promise.resolve(registration.factory(require))
},
})
const registration = registerClientFactory<{ load(): Promise<Terminal> }, Require>(entry.code)
expect(registration.chunk).toBeUndefined()
const exports = registration.factory(require)
expect(requests).toEqual([])
await expect(exports.load()).resolves.toEqual({ marker: 'terminal' })
expect(requests).toEqual(['./client.terminal.js'])
} finally {
for (const bundle of builds) await bundle[Symbol.asyncDispose]()
}
})
})
interface CompressionFixtureDetails {
describeScore(value: number): string
}
interface CompressionFixtureEntry {
calculateScore(values: readonly number[]): number
activate(): number
incrementScore(value: number): number
decrementScore(value: number): number
FixtureAccumulator: { new (seed: number): { total(values: readonly number[]): number }; readonly name: string }
loadDetails(): Promise<CompressionFixtureDetails>
}
type CompressionFixtureRequire = ((specifier: string) => never) & {
async(specifier: string): Promise<CompressionFixtureDetails>
}
describe('production client bundle compression', () => {
it('keeps executable exports, lazy chunks, names, notices and maps while compressing production only', async () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-client-compression-'))
onTestFinished(() => { rmSync(root, { recursive: true, force: true }) })
const directory = join(root, 'lib/types/client')
mkdirSync(directory, { recursive: true })
writeFileSync(join(root, 'package.json'), JSON.stringify({ name: REQUESTING_PACKAGE, type: 'module' }))
// Every long local contributes to a runtime result; comments and dead branches cannot earn the byte reduction.
const terms = Array.from({ length: 24 }, (_, index) => `intermediateContributionForInputPosition${index}`)
const entrySource = [
'/*! @license Fixture arithmetic license */',
'export function calculateScore(values) {',
...terms.map((name, index) => ` const ${name} = values[${index}] * ${index + 1} + ${index + 2};`),
` return ${terms.join(' + ')};`,
'}',
'export class FixtureAccumulator {',
' constructor(seed) { this.seed = seed; }',
' total(values) { return this.seed + calculateScore(values); }',
'}',
'export const activate = () => 7;',
'export { collisionLabel as incrementScore } from "./increment.js";',
'export { collisionLabel as decrementScore } from "./decrement.js";',
'export function loadDetails() { return import("./details.js"); }',
'',
].join('\n')
const detailSource = [
'/*! @license Fixture detail license */',
'export function describeScore(value) {',
' const descriptiveScorePrefix = "score";',
' return descriptiveScorePrefix + ":" + value;',
'}',
'',
].join('\n')
writeFileSync(join(directory, 'index.js'), entrySource)
writeFileSync(join(directory, 'details.js'), detailSource)
writeFileSync(join(directory, 'increment.js'), 'export function collisionLabel(value) { return value + 1; }\n')
writeFileSync(join(directory, 'decrement.js'), 'export function collisionLabel(value) { return value - 1; }\n')
const namesByMode = new Map<string, readonly string[]>()
for (const mode of ['production', 'development'] as const) {
const previousNodeEnv = process.env.NODE_ENV
const noticeBody = '// Copyright Fixture Authors\n// Permission is granted to use this fixture.'
let config: UserConfig | undefined
try {
process.env.NODE_ENV = mode
config = clientBundle(root, ['lib/types/index.js'], {
clientBanner: fileName => `//! Fixture banner for ${fileName}\n${noticeBody}`,
})({ env: { DSH_BUILD_FACE: 'client' } }).find(candidate => candidate.platform === 'browser')
} finally {
if (previousNodeEnv === undefined) delete process.env.NODE_ENV
else process.env.NODE_ENV = previousNodeEnv
}
if (config === undefined) throw new Error('client config missing')
const builds = await build({
...config, cwd: root, config: false, tsconfig: false,
write: false, clean: false, exports: false, report: false, logLevel: 'silent',
})
try {
const chunks = builds.flatMap(bundle => bundle.chunks).filter(chunk => chunk.type === 'chunk')
expect(chunks.map(chunk => chunk.fileName).sort()).toEqual(['client.details.js', 'client.js'])
const entry = chunks.find(chunk => chunk.fileName === 'client.js')
const details = chunks.find(chunk => chunk.fileName === 'client.details.js')
if (entry === undefined || details === undefined) throw new Error('client fixture outputs missing')
const requests: string[] = []
const require: CompressionFixtureRequire = Object.assign((specifier: string): never => {
throw new Error(`Unexpected synchronous module request: ${specifier}`)
}, {
async(specifier: string): Promise<CompressionFixtureDetails> {
requests.push(specifier)
expect(specifier).toBe('./client.details.js')
const registration = registerClientFactory<CompressionFixtureDetails, CompressionFixtureRequire>(details.code)
expect(registration.chunk).toBe('client.details.js')
return Promise.resolve(registration.factory(require))
},
})
const registration = registerClientFactory<CompressionFixtureEntry, CompressionFixtureRequire>(entry.code)
expect(registration.chunk).toBeUndefined()
const exports = registration.factory(require)
const values = Array.from({ length: terms.length }, (_, index) => index * 3 - 7)
const expected = values.reduce((sum, value, index) => sum + value * (index + 1) + index + 2, 0)
expect(exports.calculateScore(values)).toBe(expected)
expect(new exports.FixtureAccumulator(9).total(values)).toBe(expected + 9)
expect(exports.incrementScore(expected)).toBe(expected + 1)
expect(exports.decrementScore(expected)).toBe(expected - 1)
expect(exports.calculateScore.name).toBe('calculateScore')
expect(exports.activate()).toBe(7)
expect(exports.activate.name).toBe('activate')
expect(exports.FixtureAccumulator.name).toBe('FixtureAccumulator')
namesByMode.set(mode, [exports.incrementScore.name, exports.decrementScore.name])
expect(requests).toEqual([])
const loaded = await exports.loadDetails()
expect(requests).toEqual(['./client.details.js'])
expect(loaded.describeScore(expected)).toBe(`score:${expected}`)
expect(loaded.describeScore.name).toBe('describeScore')
for (const [chunk, source, notice, name] of [
[entry, entrySource, 'Fixture arithmetic license', 'calculateScore'],
[details, detailSource, 'Fixture detail license', 'describeScore'],
] as const) {
expect(chunk.code).toContain(`@license ${notice}`)
expect(chunk.code).toContain(`//! Fixture banner for ${chunk.fileName}\n${noticeBody}`)
expect(chunk.map?.sourcesContent).toContain(source)
expect(chunk.map?.mappings.length).toBeGreaterThan(0)
expect(chunk.code.trimEnd().endsWith(`//# sourceMappingURL=${chunk.fileName}.map`)).toBe(true)
if (chunk.map === null) throw new Error('client fixture source map missing')
const map = new SourceMap({
...chunk.map, file: chunk.fileName, sourceRoot: '',
sourcesContent: chunk.map.sourcesContent.map(content => content ?? ''),
})
const marker = `function ${name}`
expect(chunk.code).toContain(marker)
// Rolldown maps a function declaration to the start of its export statement.
const generatedOffset = chunk.code.indexOf(marker)
const originalOffset = source.indexOf(`export ${marker}`)
const generatedLines = chunk.code.slice(0, generatedOffset).split('\n')
const originalLines = source.slice(0, originalOffset).split('\n')
expect(map.findEntry(generatedLines.length - 1, generatedLines.at(-1)!.length)).toMatchObject({
originalLine: originalLines.length - 1,
originalColumn: originalLines.at(-1)!.length,
})
}
if (mode === 'production') {
// These ceilings include the executable factory, loader call, legal notices and source-map reference.
expect(Buffer.byteLength(entry.code)).toBeLessThanOrEqual(1600)
expect(Buffer.byteLength(details.code)).toBeLessThanOrEqual(600)
} else {
expect(entry.code).toContain('intermediateContributionForInputPosition0')
}
} finally {
for (const bundle of builds) await bundle[Symbol.asyncDispose]()
}
}
// Minification preserves the bundler's names, including any static-module name collision suffixes.
expect(namesByMode.get('production')).toEqual(namesByMode.get('development'))
})
})
function clientSourceMapPath(packagePath: string): string {
return fileURLToPath(new URL(`../packages/${packagePath}/lib/client.js.map`, import.meta.url))
}
@@ -0,0 +1,23 @@
{"type":"session","version":4,"id":"{{session:1}}","createdAt":1788240617068,"cwd":"{{cwd}}","isSeeded":false,"delegationDepth":0,"agentPreset":"standard"}
{"type":"permission/preset","data":{"preset":"workspace-write"}}
{"type":"sandbox/mode","data":{"mode":"workspace-write"}}
{"type":"approval/policy","data":{"policy":"ask"}}
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Use the ask_user_question tool to ask me exactly one multi-select question with id \"checks\", question \"Which checks should run before merging?\", header \"Checks\", and three options in this order: label \"Unit tests (Recommended)\", label \"Full e2e suite\", and label \"Type check (Recommended)\". Set multi_select to true. After I answer, reply with the single word DONE and stop."}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"role":"user","id":"{{message:1}}"}]}}
{"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":"{{message:2}}"}},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"Use the ask_user_question tool to ask me exactly one multi-select question with id \"checks\", question \"Which checks should run before merging?\", header \"Checks\", and three options in this order: label \"Unit tests (Recommended)\", label \"Full e2e suite\", and label \"Type check (Recommended)\". Set multi_select to true. After I answer, reply with the single word DONE and stop."}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\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\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"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":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}
{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}}
{"type":"session/title","data":{"title":"Use the ask_user_question tool to","messageSeqs":[8],"source":{"kind":"fallback"}}}
{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants a multi-select question with two recommended options. Let me ask it."},{"type":"tool-call","id":"call_00_RecommendedChecks0001","name":"ask_user_question","arguments":"{\"questions\": [{\"id\": \"checks\", \"question\": \"Which checks should run before merging?\", \"header\": \"Checks\", \"multi_select\": true, \"options\": [{\"label\": \"Unit tests (Recommended)\"}, {\"label\": \"Full e2e suite\"}, {\"label\": \"Type check (Recommended)\"}]}]}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:5}}"},"usage":{"inputTokens":113,"outputTokens":80,"cacheReadTokens":4096,"reasoningTokens":16},"stream":[{"type":"chunk","time":1790389322730,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1790389322746,"index":0,"dt":[],"texts":["The user wants a multi-select question with two recommended options. Let me ask it."]},{"type":"chunk","time":1790389322762,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1790389322778,"index":1,"dt":[16],"id":"call_00_RecommendedChecks0001","name":"ask_user_question","args":["","{\"questions\": [{\"id\": \"checks\", \"question\": \"Which checks should run before merging?\", \"header\": \"Checks\", \"multi_select\": true, \"options\": [{\"label\": \"Unit tests (Recommended)\"}, {\"label\": \"Full e2e suite\"}, {\"label\": \"Type check (Recommended)\"}]}]}"]},{"type":"chunk","time":1790389322810,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants a multi-select question with two recommended options. Let me ask it."}}},{"type":"chunk","time":1790389322826,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_RecommendedChecks0001","name":"ask_user_question","arguments":"{\"questions\": [{\"id\": \"checks\", \"question\": \"Which checks should run before merging?\", \"header\": \"Checks\", \"multi_select\": true, \"options\": [{\"label\": \"Unit tests (Recommended)\"}, {\"label\": \"Full e2e suite\"}, {\"label\": \"Type check (Recommended)\"}]}]}"}}},{"type":"chunk","time":1790389322842,"chunk":{"type":"usage","usage":{"inputTokens":113,"outputTokens":80,"cacheReadTokens":4096,"reasoningTokens":16}}},{"type":"chunk","time":1790389322858,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"}
{"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_00_RecommendedChecks0001","name":"ask_user_question","arguments":"{\"questions\": [{\"id\": \"checks\", \"question\": \"Which checks should run before merging?\", \"header\": \"Checks\", \"multi_select\": true, \"options\": [{\"label\": \"Unit tests (Recommended)\"}, {\"label\": \"Full e2e suite\"}, {\"label\": \"Type check (Recommended)\"}]}]}"}}
{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_00_RecommendedChecks0001"},"toolCallId":"call_00_RecommendedChecks0001","content":[{"type":"text","text":"{\"answers\":[{\"id\":\"checks\",\"selected\":[\"Unit tests (Recommended)\",\"Type check (Recommended)\"]}]}"}],"isError":false,"id":"{{message:6}}"}},"sourceEventSeqs":[15],"surfaceOp":"append"}
{"type":"step/end","data":{"turn":1,"step":1}}
{"type":"step/start","data":{"turn":1,"step":2}}
{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user kept both recommended checks. I should reply DONE and stop."},{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:7}}"},"usage":{"inputTokens":220,"outputTokens":18,"cacheReadTokens":4096,"reasoningTokens":14},"stream":[{"type":"chunk","time":1790389325337,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1790389325353,"index":0,"dt":[],"texts":["The user kept both recommended checks. I should reply DONE and stop."]},{"type":"chunk","time":1790389325369,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1790389325385,"index":1,"dt":[],"texts":["DONE"]},{"type":"chunk","time":1790389325401,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user kept both recommended checks. I should reply DONE and stop."}}},{"type":"chunk","time":1790389325417,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1790389325433,"chunk":{"type":"usage","usage":{"inputTokens":220,"outputTokens":18,"cacheReadTokens":4096,"reasoningTokens":14}}},{"type":"chunk","time":1790389325449,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"}
{"type":"step/end","data":{"turn":1,"step":2}}
{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}}
@@ -0,0 +1,7 @@
version: 1
scenario: question-composer-recommended
profile: web
composition: web-default
recording: authored
header:
class: web-default
@@ -0,0 +1,16 @@
- region "Which checks should run before merging?":
- text: Checks
- button "Collapse the question card" [expanded]
- button "Dismiss all questions"
- heading "Which checks should run before merging?" [level=2]
- group:
- checkbox "Unit tests" [checked]: Unit tests Recommended
- checkbox "Full e2e suite"
- checkbox "Type check" [checked]: Type check Recommended
- textbox "Type your answer"
- button "Previous question" [disabled]
- text: 1 / 1
- button "Next question" [disabled]
- status
- button "Skip"
- button "Submit"
+1
View File
@@ -62,6 +62,7 @@
"apps/web/tests/subagent-fork-schedule.snapshot.ts",
"apps/web/tests/live-interactions.e2e.ts",
"apps/web/tests/question-composer.e2e.ts",
"apps/web/tests/question-composer-recommended.e2e.ts",
"apps/web/tests/question-ptc.e2e.ts",
"apps/web/tests/approval-composer.e2e.ts",
"apps/web/tests/plan-control-row.e2e.ts",