Merge pull request #4681 from deepseek-harness/xtr/default-workspace-first-send

feat(workspace): prepare a default workspace on startup
This commit is contained in:
07akioni authored and GitHub committed 2026-09-20 21:04:06 +08:00
commit 27fa7ed9ff
62 files changed
+1160 -63

No files matched your search

@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.md
2026-07-25-web-client-session-scope-and-provide-channel.md: 32be87f3a0a4f8da92100ec7351af788862532f7
2026-07-25-web-client-session-scope-and-provide-channel.zh.md: b2e7efae98efb69d5f34d6719a382221ffc7a00d
2026-07-25-web-client-session-scope-and-provide-channel.md: 76561bc0e330b3e3a26607569ae327217d0a0b67
2026-07-25-web-client-session-scope-and-provide-channel.zh.md: d5d92b2ca53ba78929dd8591a6ded7028e4fed24
@@ -26,7 +26,7 @@ The reference-owned lifetime and Provider targeting now follow [Client Session r
Host-side `session.create(workspaceId)` produces Session + Agent + cwd in one piece (an atomic bundle, never split); the client side is the mirror of that birth — the instant a session row enters the list mirror, the client mints its Agent scope (actx + provide + the full input surface mounted):
- Session identity is the host's true form from birth: the sessionId arrives via the `session.create` response / the `host/session-added` frame, and every client-side address (the scope tag, slot store keys, RPC addressing) uses that same id.
- The materialization moment = the instant the user picks a Workspace (cwd settled): the client calls `session.create({workspaceId})` on the spot and receives the complete entity.
- A manual Workspace pick or successful [first-use startup initialization](../feature/2026-09-20-default-workspace.md) establishes cwd before the client calls `session.create({workspaceId})` and receives the complete entity.
- "New Session with no workspace picked" is a **pure view state** (a navigation position) corresponding to no session/scope entity; until the pick, the composer is locked whole (no slash, no plain text).
- A "blank session" is an ordinary materialized session with no turn yet; to Agent-scope plugins on the host (goal/plan/skill/…) it remains an ordinary Session, so slash/plan are naturally live.
@@ -26,7 +26,7 @@ web client 只有一张全局会话面:slot 全部从根上下文渲染,插
host 侧 `session.create(workspaceId)` 一体产出 Session + Agent + cwd(作为不可拆分的原子整体);client 侧就是这次出生的镜像——会话行进入 list mirror 的瞬间,client 为它铸 Agent scope(actx + provide + 输入面全套挂上):
- 会话身份自出生即为 host 真身:sessionId 由 `session.create` 响应 / `host/session-added` 帧带来,client 侧一切寻址(scope tag、slot store 键、RPC 地址)用的都是同一个 id。
- 实体化时点 = 用户选定 Workspace(cwd 确定)的瞬间:client 当场调 `session.create({workspaceId})`,拿到完整实体。
- 手动选定 Workspace 或完成[首次使用的启动初始化](../feature/2026-09-20-default-workspace.zh.md) 后,cwd 已确定,client 再调 `session.create({workspaceId})`,拿到完整实体。
- 「New Session 且未选 workspace」是**纯视图态**(一个导航位置),不对应任何会话/scope 实体;选定之前 composer 整体锁死(无 slash、无纯文本)。
- 「空会话」是尚无轮次的普通实体化会话;对 host 上的 Agent-scope 插件(goal/plan/skill(技能)/…)而言,它仍是普通 Session,因此 slash/plan 自然可用。
@@ -0,0 +1,6 @@
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-09-20-default-workspace.md
2026-09-20-default-workspace.md: 1674079403b17fb1bd984052a85975609179cad0
2026-09-20-default-workspace.zh.md: 81a7c96efa3d8b8d4673b684b59babe339706f29
@@ -0,0 +1,33 @@
# Agent Note: First-use default Workspace
Status: implemented
English | [中文](2026-09-20-default-workspace.zh.md)
## Problem
A new installation requires a directory choice before the user can send a first message. Removing that prerequisite must preserve the Session's fixed working directory and must not treat hidden or archived history as a new installation.
## Decision
Startup waits for complete Workspace and Session baselines. When both lists are empty, the Client asks the Host to prepare the default Workspace, then creates or reuses and selects its blank Session. Input stays unavailable until a Session exists and uses the ordinary composer pipeline thereafter. [Session scope and provisioning](../architecture/2026-07-25-web-client-session-scope-and-provide-channel.md) owns blank-Session reuse and provisioning rationale.
The [Workspace registry](../../../../packages/workspace/workspace/README.md#first-use-workspace) owns eligibility and directory preparation. All live Sessions, persisted headers, and archived identities count, including entries absent from the sidebar. The operation shares the registry mutation queue and rechecks Session history after directory preparation because Sessions can start independently.
The Client resolves the initial directory name and title from its language at startup. The Host controller resolves the Documents location; the registry receives a directory resolver with no locale dependency. The resolver runs inside the mutation queue only for eligible creation, so repeated requests reuse the durable Workspace without another OS lookup. A durable Workspace id records successful initialization independently of that name. Renaming, changing language, restarting, or deleting the registration cannot initialize another default. The marker commits with the registration, so a failed registration can retry. Directory contents remain subject to the existing [metadata-only deletion policy](2026-07-27-workspace-registration-deletion.md).
Ineligible first use returns no Workspace without a failure dialog. Preparation failure offers the existing folder picker; startup does not retry on later list notifications. A successful registration survives Session creation or prompt failure. Selecting either the default or a manually picked Workspace never submits a message.
## Alternatives considered
- Creating only when sending avoids unused directories but requires a separate local draft, transfer into a Session, and coordination of the first submission. Startup creation accepts the early filesystem effect and uses ordinary Session input throughout.
- Falling back to `<home>/Documents` when system lookup is unavailable would choose an unverified Documents location; deployments that need another directory use the explicit Host override.
- Inferring first use from visible sidebar rows would ignore archived, hidden, and cwd-less Sessions.
- Using the localized path as the initialization marker would allow language changes or deletion to create another default.
- Changing a Session's cwd after creation would change the meaning of its recorded tools and attachments.
## Consequences
Opening a new installation can create a directory and blank Session before the user sends a message. Directory authorization and preparation failures can appear during startup. Preparation remains a Host responsibility for both Desktop and remote Web clients, so remote users use the Host account's Documents location. Unavailable Documents lookup fails with the same folder-selection recovery as directory creation failure.
The feature preserves [reference-owned Client Session lifetimes](../architecture/2026-09-15-client-session-references.md) and requires no agent-loop or Session-event change. Registry and client tests cover retries, hidden history, concurrency, and startup cancellation; the [browser scenario](../../../../apps/web/tests/default-workspace.e2e.ts) verifies the assembled startup, reload, first-send, and picker paths with an isolated Documents directory and recorded Session replay.
@@ -0,0 +1,33 @@
# Agent Note: 首次使用默认 Workspace
Status: implemented
[English](2026-09-20-default-workspace.md) | 中文
## Problem
新安装的应用要求用户先选目录才能发送第一条消息。去掉这一步前置操作时,必须保留 Session 的固定工作目录,也不能把隐藏或已归档的历史误判为新安装。
## Decision
启动时等待完整的 Workspace 和 Session 基线。两份列表均为空时,Client 请求 Host 准备默认 Workspace,随后创建或复用并选中其空白 Session。Session 存在前不可输入,之后使用常规 composer 流程。[Session scope 与供给通道](../architecture/2026-07-25-web-client-session-scope-and-provide-channel.zh.md)负责 blank Session 复用与供给通道的理由。
[Workspace registry](../../../../packages/workspace/workspace/README.zh.md#first-use-workspace)负责资格判断和目录准备。所有 live Session、持久化 header 和已归档身份都计入判断,包括侧栏中不可见的条目。操作共用 registry 修改队列,并在目录准备后重新检查 Session 历史,因为 Session 可以独立启动。
Client 在启动时按其语言解析初始目录名和标题。Host 控制器解析 Documents 位置;注册表接收不依赖 locale 的目录解析器。解析器仅在允许创建时于变更队列内运行,因此重复请求直接复用持久化的 Workspace,无需再次查询操作系统目录。持久化 Workspace id 独立于名称记录初始化成功。改名、切换语言、重启或删除登记均不能再次初始化默认工作区。标记与登记一起提交,因此登记失败可以重试。目录内容仍遵循已有的[仅删除元数据策略](2026-07-27-workspace-registration-deletion.zh.md)。
不符合首次使用条件时不返回 Workspace,也不显示失败弹窗。准备失败时提供现有文件夹选择器;后续列表通知不会触发启动流程重试。成功的登记会在 Session 创建或提示词发送失败后保留。选中默认或手动选择的 Workspace 均不会提交消息。
## Alternatives considered
- 仅在发送时创建可以避免未使用的目录,但需要独立的本地草稿、向 Session 转移草稿及首次提交协调逻辑。启动时创建接受提前写入文件系统的副作用,始终使用普通 Session 输入。
- 系统查询不可用时回退到 `<home>/Documents`,会选择未经确认的 Documents 位置;需要其他目录的部署使用显式 Host 覆盖配置。
- 根据侧栏可见行推断首次使用,会忽略已归档、隐藏和无 cwd 的 Session。
- 将本地化路径作为初始化标记,会允许切换语言或删除后再次创建默认工作区。
- 在 Session 创建后更改 cwd,会改变其已记录工具和附件的含义。
## Consequences
打开新安装的应用即可在用户发送消息前创建目录和空白 Session。目录授权与准备失败提示可能在启动期间出现。Desktop 和远程 Web 客户端均由 Host 准备目录,因此远程用户使用 Host 账户的 Documents 位置。Documents 查询不可用时,采用与目录创建失败相同的文件夹选择恢复路径。
该功能保留[由引用持有的 Client Session 生命周期](../architecture/2026-09-15-client-session-references.zh.md),无需修改 agent-loop 或 Session 事件。Registry 和客户端测试覆盖重试、隐藏历史、并发及启动取消;[浏览器场景](../../../../apps/web/tests/default-workspace.e2e.ts)通过隔离的 Documents 目录和已录制 Session 回放验证完整装配下的启动、刷新、首次发送与选择器路径。
+2 -2
View File
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write apps/web/tests/README.md
README.md: b2fa27bb7a60ed78309bf81e77b9cd5217bbee2a
README.zh.md: 29ae2e86018257a4fc2379ea2563c8b5e5e9036f
README.md: 8b9c58ce9e4cf2f5f6978c0c6eb5517fe000d3d2
README.zh.md: 199ae3b56166aa2ffa1c0bed9a16b844ffd7b74f
+2
View File
@@ -4,6 +4,8 @@ English | [中文](README.zh.md)
These tests boot the real web composition in-process and drive it with a real Chromium over real HTTP. The lane's mechanics — modes, fixtures, goldens, and the deliberate composition divergences from `dsh web` — are documented in [`scaffold.ts`](scaffold.ts) and the [browser e2e Agent Note](../../../.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md).
Ordinary scenarios begin with no registered Workspace or Session and a durable marker recording a removed default Workspace, so explicit folder-selection scenarios retain control of their cwd. `launchWebScaffold({ firstUse: true })` leaves initialization eligible for startup scenarios.
## Completion observations
State-sensitive cases use Workspace, admission, attachment, and model-stream barriers to separate visible intermediate states from completed operations. Details close waits for frame transitions; archive verification assigns an explicit title to the seeded Session and follows that identity across reload. See the [CI fixture synchronization decision](../../../.agents/notes/implemented/testing/2026-09-08-ci-completion-observations.md).
+2
View File
@@ -4,6 +4,8 @@
这些测试在进程内启动真实的 web 组合,并用真实 Chromium 通过真实 HTTP 驱动它。该 lane 的运行机制——模式、fixture(测试前置数据)、golden,以及与 `dsh web` 之间刻意保留的组合差异——记录在 [`scaffold.ts`](scaffold.ts) 和 [浏览器 e2e Agent Note](../../../.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.zh.md) 中。
普通场景以没有已登记 Workspace 或 Session、但持久化标记记录默认 Workspace 已被删除的状态启动,使显式文件夹选择场景自行决定 cwd。`launchWebScaffold({ firstUse: true })` 保留初始化资格,供启动场景使用。
## 完成状态观察
依赖状态的用例使用 Workspace、接纳、附件和模型流屏障,区分可见中间状态与已完成操作。详情关闭等待框架过渡结束;归档验证为 seed Session 设置显式标题,并跨重载跟踪该身份。参见 [CI fixture 同步决策](../../../.agents/notes/implemented/testing/2026-09-08-ci-completion-observations.zh.md)。
+135
View File
@@ -0,0 +1,135 @@
/** First-use startup prepares a durable Workspace through the shipped Web composition. */
import { mkdir, readFile, stat, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { chromium } from 'playwright'
import { describe, expect, it, onTestFinished } from 'vitest'
import {
assertFinalWorkspaceSnapshot, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, launchWebScaffold,
selectedSessionFixture, watchConsole, webSnapshotMode,
} from './scaffold.ts'
import { newEnglishPage, saveFailureShot } from './support.ts'
const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/fresh-round-trip/session.v3.jsonl', import.meta.url))
const EXPECTED = fileURLToPath(new URL('../../../snapshots/web/default-workspace/ui.expected.md', import.meta.url))
const FAILURE_EXPECTED = fileURLToPath(new URL('./expected/default-workspace/failure.expected.md', import.meta.url))
const MODE = webSnapshotMode()
describe.skipIf(MODE === 'record')('web e2e: default Workspace', () => {
it('prepares a blank Session on startup, reuses it after reload, and sends through the ordinary composer', async () => {
const fixture = await selectedSessionFixture(FIXTURE)
const scaffold = await launchWebScaffold({
firstUse: true,
replayFixture: fixture,
// The shared recording remains read-only; replay compares the complete persisted Session.
compareReplaySession: MODE === 'replay',
paceMs: 5,
})
onTestFinished(() => scaffold.close())
const browser = await chromium.launch()
try {
const page = await newEnglishPage(browser)
const tripwire = watchConsole(page)
try {
await page.goto(scaffold.authenticatedUrl)
const input = page.locator('[data-composer-input][contenteditable="true"]').first()
await input.waitFor()
expect(scaffold.ctx.workspaceRegistry.list()).toHaveLength(1)
const initialSession = scaffold.ctx.sessions.list()[0]!
expect(scaffold.ctx.sessions.list()).toHaveLength(1)
expect(initialSession.snapshotEvents().some(event => event.type === 'user/message')).toBe(false)
await page.reload()
await input.waitFor()
expect(scaffold.ctx.sessions.list().map(session => session.id)).toEqual([initialSession.id])
const prompt = fixtureUserPrompts(await readFile(fixture, 'utf8'))[0]!
await input.fill(prompt)
const settled = scaffold.whenTurnSettled()
await input.press('Enter')
const sessionId = await settled
const workspace = scaffold.ctx.workspaceRegistry.list()[0]!
expect(workspace.title).toBe('Default workspace')
expect(workspace.path).toBe(join(scaffold.workspaceCwd, 'Documents', 'deepseek-harness', 'Default workspace'))
expect((await stat(workspace.path)).isDirectory()).toBe(true)
expect(workspace.sessionIds).toContain(sessionId)
expect(scaffold.ctx.sessions.get(sessionId)?.header.cwd).toBe(workspace.path)
await assertFinalWorkspaceSnapshot(fileURLToPath(new URL('../../../snapshots/web/default-workspace', import.meta.url)), workspace.path)
await page.getByText('DONE', { exact: true }).waitFor()
await compareOrRefreshGolden(EXPECTED, await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd), MODE)
expect(tripwire.pageErrors).toEqual([])
expect(tripwire.warnings).toEqual([])
} catch (error) {
await saveFailureShot(page, 'web-e2e-default-workspace')
throw error
}
} finally {
await browser.close()
}
})
it('reports a startup directory conflict and opens the composed folder picker for recovery', async () => {
const scaffold = await launchWebScaffold({ firstUse: true })
onTestFinished(() => scaffold.close())
const parent = join(scaffold.workspaceCwd, 'Documents', 'deepseek-harness')
await mkdir(parent, { recursive: true })
await writeFile(join(parent, '默认工作区'), 'occupied')
const chosen = join(scaffold.workspaceCwd, 'chosen')
await mkdir(chosen)
const browser = await chromium.launch()
try {
const page = await browser.newPage({ locale: 'zh-CN', timezoneId: 'Asia/Shanghai' })
const tripwire = watchConsole(page)
try {
await page.goto(scaffold.authenticatedUrl)
const input = page.locator('[data-composer-input][contenteditable="true"]').first()
const notice = page.getByRole('alert').filter({ hasText: '无法创建默认工作区' })
await notice.waitFor()
expect(scaffold.ctx.workspaceRegistry.list()).toEqual([])
expect(scaffold.ctx.sessions.list()).toEqual([])
await compareOrRefreshGolden(FAILURE_EXPECTED, await notice.ariaSnapshot(), MODE)
expect(await page.getByRole('dialog').count()).toBe(0)
expect(await input.count()).toBe(0)
await page.getByRole('button', { name: '选择工作区', exact: true }).click()
const picker = page.getByRole('dialog', { name: '选择工作区目录' })
await picker.waitFor()
await picker.getByRole('button', { name: '编辑路径', exact: true }).click()
await picker.getByRole('textbox', { name: '编辑路径' }).fill(chosen)
await page.keyboard.press('Enter')
await picker.getByRole('button', { name: '打开', exact: true }).click()
await picker.waitFor({ state: 'hidden' })
await expect.poll(() => scaffold.ctx.workspaceRegistry.list().length).toBe(1)
await input.waitFor()
expect(await input.textContent()).toBe('')
expect(scaffold.ctx.workspaceRegistry.list()[0]?.path).toBe(chosen)
expect(scaffold.ctx.sessions.list()).toHaveLength(1)
expect(scaffold.ctx.sessions.list().every(session =>
session.snapshotEvents().every(event => event.type !== 'user/message'))).toBe(true)
expect(tripwire.pageErrors).toEqual([])
expect(tripwire.warnings).toEqual([])
} catch (error) {
await saveFailureShot(page, 'web-e2e-default-workspace-failure')
throw error
}
} finally {
await browser.close()
}
})
it('keeps an explicitly deleted default absent on startup', async () => {
const scaffold = await launchWebScaffold()
onTestFinished(() => scaffold.close())
const browser = await chromium.launch()
try {
const page = await newEnglishPage(browser)
const attempted = page.waitForResponse(response => response.url().includes('/api/workspace/initializeDefault'))
await page.goto(scaffold.authenticatedUrl)
expect((await attempted).ok()).toBe(true)
await page.getByRole('button', { name: 'Choose workspace', exact: true }).waitFor()
expect(await page.getByRole('alert').filter({ hasText: 'Unable to create default workspace' }).count()).toBe(0)
expect(await page.locator('[data-composer-input][contenteditable="true"]').count()).toBe(0)
expect(scaffold.ctx.workspaceRegistry.list()).toEqual([])
expect(scaffold.ctx.sessions.list()).toEqual([])
} finally {
await browser.close()
}
})
})
@@ -0,0 +1 @@
- alert: 无法创建默认工作区,请通过“选择工作区”选择文件夹
+8
View File
@@ -392,6 +392,8 @@ export interface LaunchOptions {
deepSeekMissingCredential?: boolean
/** Leave the current welcome notice pending; ordinary scenarios pre-acknowledge it before browser boot. */
welcomeNoticePending?: boolean
/** Leave first-use Workspace initialization eligible; ordinary scenarios start after the default was removed. */
firstUse?: boolean
/**
* Patch the shipped DeepSeek search row to a deterministic endpoint and
* credential reference. Browser search scenarios keep the real provider and
@@ -592,6 +594,8 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise<We
// to an absolute temp root (removed with the workspace at close) so tests
// never write the user's harness home.
{ id: 'storage-json', config: { root: join(workspaceCwd, '.dsh-storages') } },
// First-use initialization must create directories only inside this scaffold's temporary world.
{ id: 'workspace-controller', config: { documentsDirectory: join(workspaceCwd, 'Documents') } },
// Skill discovery is model-visible input. Pin every host-level root inside
// the owned temp world so ~/.dsh, ~/.agents, and a bundled-root env setting
// cannot change replay requests or conversation goldens. Project roots stay
@@ -815,6 +819,10 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise<We
op: 'set', path: [WELCOME_NOTICE_ACK_FIELD], value: WELCOME_NOTICE_VERSION,
}])
}
if (options.firstUse !== true && ctx.workspaceRegistry.list().length === 0) {
const initial = await ctx.workspaceRegistry.initializeDefault(async () => ({ path: workspaceCwd, title: 'Workspace' }))
if (initial !== undefined) await ctx.workspaceRegistry.delete(initial.id)
}
const boundPort = ctx.get('webServer')?.port
if (boundPort === undefined) {
throw new Error('web e2e scaffold: webServer service missing after settled boot')
+1
View File
@@ -63,6 +63,7 @@
"tests/deepseek-messages-chat.e2e.ts",
"tests/models-settings-recovery.e2e.ts",
"tests/default-model.e2e.ts",
"tests/default-workspace.e2e.ts",
"tests/github-ready-review.e2e.ts",
"tests/streaming-fence-highlight.e2e.ts",
"tests/declared-reasoning.e2e.ts",
+2 -2
View File
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write docs/config-catalog.md
config-catalog.md: 2927b510976631695978f46ed3c012641b4d73a9
config-catalog.zh.md: 6d57dbe759fee5eaea9e755731fcf22666e8f0f3
config-catalog.md: 6bd14a5aa194de15463c0d63639c0f5095995f99
config-catalog.zh.md: ed0a6cbcc7b28e3875b50ba90e427ca06e90a8dc
+18 -1
View File
@@ -276,6 +276,24 @@ export interface Config {
Source: [`packages/api/terminal-controller/src/index.ts:26`](../packages/api/terminal-controller/src/index.ts)
<a id="deepseek-aidsh-api-workspace-controller"></a>
## `@deepseek-ai/dsh-api-workspace-controller`
Requires: `typert` · `workspaceRegistry`
```ts config-catalog
/** First-use directory policy for the Host account. */
export interface Config {
/** Override the system Documents directory with a fully qualified path. */
documentsDirectory?: string
/** Maximum duration of the operating system's Documents lookup. */
documentsLookupTimeoutMs?: number
}
```
Source: [`packages/api/workspace-controller/src/index.ts:34`](../packages/api/workspace-controller/src/index.ts)
<a id="deepseek-aidsh-api-workspace-files"></a>
## `@deepseek-ai/dsh-api-workspace-files`
@@ -3802,7 +3820,6 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co
- `@deepseek-ai/dsh-acp-app` — requires `cmdlineArgs` ([`packages/bundle/acp-app/src/index.ts`](../packages/bundle/acp-app/src/index.ts))
- `@deepseek-ai/dsh-agent` ([`packages/core/agent/src/index.ts`](../packages/core/agent/src/index.ts))
- `@deepseek-ai/dsh-api-remotes` — requires `typertGateway` ([`packages/api/remotes/src/index.ts`](../packages/api/remotes/src/index.ts))
- `@deepseek-ai/dsh-api-workspace-controller` — requires `typert` · `workspaceRegistry` ([`packages/api/workspace-controller/src/index.ts`](../packages/api/workspace-controller/src/index.ts))
- `@deepseek-ai/dsh-authorization` — requires `credentials` ([`packages/credentials/authorization/src/index.ts`](../packages/credentials/authorization/src/index.ts))
- `@deepseek-ai/dsh-browser-use` ([`packages/browser-use/browser-use/src/index.ts`](../packages/browser-use/browser-use/src/index.ts))
- `@deepseek-ai/dsh-client-file-upload` — requires `agents` · `attachments` · `commands` · `connection` ([`packages/client/file-upload/src/index.ts`](../packages/client/file-upload/src/index.ts))
+18 -1
View File
@@ -278,6 +278,24 @@ export interface Config {
来源: [`packages/api/terminal-controller/src/index.ts:26`](../packages/api/terminal-controller/src/index.ts)
<a id="deepseek-aidsh-api-workspace-controller"></a>
## `@deepseek-ai/dsh-api-workspace-controller`
需要:`typert` · `workspaceRegistry`
```ts config-catalog
/** First-use directory policy for the Host account. */
export interface Config {
/** Override the system Documents directory with a fully qualified path. */
documentsDirectory?: string
/** Maximum duration of the operating system's Documents lookup. */
documentsLookupTimeoutMs?: number
}
```
源码:[`packages/api/workspace-controller/src/index.ts:34`](../packages/api/workspace-controller/src/index.ts)
<a id="deepseek-aidsh-api-workspace-files"></a>
## `@deepseek-ai/dsh-api-workspace-files`
@@ -3804,7 +3822,6 @@ export interface Config {
- `@deepseek-ai/dsh-acp-app` — 需要 `cmdlineArgs`([`packages/bundle/acp-app/src/index.ts`](../packages/bundle/acp-app/src/index.ts))
- `@deepseek-ai/dsh-agent`([`packages/core/agent/src/index.ts`](../packages/core/agent/src/index.ts))
- `@deepseek-ai/dsh-api-remotes` — 需要 `typertGateway`([`packages/api/remotes/src/index.ts`](../packages/api/remotes/src/index.ts))
- `@deepseek-ai/dsh-api-workspace-controller` — 需要 `typert` · `workspaceRegistry`([`packages/api/workspace-controller/src/index.ts`](../packages/api/workspace-controller/src/index.ts))
- `@deepseek-ai/dsh-authorization` — 需要 `credentials`([`packages/credentials/authorization/src/index.ts`](../packages/credentials/authorization/src/index.ts))
- `@deepseek-ai/dsh-browser-use` ([`packages/browser-use/browser-use/src/index.ts`](../packages/browser-use/browser-use/src/index.ts))
- `@deepseek-ai/dsh-client-file-upload` — 需要 `agents` · `attachments` · `commands` · `connection`([`packages/client/file-upload/src/index.ts`](../packages/client/file-upload/src/index.ts))
+2 -2
View File
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write docs/subsystems/workspace.md
workspace.md: 9fe5f2bf4c62ba7d4f878b7b2f34490f43ca0b81
workspace.zh.md: 63681e1a459c81a327654cfafa1f5cb2f231d6c8
workspace.md: 323323946ac92bbc03962b83c5e77a81a960d89a
workspace.zh.md: aedd1134305aaa7e97ccd449631ff72446bf28b4
+24
View File
@@ -121,6 +121,10 @@ Ownership truth is the record's ordered `sessionIds`, never derived from session
Sessions get their cwd at create time from whoever creates them, not from this registry — the API gateway resolves a new session's cwd from the chosen workspace's `path` (falling back to an explicit or default cwd), creates the session so the cwd lands in its immutable [`SessionHeader`](persistence.md#sessionheader--metadata-beside-the-log), then calls `attachSession`, which re-validates that stored header cwd against the workspace path. On the first successful start, the registry bootstraps history from persisted headers alone (`id`, `cwd`, `createdAt` — never event bodies), grouping sessions with a valid canonical cwd into per-directory workspaces, newest first; the initialized marker is written last so an interrupted bootstrap resumes safely. The bootstrap is one-time: cwd-less legacy sessions stay Ungrouped, and sessions created afterwards join a workspace only through `attachSession`.
## Default Workspace initialization
The controller's [transport types](../../packages/api/workspace-controller/src/types.ts) define `WorkspaceInitializeDefaultRequest`: a Client-resolved `directoryName` and initial `title`. The Host resolves the Documents location and asks the registry to initialize once. Locale selection belongs to the Client; the registry accepts a directory resolver and commits the registration with its durable identity. [First-use behavior and configuration](../../packages/api/workspace-controller/README.md#first-use-workspace) describe reuse and failure handling.
## Session pinning
The controller's [transport types](../../packages/api/workspace-controller/src/types.ts) define `WorkspacePinSessionRequest` and `WorkspaceUnpinSessionRequest`, each carrying one `sessionId`. Both operations return `WorkspacePinValue`: the complete `pinnedSessionIds` array of Session ids, most recently pinned first. Pinning requires a known, unarchived Session; unpinning an id that is not pinned succeeds without changing the set. Archiving removes the Session's pin in the same durable write, and unarchiving does not restore it.
@@ -301,6 +305,14 @@ Host service backing the generated `ctx.remote.workspace` namespace.
*/
@Remote('create') create(request: WorkspaceCreateRequest): Promise<WorkspaceCreateValue>
/**
* Initialize or reuse the default Workspace during first-use startup.
* @param request - initial directory name and title; never rename an existing default.
* @param signal - caller lifetime; cancels native directory lookup.
* @returns the durable Workspace, or undefined when first-use initialization is ineligible; creates no Session or message.
*/
@Remote('initializeDefault') async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal: AbortSignal): Promise<WorkspaceValue | undefined>
/**
* Rename one Workspace to a unique non-blank title.
* @param request - Workspace identity and proposed title.
@@ -466,6 +478,18 @@ Durable workspace registry. Startup waits for `sessionPersistence`, builds one c
*/
async create(path: string, title?: string): Promise<Workspace>
/**
* Initialize the default Workspace only while both the registry and Session
* history are empty. Repeated requests reuse its durable identity; deleting
* that registration permanently disables automatic creation.
* @param resolveDirectory - resolve the absolute directory and initial title;
* called only for eligible creation, inside the registry mutation queue.
* Missing directories are created recursively before registration.
* After resolution, caller cancellation does not roll back creation or registration.
* @returns the initialized Workspace, or undefined when automatic creation is ineligible.
*/
initializeDefault(resolveDirectory: () => Promise<{ path: string; title: string }>): Promise<Workspace | undefined>
/**
* Look up a workspace by id.
* @param id - Workspace id.
+24
View File
@@ -121,6 +121,10 @@ interface Workspace {
会话的 cwd 在创建时由创建者赋予,而不是由本注册表赋予——API 网关从所选工作区的 `path` 解析新会话的 cwd(回退到显式或默认 cwd),先创建会话使 cwd 落入其不可变的 [`SessionHeader`](persistence.zh.md#sessionheader--metadata-beside-the-log),再调用 `attachSession`,后者会把已存储的 header cwd 与工作区路径重新校验一遍。首次成功启动时,注册表仅凭已持久化的 header(`id`、`cwd`、`createdAt`——绝不读事件正文)引导历史:把规范 cwd 有效的会话按目录分组为工作区,最新的排在最前;「已初始化」标记最后写入,因此被中断的引导可以安全续跑。引导只发生这一次:没有 cwd 的历史遗留会话保持 Ungrouped,此后创建的会话只能通过 `attachSession` 加入工作区。
## 默认工作区初始化
控制器的[传输类型](../../packages/api/workspace-controller/src/types.ts)定义了 `WorkspaceInitializeDefaultRequest`,包含 Client 解析出的 `directoryName` 和初始 `title`。Host 解析 Documents 位置,并请求注册表执行一次初始化。语言选择由 Client 负责;注册表接收目录解析器,并将登记与持久化身份一起提交。[首次使用行为与配置](../../packages/api/workspace-controller/README.zh.md#first-use-workspace)说明复用和失败处理。
## 会话置顶
控制器的[传输类型](../../packages/api/workspace-controller/src/types.ts)定义了 `WorkspacePinSessionRequest` 和 `WorkspaceUnpinSessionRequest`,两者都携带一个 `sessionId`。两个操作都返回 `WorkspacePinValue`:完整的会话 id 数组 `pinnedSessionIds`,最近置顶的会话排在前面。置顶要求会话已知且未归档;对未置顶的 id 取消置顶会成功,且不改变集合。归档在同一次持久化写入中移除该会话的置顶,取消归档不会恢复置顶。
@@ -301,6 +305,14 @@ Host service backing the generated `ctx.remote.workspace` namespace.
*/
@Remote('create') create(request: WorkspaceCreateRequest): Promise<WorkspaceCreateValue>
/**
* Initialize or reuse the default Workspace during first-use startup.
* @param request - initial directory name and title; never rename an existing default.
* @param signal - caller lifetime; cancels native directory lookup.
* @returns the durable Workspace, or undefined when first-use initialization is ineligible; creates no Session or message.
*/
@Remote('initializeDefault') async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal: AbortSignal): Promise<WorkspaceValue | undefined>
/**
* Rename one Workspace to a unique non-blank title.
* @param request - Workspace identity and proposed title.
@@ -466,6 +478,18 @@ Durable workspace registry. Startup waits for `sessionPersistence`, builds one c
*/
async create(path: string, title?: string): Promise<Workspace>
/**
* Initialize the default Workspace only while both the registry and Session
* history are empty. Repeated requests reuse its durable identity; deleting
* that registration permanently disables automatic creation.
* @param resolveDirectory - resolve the absolute directory and initial title;
* called only for eligible creation, inside the registry mutation queue.
* Missing directories are created recursively before registration.
* After resolution, caller cancellation does not roll back creation or registration.
* @returns the initialized Workspace, or undefined when automatic creation is ineligible.
*/
initializeDefault(resolveDirectory: () => Promise<{ path: string; title: string }>): Promise<Workspace | undefined>
/**
* Look up a workspace by id.
* @param id - Workspace id.
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/api/workspace-controller/README.md
README.md: 46556b0105bb5186cf27b56faee4127b358eac9b
README.zh.md: 9d210c10486a71772cf6c0a10480b734fa992441
README.md: 27053331007681eb373b4537514bbe701dad660d
README.zh.md: d0726496de5dcf623fedb531ad988b3c608fc2ac
@@ -26,6 +26,20 @@ The Host controller serializes mutations whose correctness depends on current re
The Client entry provides `ClientWorkspaceModel` and `createWorkspaceStateStream()`. The model owns Workspace rows, registry order, archived and pinned Session identities, unary mutation echoes, and stream/unary race resolution. A newer Host row wins by `updatedAt`; a committed stream order outranks an older unary response; a removed Workspace id cannot be resurrected by delayed data. Pin snapshots change only when their identities or order change. The package exposes framework-neutral snapshots and subscriptions, leaving navigation policy and React hooks to the UI owner.
<a id="first-use-workspace"></a>
### First-use Workspace
`workspace.initializeDefault({ directoryName, title })` returns the durable default Workspace; the Client service exposes the same request as `workspaces.initializeDefault(request, signal?)`. The [Workspace Client](../../client/ui-workspace/README.md) resolves these names from its startup language. The Host places the directory under its account's `<Documents>/deepseek-harness`, including on remote Web hosts. The directory name must be one non-blank segment without separators, colon, NUL, surrounding whitespace, or a trailing dot; the title must be non-blank. OS filename restrictions also apply. Linux system lookup requires `xdg-user-dir` with an enabled Documents directory; hosts without it must configure `documentsDirectory` or use the folder picker.
The [Workspace registry](../../workspace/workspace/README.md#first-use-workspace) owns eligibility, directory creation, and durable initialization. An existing default Workspace is returned without another Documents lookup; request names do not rename it. Ineligible first use returns `undefined`, so startup can leave directory selection to the user. Invalid names reject with `gateway/bad-request`; lookup and creation failures use standard Remote error handling. Initialization creates no Session and sends no message.
| Configuration | Default | Purpose |
| --- | --- | --- |
| `documentsDirectory` | System Documents directory | Fully qualified Host directory override |
| `documentsLookupTimeoutMs` | `10000` | Positive maximum duration of OS directory lookup, in milliseconds |
Documents lookup holds the registry mutation queue, so other Workspace mutations, including registration of a picked directory, can wait up to `documentsLookupTimeoutMs`. Cancellation can stop the lookup; after resolution succeeds, it does not roll back creation or registration.
-----
<a id="model-experience"></a>
@@ -26,6 +26,20 @@ Host 控制器会串行执行正确性取决于当前注册表状态的变更,
Client 入口提供 `ClientWorkspaceModel` 和 `createWorkspaceStateStream()`。该模型拥有 Workspace 行、registry 顺序、归档与置顶会话身份、一元变更回显,以及流与一元调用的竞态处理。较新的 Host 行按 `updatedAt` 获胜;已提交的流顺序优先于较旧的一元响应;已经移除的 Workspace id 不会被延迟数据复活。置顶快照仅在会话身份或顺序变化时更新。该包公开与框架无关的快照和订阅,把导航策略与 React 钩子留给 UI owner。
<a id="first-use-workspace"></a>
### 首次使用工作区
`workspace.initializeDefault({ directoryName, title })` 返回持久化的默认工作区;Client service 通过 `workspaces.initializeDefault(request, signal?)` 提供同一请求。[Workspace Client](../../client/ui-workspace/README.zh.md)按启动时的语言解析这些名称。Host 将目录放在其账户的 `<Documents>/deepseek-harness` 下,远程 Web Host 也遵循此规则。目录名必须是非空的单个片段,不能含分隔符、冒号、NUL、首尾空白或末尾句点;标题不能为空。操作系统的文件名限制同样适用。Linux 系统查询要求存在 `xdg-user-dir` 且启用了 Documents 目录;不具备该条件的 Host 必须配置 `documentsDirectory` 或使用文件夹选择器。
[Workspace 注册表](../../workspace/workspace/README.zh.md#first-use-workspace)负责资格判断、目录创建和持久化初始化。已有默认工作区直接返回,不再查询 Documents;请求中的名称不会将其重命名。不满足首次使用条件时返回 `undefined`,启动流程可将目录选择留给用户。名称无效时以 `gateway/bad-request` 拒绝;查询和创建失败遵循标准 Remote 错误处理。初始化不创建 Session,也不发送消息。
| 配置 | 默认值 | 用途 |
| --- | --- | --- |
| `documentsDirectory` | 系统 Documents 目录 | 完全限定的 Host 目录覆盖值 |
| `documentsLookupTimeoutMs` | `10000` | 操作系统目录查询的正数最大时长,单位为毫秒 |
Documents 查询占用注册表变更队列,因此其他 Workspace 变更(包括登记已选目录)最多可能等待 `documentsLookupTimeoutMs`。取消可以停止查询;解析成功后,取消不会回滚创建或登记。
-----
<a id="model-experience"></a>
@@ -66,6 +66,8 @@
"license": "MIT",
"dependencies": {
"@deepseek-ai/dsh-deque": "workspace:^",
"@deepseek-ai/dsh-native-command": "workspace:^",
"@deepseek-ai/schemastery": "workspace:^",
"zod": "^4.4.3"
},
"peerDependencies": {
@@ -17,7 +17,7 @@ export type {
} from './model.ts'
export { WorkspaceController, WorkspaceCreateError } from './service.ts'
export type { IWorkspaces, WorkspaceSource } from './service.ts'
export type { WorkspaceId, WorkspaceView } from '../types.ts'
export type { WorkspaceId, WorkspaceInitializeDefaultRequest, WorkspaceView } from '../types.ts'
type WorkspaceBaselineFrame = Extract<WorkspaceFollowFrame, { type: 'baseline' }>
@@ -12,6 +12,7 @@ import type {
WorkspaceCreateValue,
WorkspaceDeleteValue,
WorkspaceInsertSessionBeforeRequest,
WorkspaceInitializeDefaultRequest,
WorkspaceOrderValue,
WorkspacePinSessionRequest,
WorkspacePinValue,
@@ -101,6 +102,20 @@ export class ClientWorkspaceModel implements WorkspaceFollowSink {
return result
}
/**
* Initialize the default Workspace and merge its authoritative row.
* @param request - initial directory name and title.
* @param signal - caller lifetime.
* @returns generated Remote result.
*/
async initializeDefault(
request: WorkspaceInitializeDefaultRequest, signal?: AbortSignal,
): Promise<RemoteResult<WorkspaceValue | undefined>> {
const result = await this.remote.initializeDefault(request, signal)
if (result.ok && result.value !== undefined) this.upsert(result.value.workspace)
return result
}
/**
* Rename a Workspace and merge the unary result immediately.
* @param workspaceId - target Workspace.
@@ -4,7 +4,7 @@ import { Service, type Context } from '@deepseek-ai/cordis'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import type { RemoteFailure } from '@deepseek-ai/dsh-typert-protocol'
import type { WorkspaceId } from '@deepseek-ai/dsh-workspace/types'
import type { WorkspaceView } from '../types.ts'
import type { WorkspaceInitializeDefaultRequest, WorkspaceView } from '../types.ts'
import type { ClientWorkspaceModel, WorkspaceSnapshot } from './model.ts'
/** Structured create failure for callers that distinguish Host business errors. */
@@ -39,6 +39,13 @@ export interface IWorkspaces {
* @returns the created or idempotently resolved Workspace.
*/
create(input: { path: string }): Promise<WorkspaceView>
/**
* Initialize or reuse the default Workspace.
* @param request - initial directory name and title.
* @param signal - caller lifetime.
* @returns the prepared Workspace, or undefined when first-use initialization is ineligible; rejects on preparation failure.
*/
initializeDefault(request: WorkspaceInitializeDefaultRequest, signal?: AbortSignal): Promise<WorkspaceView | undefined>
/**
* Rename a Workspace.
* @param workspaceId - target Workspace.
@@ -110,6 +117,12 @@ export class WorkspaceController extends Service implements IWorkspaces {
return result.value.workspace
}
async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal?: AbortSignal): Promise<WorkspaceView | undefined> {
const result = await this.model.initializeDefault(request, signal)
if (!result.ok) throw new WorkspaceCreateError(result.error)
return result.value?.workspace
}
async rename(workspaceId: WorkspaceId, title: string): Promise<WorkspaceView> {
const result = await this.model.rename(workspaceId, title)
if (!result.ok) throw commandError('rename', result.error)
@@ -0,0 +1,79 @@
/** Resolve the Host account's Documents directory for first-use Workspace creation. */
import { homedir } from 'node:os'
import { posix, win32 } from 'node:path'
import { runNativeCommand, type NativeCommandRunner } from '@deepseek-ai/dsh-native-command'
/** Platform observations replaceable in directory-resolution tests. */
interface DocumentsDirectoryInternals {
readonly platform?: NodeJS.Platform
readonly home?: string
readonly run?: NativeCommandRunner
}
/**
* Validate a configured or OS-returned Documents path without resolving it against cwd.
* @param directory - fully qualified directory spelling.
* @param platform - Host platform.
* @returns the normalized directory.
*/
export function validateDocumentsDirectory(directory: string, platform: NodeJS.Platform = process.platform): string {
const paths = platform === 'win32' ? win32 : posix
const root = paths.parse(directory).root
if (!paths.isAbsolute(directory) || (platform === 'win32' && (root === '\\' || root === '/'))) {
throw new Error(`Documents directory must be fully qualified: '${directory}'`)
}
return paths.normalize(directory)
}
/**
* Resolve the first-use directory on the Host without creating files.
* @param directoryName - validated single directory name supplied by the Client.
* @param documentsDirectory - explicit deployment override for the system Documents directory.
* @param signal - caller lifetime and lookup deadline.
* @param internals - platform facts and native command runner.
* @returns the absolute candidate path.
*/
export async function defaultWorkspaceDirectory(
directoryName: string,
documentsDirectory: string | undefined,
signal: AbortSignal,
internals: DocumentsDirectoryInternals = {},
): Promise<string> {
const platform = internals.platform ?? process.platform
const paths = platform === 'win32' ? win32 : posix
signal.throwIfAborted()
let directory = documentsDirectory
if (directory === undefined) {
const run = internals.run ?? runNativeCommand
let stdout: string
switch (platform) {
case 'darwin':
({ stdout } = await run('osascript', [
'-e', 'POSIX path of (path to documents folder from user domain without folder creation)',
], signal))
break
case 'win32':
({ stdout } = await run('powershell.exe', [
'-NoLogo', '-NoProfile', '-NonInteractive', '-Command',
'[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); '
+ '[Environment]::GetFolderPath([Environment+SpecialFolder]::MyDocuments, '
+ '[Environment+SpecialFolderOption]::DoNotVerify)',
], signal))
break
case 'linux':
({ stdout } = await run('xdg-user-dir', ['DOCUMENTS'], signal))
break
default:
throw new Error(`system Documents directory is unavailable on ${platform}`)
}
directory = stdout.replace(/[\r\n]+$/, '')
// XDG reports the home directory when this user directory is disabled.
if (directory === '' || (platform === 'linux' && paths.normalize(directory) === (internals.home ?? homedir()))) {
throw new Error('system Documents directory is unavailable')
}
}
directory = validateDocumentsDirectory(directory, platform)
signal.throwIfAborted()
return paths.join(directory, 'deepseek-harness', directoryName)
}
+52 -4
View File
@@ -1,10 +1,12 @@
/** Host Workspace Remote owner: explicit commands and reconnect-safe state. */
import { Context } from '@deepseek-ai/cordis'
import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
import z from '@deepseek-ai/schemastery'
import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
import { WorkspaceCommands } from './commands.ts'
import { DirectoryPickerController } from './directory-picker.ts'
import { WorkspaceFeed } from './feed.ts'
import { WorkspaceFeed, workspaceView } from './feed.ts'
import { defaultWorkspaceDirectory, validateDocumentsDirectory } from './default-directory.ts'
import type {
WorkspaceArchiveSessionRequest,
WorkspaceArchiveValue,
@@ -14,6 +16,7 @@ import type {
WorkspaceDeleteValue,
WorkspaceFollowFrame,
WorkspaceInsertBeforeRequest,
WorkspaceInitializeDefaultRequest,
WorkspaceInsertSessionBeforeRequest,
WorkspaceOrderValue,
WorkspacePinSessionRequest,
@@ -27,6 +30,17 @@ import type {
export type * from './types.ts'
export { DirectoryPickerController } from './directory-picker.ts'
/** First-use directory policy for the Host account. */
export interface Config {
/** Override the system Documents directory with a fully qualified path. */
documentsDirectory?: string
/** Maximum duration of the operating system's Documents lookup. */
documentsLookupTimeoutMs?: number
}
/** Directory policy after schema defaults have been applied. */
type ResolvedConfig = Config & { documentsLookupTimeoutMs: number }
declare module '@deepseek-ai/cordis' {
interface Context {
/** Host Workspace business API and Remote namespace owner. */
@@ -38,12 +52,23 @@ declare module '@deepseek-ai/cordis' {
export class WorkspaceController extends TypertRemoteService {
static inject = ['typert', 'workspaceRegistry']
static Config: z<Config, ResolvedConfig> = z.object({
documentsDirectory: z.string(),
documentsLookupTimeoutMs: z.natural().min(1).default(10_000),
})
private readonly config: ResolvedConfig
private readonly commands: WorkspaceCommands
private readonly feed: WorkspaceFeed
/** @param ctx - Host context containing the Workspace registry. */
constructor(ctx: Context) {
/**
* @param ctx - Host context containing the Workspace registry.
* @param config - first-use directory policy.
*/
constructor(ctx: Context, config: Config = {}) {
super(ctx, 'workspaceController', { namespace: 'workspace' })
this.config = WorkspaceController.Config(config)
if (this.config.documentsDirectory !== undefined) validateDocumentsDirectory(this.config.documentsDirectory)
this.commands = new WorkspaceCommands(ctx)
this.feed = new WorkspaceFeed(ctx)
// This package is the Loader entry for both Remote owners it hosts: the
@@ -63,6 +88,29 @@ export class WorkspaceController extends TypertRemoteService {
return this.commands.create(request)
}
/**
* Initialize or reuse the default Workspace during first-use startup.
* @param request - initial directory name and title; never rename an existing default.
* @param signal - caller lifetime; cancels native directory lookup.
* @returns the durable Workspace, or undefined when first-use initialization is ineligible; creates no Session or message.
*/
@Remote('initializeDefault')
async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal: AbortSignal): Promise<WorkspaceValue | undefined> {
const { directoryName, title } = request
if (directoryName.trim() === '' || directoryName !== directoryName.trim()
|| directoryName.endsWith('.') || /[/\\:\0]/.test(directoryName) || title.trim() === '') {
throw new RemoteError('gateway/bad-request', 'default Workspace requires a directory name and non-blank title', {})
}
const workspace = await this.ctx.workspaceRegistry.initializeDefault(async () => {
const timeout = AbortSignal.timeout(this.config.documentsLookupTimeoutMs)
const path = await defaultWorkspaceDirectory(
directoryName, this.config.documentsDirectory, AbortSignal.any([signal, timeout]),
)
return { path, title }
})
return workspace === undefined ? undefined : { workspace: workspaceView(workspace) }
}
/**
* Rename one Workspace to a unique non-blank title.
* @param request - Workspace identity and proposed title.
@@ -54,6 +54,14 @@ export interface WorkspaceCreateRequest {
readonly path: string
}
/** Names chosen by the first-use Client before default Workspace initialization. */
export interface WorkspaceInitializeDefaultRequest {
/** Host rejects blank names, separators, colon, NUL, surrounding whitespace, and trailing dots; OS filename restrictions also apply. */
readonly directoryName: string
/** Initial display title, retained across language changes. */
readonly title: string
}
/** Created or previously registered Workspace. */
export interface WorkspaceCreateValue {
readonly workspace: WorkspaceView
@@ -0,0 +1,48 @@
import { describe, expect, it, vi } from 'vitest'
import type { NativeCommandRunner } from '@deepseek-ai/dsh-native-command'
import { defaultWorkspaceDirectory, validateDocumentsDirectory } from '../src/default-directory.ts'
describe('system Documents directory', () => {
it.each([
['darwin', '/Users/a/文档/\n', '/Users/a/文档/deepseek-harness/默认工作区', 'osascript'],
['win32', 'D:\\Redirected Documents\r\n', 'D:\\Redirected Documents\\deepseek-harness\\默认工作区', 'powershell.exe'],
['linux', '/home/a/My Documents\n', '/home/a/My Documents/deepseek-harness/默认工作区', 'xdg-user-dir'],
] as const)('uses the %s account directory and preserves spaces and Unicode', async (platform, stdout, path, command) => {
const run = vi.fn<NativeCommandRunner>(async () => ({ stdout, stderr: '' }))
const signal = new AbortController().signal
await expect(defaultWorkspaceDirectory('默认工作区', undefined, signal, { platform, run })).resolves.toBe(path)
expect(run).toHaveBeenCalledWith(command, expect.any(Array), signal)
})
it.each(['Default workspace', '默认工作区', 'default-workspace'])('uses the configured directory with name %s', async (folder) => {
const run = vi.fn<NativeCommandRunner>()
await expect(defaultWorkspaceDirectory(folder, '/documents', new AbortController().signal, { platform: 'linux', run }))
.resolves.toBe(`/documents/deepseek-harness/${folder}`)
expect(run).not.toHaveBeenCalled()
})
it.each(['', '\r\n', '/home/a\n'])('rejects an unavailable XDG directory %j', async (stdout) => {
const run: NativeCommandRunner = async () => ({ stdout, stderr: '' })
await expect(defaultWorkspaceDirectory('Default workspace', undefined, new AbortController().signal, { platform: 'linux', home: '/home/a', run }))
.rejects.toThrow('unavailable')
})
it('propagates lookup failure and cancellation', async () => {
const run: NativeCommandRunner = async () => { throw new Error('lookup denied') }
await expect(defaultWorkspaceDirectory('Default workspace', undefined, new AbortController().signal, { platform: 'darwin', run }))
.rejects.toThrow('lookup denied')
await expect(defaultWorkspaceDirectory('Default workspace', '/documents', AbortSignal.abort(), { platform: 'linux' }))
.rejects.toThrow()
await expect(defaultWorkspaceDirectory('Default workspace', undefined, new AbortController().signal, { platform: 'freebsd' }))
.rejects.toThrow('unavailable')
})
it.each(['relative', 'C:relative', '\\rooted'])('rejects a Windows path without a fully qualified root: %s', (path) => {
expect(() => validateDocumentsDirectory(path, 'win32')).toThrow('fully qualified')
})
it('accepts redirected UNC Documents directories', () => {
expect(validateDocumentsDirectory('\\\\server\\share\\Documents', 'win32')).toBe('\\\\server\\share\\Documents')
expect(() => validateDocumentsDirectory('relative', 'linux')).toThrow('fully qualified')
})
})
@@ -69,6 +69,7 @@ function deferred<T>(): Deferred<T> {
}
class FakeWorkspaceRemote implements WorkspaceRemote {
readonly initializeDefault = vi.fn<WorkspaceRemote['initializeDefault']>(async () => remoteOk({ workspace: workspace('default') }))
readonly calls: Array<{ readonly method: string; readonly request: unknown }> = []
onCreate: (request: WorkspaceCreateRequest) => Promise<RemoteResult<WorkspaceCreateValue>> = request =>
Promise.resolve(remoteOk({ workspace: workspace(request.path.split('/').pop() ?? 'workspace'), created: true }))
@@ -170,6 +171,26 @@ function baseline(
}
describe('ClientWorkspaceModel', () => {
it('publishes the prepared Workspace and leaves the list unchanged on refusal', async () => {
const remote = new FakeWorkspaceRemote()
const model = modelFor(remote)
baseline(model)
const signal = new AbortController().signal
await expect(model.initializeDefault({ directoryName: '默认工作区', title: '默认工作区' }, signal)).resolves.toMatchObject({ ok: true })
expect(remote.initializeDefault).toHaveBeenCalledWith({ directoryName: '默认工作区', title: '默认工作区' }, signal)
expect(model.getSnapshot().items.map(item => item.workspaceId)).toEqual(['default'])
const before = model.getSnapshot()
remote.initializeDefault.mockResolvedValueOnce(remoteOk(undefined))
await expect(model.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' }))
.resolves.toEqual({ ok: true, value: undefined })
expect(model.getSnapshot()).toBe(before)
remote.initializeDefault.mockResolvedValueOnce(workspaceError(
new RemoteError('gateway/bad-request', 'choose a folder', {}),
))
await expect(model.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' })).resolves.toMatchObject({ ok: false })
expect(model.getSnapshot()).toBe(before)
})
it('replaces reconnect state and applies ordered increments', () => {
const model = modelFor()
expect(model.getSnapshot()).toMatchObject({ phase: 'pending', state: 'loading' })
@@ -91,6 +91,7 @@ export function followGenerations(generations: readonly StreamScript[]): StreamS
/** Default answers: every command accepted and echoed back as the row or set it names. */
export const workspaceWorld: RemoteTable = {
unary: {
'workspace/initializeDefault': (): RemoteResult<WorkspaceValue> => ok({ workspace: workspace('default') }),
'workspace/create': (request: WorkspaceCreateRequest): RemoteResult<WorkspaceCreateValue> => ok({
workspace: workspace('created', { path: request.path }), created: true,
}),
@@ -310,6 +310,18 @@ describe('Workspace state stream', () => {
})
describe('WorkspaceController', () => {
it('returns no Workspace when startup is ineligible without changing the list', async ({ mock, start }) => {
const { remote, client } = await gatewayClient(mock, start)
const model = new ClientWorkspaceModel(remote.workspace)
model.replaceBaseline({ items: [], archivedSessionIds: [], pinnedSessionIds: [] })
const controller = new WorkspaceController(client.ctx, model)
const before = model.getSnapshot()
mock.remote.workspace.initializeDefault.mockResolvedValueOnce({ ok: true, value: undefined })
await expect(controller.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' }))
.resolves.toBeUndefined()
expect(model.getSnapshot()).toBe(before)
})
it('publishes the model source and exposes successful Workspace commands', async ({ mock, start }) => {
const { remote, client } = await gatewayClient(mock, start)
const model = new ClientWorkspaceModel(remote.workspace)
@@ -318,6 +330,7 @@ describe('WorkspaceController', () => {
expect(controller.list).toBe(model)
expect(client.ctx.workspaces.list).toBe(model)
await expect(controller.initializeDefault({ directoryName: '默认工作区', title: '默认工作区' }, new AbortController().signal)).resolves.toMatchObject({ workspaceId: 'default' })
await expect(controller.create({ path: '/work/created' })).resolves.toMatchObject({ workspaceId: 'created' })
await expect(controller.rename(wid('one'), 'renamed')).resolves.toMatchObject({ title: 'renamed' })
await expect(controller.insertBefore(wid('one'))).resolves.toBeUndefined()
@@ -330,6 +343,7 @@ describe('WorkspaceController', () => {
await expect(controller.unpinSession(sid('session'))).resolves.toBeUndefined()
await expect(controller.delete(wid('one'))).resolves.toBeUndefined()
// Each command crosses the wire as one positional request object.
expect(mock.log.requests('workspace/initializeDefault')).toEqual([{ directoryName: '默认工作区', title: '默认工作区' }])
expect(mock.log.requests('workspace/create')).toEqual([{ path: '/work/created' }])
expect(mock.log.requests('workspace/rename')).toEqual([{ workspaceId: 'one', title: 'renamed' }])
expect(mock.log.requests('workspace/insertBefore')).toEqual([{ workspaceId: 'one' }])
@@ -347,6 +361,9 @@ describe('WorkspaceController', () => {
const missingWorkspace = new RemoteError('workspace/not-found', 'gone', { workspaceId: wid('missing') })
const missingSession = new RemoteError('session/not-found', 'missing session', { sessionId: sid('session') })
mock.remote.workspace.initializeDefault.mockResolvedValueOnce(err(new RemoteError('gateway/internal', 'directory denied', {})))
await expect(controller.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' })).rejects.toBeInstanceOf(WorkspaceCreateError)
mock.remote.workspace.create.mockResolvedValueOnce(err(new RemoteError('workspace/invalid-path', 'missing path', { path: '/missing' })))
const create = controller.create({ path: '/missing' })
await expect(create).rejects.toBeInstanceOf(WorkspaceCreateError)
@@ -41,7 +41,7 @@ function deferred<T>(): Deferred<T> {
return { promise, resolve }
}
async function harness() {
async function harness(options: { systemDocuments?: boolean } = {}) {
const root = realpathSync.native(mkdtempSync(join(tmpdir(), 'dsh-workspace-controller-')))
tempDirs.push(root)
const ctx = new Context()
@@ -59,7 +59,7 @@ async function harness() {
lookups: { configure: () => dispose },
contexts: { configureHost: () => dispose },
} as never)
const controller = new WorkspaceController(ctx)
const controller = new WorkspaceController(ctx, options.systemDocuments === true ? {} : { documentsDirectory: root })
return { controller, ctx, root, storageDomain }
}
@@ -416,3 +416,57 @@ describe('WorkspaceController follow', () => {
await expect(closing).resolves.toEqual({ done: true, value: undefined })
})
})
describe('first-use Remote', () => {
it('reuses an initialized Workspace without looking up system Documents', async () => {
const { controller, ctx, root } = await harness({ systemDocuments: true })
const workspace = await ctx.workspaceRegistry.initializeDefault(async () => ({ path: root, title: 'Existing default' }))
const signal = AbortSignal.abort()
await expect(controller.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' }, signal))
.resolves.toMatchObject({ workspace: { workspaceId: workspace!.id, path: root, title: 'Existing default' } })
})
it.each(['', ' ', '.', '..', '../outside', 'nested/name', 'nested\\name', 'C:outside', 'name\0', '.. ', 'tail.'])(
'rejects invalid directory name %j before invoking the registry', async (directoryName) => {
const { controller, ctx } = await harness()
const initialize = vi.spyOn(ctx.workspaceRegistry, 'initializeDefault').mockResolvedValue(undefined)
await expect(controller.initializeDefault({ directoryName, title: 'Default workspace' }, new AbortController().signal))
.rejects.toMatchObject({ code: 'gateway/bad-request' })
expect(initialize).not.toHaveBeenCalled()
},
)
it('rejects a blank initial title before invoking the registry', async () => {
const { controller, ctx } = await harness()
const initialize = vi.spyOn(ctx.workspaceRegistry, 'initializeDefault').mockResolvedValue(undefined)
await expect(controller.initializeDefault({ directoryName: 'default-workspace', title: ' ' }, new AbortController().signal))
.rejects.toMatchObject({ code: 'gateway/bad-request' })
expect(initialize).not.toHaveBeenCalled()
})
it('uses the requested display title independently of the directory name', async () => {
const { controller, root } = await harness()
const result = await controller.initializeDefault({ directoryName: 'default-workspace', title: 'Default workspace' }, new AbortController().signal)
expect(result?.workspace).toMatchObject({ path: join(root, 'deepseek-harness', 'default-workspace'), title: 'Default workspace' })
})
it('returns a durable Workspace without allocating a Session', async () => {
const { controller, ctx, root } = await harness()
const signal = new AbortController().signal
const result = await controller.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' }, signal)
expect(result!.workspace.path).toBe(join(root, 'deepseek-harness', 'Default workspace'))
expect(existsSync(result!.workspace.path)).toBe(true)
expect(ctx.sessions.list()).toEqual([])
expect(await controller.initializeDefault({ directoryName: '默认工作区', title: '默认工作区' }, signal)).toEqual(result)
})
it('skips ineligible first use and propagates preparation failures', async () => {
const { controller, ctx, root } = await harness()
await ctx.workspaceRegistry.create(root)
await expect(controller.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' }, new AbortController().signal))
.resolves.toBeUndefined()
vi.spyOn(ctx.workspaceRegistry, 'initializeDefault').mockRejectedValueOnce(new Error('permission denied'))
await expect(controller.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' }, new AbortController().signal))
.rejects.toThrow('permission denied')
})
})
@@ -10,15 +10,18 @@
"src/types.ts",
"src/commands.ts",
"src/directory-picker.ts",
"src/feed.ts"
"src/feed.ts",
"src/default-directory.ts"
],
"references": [
{ "path": "../../../vendor/cordis" },
{ "path": "../../../vendor/schemastery" },
{ "path": "../../core/session" },
{ "path": "../../host/directory-picker" },
{ "path": "../../storage/storage-domain" },
{ "path": "../../typert/protocol" },
{ "path": "../../util/deque" },
{ "path": "../../util/native-command" },
{ "path": "../../workspace/workspace" }
]
}
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/client/ui-workspace/README.md
README.md: ef58466364ae97707f1e0b5f0fdab5dc86c57dd5
README.zh.md: 1cf866a0f3813619e5d3637dc053d49e28ab18ec
README.md: 92e2f231ec2e25aa1716f03338a980f2c2269d16
README.zh.md: e490c4ebe63a0e11e1892d8bc02693ab63d12277
+4
View File
@@ -71,6 +71,10 @@ Navigation and startup restoration obtain the selected Session's projections fro
New Session tries to acquire the first eligible blank in catalog order; startup restoration tries the saved blank. If that writer is held, navigation creates a new Session without trying other blanks. Other acquisition failures abort the request and are currently reported only to the console. Released blanks retain their slash-command state when reused. Later navigation cancels a pending startup selection.
Once both Workspace and Session startup baselines are ready, an empty installation calls `workspaces.initializeDefault` and creates or reuses its blank Session. The composer becomes editable when that Session is selected; no message is submitted automatically. Later navigation or owner disposal prevents startup from selecting its result. Ineligible first use leaves the folder picker available without an error. Default Workspace creation failure shows a transient notice directing the user to Choose workspace, and is not retried until the next startup. Session creation failures use the ordinary restoration error handling. The registered Workspace remains available if Session creation or later submission fails.
The Client chooses the initial directory name and title from its language at startup: Chinese uses `默认工作区`, English uses `Default workspace`, and other languages use directory `default-workspace` with title `Default workspace`. The request retains those names during initialization. A successfully initialized Workspace keeps its directory and title across language changes.
<a id="understand-the-implementation"></a>
## Understand the implementation
@@ -71,6 +71,10 @@ Session 行渲染运行时的实时 `pendingInteraction` 分类:审批显示**
新建会话尝试获取列表中第一个符合条件的空白会话;启动恢复尝试已保存的空白会话。若该写锁被占用,导航直接新建 Session,不再尝试其他空白会话。其他获取错误会中止请求,目前只报告到控制台。已释放的空白会话被复用时保留 slash 命令状态。后续导航会取消尚未完成的启动选择。
Workspace 和 Session 的启动基线均就绪后,空安装环境调用 `workspaces.initializeDefault`,创建或复用其空白 Session。选中该 Session 后输入框才可编辑,不会自动提交消息。后续导航或所属上下文销毁会阻止启动流程选中其结果。不符合首次使用条件时仍可选择文件夹,不显示错误。默认工作区创建失败时显示短暂提示,引导用户通过“选择工作区”选择文件夹,直到下次启动才重试。Session 创建失败沿用普通的恢复错误处理。登记成功的工作区在 Session 创建或后续提交失败时仍然保留。
Client 在启动时按其语言选择初始目录名和标题:中文使用 `默认工作区`,英文使用 `Default workspace`,其他语言使用目录 `default-workspace` 和标题 `Default workspace`。初始化过程中保留请求中的名称。成功初始化的工作区在切换语言后保留原目录和标题。
<a id="understand-the-implementation"></a>
## 理解实现
@@ -238,12 +238,13 @@ export type SessionRowActionProps<Injected extends object = object> =
& PropsLocale<'workspace'>
& InjectFace<Injected>
/** One transient notice a row action raises; the overlay toast entry renders it. */
/** One transient Workspace notice rendered by the overlay toast entry. */
export type RowToast =
| { kind: 'archived'; sessionId: SessionId }
| { kind: 'pinFailed' }
| { kind: 'unpinFailed' }
| { kind: 'archivedNotOpenable' }
| { kind: 'defaultWorkspaceFailed' }
/** The notice on display; `seq` keys remounts so a repeated notice restarts its hold. */
export type RowToastState = RowToast & { seq: number }
@@ -377,5 +378,5 @@ export type WorkspacePickerProps =
PropsRuntime<'conversation.hero.workspace'>
& PropsRenderSlots<'conversation.hero.workspace.directoryFlow'>
& Omit<WorkspacePickerInjected, 'hooks'>
& DirectoryPickingHooks
& PropsHooks<WorkspacePickerInjected['hooks']>
& PropsLocale<'workspace'>
@@ -103,8 +103,13 @@ export function apply(ctx: Context): void {
const viewHandle = createWorkspaceViewStore()
const viewInstance = viewHandle.create()
const viewStore: typeof viewHandle = { ...viewHandle, create: () => viewInstance }
const rowToast = createSnapshotStore<RowToastState | null>(null)
let toastSeq = 0
const notify = (toast: RowToast): void => { rowToast.set({ ...toast, seq: ++toastSeq }) }
const uiWorkspace = new UiWorkspaceService(
ctx, ctx.remote.directoryPicker, workspaces, sessions, viewInstance.actions)
ctx, ctx.remote.directoryPicker, workspaces, sessions, viewInstance.actions,
() => { notify({ kind: 'defaultWorkspaceFailed' }) },
)
ctx.slots.provideRoot({ hooks: { workspaces: workspaces.list } })
ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'ui-workspace: dictionaries')
@@ -137,9 +142,6 @@ export function apply(ctx: Context): void {
// writes through its own injected callback and the surface reads through
// its bound hook.
const renameRequest = createSnapshotStore<SessionRenameTarget | null>(null)
const rowToast = createSnapshotStore<RowToastState | null>(null)
let toastSeq = 0
const notify = (toast: RowToast): void => { rowToast.set({ ...toast, seq: ++toastSeq }) }
const requestSessionRename = (sessionId: SessionId, currentTitle: string): void => {
renameRequest.set({ sessionId, currentTitle })
}
@@ -6,6 +6,8 @@
/** Simplified Chinese dictionary (the key-set source of truth). */
export const zh = {
'defaultWorkspace.failed': '无法创建默认工作区,请通过“选择工作区”选择文件夹',
'defaultWorkspace.title': '默认工作区',
'group.ungrouped': '未分组',
'session.new': '新会话',
'section.workspaces': '工作区',
@@ -99,6 +101,8 @@ export type WorkspaceKey = keyof typeof zh
/** English dictionary, checked complete against the zh key set. */
export const en = {
'defaultWorkspace.failed': 'Unable to create default workspace. Use Choose workspace to select a folder.',
'defaultWorkspace.title': 'Default workspace',
'group.ungrouped': 'Ungrouped',
'session.new': 'New Session',
'section.workspaces': 'Workspaces',
@@ -16,6 +16,8 @@ import type {
} from '@deepseek-ai/dsh-api-workspace-controller/client'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import type {} from '@deepseek-ai/dsh-client-ui-layout/client'
import type {} from '@deepseek-ai/dsh-client-locale/client'
import { en, zh } from './locales.ts'
import { pinOrderAccounts, pinOrderSource } from './pin-order.ts'
import type { WorkspaceViewStoreActions } from './stores.ts'
@@ -131,6 +133,7 @@ class UiWorkspaceService extends Service implements UiWorkspace {
* @param workspaces - pure Workspace Controller.
* @param sessions - pure Session Controller.
* @param view - the browser's viewing-store write set (one instance shared with its registration).
* @param notifyDefaultFailure - show the startup creation failure through the Workspace notice channel.
*/
constructor(
ctx: Context,
@@ -138,6 +141,7 @@ class UiWorkspaceService extends Service implements UiWorkspace {
private readonly workspaces: IWorkspaces,
private readonly sessions: ISessions,
private readonly view: Pick<WorkspaceViewStoreActions, 'pinSessionOrder'>,
private readonly notifyDefaultFailure: () => void,
) {
super(ctx, 'uiWorkspace')
ctx.effect(() => {
@@ -319,13 +323,32 @@ class UiWorkspaceService extends Service implements UiWorkspace {
&& !workspaces.archivedSessionIds.includes(summary.id)) {
sessionId = await this.reuseBlank(workspace.workspaceId, summary.id)
}
const target = workspace?.workspaceId ?? recentWorkspace(workspaces.items, sessions.byId)
let target = workspace?.workspaceId ?? recentWorkspace(workspaces.items, sessions.byId)
if (target === undefined && workspaces.items.length === 0 && sessions.ids.length === 0) {
const prepared = await this.initializeDefaultWorkspace(navigation)
if (navigation.aborted) return
target = prepared?.workspaceId
}
if (sessionId === undefined && target !== undefined) sessionId = await this.connectWorkspace(target)
if (sessionId !== undefined && !navigation.aborted) {
this.replaceMain(sessionId, navigation, 'preserve')
}
}
private async initializeDefaultWorkspace(signal: AbortSignal): Promise<WorkspaceView | undefined> {
const language = this.ctx.locale.getSnapshot().active.toLowerCase().split('-')[0]
const title = (language === 'zh' ? zh : en)['defaultWorkspace.title']
try {
return await this.workspaces.initializeDefault({
directoryName: language === 'zh' || language === 'en' ? title : 'default-workspace',
title,
}, signal)
} catch (_error: unknown) {
if (!signal.aborted) this.notifyDefaultFailure()
return undefined
}
}
/** @returns true when an archived current selection was cleared. */
private clearArchivedCurrent(): boolean {
const current = this.mainReference?.sessionId
@@ -1,8 +1,6 @@
/**
* The `shell.overlay` entry that shows the row actions' notices: the archived
* notice with its undo and "show archived" actions, pin failures, and the
* browser's "archived rows cannot be opened" notice. One notice at a time;
* a parent rerender does not extend its hold.
* The `shell.overlay` entry for Workspace and Session notices.
* One notice is visible at a time; a parent rerender does not extend its hold.
*/
import { IconWarningOutlineRegular, Toast } from '@deepseek-ai/dsh-client-ui-primitives'
import type { RowToastProps } from '../contract/slots.ts'
@@ -11,9 +9,9 @@ import type { RowToastProps } from '../contract/slots.ts'
const ARCHIVED_TOAST_HOLD_MS = 6000
/**
* Render the row actions' current notice: the archived notice with its undo
* Render the current notice: the archived notice with its undo
* and show-archived actions on a 6 s hold, or a plain warning for a failed
* pin or an archived row that was clicked.
* pin, an archived row that was clicked, or default Workspace creation.
* @param props - the notice hook, its dismissal, the two archived-notice actions, and the locale seat.
* @returns the notice on display, or null.
*/
@@ -38,7 +36,8 @@ export function RowActionToast({ useToast, dismissToast, undoArchive, showArchiv
}
const text = toast.kind === 'pinFailed'
? t('toast.pinFailed')
: toast.kind === 'unpinFailed' ? t('toast.unpinFailed') : t('toast.archivedNotOpenable')
: toast.kind === 'unpinFailed' ? t('toast.unpinFailed')
: toast.kind === 'defaultWorkspaceFailed' ? t('defaultWorkspace.failed') : t('toast.archivedNotOpenable')
return (
<Toast
key={`toast-${String(toast.seq)}`}
@@ -1,5 +1,5 @@
import { Context } from '@deepseek-ai/cordis'
import { describe, expect, it, vi } from 'vitest'
import { describe, expect, it, onTestFinished, vi } from 'vitest'
import type {
SessionListState, SessionReference, SessionSummary,
} from '@deepseek-ai/dsh-api-session-controller/client'
@@ -91,9 +91,11 @@ async function bench() {
let sessionSnapshot = sessionState([])
const subscribe = () => () => {}
const workspacesSubscribe = vi.fn(subscribe)
const initializeDefault = vi.fn(async (): Promise<WorkspaceView | undefined> => undefined)
ctx.provide('workspaces', {
list: { getSnapshot: () => workspaceSnapshot, subscribe: workspacesSubscribe },
create,
initializeDefault,
rename,
delete: vi.fn(async () => undefined),
insertBefore: vi.fn(async () => undefined),
@@ -128,7 +130,7 @@ async function bench() {
return {
ctx, slots: ctx.get('slots') as SlotRegistry, locale, create, rename,
retain, using, selectPanel, search, renameSession, binding, fork, pickDirectory, pinSession, unpinSession,
workspacesSubscribe,
workspacesSubscribe, initializeDefault,
setWorkspaces: (snapshot: WorkspaceSnapshot): void => { workspaceSnapshot = snapshot },
setSessions: (snapshot: SessionListState): void => { sessionSnapshot = snapshot },
}
@@ -182,6 +184,20 @@ describe('ui-workspace apply', () => {
])
})
it('reports a default Workspace creation failure through the shared notice overlay', async () => {
const b = await bench()
onTestFinished(() => b.ctx.fiber.dispose())
b.initializeDefault.mockRejectedValueOnce(new Error('denied'))
declare(b.slots, 'shell.overlay')
await b.ctx.plugin({ inject: [...inject], apply }).await()
const face = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected
await vi.waitFor(() => {
expect(face.hooks.toast.getSnapshot()).toMatchObject({ kind: 'defaultWorkspaceFailed' })
})
face.dismissToast()
expect(face.hooks.toast.getSnapshot()).toBeNull()
})
it('registers browser and pickers for declarations arriving before or after apply', async () => {
const before = await bench()
declare(before.slots, 'sidebar.workspaces')
@@ -387,6 +387,7 @@ describe('RowActionToast', () => {
['pinFailed', '置顶失败,请稍后重试'],
['unpinFailed', '取消置顶失败,请稍后重试'],
['archivedNotOpenable', '已归档对话暂时无法查看,请取消归档后查看'],
['defaultWorkspaceFailed', '无法创建默认工作区,请通过“选择工作区”选择文件夹'],
] as const)('shows the %s warning and takes it down when its hold ends', (kind, text) => {
vi.useFakeTimers()
try {
@@ -1,4 +1,6 @@
import { setImmediate } from 'node:timers/promises'
import { Context } from '@deepseek-ai/cordis'
import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type {
ISessions, SessionListState, SessionReference, SessionSummary,
@@ -169,6 +171,7 @@ class FakeSessions implements ISessions {
}
class FakeWorkspaces implements IWorkspaces {
readonly initializeDefault = vi.fn<IWorkspaces['initializeDefault']>(async () => undefined)
readonly list: MutableSource<WorkspaceSnapshot>
readonly archiveCalls: SessionId[] = []
readonly unarchiveCalls: SessionId[] = []
@@ -263,6 +266,8 @@ class FakeDirectoryPicker {
}
interface BenchOptions {
readonly language?: string
readonly configureWorkspaces?: (workspaces: FakeWorkspaces) => void
readonly workspaces?: WorkspaceSnapshot
readonly sessions?: SessionListState
readonly configureSessions?: (sessions: FakeSessions) => void
@@ -271,6 +276,10 @@ interface BenchOptions {
function bench(options: BenchOptions = {}) {
const ctx = new Context()
contexts.push(ctx)
const locale = new LocaleRuntime(ctx)
if (options.language === 'fr') locale.addLanguage({ id: 'fr', label: 'Français', fallback: 'en' })
locale.setLocale(options.language ?? 'en')
ctx.provide('locale', locale)
const layout = new LayoutController({
selectPanel: vi.fn(), retainMainPanels: vi.fn(),
setSidebar: vi.fn(), toggleSidebar: vi.fn(), setViewportWidth: vi.fn(),
@@ -282,19 +291,128 @@ function bench(options: BenchOptions = {}) {
const directoryPicker = new FakeDirectoryPicker()
const workspaces = new FakeWorkspaces(options.workspaces ?? workspaceState([], [], 'pending'))
const sessions = new FakeSessions(options.sessions ?? sessionState([], 'pending'))
options.configureWorkspaces?.(workspaces)
options.configureSessions?.(sessions)
const view = createWorkspaceViewStore().create()
const notifyDefaultFailure = vi.fn()
const uiWorkspace = new UiWorkspaceService(
ctx,
directoryPicker.remote,
workspaces,
sessions,
view.actions,
notifyDefaultFailure,
)
return { ctx, directoryPicker, sessions, uiWorkspace, workspaces, layout, selectPanel, view }
return { ctx, directoryPicker, sessions, uiWorkspace, workspaces, layout, selectPanel, view, notifyDefaultFailure }
}
describe('UiWorkspaceService', () => {
it.each([
['zh', '默认工作区', '默认工作区'],
['en', 'Default workspace', 'Default workspace'],
['fr', 'default-workspace', 'Default workspace'],
])('prepares and selects the default Workspace after both startup baselines (%s)', async (language, directoryName, title) => {
const b = bench({ language, configureWorkspaces: (workspaces) => {
workspaces.initializeDefault.mockImplementation(async () => {
const item = workspace('default')
workspaces.list.set(workspaceState([item]))
return item
})
} })
expect(b.workspaces.initializeDefault).not.toHaveBeenCalled()
b.sessions.list.set(sessionState())
expect(b.workspaces.initializeDefault).not.toHaveBeenCalled()
b.workspaces.list.set(workspaceState())
await vi.waitFor(() => {
expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('created-default'), { source: 'mainView' })
})
expect(b.workspaces.initializeDefault).toHaveBeenCalledExactlyOnceWith({ directoryName, title }, expect.any(AbortSignal))
expect(b.sessions.create).toHaveBeenCalledWith({ workspaceId: wid('default') })
expect(b.notifyDefaultFailure).not.toHaveBeenCalled()
})
it('leaves an ineligible empty installation without a Session or failure notice', async () => {
const b = bench({ workspaces: workspaceState(), sessions: sessionState() })
await setImmediate()
b.workspaces.list.set(workspaceState())
b.sessions.list.set(sessionState())
await setImmediate()
expect(b.workspaces.initializeDefault).toHaveBeenCalledOnce()
expect(b.sessions.create).not.toHaveBeenCalled()
expect(b.notifyDefaultFailure).not.toHaveBeenCalled()
})
it('requires explicit selection when the startup Session list contains history', async () => {
const b = bench({ workspaces: workspaceState(), sessions: sessionState([summary('history')]) })
await setImmediate()
expect(b.workspaces.initializeDefault).not.toHaveBeenCalled()
expect(b.sessions.create).not.toHaveBeenCalled()
})
it('publishes a startup directory failure once without creating a Session', async () => {
const b = bench({ workspaces: workspaceState(), sessions: sessionState(), configureWorkspaces: (workspaces) => {
workspaces.initializeDefault.mockRejectedValueOnce(new Error('denied'))
} })
await vi.waitFor(() => { expect(b.notifyDefaultFailure).toHaveBeenCalledOnce() })
b.workspaces.list.set(workspaceState())
await setImmediate()
expect(b.workspaces.initializeDefault).toHaveBeenCalledOnce()
expect(b.sessions.create).not.toHaveBeenCalled()
expect(b.notifyDefaultFailure).toHaveBeenCalledOnce()
})
it.each(['session', 'panel', 'disposal'] as const)('cancels startup directory preparation after %s navigation', async (kind) => {
const pending = Promise.withResolvers<WorkspaceView>()
const b = bench({ workspaces: workspaceState(), sessions: sessionState(), configureWorkspaces: (workspaces) => {
workspaces.initializeDefault.mockReturnValueOnce(pending.promise)
} })
if (kind === 'session') b.uiWorkspace.openSession(sid('manual'))
else if (kind === 'panel') b.layout.selectPanel('other-panel' as MainPanelId)
else await b.ctx.fiber.dispose()
expect(b.workspaces.initializeDefault.mock.calls[0]![1]?.aborted).toBe(true)
pending.resolve(workspace('default'))
await setImmediate()
expect(b.sessions.create).not.toHaveBeenCalled()
expect(b.sessions.retain.mock.calls.map(args => args[0])).toEqual(kind === 'session' ? [sid('manual')] : [])
expect(b.notifyDefaultFailure).not.toHaveBeenCalled()
})
it.each(['session', 'panel', 'disposal'] as const)('suppresses a startup directory failure after %s navigation', async (kind) => {
const pending = Promise.withResolvers<WorkspaceView>()
const b = bench({ workspaces: workspaceState(), sessions: sessionState(), configureWorkspaces: (workspaces) => {
workspaces.initializeDefault.mockReturnValueOnce(pending.promise)
} })
if (kind === 'session') b.uiWorkspace.openSession(sid('manual'))
else if (kind === 'panel') b.layout.selectPanel('other-panel' as MainPanelId)
else await b.ctx.fiber.dispose()
pending.reject(new Error('late failure'))
await setImmediate()
expect(b.sessions.create).not.toHaveBeenCalled()
expect(b.notifyDefaultFailure).not.toHaveBeenCalled()
})
it.each([false, true])('reports Session failure without a directory error and retains the Workspace (superseded: %s)', async (superseded) => {
const warning = vi.spyOn(console, 'warn').mockImplementation(() => {})
const created = Promise.withResolvers<SessionId>()
const b = bench({ workspaces: workspaceState(), sessions: sessionState(), configureWorkspaces: (workspaces) => {
workspaces.initializeDefault.mockImplementationOnce(async () => {
const item = workspace('default')
workspaces.list.set(workspaceState([item]))
return item
})
}, configureSessions: (sessions) => { sessions.create.mockReturnValueOnce(created.promise) } })
await vi.waitFor(() => { expect(b.sessions.create).toHaveBeenCalledOnce() })
if (superseded) b.layout.selectPanel('other-panel' as MainPanelId)
const failure = new Error('session failed')
created.reject(failure)
await vi.waitFor(() => {
expect(warning).toHaveBeenCalledExactlyOnceWith('initial Session restoration failed:', failure)
})
expect(b.workspaces.list.getSnapshot().items).toEqual([workspace('default')])
expect(b.notifyDefaultFailure).not.toHaveBeenCalled()
expect(b.sessions.retain).not.toHaveBeenCalled()
})
it('retains an explicit main target before revealing its Conversation', () => {
const b = bench()
b.uiWorkspace.openSession(sid('target'))
@@ -3266,6 +3266,12 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
parameters: [{ name: 'request', description: 'directory path to register.' }],
returns: 'the Workspace and whether this call created it.',
},
{
signature: '@Remote(\'initializeDefault\') async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal: AbortSignal): Promise<WorkspaceValue | undefined>',
description: 'Initialize or reuse the default Workspace during first-use startup.',
parameters: [{ name: 'request', description: 'initial directory name and title; never rename an existing default.' }, { name: 'signal', description: 'caller lifetime; cancels native directory lookup.' }],
returns: 'the durable Workspace, or undefined when first-use initialization is ineligible; creates no Session or message.',
},
{
signature: '@Remote(\'rename\') rename(request: WorkspaceRenameRequest): Promise<WorkspaceValue>',
description: 'Rename one Workspace to a unique non-blank title.',
@@ -3383,6 +3389,12 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
parameters: [{ name: 'path', description: 'Existing directory to own, in a fully qualified path spelling.' }, { name: 'title', description: 'Display title used only when a new record is created.' }],
returns: 'the existing or newly durable workspace.',
},
{
signature: 'initializeDefault(resolveDirectory: () => Promise<{ path: string; title: string }>): Promise<Workspace | undefined>',
description: 'Initialize the default Workspace only while both the registry and Session history are empty. Repeated requests reuse its durable identity; deleting that registration permanently disables automatic creation.',
parameters: [{ name: 'resolveDirectory', description: 'resolve the absolute directory and initial title; called only for eligible creation, inside the registry mutation queue. Missing directories are created recursively before registration. After resolution, caller cancellation does not roll back creation or registration.' }],
returns: 'the initialized Workspace, or undefined when automatic creation is ineligible.',
},
{
signature: 'get(id: WorkspaceId): Workspace | undefined',
description: 'Look up a workspace by id.',
@@ -7307,6 +7319,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [
name: 'WorkspaceFollowIncrement',
declaration: 'export type WorkspaceFollowIncrement = {\n readonly type: \'upsert\';\n readonly workspace: WorkspaceView;\n} | {\n readonly type: \'remove\';\n readonly workspaceId: WorkspaceId;\n} | {\n readonly type: \'order\';\n readonly workspaceIds: readonly WorkspaceId[];\n} | {\n readonly type: \'archived\';\n readonly archivedSessionIds: readonly SessionId[];\n} | {\n readonly type: \'pinned\';\n readonly pinnedSessionIds: readonly SessionId[];\n};',
},
{
name: 'WorkspaceInitializeDefaultRequest',
declaration: 'export interface WorkspaceInitializeDefaultRequest {\n readonly directoryName: string;\n readonly title: string;\n}',
},
{
name: 'WorkspaceInsertBeforeRequest',
declaration: 'export interface WorkspaceInsertBeforeRequest {\n readonly workspaceId: WorkspaceId;\n readonly beforeWorkspaceId?: WorkspaceId;\n}',
@@ -13,6 +13,8 @@ export const remoteDefaultResponses: RemoteTable = {
unary: {
// api-session-controller `sessions.handleConnected()` on `connection/reset`.
'session/list': ok({ items: [] }),
// ui-workspace startup with no entries; first-use initialization is ineligible.
'workspace/initializeDefault': ok(undefined),
// ui-settings `mirror.ensure()` at apply and again on `connection/reset`.
'settings/describe': ok({ writable: true, hasDocument: false, namespaces: [] }),
// ui-model-selection `ModelDirectoryResolver` constructor.
@@ -1,7 +1,7 @@
/** Test-owned workspaces face: the renderer standard-kit observable plus recorded actions. */
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
import type {
IWorkspaces, WorkspaceId, WorkspaceSnapshot, WorkspaceView,
IWorkspaces, WorkspaceId, WorkspaceInitializeDefaultRequest, WorkspaceSnapshot, WorkspaceView,
} from '@deepseek-ai/dsh-api-workspace-controller/client'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import type { SnapshotStore } from '@deepseek-ai/dsh-client-store'
@@ -80,6 +80,18 @@ export class TestWorkspaces implements IWorkspaces {
} as unknown as WorkspaceView
}
/**
* Initialize the default Workspace through a test stub; defaults to an ineligible first use.
* @param request - initial directory name and title.
* @param signal - caller lifetime.
* @returns the stubbed Workspace, or undefined when initialization is ineligible.
*/
async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal?: AbortSignal): Promise<WorkspaceView | undefined> {
this.calls.push({ method: 'initializeDefault', args: [request, signal] })
const stub = this.stubs.get('initializeDefault')
return await (stub?.(request, signal) as Promise<WorkspaceView | undefined> | undefined)
}
/**
* Rename a Workspace (recorded). The default echoes a minimal view.
* @param workspaceId - target workspace.
@@ -557,6 +557,28 @@ describe('workspaces', () => {
expect(view.container.textContent).toContain('ws:pending')
await runtime.dispose()
})
it('skips default initialization without a fixture and forwards a configured request and lifetime', async () => {
const runtime = await SlotTestRuntime.create()
try {
const request = { directoryName: 'default-workspace', title: 'Default workspace' }
const signal = new AbortController().signal
await expect(runtime.workspaces.initializeDefault(request, signal)).resolves.toBeUndefined()
const workspace = {
workspaceId: 'default' as WorkspaceId, title: request.title, path: '/default', sessionIds: [],
createdAt: '2026-09-20T00:00:00Z', updatedAt: '2026-09-20T00:00:00Z',
}
const initialize = vi.fn(async () => workspace)
runtime.workspaces.stub('initializeDefault', initialize)
await expect(runtime.workspaces.initializeDefault(request, signal)).resolves.toBe(workspace)
expect(initialize).toHaveBeenCalledWith(request, signal)
expect(runtime.workspaces.calls).toEqual([
{ method: 'initializeDefault', args: [request, signal] },
{ method: 'initializeDefault', args: [request, signal] },
])
} finally {
await runtime.dispose()
}
})
})
describe('feature mount and disposal', () => {
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/workspace/workspace/README.md
README.md: 51fa66d346ffc4027397d8851b0c81ea87269ded
README.zh.md: 102308d3257ba13d3ec851adcbdb1d4c159abc14
README.md: 897aca8eb725bc9c3e0808e394e5c976886dd877
README.zh.md: dc7a81340c9b134110975e700d43d5569fa6f03d
+11 -2
View File
@@ -33,7 +33,7 @@ Use it when the product shows a persistent workspace surface — a sidebar, sess
### Setting up
The package takes no configuration of its own; it needs a session store, a session persistence backend, and the storage rows that keep its records. A minimal composition:
The package needs a session store, a session persistence backend, and the storage rows that keep its records. A minimal composition:
```yaml
- name: '@deepseek-ai/dsh-session'
@@ -59,6 +59,15 @@ await project.setTitle('Renamed')
ctx.workspaceRegistry.list() // shows the project, newest first
```
<a id="first-use-workspace"></a>
### First-use Workspace
`initializeDefault(resolveDirectory)` initializes the default Workspace without creating a Session. Initial creation requires an empty Workspace registry and no live, persisted, or archived Session, including Sessions without a working directory. The registry checks persistent history directly; an empty visible sidebar is insufficient.
The directory resolver runs inside the mutation queue only when creation is eligible. It returns an absolute path and initial title; the registry creates missing parent directories, canonicalizes the path, rechecks Session history, and commits the Workspace with its initialization marker. An existing directory is reused; a file conflict or directory failure rejects initialization. The [Host controller](../../api/workspace-controller/README.md#first-use-workspace) supplies the Documents path policy.
The first successful registration records its identity durably. Repeated calls return it without resolving a directory again; renaming keeps that identity, and deleting its registration does not permit another automatic creation. Directory or registration failure leaves initialization unset for retry. Directories created before a later failure remain on disk. Once directory resolution succeeds, caller cancellation does not roll back directory creation or registration. The [first-use decision](../../../.agents/notes/implemented/feature/2026-09-20-default-workspace.md) explains this lifetime.
### Grouping sessions under a project
A session joins the project of the directory it runs in: create a session in a project's directory and it appears under that project, newest first. A session can only belong to one project. A session whose directory cannot be validated — no recorded directory, or a moved or deleted folder — cannot join and stays ungrouped.
@@ -102,7 +111,7 @@ The API has two owners: `WorkspaceRegistry` creates, orders, and deletes project
### Durable shape
The registry opens the `workspace` domain (version 2): a `workspaces` table keyed by `WorkspaceId` plus one global state holding `workspaceIds` (the authoritative display order), `archivedSessionIds`, `pinnedSessionIds`, and the optional `pendingMutation` marker. Archive and pin sets contain Session id strings, default to empty, and carry no per-entry objects or timestamps; the pin array keeps the most recently pinned id first. Archiving clears the pin in the same global-state write without changing Workspace membership. Unarchive runs no session-existence probe, because dropping an id from the set cannot introduce an unknown one, while archive verifies the session before adding it.
The registry opens the `workspace` domain (version 2): a `workspaces` table keyed by `WorkspaceId` plus one global state holding `workspaceIds` (the authoritative display order), `archivedSessionIds`, `pinnedSessionIds`, the optional `defaultWorkspaceId` first-use identity, and the optional `pendingMutation` marker. Archive and pin sets contain Session id strings, default to empty, and carry no per-entry objects or timestamps; the pin array keeps the most recently pinned id first. Archiving clears the pin in the same global-state write without changing Workspace membership. Unarchive runs no session-existence probe, because dropping an id from the set cannot introduce an unknown one, while archive verifies the session before adding it.
### Lifecycle
+11 -2
View File
@@ -33,7 +33,7 @@ kind: "package-reference"
### 设置
此包本身不声明任何配置;它需要会话存储、会话持久化后端,以及保存其记录的存储行。最小组合如下:
此包需要会话存储、会话持久化后端,以及保存其记录的存储行。最小组合如下:
```yaml
- name: '@deepseek-ai/dsh-session'
@@ -59,6 +59,15 @@ await project.setTitle('Renamed')
ctx.workspaceRegistry.list() // shows the project, newest first
```
<a id="first-use-workspace"></a>
### 首次使用工作区
`initializeDefault(resolveDirectory)` 初始化默认 Workspace,不创建 Session。首次创建要求 Workspace 注册表为空,且不存在运行时、持久化或已归档 Session,包括没有工作目录的 Session。注册表直接检查持久化历史;仅凭可见侧边栏为空不足以判断。
目录解析器仅在允许创建时于变更队列内运行。它返回绝对路径和初始标题;注册表创建缺失的父目录、规范化路径、重新检查 Session 历史,再一起提交 Workspace 和初始化标记。已存在的目录直接复用;文件冲突或目录操作失败时拒绝初始化。[Host 控制器](../../api/workspace-controller/README.zh.md#first-use-workspace)提供 Documents 路径策略。
首次成功登记会持久保存工作区身份。重复调用直接返回它,不再解析目录;改名保留该身份,删除登记也不会允许再次自动创建。目录或登记失败时,初始化状态保持未设置,可以重试。后续步骤失败前已创建的目录会保留在磁盘上。目录解析成功后,调用方取消操作不会回滚目录创建或登记。[首次使用决策](../../../.agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md)说明这一生命周期。
### 将会话归入项目
会话加入它运行目录所在的项目:在项目目录中创建会话,它就会出现在该项目下,新到旧排列。一个会话只能属于一个项目。目录无法校验的会话——没有记录目录,或目录被移动、删除——无法加入,保持 Ungrouped。
@@ -102,7 +111,7 @@ ctx.workspaceRegistry.list() // shows the project, newest first
### 持久形态
注册表打开 `workspace` 领域(版本 2):一张以 `WorkspaceId` 为键的 `workspaces` 表,加上一个持有 `workspaceIds`(权威显示顺序)、`archivedSessionIds`、`pinnedSessionIds` 与可选 `pendingMutation` 标记的全局状态。归档与置顶集合存储会话 id 字符串,默认值为空,不包含逐项对象或时间戳;置顶数组把最近置顶的 id 放在前面。归档在同一次全局状态写入中清除置顶,但不改变 Workspace 成员关系。取消归档不做会话存在性探测,因为从集合中移除 id 不可能引入未知 id,而归档会在加入前校验会话。
注册表打开 `workspace` 领域(版本 2):一张以 `WorkspaceId` 为键的 `workspaces` 表,加上一个持有 `workspaceIds`(权威显示顺序)、`archivedSessionIds`、`pinnedSessionIds`、可选的首次使用身份 `defaultWorkspaceId` 与可选 `pendingMutation` 标记的全局状态。归档与置顶集合存储会话 id 字符串,默认值为空,不包含逐项对象或时间戳;置顶数组把最近置顶的 id 放在前面。归档在同一次全局状态写入中清除置顶,但不改变 Workspace 成员关系。取消归档不做会话存在性探测,因为从集合中移除 id 不可能引入未知 id,而归档会在加入前校验会话。
### 生命周期
+38 -13
View File
@@ -6,7 +6,7 @@
*/
import { randomUUID } from 'node:crypto'
import { stat } from 'node:fs/promises'
import { mkdir, stat } from 'node:fs/promises'
import { Context, Service } from '@deepseek-ai/cordis'
import type { SessionHeader, SessionId } from '@deepseek-ai/dsh-session'
import type {} from '@deepseek-ai/dsh-session-persistence'
@@ -15,7 +15,7 @@ import { WorkspaceEntity } from './entity.ts'
import type { WorkspaceEntityHost } from './entity.ts'
export { WorkspaceMoveInvalidError } from './entity.ts'
import { defaultWorkspaceTitle, realpathNormalize } from './paths.ts'
import { defaultWorkspaceTitle, fullyQualifiedWorkspacePath, realpathNormalize } from './paths.ts'
import { workspaceDomainSpec } from './spec.ts'
import type { WorkspaceDomainState, WorkspaceRecord } from './spec.ts'
import type { Workspace, WorkspaceId as WorkspaceIdBrand } from './types.ts'
@@ -175,6 +175,35 @@ export class WorkspaceRegistry extends Service {
return await this.enqueueOperation(() => this.createCanonical(canonical, title))
}
/**
* Initialize the default Workspace only while both the registry and Session
* history are empty. Repeated requests reuse its durable identity; deleting
* that registration permanently disables automatic creation.
* @param resolveDirectory - resolve the absolute directory and initial title;
* called only for eligible creation, inside the registry mutation queue.
* Missing directories are created recursively before registration.
* After resolution, caller cancellation does not roll back creation or registration.
* @returns the initialized Workspace, or undefined when automatic creation is ineligible.
*/
initializeDefault(resolveDirectory: () => Promise<{ path: string; title: string }>): Promise<Workspace | undefined> {
return this.enqueueOperation(async () => {
const state = this.requireState()
if (state.defaultWorkspaceId !== undefined) return this.entities.get(state.defaultWorkspaceId)
const sessions = this.ctx.get('sessions')
if (sessions === undefined) throw new Error('default Workspace initialization requires the Session store')
if (state.workspaceIds.length > 0 || state.archivedSessionIds.length > 0
|| sessions.list().length > 0 || (await this.listStoredHeaders()).length > 0) return undefined
const { path, title } = await resolveDirectory()
if (!fullyQualifiedWorkspacePath(path)) throw new TypeError(`Workspace path is not fully qualified: '${path}'`)
await mkdir(path, { recursive: true })
const canonical = await realpathNormalize(path)
// A Session can start outside the registry queue while directory preparation awaits I/O.
if ((await this.listStoredHeaders()).length > 0 || sessions.list().length > 0) return undefined
return this.createCanonical(canonical, title, true)
})
}
/**
* Look up a workspace by id.
* @param id - Workspace id.
@@ -379,7 +408,7 @@ export class WorkspaceRegistry extends Service {
return undefined
}
private async createCanonical(canonical: string, title?: string): Promise<WorkspaceEntity> {
private async createCanonical(canonical: string, title?: string, firstUse = false): Promise<WorkspaceEntity> {
for (const entity of this.entities.values()) {
if (entity.path === canonical) return entity
}
@@ -425,10 +454,11 @@ export class WorkspaceRegistry extends Service {
try {
await this.setState({
...state,
pendingMutation: undefined,
initialized: true,
...(firstUse ? { defaultWorkspaceId: id } : {}),
workspaceIds: [id, ...state.workspaceIds],
archivedSessionIds: state.archivedSessionIds,
pinnedSessionIds: state.pinnedSessionIds,
})
} catch (error) {
this.entities.delete(id)
@@ -458,10 +488,10 @@ export class WorkspaceRegistry extends Service {
if (entity === undefined) return false
const state = this.requireState()
const nextState = {
...state,
pendingMutation: undefined,
initialized: true,
workspaceIds: state.workspaceIds.filter(workspaceId => workspaceId !== id),
archivedSessionIds: state.archivedSessionIds,
pinnedSessionIds: state.pinnedSessionIds,
}
await this.setState({
...nextState,
@@ -515,12 +545,7 @@ export class WorkspaceRegistry extends Service {
)
}
await this.requireTable().delete(pending.workspaceId)
await this.setState({
initialized: state.initialized,
workspaceIds: state.workspaceIds,
archivedSessionIds: state.archivedSessionIds,
pinnedSessionIds: state.pinnedSessionIds,
})
await this.setState({ ...state, pendingMutation: undefined })
}
private async bootstrap(headers: readonly SessionHeader[]): Promise<void> {
+2
View File
@@ -56,6 +56,8 @@ const workspacePendingMutation = z.discriminatedUnion('operation', [
*/
export const workspaceDomainState = z.object({
initialized: z.boolean(),
/** First-use Workspace identity, retained after its registration is deleted. */
defaultWorkspaceId: workspaceId.optional(),
workspaceIds: z.array(workspaceId),
archivedSessionIds: z.array(sessionId).default([]),
pinnedSessionIds: z.array(sessionId).default([]),
@@ -2,7 +2,7 @@ import type { z } from 'zod'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { mkdir, mkdtemp, realpath, rm, symlink, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { basename, join } from 'node:path'
import { basename, join, relative } from 'node:path'
import { Context } from '@deepseek-ai/cordis'
import Storage from '@deepseek-ai/dsh-storage'
import type { StorageBackend } from '@deepseek-ai/dsh-storage'
@@ -1156,3 +1156,145 @@ describe('registry-global session unpin', () => {
expect(result.list.mock.calls.length).toBe(listingsBefore)
})
})
describe('first-use Workspace preparation', () => {
const contexts: Context[] = []
afterEach(async () => {
for (const ctx of contexts.splice(0)) await ctx.fiber.dispose()
})
async function firstUse(options: HarnessOptions = {}) {
const directoryRoot = await makeDir('first-use')
const result = await harness({ liveSessions: [], ...options })
contexts.push(result.ctx)
const resolveDirectory = vi.fn(async () => ({ path: join(directoryRoot, 'nested', 'Workspace'), title: 'Workspace' }))
return { ...result, directoryRoot, resolveDirectory }
}
it('creates parent directories and resolves only one directory for concurrent initialization', async () => {
const h = await firstUse()
const laterDirectory = vi.fn(async () => { throw new Error('directory lookup unavailable') })
const [first, repeated] = await Promise.all([
h.registry.initializeDefault(h.resolveDirectory), h.registry.initializeDefault(laterDirectory),
])
expect(first).toBeDefined()
expect(repeated).toBe(first)
expect(h.resolveDirectory).toHaveBeenCalledOnce()
expect(laterDirectory).not.toHaveBeenCalled()
expect(first?.path).toBe(await realpath(join(h.directoryRoot, 'nested', 'Workspace')))
expect(first?.title).toBe('Workspace')
expect(h.registry.list()).toEqual([first])
expect(storedState(h.pool).defaultWorkspaceId).toBe(first?.id)
expect(h.ctx.sessions.list()).toEqual([])
expect(h.open).not.toHaveBeenCalled()
})
it('reuses an existing directory without changing its contents', async () => {
const h = await firstUse()
const directory = join(h.directoryRoot, 'nested', 'Workspace')
await mkdir(directory, { recursive: true })
await writeFile(join(directory, 'keep.txt'), 'keep')
expect((await h.registry.initializeDefault(h.resolveDirectory))?.path).toBe(directory)
const { readFile } = await import('node:fs/promises')
expect(await readFile(join(directory, 'keep.txt'), 'utf8')).toBe('keep')
})
it('leaves initialization retryable when directory resolution fails', async () => {
const h = await firstUse()
h.resolveDirectory.mockRejectedValueOnce(new Error('lookup unavailable'))
await expect(h.registry.initializeDefault(h.resolveDirectory)).rejects.toThrow('lookup unavailable')
expect(storedState(h.pool).defaultWorkspaceId).toBeUndefined()
expect(await h.registry.initializeDefault(h.resolveDirectory)).toBeDefined()
})
it('rejects a relative candidate before creating its directory', async () => {
const h = await firstUse()
const candidate = join(h.directoryRoot, 'relative')
h.resolveDirectory.mockResolvedValueOnce({ path: relative(process.cwd(), candidate), title: 'Workspace' })
await expect(h.registry.initializeDefault(h.resolveDirectory)).rejects.toThrow('fully qualified')
await expect(realpath(candidate)).rejects.toMatchObject({ code: 'ENOENT' })
expect(h.registry.list()).toEqual([])
expect(storedState(h.pool).defaultWorkspaceId).toBeUndefined()
})
it('keeps the initialization marker across deletion and restart', async () => {
const h = await firstUse()
const workspace = (await h.registry.initializeDefault(h.resolveDirectory))!
await workspace.setTitle('Renamed')
expect((await h.registry.initializeDefault(h.resolveDirectory))?.title).toBe('Renamed')
await h.registry.delete(workspace.id)
await h.ctx.fiber.dispose()
const restarted = await firstUse({ pool: h.pool })
await expect(restarted.registry.initializeDefault(restarted.resolveDirectory)).resolves.toBeUndefined()
expect(storedState(h.pool).defaultWorkspaceId).toBe(workspace.id)
expect(restarted.registry.list()).toEqual([])
expect(restarted.resolveDirectory).not.toHaveBeenCalled()
})
it.each(['persisted', 'live', 'archived'] as const)('refuses automatic creation for a %s cwd-less Session', async (kind) => {
const history = header('old')
const h = await firstUse(kind === 'persisted' ? { sessions: [history] } : { liveSessions: [history] })
if (kind === 'archived') await h.registry.archiveSession(history.id)
await expect(h.registry.initializeDefault(h.resolveDirectory)).resolves.toBeUndefined()
expect(h.registry.list()).toEqual([])
expect(storedState(h.pool).defaultWorkspaceId).toBeUndefined()
expect(h.resolveDirectory).not.toHaveBeenCalled()
})
it('refuses a non-empty Workspace list and newly persisted history', async () => {
const h = await firstUse()
const explicit = await h.registry.create(h.directoryRoot)
await expect(h.registry.initializeDefault(h.resolveDirectory)).resolves.toBeUndefined()
await h.registry.delete(explicit.id)
h.setSessions([header('arrived')])
await expect(h.registry.initializeDefault(h.resolveDirectory)).resolves.toBeUndefined()
})
it('fails on a same-path file and remains eligible after it is removed', async () => {
const h = await firstUse()
const parent = join(h.directoryRoot, 'nested')
await mkdir(parent)
const path = join(parent, 'Workspace')
await writeFile(path, 'occupied')
await expect(h.registry.initializeDefault(h.resolveDirectory)).rejects.toThrow()
expect(storedState(h.pool).defaultWorkspaceId).toBeUndefined()
expect(h.registry.list()).toEqual([])
await rm(path)
expect((await h.registry.initializeDefault(h.resolveDirectory))?.path).toBe(path)
})
it.each(['persisted', 'live'] as const)('refuses registration when a %s Session appears during directory preparation', async (kind) => {
const h = await firstUse()
const arrived = header('arrived-during-preparation')
if (kind === 'persisted') {
h.list.mockResolvedValueOnce([]).mockResolvedValueOnce([
{ header: arrived, revision: SessionPersistenceRevision('arrived-revision') },
])
} else {
vi.spyOn(h.ctx.sessions, 'list').mockReturnValueOnce([]).mockReturnValueOnce([{ header: arrived }] as never)
}
await expect(h.registry.initializeDefault(h.resolveDirectory)).resolves.toBeUndefined()
expect(h.registry.list()).toEqual([])
expect(storedState(h.pool).defaultWorkspaceId).toBeUndefined()
})
it('does not infer an empty live Session store when the peer is unavailable', async () => {
const h = await harness()
contexts.push(h.ctx)
const resolveDirectory = vi.fn(async () => { throw new Error('unexpected directory lookup') })
await expect(h.registry.initializeDefault(resolveDirectory)).rejects.toThrow('Session store')
expect(resolveDirectory).not.toHaveBeenCalled()
expect(storedState(h.pool).defaultWorkspaceId).toBeUndefined()
})
it('rolls back a failed final marker write and allows a retry', async () => {
const pool = new MemoryMediaPool()
const h = await firstUse({ pool, backend: selectiveFailureBackend(pool, { globalAt: 3 }) })
await expect(h.registry.initializeDefault(h.resolveDirectory)).rejects.toThrow('marker failure')
expect(h.registry.list()).toEqual([])
expect(storedState(pool).defaultWorkspaceId).toBeUndefined()
await expect(realpath(join(h.directoryRoot, 'nested', 'Workspace'))).resolves.toBe(join(h.directoryRoot, 'nested', 'Workspace'))
expect(await h.registry.initializeDefault(h.resolveDirectory)).toBeDefined()
})
})
+6
View File
@@ -1315,6 +1315,12 @@ importers:
'@deepseek-ai/dsh-deque':
specifier: workspace:^
version: link:../../util/deque
'@deepseek-ai/dsh-native-command':
specifier: workspace:^
version: link:../../util/native-command
'@deepseek-ai/schemastery':
specifier: link:../../../vendor/schemastery
version: link:../../../vendor/schemastery
zod:
specifier: ^4.4.3
version: 4.4.3
+1
View File
@@ -682,6 +682,7 @@ export const LINK_MAP: Readonly<Record<string, string>> = {
WorkspaceArchiveSessionRequest: 'workspace.md',
WorkspaceArchiveValue: 'workspace.md',
WorkspaceCreateRequest: 'workspace.md',
WorkspaceInitializeDefaultRequest: 'workspace.md',
WorkspaceCreateValue: 'workspace.md',
WorkspaceDeleteRequest: 'workspace.md',
WorkspaceDeleteValue: 'workspace.md',
@@ -0,0 +1,11 @@
version: 1
scenario: default-workspace
profile: web
composition: web-default
recording: authored
workspace:
final: true
header:
class: web-default
session:
source: ../fresh-round-trip/session.v3.jsonl
@@ -0,0 +1,26 @@
- banner:
- navigation "Session hierarchy": Use the bash tool to
- text: Standard mode
- button "More actions"
- button "Open right sidebar"
- tablist:
- tab "Chat" [selected]
- tab "Trajectory"
- button "System prompt"
- text: "Use the bash tool to run exactly: echo WEB_E2E_OK. Then reply with the single word DONE and stop. {{clock}}"
- button "Copy"
- button "1 tool call"
- paragraph: DONE
- button "Copy"
- button "Good response"
- button "Bad response"
- button "Branch into a new conversation"
- text: {{clock}}
- textbox "Message or run a task, / commands, @ files or sessions"
- button "Add files or run commands"
- 'button "Access mode, current: Workspace Write"': Workspace Write
- button "Select model, current DeepSeek-V4-Flash": DeepSeek-V4-Flash
- button "Send message" [disabled]
- button "1 turns 2 steps · {{throughput}} tok/s": 1 turns 2 steps{{throughput}} tok/s
- button "15.8K tok · Cache hit 99%": 15.8K tokCache hit 99%
- button "6% of context used": 6%
@@ -0,0 +1 @@
+1
View File
@@ -64,6 +64,7 @@
"apps/web/tests/public-mount.e2e.ts",
"apps/web/tests/workspace-new-session-folding.e2e.ts",
"apps/web/tests/workspace-management.e2e.ts",
"apps/web/tests/default-workspace.e2e.ts",
"apps/web/tests/workspace-recency.e2e.ts",
"apps/web/tests/session-unarchive.e2e.ts",
"apps/web/tests/replay-round-trip.e2e.ts",