Merge pull request #5982 from deepseek-harness/worktree-spacebrowser
feat(ui-workspace): expose session ids and unify toast presentation
This commit is contained in:
commit
d6be036d67
56 files changed
+1028
-360
No files matched your search
@@ -30,7 +30,7 @@ it('places dynamic Session menu rows by order among the shipped ones and removes
|
||||
const scaffold = await launchWebScaffold({ extraInstallAnchors: [join(FIXTURE, 'package.json')] })
|
||||
onTestFinished(() => scaffold.close())
|
||||
const workspace = await scaffold.ctx.workspaceRegistry.create(scaffold.workspaceCwd)
|
||||
const sessionId = await seedSession(scaffold, await readFile(SESSION_SEED, 'utf8'), 'session-menu-actions-web-e2e')
|
||||
const sessionId = await seedSession(scaffold, await readFile(SESSION_SEED, 'utf8'), 'session-c4421b66-252e-44c0-80ed-6e320abeba25')
|
||||
await workspace.attachSession(sessionId)
|
||||
await scaffold.ctx.sessionController.rename({ sessionId, title: SESSION_TITLE })
|
||||
const entryId = await scaffold.ctx.loader.create({ name: '@fixture/live-client' })
|
||||
@@ -71,13 +71,18 @@ it('places dynamic Session menu rows by order among the shipped ones and removes
|
||||
await row.hover()
|
||||
await trigger.click()
|
||||
await menu.waitFor()
|
||||
const remainingNames = ['Pin session', 'Rename', 'Fork session', 'Archive session']
|
||||
const remainingNames = ['Pin session', 'Rename', 'Fork session', 'Archive session', 'Copy Session ID']
|
||||
const remainingItems = menu.getByRole('menuitem')
|
||||
expect(await remainingItems.count()).toBe(remainingNames.length)
|
||||
for (const [index, name] of remainingNames.entries()) {
|
||||
expect(await remainingItems.nth(index).and(menu.getByRole('menuitem', { name, exact: true })).count()).toBe(1)
|
||||
}
|
||||
expect(await menu.getByRole('separator').count()).toBe(0)
|
||||
await page.context().grantPermissions(['clipboard-read', 'clipboard-write'])
|
||||
await menu.getByRole('menuitem', { name: 'Copy Session ID', exact: true }).click()
|
||||
await expect.poll(() => menu.count()).toBe(0)
|
||||
await page.getByRole('alert').filter({ hasText: 'Session ID copied' }).waitFor()
|
||||
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(sessionId)
|
||||
expect(console.pageErrors).toEqual([])
|
||||
await assertFixtureInventory(EXPECTED, [
|
||||
'bootstrap-rebuild.expected.md', 'enabled.expected.md', 'recovered.expected.md',
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
- menuitem "Rename"
|
||||
- menuitem "Fork session"
|
||||
- menuitem "Archive session"
|
||||
- menuitem "Copy Session ID"
|
||||
- separator
|
||||
- menuitem "Export session"
|
||||
- menuitem "Copy session ID"
|
||||
@@ -3,3 +3,4 @@
|
||||
- menuitem "Rename"
|
||||
- menuitem "Fork session"
|
||||
- menuitem "Archive session"
|
||||
- menuitem "Copy Session ID"
|
||||
@@ -3,3 +3,4 @@
|
||||
- menuitem "Rename"
|
||||
- menuitem "Fork session"
|
||||
- menuitem "Archive session"
|
||||
- menuitem "Copy Session ID"
|
||||
@@ -89,7 +89,7 @@ window.__ModuleLoader__.load({
|
||||
)
|
||||
})
|
||||
ctx.slots.inject('sidebar.workspaces.session.menu.item', function* () {
|
||||
// The shipped rows end at archive (400); these follow as one group,
|
||||
// The shipped rows end at Session ID (450); these follow as one group,
|
||||
// opened by the export row's hairline.
|
||||
yield registerSessionAction('fixture.export-session', 500, 'exportSession', true)
|
||||
yield registerSessionAction('fixture.copy-session-id', 600, 'copySessionId', false)
|
||||
|
||||
@@ -937,7 +937,7 @@ describe('web e2e: settings modal and General preferences', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('web e2e: browser-local collapse timing preference', () => {
|
||||
describe('web e2e: Host-backed collapse timing preference', () => {
|
||||
let scaffold: WebScaffold
|
||||
let browser: Browser
|
||||
const uiWait = { timeout: 10_000 }
|
||||
@@ -968,11 +968,12 @@ describe('web e2e: browser-local collapse timing preference', () => {
|
||||
title: 'When to Collapse Work Details', completion: 'On completion', nextInput: 'On next message',
|
||||
description: 'Choose when to automatically collapse work details',
|
||||
},
|
||||
] as const)('keeps $locale collapse timing on $theme only for the current Client', async (copy) => {
|
||||
] as const)('persists $locale collapse timing on $theme across Clients', async (copy) => {
|
||||
const contextOptions = {
|
||||
viewport: { width: 1680, height: 1000 }, locale: copy.browserLocale,
|
||||
colorScheme: copy.theme, timezoneId: 'Asia/Shanghai',
|
||||
}
|
||||
await scaffold.ctx.settings.update('ui-chat', { collapseTiming: 'completion' })
|
||||
const context = await browser.newContext(contextOptions)
|
||||
onTestFinished(() => context.close())
|
||||
const page = await context.newPage()
|
||||
@@ -1070,19 +1071,23 @@ describe('web e2e: browser-local collapse timing preference', () => {
|
||||
await menu.waitFor({ state: 'hidden' })
|
||||
await page.setViewportSize({ width: 1680, height: 1000 })
|
||||
await timing.getByRole('button', { name: copy.nextInput, exact: true }).waitFor()
|
||||
expect(await readPersistence()).toEqual(before)
|
||||
await expect.poll(() => scaffold.ctx.settings.describe().find(row => row.ns === 'ui-chat')?.value, uiWait)
|
||||
.toMatchObject({ transcriptView: 'detailed', collapseTiming: 'next-input' })
|
||||
const saved = await readPersistence()
|
||||
expect(saved.host).not.toBe(before.host)
|
||||
expect(saved.storage).toEqual(before.storage)
|
||||
await dialog.getByRole('button', { name: copy.close, exact: true }).click()
|
||||
await openSettings(page, copy.locale)
|
||||
await timing.getByRole('button', { name: copy.nextInput, exact: true }).waitFor()
|
||||
expect(await readPersistence()).toEqual(before)
|
||||
expect(await readPersistence()).toEqual(saved)
|
||||
await dialog.getByRole('button', { name: copy.close, exact: true }).click()
|
||||
|
||||
const warningStart = tripwire.warnings.length
|
||||
await page.reload({ waitUntil: 'load' })
|
||||
await openSettings(page, copy.locale)
|
||||
await timing.getByRole('button', { name: copy.completion, exact: true }).waitFor()
|
||||
await timing.getByRole('button', { name: copy.nextInput, exact: true }).waitFor()
|
||||
acknowledgeReloadConnectionLoss(tripwire, warningStart)
|
||||
expect(await readPersistence()).toEqual(before)
|
||||
expect(await readPersistence()).toEqual(saved)
|
||||
if (screenshotDir !== undefined) {
|
||||
await page.screenshot({ path: join(screenshotDir, 'reloaded.png'), fullPage: true })
|
||||
}
|
||||
@@ -1094,10 +1099,10 @@ describe('web e2e: browser-local collapse timing preference', () => {
|
||||
await openSettings(sharedPage, copy.locale)
|
||||
const sharedTiming = sharedPage.getByRole('dialog', { name: copy.settings, exact: true })
|
||||
.getByText(copy.title, { exact: true }).locator('../..')
|
||||
await sharedTiming.getByRole('button', { name: copy.completion, exact: true }).waitFor()
|
||||
await sharedTiming.getByRole('button', { name: copy.nextInput, exact: true }).waitFor()
|
||||
const sharedPersistence = await readPersistence(sharedPage)
|
||||
expect(sharedPersistence.host).toBe(before.host)
|
||||
expect(sharedPersistence.settings).toEqual(before.settings)
|
||||
expect(sharedPersistence.host).toBe(saved.host)
|
||||
expect(sharedPersistence.settings).toEqual(saved.settings)
|
||||
expect(sharedPersistence.storage.local).toEqual(before.storage.local)
|
||||
if (screenshotDir !== undefined) {
|
||||
await sharedPage.screenshot({ path: join(screenshotDir, 'shared-tab.png'), fullPage: true })
|
||||
@@ -1113,22 +1118,24 @@ describe('web e2e: browser-local collapse timing preference', () => {
|
||||
await openSettings(isolatedPage, copy.locale)
|
||||
const isolatedTiming = isolatedPage.getByRole('dialog', { name: copy.settings, exact: true })
|
||||
.getByText(copy.title, { exact: true }).locator('../..')
|
||||
await isolatedTiming.getByRole('button', { name: copy.completion, exact: true }).waitFor()
|
||||
await isolatedTiming.getByRole('button', { name: copy.nextInput, exact: true }).waitFor()
|
||||
const isolatedPersistence = await readPersistence(isolatedPage)
|
||||
expect(isolatedPersistence.host).toBe(before.host)
|
||||
expect(isolatedPersistence.settings).toEqual(before.settings)
|
||||
expect(isolatedPersistence.host).toBe(saved.host)
|
||||
expect(isolatedPersistence.settings).toEqual(saved.settings)
|
||||
if (screenshotDir !== undefined) {
|
||||
await isolatedPage.screenshot({ path: join(screenshotDir, 'isolated-context.png'), fullPage: true })
|
||||
}
|
||||
|
||||
expect(await readPersistence()).toEqual(before)
|
||||
await timing.getByRole('button', { name: copy.completion, exact: true }).click()
|
||||
await page.getByRole('menuitem', { name: copy.nextInput, exact: true }).click()
|
||||
expect(await readPersistence()).toEqual(saved)
|
||||
await timing.getByRole('button', { name: copy.nextInput, exact: true }).click()
|
||||
await page.getByRole('menuitem', { name: copy.completion, exact: true }).click()
|
||||
await timing.getByRole('button', { name: copy.completion, exact: true }).waitFor()
|
||||
expect(await readPersistence()).toEqual(before)
|
||||
expect(settingsWrites).toEqual([])
|
||||
await expect.poll(() => scaffold.ctx.settings.describe().find(row => row.ns === 'ui-chat')?.value, uiWait)
|
||||
.toMatchObject({ transcriptView: 'detailed', collapseTiming: 'completion' })
|
||||
expect((await readPersistence()).storage).toEqual(before.storage)
|
||||
await sharedTiming.getByRole('button', { name: copy.completion, exact: true }).waitFor()
|
||||
await isolatedTiming.getByRole('button', { name: copy.completion, exact: true }).waitFor()
|
||||
expect(settingsWrites.length).toBeGreaterThan(0)
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
expect(tripwire.warnings).toEqual([])
|
||||
expect(sharedTripwire.pageErrors).toEqual([])
|
||||
|
||||
@@ -190,7 +190,8 @@ root
|
||||
├─ shell.bottom
|
||||
├─ shell.leading
|
||||
└─ shell.overlay
|
||||
└─ shell.quota-notice
|
||||
├─ shell.quota-notice
|
||||
└─ workspace.toast
|
||||
```
|
||||
|
||||
The generated Client inspect catalog is the exhaustive contract for each key: cardinality, scope, owner props, standard props, current occupants, declaration owner, and replacement risk. A running dynamic package can query the live tree and an exact key with `cordis_inspect what:"client"`; the source catalog is generated from `SlotMap` declarations and `slots.register()` call sites by `pnpm run gen-client-catalog`.
|
||||
|
||||
@@ -192,7 +192,8 @@ root
|
||||
├─ shell.bottom
|
||||
├─ shell.leading
|
||||
└─ shell.overlay
|
||||
└─ shell.quota-notice
|
||||
├─ shell.quota-notice
|
||||
└─ workspace.toast
|
||||
```
|
||||
|
||||
生成的 Client inspect catalog 是每个 key 的完整参考,包含 cardinality、scope、owner props、标准 props、当前 occupant、声明 owner 与替换风险。运行中的动态包可以用 `cordis_inspect what:"client"` 查询实时树与某个精确 key;源码 catalog 由 `pnpm run gen-client-catalog` 根据 `SlotMap` 声明和 `slots.register()` 调用点生成。
|
||||
|
||||
@@ -9,8 +9,8 @@
|
||||
en: d61a7e78bbc1fb56
|
||||
zh: 8397869f70cd5b28
|
||||
/workspaces/the-workspace-entity:
|
||||
en: 697698bc46adc477
|
||||
zh: 73d073933ed68c53
|
||||
en: ce5b65fb4d0b0c7b
|
||||
zh: aa332a17810d583a
|
||||
/workspaces/the-registry-ctx-workspaceregistry:
|
||||
en: 73b54ccf836b7f46
|
||||
zh: 7ee93ba8bb0a616a
|
||||
|
||||
@@ -25,9 +25,10 @@ Consumers see only the `Workspace` interface; the implementation stays package-p
|
||||
```ts type-equiv
|
||||
/**
|
||||
* One workspace: a stable id over an existing directory, a display title, and
|
||||
* an ordered candidate account of sessions. Membership requires both an id in
|
||||
* that account and a session header whose canonical cwd equals the workspace
|
||||
* path. Consumers only see this interface; the implementation stays private.
|
||||
* an ordered candidate account of sessions. Membership validates header cwd
|
||||
* against the workspace path, but preserves an existing account when its
|
||||
* fully qualified cwd is missing. Consumers only see this interface; the
|
||||
* implementation stays private.
|
||||
*/
|
||||
interface Workspace {
|
||||
/** Stable record id (generated uuid). */
|
||||
@@ -54,8 +55,11 @@ interface Workspace {
|
||||
* prepended at attach, explicit reordering goes through
|
||||
* `insertSessionBefore`, and activity never reorders. The durable candidate
|
||||
* account is filtered synchronously: missing headers, invalid cwd values,
|
||||
* and canonical cwd mismatches are never returned. A subsequent workspace
|
||||
* mutation prunes those filtered candidates durably.
|
||||
* and canonical cwd mismatches are never returned. A fully qualified cwd
|
||||
* whose realpath or directory stat fails with ENOENT preserves an existing
|
||||
* candidate, including a dangling symlink; other filesystem failures do not.
|
||||
* A subsequent mutation prunes filtered candidates, not missing-directory
|
||||
* candidates. This does not admit new sessions or recreate directories.
|
||||
*/
|
||||
readonly sessionIds: readonly SessionId[]
|
||||
|
||||
@@ -113,7 +117,7 @@ interface Workspace {
|
||||
}
|
||||
```
|
||||
|
||||
Ownership truth is the record's ordered `sessionIds`, never derived from session cwd — but membership requires both: an id on the account and a header whose canonical cwd equals the workspace path, so one session structurally belongs to at most one workspace. Failed writes reject (`insertSessionBefore` account errors as `WorkspaceMoveInvalidError`, storage failures as plain errors); every accepted mutation stamps `updatedAt` and durably prunes candidates that no longer pass the membership check.
|
||||
Ownership truth is the record's ordered `sessionIds`, never derived from session cwd. Membership validates the recorded header cwd against the workspace path; an existing candidate remains owned when its fully qualified cwd fails resolution or directory stat with `ENOENT`. This preserves missing-directory and dangling-symlink accounts without admitting new sessions. Failed writes reject (`insertSessionBefore` account errors as `WorkspaceMoveInvalidError`, storage failures as plain errors); every accepted mutation stamps `updatedAt` and durably prunes candidates that no longer pass the membership check.
|
||||
|
||||
## The registry: `ctx.workspaceRegistry`
|
||||
|
||||
|
||||
@@ -25,9 +25,10 @@ type WorkspaceId = Branded<'WorkspaceId'>
|
||||
```ts type-equiv
|
||||
/**
|
||||
* One workspace: a stable id over an existing directory, a display title, and
|
||||
* an ordered candidate account of sessions. Membership requires both an id in
|
||||
* that account and a session header whose canonical cwd equals the workspace
|
||||
* path. Consumers only see this interface; the implementation stays private.
|
||||
* an ordered candidate account of sessions. Membership validates header cwd
|
||||
* against the workspace path, but preserves an existing account when its
|
||||
* fully qualified cwd is missing. Consumers only see this interface; the
|
||||
* implementation stays private.
|
||||
*/
|
||||
interface Workspace {
|
||||
/** Stable record id (generated uuid). */
|
||||
@@ -54,8 +55,11 @@ interface Workspace {
|
||||
* prepended at attach, explicit reordering goes through
|
||||
* `insertSessionBefore`, and activity never reorders. The durable candidate
|
||||
* account is filtered synchronously: missing headers, invalid cwd values,
|
||||
* and canonical cwd mismatches are never returned. A subsequent workspace
|
||||
* mutation prunes those filtered candidates durably.
|
||||
* and canonical cwd mismatches are never returned. A fully qualified cwd
|
||||
* whose realpath or directory stat fails with ENOENT preserves an existing
|
||||
* candidate, including a dangling symlink; other filesystem failures do not.
|
||||
* A subsequent mutation prunes filtered candidates, not missing-directory
|
||||
* candidates. This does not admit new sessions or recreate directories.
|
||||
*/
|
||||
readonly sessionIds: readonly SessionId[]
|
||||
|
||||
@@ -113,7 +117,7 @@ interface Workspace {
|
||||
}
|
||||
```
|
||||
|
||||
所有权的真源是记录中有序的 `sessionIds`,绝不从会话 cwd 派生——但成员资格要求两者同时成立:账本上有其 id,且 header 的规范 cwd 等于工作区路径,因此一个会话在结构上至多属于一个工作区。失败的写入会拒绝(`insertSessionBefore` 的账本错误以 `WorkspaceMoveInvalidError` 拒绝,存储失败以普通错误拒绝);每次被接受的变更都盖上 `updatedAt` 时间戳,并持久修剪不再通过成员资格检查的候选项。
|
||||
所有权的真源是记录中有序的 `sessionIds`,绝不从会话 cwd 派生。成员资格将记录的 header cwd 与工作区路径校验;已有候选的完全限定 cwd 在路径解析或目录 stat 时返回 `ENOENT`,仍保留其归属。这会保留目录缺失或符号链接失效时的记账关系,但不会接纳新会话。失败的写入会拒绝(`insertSessionBefore` 的账本错误以 `WorkspaceMoveInvalidError` 拒绝,存储失败以普通错误拒绝);每次被接受的变更都盖上 `updatedAt` 时间戳,并持久修剪不再通过成员资格检查的候选项。
|
||||
|
||||
## 注册表:`ctx.workspaceRegistry`
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ Packages here are named with the directory prefix: `@deepseek-ai/dsh-client-<nam
|
||||
|
||||
The [Slots reference](../../docs/subsystems/slots.md) owns the current design; these are the rules you must not violate when writing or reviewing client code:
|
||||
|
||||
1. **Two declaration forms**: use `ctx.slots.register({ name, children?, store?, inject? }, Component)` for a parent-owned extension position. Use `ctx.slots.registerFactory()` only when one reusable assembly needs independent render occurrences under unrelated parents. The shell alone renders `'root'`.
|
||||
1. **Two declaration forms**: use `ctx.slots.register({ name, children?, store?, inject? }, Component)` for a parent-owned extension position. Designers may use `ctx.slots.registerFactory()` for a component or assembly they consider reusable, without requiring multiple existing callers or unrelated parents ([applicability](ui-slots/README.md#reusable-component-factories)). The shell alone renders `'root'`.
|
||||
2. **children = declaration + authorization**: the slots your component renders are exactly the keys of its registration's `children` object (spec values: `kind`/`scope`). Factory children obey the same `SlotMap` checks and global ownership rule. Rendering an undeclared slot, or declaring one someone else declared, fails at load. Slot names mirror the composition path: `<domain>.<entry>.<hole>` (for example, `'tool.call.toolview'`).
|
||||
3. **Component props are the five shares, all derived**: `PropsRuntime<K>` (owner data plus scope/global seats), `PropsRenderSlots<S>` (children), `PropsRenderFactories` (`renderFactorySlot`), `PropsStore<H>` (store), and the inject face. Never hand-write or locally re-type a derived member. Factory props follow the corresponding `Factory*PropsOf` aliases.
|
||||
4. **Hooks are framework-made only**: standing seats include `useSession`, `useSessions`, `useWorkspaces`, `useStore`, `renderSlot`, and `renderFactorySlot`; Factory definitions additionally receive `useFactorySlot`. The renderer also binds `use<Name>` hooks from provide contributions and inject `hooks` compartments. Business code never creates a hook or selector as a prop value — pass plain data and callbacks. (Component-internal behavioral hooks that subscribe to nothing external are fine.)
|
||||
@@ -153,7 +153,7 @@ Bringing up a new `packages/client/<name>` plugin package (ui-workspace is a com
|
||||
|
||||
1. **Check the [ui-primitives catalog](ui-primitives/README.md#component-catalog) before writing a control.** A plugin cannot import another plugin's component, so `ui-primitives` is the only place a control can be shared; the catalog states when to reuse, when to promote, and when your own package is the right home.
|
||||
|
||||
2. Compose through `register`: add the slot to `SlotMap`, declare it in its parent entry's `children`, and register your component. Use a Component Factory only for a reusable assembly rendered independently under unrelated parents; see the [Slots reference](../../docs/subsystems/slots.md).
|
||||
2. Compose through `register`: add the slot to `SlotMap`, declare it in its parent entry's `children`, and register your component. A component or assembly designed for reuse may instead use a Component Factory; one-off components need not become Factories. See the [Slots reference](../../docs/subsystems/slots.md).
|
||||
3. Type ordinary props from the five shares (`PropsRuntime` & `PropsRenderSlots` & `PropsRenderFactories` & `PropsStore` & inject face), and use the derived `Factory*PropsOf` aliases for Factory Components. Shared or remount-surviving state goes in a declared store; component-private state stays local.
|
||||
4. Component tests feed props directly (`createXXXStore().create()` for the store data; plain stubs for framework hooks) and assert behavior without render machinery.
|
||||
5. Tokens only in CSS; product copy follows the localization rule above; English comments.
|
||||
|
||||
@@ -30,8 +30,8 @@
|
||||
en: b4cd36e7ab91281e
|
||||
zh: 8ccf412b9dde61d5
|
||||
/deepseek-ai-dsh-client-ui-chat/turn-process-folding:
|
||||
en: 0c63ffa8f245050e
|
||||
zh: f421d1a569b16c3d
|
||||
en: 4cd7c81d70d2f365
|
||||
zh: 18eca6d16e44b6c2
|
||||
/deepseek-ai-dsh-client-ui-chat/grouped-rendering:
|
||||
en: 8b2586e6b9f188a7
|
||||
zh: 6687f9e67432d04f
|
||||
|
||||
@@ -86,7 +86,7 @@ When Chat ends with an open Turn control and that Turn has no visible input, the
|
||||
|
||||
Work-details modes control process-group display and reasoning previews. Compact, Standard, and Detailed fold eligible completed Turns without hiding the final answer; Verbose retains the duration/status header without a collapse action and shows historical process rows directly. The [business-rule reference](src/client/conversation-nodes/README.md#display-modes) contains the mode table, title behavior, whole-Turn eligibility, clocks, and disclosure resets.
|
||||
|
||||
The Settings row below Work details offers an [independent collapse-timing preference](src/client/conversation-nodes/README.md#collapse-timing).
|
||||
The Settings row below Work details offers an [independent collapse-timing preference](src/client/conversation-nodes/README.md#collapse-timing), saved through the same Host profile configuration.
|
||||
|
||||
-----
|
||||
|
||||
|
||||
@@ -86,7 +86,7 @@ Chat 末尾为进行中的 Turn 控制行,且该轮尚无可见输入时,第
|
||||
|
||||
工作步骤展示模式控制过程组显示与推理预览。简洁、标准、详细模式收起符合条件的已完成轮次,不隐藏最终答案;完全展开模式保留时长或状态抬头,但不支持收起,历史过程行直接显示。[业务规则明细](src/client/conversation-nodes/README.zh.md#display-modes) 统一说明模式表、组头行为、整轮折叠资格、时钟与开合重置。
|
||||
|
||||
工作步骤展示下方的设置行提供[独立的收起时机设置](src/client/conversation-nodes/README.zh.md#collapse-timing)。
|
||||
工作步骤展示下方的设置行提供[独立的收起时机设置](src/client/conversation-nodes/README.zh.md#collapse-timing),通过相同的 Host profile 配置保存。
|
||||
|
||||
-----
|
||||
|
||||
|
||||
@@ -8,6 +8,18 @@ export const CHAT_SETTINGS_NAMESPACE = 'ui-chat'
|
||||
/** Field carrying the work-details presentation mode. */
|
||||
export const TRANSCRIPT_VIEW_FIELD = 'transcriptView'
|
||||
|
||||
/** Field carrying the independent work-details collapse timing. */
|
||||
export const COLLAPSE_TIMING_FIELD = 'collapseTiming'
|
||||
|
||||
/** Available points when a completed Turn returns to its historical presentation. */
|
||||
export const COLLAPSE_TIMINGS = ['completion', 'next-input'] as const
|
||||
|
||||
/** When a completed Turn returns to its historical presentation. */
|
||||
export type CollapseTiming = typeof COLLAPSE_TIMINGS[number]
|
||||
|
||||
/** Preserve completion-time folding when no timing preference is saved. */
|
||||
export const DEFAULT_COLLAPSE_TIMING: CollapseTiming = 'completion'
|
||||
|
||||
/** Work-details presentation modes a user can choose. */
|
||||
export const TRANSCRIPT_VIEW_MODES = ['compact', 'standard', 'detailed', 'verbose'] as const
|
||||
|
||||
@@ -50,6 +62,8 @@ export const DEFAULT_LINK_OPENING: LinkOpening = 'sidebar'
|
||||
export interface ChatSettings {
|
||||
/** Work-details preference; absence uses the client default, and legacy saved values remain accepted. */
|
||||
transcriptView?: TranscriptViewMode | typeof LEGACY_TRANSCRIPT_VIEW_MODE | typeof LEGACY_EXPANDED_TRANSCRIPT_VIEW_MODE | null
|
||||
/** Independent collapse timing; absence preserves completion-time folding. */
|
||||
collapseTiming?: CollapseTiming
|
||||
/** Detail level for composer statistics and completed-Turn usage. */
|
||||
performanceUsage: PerformanceUsageMode
|
||||
/** Default destination for Chat HTTP(S) links. */
|
||||
@@ -58,6 +72,7 @@ export interface ChatSettings {
|
||||
|
||||
/** Durable Chat schema; also the wire envelope the browser scope validates against. */
|
||||
export const ChatSettingsFields = {
|
||||
[COLLAPSE_TIMING_FIELD]: z.union([...COLLAPSE_TIMINGS]).default(DEFAULT_COLLAPSE_TIMING),
|
||||
linkOpening: z.union(['sidebar', 'new-tab']).default(DEFAULT_LINK_OPENING),
|
||||
performanceUsage: z.union([...PERFORMANCE_USAGE_MODES]).default(DEFAULT_PERFORMANCE_USAGE),
|
||||
// Missing and unrecognized modes defer to the client's default.
|
||||
|
||||
@@ -33,8 +33,8 @@
|
||||
en: b25bf00ce3a6a119
|
||||
zh: 0ab47a4014ea5e1e
|
||||
/chat-conversation-node-rules/display-modes/collapse-timing:
|
||||
en: c31be5bb8cb77dc7
|
||||
zh: 9550ab598119076f
|
||||
en: a7cd26255c76f714
|
||||
zh: c8dc2475c3ce3739
|
||||
/chat-conversation-node-rules/display-modes/group-title-rules:
|
||||
en: 5b40d65e660549b7
|
||||
zh: 09b6894aa00154e7
|
||||
|
||||
@@ -136,7 +136,7 @@ Reading a default does not automatically save configuration. When the user chang
|
||||
<a id="collapse-timing"></a>
|
||||
### Collapse timing
|
||||
|
||||
Settings → General → Collapse work details appears directly below Work details and is independent of the display mode. On completion is the default and retains immediate folding and tail positioning. On next message enables delayed folding and its coordinated transitions. The choice lasts for the current Client instance: closing Settings preserves it; reloading or reopening the app resets it to On completion. It never writes Host settings, browser storage, or Session data.
|
||||
Settings → General → Collapse work details appears directly below Work details and is independent of the display mode. On completion is the default and retains immediate folding and tail positioning. On next message enables delayed folding and its coordinated transitions. The choice is saved as `ui-chat.collapseTiming` through the same Host profile settings as Work details and is restored after reload or reopening the app. Profiles without a saved value use On completion without writing that default. It does not write browser storage or Session data.
|
||||
|
||||
With On next message, the latest Turn keeps its running presentation after completion: Compact and Standard retain their process headers, and Detailed retains its flat process rows. A pending ordinary transcript submission or a newer Turn ends this exemption without clearing the reader's manual whole-Turn choice. Inner disclosures reset only when their outer process actually hides. Queued input and steering alone do not end it. The latest Turn of a reopened Session also receives the exemption; manual whole-Turn choices still take precedence. Switching back to On completion ends the exemption immediately.
|
||||
|
||||
|
||||
@@ -136,7 +136,7 @@ description: "Chat 过程分组与活动摘要的明细业务规则。"
|
||||
<a id="collapse-timing"></a>
|
||||
### 收起时机
|
||||
|
||||
设置 → 通用设置 → 过程收起时机位于工作步骤展示正下方,与展示模式独立。「完成时收起」是默认值,保留立即折叠和即时跟尾定位;「下次发送时收起」启用延后折叠及其协调过渡。选择仅在当前 Client 实例内有效:关闭设置面板后保留,刷新或重新打开应用时恢复为「完成时收起」。此偏好不写入 Host 设置、浏览器存储或 Session 数据。
|
||||
设置 → 通用设置 → 过程收起时机位于工作步骤展示正下方,与展示模式独立。「完成时收起」是默认值,保留立即折叠和即时跟尾定位;「下次发送时收起」启用延后折叠及其协调过渡。选择以 `ui-chat.collapseTiming` 保存到与工作步骤展示相同的 Host profile 设置,刷新或重新打开应用后会恢复。未保存此值的 profile 使用「完成时收起」,不会自动写入默认值。此偏好不写入浏览器存储或 Session 数据。
|
||||
|
||||
选择「下次发送时收起」后,最新轮次完成时保留运行中的呈现:简洁和标准保留过程组头,详细保留平铺过程行。普通 transcript 输入进入待发送状态,或出现更新轮次时,取消这项例外,但保留用户对整轮的手动开合选择。只有外层过程实际隐藏时,才重置内部开合。排队输入和单独的 steering 不会取消例外。重新打开 Session 时,其最新轮次也享有例外;整轮的手动开合选择仍优先。切回「完成时收起」会立即取消例外。
|
||||
|
||||
|
||||
@@ -1,19 +1,14 @@
|
||||
/** Chat presentation derived from Host-backed detail and in-memory collapse timing. */
|
||||
/** Chat presentation derived from Host-backed detail and collapse timing. */
|
||||
|
||||
import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store'
|
||||
import type { TranscriptViewMode } from '../chat-settings.ts'
|
||||
|
||||
/** Available points when a completed Turn returns to its historical presentation. */
|
||||
export const COLLAPSE_TIMINGS = ['completion', 'next-input'] as const
|
||||
|
||||
/** When a completed Turn returns to its historical presentation. */
|
||||
export type CollapseTiming = typeof COLLAPSE_TIMINGS[number]
|
||||
import type { CollapseTiming, TranscriptViewMode } from '../chat-settings.ts'
|
||||
export { COLLAPSE_TIMINGS, type CollapseTiming } from '../chat-settings.ts'
|
||||
|
||||
/** Presentation capabilities that one work-details mode enables. */
|
||||
export interface ChatPresentationPolicy {
|
||||
/** Preference identity for layout resets and diagnostics; renderers select the capabilities below. */
|
||||
readonly mode: TranscriptViewMode
|
||||
/** Browser-local experiment; completion retains the default immediate folding and scrolling. */
|
||||
/** Saved collapse timing; completion retains the default immediate folding and scrolling. */
|
||||
readonly collapseTiming: CollapseTiming
|
||||
/** Whether a normally completed Turn folds its process rows behind the whole-Turn control. */
|
||||
readonly foldCompletedTurns: boolean
|
||||
@@ -73,7 +68,7 @@ const TIMING_POLICIES = {
|
||||
/**
|
||||
* Resolve a stable policy for one detail mode and collapse timing.
|
||||
* @param mode - persisted work-details mode.
|
||||
* @param collapseTiming - in-memory timing; defaults to immediate completion folding.
|
||||
* @param collapseTiming - persisted timing; defaults to immediate completion folding.
|
||||
* @returns the same policy object for the same pair of choices.
|
||||
*/
|
||||
export function presentationPolicyFor(
|
||||
@@ -84,9 +79,9 @@ export function presentationPolicyFor(
|
||||
}
|
||||
|
||||
/**
|
||||
* Combine Host-backed detail and in-memory timing without owning subscriptions.
|
||||
* Combine Host-backed detail and persisted timing without owning subscriptions.
|
||||
* @param mode - live work-details mode.
|
||||
* @param collapseTiming - live, in-memory collapse timing.
|
||||
* @param collapseTiming - live Host-backed collapse timing.
|
||||
* @returns observable policy whose subscriptions follow both preferences.
|
||||
*/
|
||||
export function derivePresentationPolicy(
|
||||
|
||||
@@ -12,12 +12,12 @@ export interface TranscriptViewRowInjected {
|
||||
hooks: {
|
||||
/** Persisted work-details preference bound as useTranscriptView. */
|
||||
transcriptView: SnapshotStore<TranscriptViewMode>
|
||||
/** Browser-local timing bound as useCollapseTiming. */
|
||||
/** Persisted collapse timing bound as useCollapseTiming. */
|
||||
collapseTiming: SnapshotStore<CollapseTiming>
|
||||
}
|
||||
/** Change the work-details presentation. */
|
||||
setTranscriptView: (mode: TranscriptViewMode) => void
|
||||
/** Retain collapse timing for this Client lifetime without changing Host settings. */
|
||||
/** Persist collapse timing independently of the work-details mode. */
|
||||
setCollapseTiming: (timing: CollapseTiming) => void
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ const COLLAPSE_LABELS = {
|
||||
} as const satisfies Record<CollapseTiming, ChatKey>
|
||||
|
||||
/**
|
||||
* Render work-details and browser-local collapse-timing selectors.
|
||||
* Render the independent, Host-backed work-details and collapse-timing selectors.
|
||||
* @param props - composed Settings slot props.
|
||||
* @returns the preference row.
|
||||
*/
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
/** Host-backed work details and independent, in-memory collapse timing. */
|
||||
/** Independent work-details preferences backed by the same Host configuration form. */
|
||||
|
||||
import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store'
|
||||
import type { ConfigForm } from '@deepseek-ai/dsh-client-ui-settings/client'
|
||||
import type { CollapseTiming } from './presentation-policy.ts'
|
||||
import {
|
||||
COLLAPSE_TIMING_FIELD, DEFAULT_COLLAPSE_TIMING,
|
||||
DEFAULT_TRANSCRIPT_VIEW_MODE, LEGACY_TRANSCRIPT_VIEW_MODE, LEGACY_EXPANDED_TRANSCRIPT_VIEW_MODE, TRANSCRIPT_VIEW_FIELD,
|
||||
type ChatSettings, type TranscriptViewMode,
|
||||
} from '../chat-settings.ts'
|
||||
@@ -13,8 +14,8 @@ export class TranscriptViewPolicy {
|
||||
private readonly unsubscribe: () => void
|
||||
/** Reactive current mode, including the client default before Host settings arrive. */
|
||||
readonly mode: SnapshotStore<TranscriptViewMode>
|
||||
/** Independent Client-lifetime choice; each new instance starts with completion-time folding. */
|
||||
readonly collapseTiming: SnapshotStore<CollapseTiming> = createSnapshotStore<CollapseTiming>('completion')
|
||||
/** Reactive collapse timing, defaulting to completion until Host settings arrive. */
|
||||
readonly collapseTiming: SnapshotStore<CollapseTiming> = createSnapshotStore<CollapseTiming>(DEFAULT_COLLAPSE_TIMING)
|
||||
|
||||
/**
|
||||
* @param host - durable Chat settings scope.
|
||||
@@ -43,11 +44,13 @@ export class TranscriptViewPolicy {
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep collapse timing in memory without writing Host or browser storage.
|
||||
* Publish and persist collapse timing without changing the work-details mode.
|
||||
* @param timing - immediate completion folding or deferred folding at the next input.
|
||||
*/
|
||||
setCollapseTiming(timing: CollapseTiming): void {
|
||||
if (this.collapseTiming.getSnapshot() === timing) return
|
||||
this.collapseTiming.set(timing)
|
||||
void this.host.set(COLLAPSE_TIMING_FIELD, timing)
|
||||
}
|
||||
|
||||
/** Adopt the latest accepted Host section without writing it back. */
|
||||
@@ -58,5 +61,7 @@ export class TranscriptViewPolicy {
|
||||
const mode = saved === LEGACY_TRANSCRIPT_VIEW_MODE || saved === LEGACY_EXPANDED_TRANSCRIPT_VIEW_MODE
|
||||
? 'detailed' : saved ?? this.defaultMode
|
||||
if (this.mode.getSnapshot() !== mode) this.mode.set(mode)
|
||||
const timing = section.collapseTiming ?? DEFAULT_COLLAPSE_TIMING
|
||||
if (this.collapseTiming.getSnapshot() !== timing) this.collapseTiming.set(timing)
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
import type {} from '@deepseek-ai/dsh-settings'
|
||||
|
||||
import type { Volatile, Context } from '@deepseek-ai/cordis'
|
||||
import type { ChatSettings, LinkOpening, PerformanceUsageMode } from './chat-settings.ts'
|
||||
import type { ChatSettings, CollapseTiming, LinkOpening, PerformanceUsageMode } from './chat-settings.ts'
|
||||
import z from '@deepseek-ai/schemastery'
|
||||
import { TRANSCRIPT_VIEW_FIELD } from './chat-settings.ts'
|
||||
|
||||
@@ -18,6 +18,8 @@ export {
|
||||
export interface Config {
|
||||
/** Completed turn transcript presentation. */
|
||||
transcriptView: Volatile<ChatSettings['transcriptView']>
|
||||
/** When completed work details return to their historical presentation. */
|
||||
collapseTiming: Volatile<CollapseTiming>
|
||||
/** Performance and usage detail level. */
|
||||
performanceUsage: Volatile<PerformanceUsageMode>
|
||||
/** Default destination for Chat HTTP(S) links. */
|
||||
@@ -27,6 +29,7 @@ export interface Config {
|
||||
/** Live preferences projected to the browser. */
|
||||
export const Config = z.object({
|
||||
[TRANSCRIPT_VIEW_FIELD]: ChatSettingsFields[TRANSCRIPT_VIEW_FIELD].volatile(),
|
||||
collapseTiming: ChatSettingsFields.collapseTiming.volatile(),
|
||||
performanceUsage: ChatSettingsFields['performanceUsage'].volatile(),
|
||||
linkOpening: ChatSettingsFields.linkOpening.volatile(),
|
||||
})
|
||||
|
||||
@@ -137,7 +137,7 @@ async function bench(initialSettings?: ChatSettings, withBrowserRegistry = true,
|
||||
}
|
||||
|
||||
describe('Chat inject API', () => {
|
||||
it('projects independent Settings choices without saving timing to Host settings', async () => {
|
||||
it('projects independent Settings choices and saves timing to Host settings', async () => {
|
||||
const b = await bench()
|
||||
try {
|
||||
const row = b.runtime.slots.entries('settings.general.item')
|
||||
@@ -149,12 +149,12 @@ describe('Chat inject API', () => {
|
||||
expect(presentation.getSnapshot()).toMatchObject({ mode: 'detailed', collapseTiming: 'completion' })
|
||||
setCollapseTiming('next-input')
|
||||
expect(presentation.getSnapshot()).toMatchObject({ mode: 'detailed', collapseTiming: 'next-input' })
|
||||
expect(b.chatSettings.set).not.toHaveBeenCalled()
|
||||
b.chatSettings.publish({ status: 'ready', value: { linkOpening: 'sidebar', transcriptView: 'standard', performanceUsage: 'detailed' }, revision: 1, writable: true })
|
||||
expect(b.chatSettings.set).toHaveBeenCalledWith('collapseTiming', 'next-input')
|
||||
b.chatSettings.publish({ status: 'ready', value: { linkOpening: 'sidebar', transcriptView: 'standard', performanceUsage: 'detailed', collapseTiming: 'next-input' }, revision: 1, writable: true })
|
||||
expect(presentation.getSnapshot()).toMatchObject({ mode: 'standard', collapseTiming: 'next-input' })
|
||||
setCollapseTiming('completion')
|
||||
expect(presentation.getSnapshot()).toMatchObject({ mode: 'standard', collapseTiming: 'completion' })
|
||||
expect(b.chatSettings.set).not.toHaveBeenCalled()
|
||||
expect(b.chatSettings.set).toHaveBeenLastCalledWith('collapseTiming', 'completion')
|
||||
expect(b.session.prompt).not.toHaveBeenCalled()
|
||||
expect(b.session.cancel).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
|
||||
@@ -200,7 +200,7 @@ describe('Chat apply wiring', () => {
|
||||
expect(face.hooks.transcriptView.getSnapshot()).toBe('compact')
|
||||
})
|
||||
|
||||
it('resets in-memory collapse timing when the Chat plugin remounts', async () => {
|
||||
it('restores saved collapse timing when the Chat plugin remounts', async () => {
|
||||
const b = await bench()
|
||||
try {
|
||||
const row = b.runtime.slots.entries('settings.general.item')
|
||||
@@ -211,8 +211,8 @@ describe('Chat apply wiring', () => {
|
||||
expect(hooks.collapseTiming.getSnapshot()).toBe('completion')
|
||||
setCollapseTiming('next-input')
|
||||
expect(hooks.collapseTiming.getSnapshot()).toBe('next-input')
|
||||
expect(b.chatSettings.set).not.toHaveBeenCalled()
|
||||
b.chatSettings.publish({ status: 'ready', value: { linkOpening: 'sidebar', transcriptView: 'standard', performanceUsage: 'detailed' }, revision: 1, writable: true })
|
||||
expect(b.chatSettings.set).toHaveBeenCalledExactlyOnceWith('collapseTiming', 'next-input')
|
||||
b.chatSettings.publish({ status: 'ready', value: { linkOpening: 'sidebar', transcriptView: 'standard', performanceUsage: 'detailed', collapseTiming: 'next-input' }, revision: 1, writable: true })
|
||||
expect(hooks.transcriptView.getSnapshot()).toBe('standard')
|
||||
expect(hooks.collapseTiming.getSnapshot()).toBe('next-input')
|
||||
expect(b.runtime.slots.entries('settings.general.item').map(entry => entry.options.id))
|
||||
@@ -226,9 +226,9 @@ describe('Chat apply wiring', () => {
|
||||
const remounted = remountedRow.inject!()
|
||||
const remountedHooks = remounted.hooks as TranscriptViewRowInjected['hooks']
|
||||
expect(remountedHooks.collapseTiming).not.toBe(hooks.collapseTiming)
|
||||
expect(remountedHooks.collapseTiming.getSnapshot()).toBe('completion')
|
||||
expect(remountedHooks.collapseTiming.getSnapshot()).toBe('next-input')
|
||||
expect(remountedHooks.transcriptView.getSnapshot()).toBe('standard')
|
||||
expect(b.chatSettings.set).not.toHaveBeenCalled()
|
||||
expect(b.chatSettings.set).toHaveBeenCalledExactlyOnceWith('collapseTiming', 'next-input')
|
||||
expect(b.runtime.slots.entries('settings.general.item').map(entry => entry.options.id))
|
||||
.toEqual(['transcript-view', 'link-opening', 'composer-enter', 'performance-usage'])
|
||||
} finally {
|
||||
|
||||
@@ -14,9 +14,9 @@ describe('ui-chat Host settings', () => {
|
||||
const configuration = await liveConfig(ctx, { Config, apply })
|
||||
const { fiber } = configuration
|
||||
|
||||
expect(plainConfig(configuration.fiber.config)).toEqual({ performanceUsage: 'detailed', linkOpening: 'sidebar' })
|
||||
expect(plainConfig(configuration.fiber.config)).toEqual({ performanceUsage: 'detailed', linkOpening: 'sidebar', collapseTiming: 'completion' })
|
||||
await configuration.update({ transcriptView: 'normal' })
|
||||
expect(plainConfig(configuration.fiber.config)).toEqual({ transcriptView: 'normal', performanceUsage: 'detailed', linkOpening: 'sidebar' })
|
||||
expect(plainConfig(configuration.fiber.config)).toEqual({ transcriptView: 'normal', performanceUsage: 'detailed', linkOpening: 'sidebar', collapseTiming: 'completion' })
|
||||
for (const mode of ['expanded', 'compact', 'standard', 'detailed', 'verbose']) {
|
||||
await configuration.update({ transcriptView: mode })
|
||||
expect(plainConfig(configuration.fiber.config)).toMatchObject({ transcriptView: mode })
|
||||
@@ -35,6 +35,21 @@ describe('ui-chat Host settings', () => {
|
||||
await fiber.dispose()
|
||||
})
|
||||
|
||||
it('validates collapse timing and restores its saved config independently of work details', async () => {
|
||||
const ctx = new Context()
|
||||
const configuration = await liveConfig(ctx, { Config, apply })
|
||||
expect(plainConfig(configuration.fiber.config)).toMatchObject({ collapseTiming: 'completion' })
|
||||
await configuration.update({ transcriptView: 'compact', collapseTiming: 'next-input' })
|
||||
const saved = plainConfig(configuration.fiber.config)
|
||||
if (typeof saved !== 'object' || saved === null) throw new Error('expected saved configuration object')
|
||||
expect(saved).toMatchObject({ transcriptView: 'compact', collapseTiming: 'next-input' })
|
||||
await expect(configuration.update({ collapseTiming: 'never' })).rejects.toThrow()
|
||||
await configuration.fiber.dispose()
|
||||
const restored = await liveConfig(ctx, { Config, apply }, saved)
|
||||
expect(plainConfig(restored.fiber.config)).toMatchObject({ transcriptView: 'compact', collapseTiming: 'next-input' })
|
||||
await restored.fiber.dispose()
|
||||
})
|
||||
|
||||
it('loads without a settings provider', async () => {
|
||||
const ctx = new Context()
|
||||
await expect(ctx.plugin({ Config, apply }).await()).resolves.toBeDefined()
|
||||
|
||||
@@ -7,7 +7,7 @@ import { TranscriptViewPolicy } from '../src/client/transcript-view.ts'
|
||||
afterEach(() => { vi.restoreAllMocks() })
|
||||
|
||||
describe('TranscriptViewPolicy', () => {
|
||||
it('defaults to completion and changes timing without reading or writing browser storage', () => {
|
||||
it('defaults to completion and persists explicit timing without reading or writing browser storage', () => {
|
||||
const storageReads = vi.spyOn(Storage.prototype, 'getItem').mockReturnValue('"next-input"')
|
||||
const storageWrites = vi.spyOn(Storage.prototype, 'setItem')
|
||||
const storageRemovals = vi.spyOn(Storage.prototype, 'removeItem')
|
||||
@@ -32,7 +32,9 @@ describe('TranscriptViewPolicy', () => {
|
||||
expect(timingChanged).toHaveBeenCalledTimes(2)
|
||||
expect(policy.mode.getSnapshot()).toBe('detailed')
|
||||
expect(modeChanged).not.toHaveBeenCalled()
|
||||
expect(host.set).not.toHaveBeenCalled()
|
||||
expect(host.set).toHaveBeenCalledTimes(2)
|
||||
expect(host.set).toHaveBeenNthCalledWith(1, 'collapseTiming', 'next-input')
|
||||
expect(host.set).toHaveBeenNthCalledWith(2, 'collapseTiming', 'completion')
|
||||
expect(storageReads).not.toHaveBeenCalled()
|
||||
expect(storageWrites).not.toHaveBeenCalled()
|
||||
expect(storageRemovals).not.toHaveBeenCalled()
|
||||
@@ -44,18 +46,19 @@ describe('TranscriptViewPolicy', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('starts each instance with completion timing while adopting the accepted Host mode', () => {
|
||||
it('restores both saved preferences in each new instance', () => {
|
||||
const host = stubConfigForm<ChatSettings>()
|
||||
host.publish({ status: 'ready', value: { linkOpening: 'sidebar', transcriptView: 'standard', performanceUsage: 'detailed' }, revision: 1, writable: true })
|
||||
const first = new TranscriptViewPolicy(host.scope)
|
||||
try {
|
||||
first.setCollapseTiming('next-input')
|
||||
host.publish({ value: { linkOpening: 'sidebar', transcriptView: 'standard', performanceUsage: 'detailed', collapseTiming: 'next-input' }, revision: 2 })
|
||||
const second = new TranscriptViewPolicy(host.scope)
|
||||
try {
|
||||
expect(first.collapseTiming.getSnapshot()).toBe('next-input')
|
||||
expect(second.collapseTiming.getSnapshot()).toBe('completion')
|
||||
expect(second.collapseTiming.getSnapshot()).toBe('next-input')
|
||||
expect(second.mode.getSnapshot()).toBe('standard')
|
||||
expect(host.set).not.toHaveBeenCalled()
|
||||
expect(host.set).toHaveBeenCalledExactlyOnceWith('collapseTiming', 'next-input')
|
||||
} finally {
|
||||
second.dispose()
|
||||
}
|
||||
@@ -65,21 +68,21 @@ describe('TranscriptViewPolicy', () => {
|
||||
expect(host.listenerCount()).toBe(0)
|
||||
})
|
||||
|
||||
it('adopts Host mode updates without overriding the local timing choice', () => {
|
||||
it('adopts independent Host mode and timing updates without writing them back', () => {
|
||||
const host = stubConfigForm<ChatSettings>()
|
||||
const policy = new TranscriptViewPolicy(host.scope)
|
||||
try {
|
||||
policy.setCollapseTiming('next-input')
|
||||
host.publish({ status: 'ready', value: { linkOpening: 'sidebar', transcriptView: 'compact', performanceUsage: 'detailed' }, revision: 1, writable: true })
|
||||
host.publish({ status: 'ready', value: { linkOpening: 'sidebar', transcriptView: 'compact', performanceUsage: 'detailed', collapseTiming: 'next-input' }, revision: 1, writable: true })
|
||||
expect(policy.mode.getSnapshot()).toBe('compact')
|
||||
expect(policy.collapseTiming.getSnapshot()).toBe('next-input')
|
||||
policy.setMode('verbose')
|
||||
expect(policy.collapseTiming.getSnapshot()).toBe('next-input')
|
||||
expect(host.set).toHaveBeenCalledExactlyOnceWith('transcriptView', 'verbose')
|
||||
expect(host.set).toHaveBeenNthCalledWith(2, 'transcriptView', 'verbose')
|
||||
host.publish({ value: { linkOpening: 'sidebar', transcriptView: 'standard', performanceUsage: 'detailed' }, revision: 2 })
|
||||
expect(policy.mode.getSnapshot()).toBe('standard')
|
||||
expect(policy.collapseTiming.getSnapshot()).toBe('next-input')
|
||||
expect(host.set).toHaveBeenCalledTimes(1)
|
||||
expect(policy.collapseTiming.getSnapshot()).toBe('completion')
|
||||
expect(host.set).toHaveBeenCalledTimes(2)
|
||||
} finally {
|
||||
policy.dispose()
|
||||
}
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
en: 05691d44a0c6c48f
|
||||
zh: 434033d5761297f3
|
||||
/deepseek-ai-dsh-client-ui-slots/use-this-package/reusable-component-factories:
|
||||
en: 301de67bf2779ae6
|
||||
zh: 6e9d405ee1063d53
|
||||
en: 71cbe7aa26f3ff80
|
||||
zh: 0e35265d4d95cc36
|
||||
/deepseek-ai-dsh-client-ui-slots/use-this-package/the-five-framework-props-shares:
|
||||
en: 45e2933a5e084956
|
||||
zh: 938deedaf489f892
|
||||
|
||||
@@ -29,7 +29,7 @@ Compose UI through this package whenever you write a client plugin: register a c
|
||||
|
||||
### Reusable Component Factories
|
||||
|
||||
Use a Component Factory when one package defines an assembly that unrelated parents render independently. Declare its complete type in `SlotFactoryMap`, install the definition with `ctx.slots.registerFactory()`, render occurrences through the injected `renderFactorySlot()`, and select each declared local Component through the call's `slots` option. The definition reads that choice through `useFactorySlot(name, fallback)`.
|
||||
A designer may choose a Component Factory for a component or assembly they consider reusable, even with one current caller; unrelated parents, separate packages, and additional injection or local slots are not prerequisites. A one-off component need not use a Factory. Declare its complete type in `SlotFactoryMap`, install the definition with `ctx.slots.registerFactory()`, render occurrences through the injected `renderFactorySlot()`, and select each declared local Component through the call's `slots` option. The definition reads that choice through `useFactorySlot(name, fallback)`.
|
||||
|
||||
Factory `children` remain ordinary global Slots and must match `SlotMap`, while local `slots` select one Component per occurrence. An occurrence inherits its render-position scope; `renderFactorySlot()` does not accept a Session identity. Shared Store handles use ordinary scope resolution. A Store factory stays lazy until an occurrence first materializes, then creates one handle for that render position and rejects a persistent Store spec whose key would collide across occurrences.
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ kind: "package-library"
|
||||
|
||||
### 可复用 Component Factory
|
||||
|
||||
当一个包定义装配、而互不相关的 parents 需要独立渲染它时,使用 Component Factory。在 `SlotFactoryMap` 中声明完整类型,通过 `ctx.slots.registerFactory()` 安装 definition,通过注入的 `renderFactorySlot()` 渲染 occurrences,并通过调用的 `slots` 选项选择每个已声明的局部 Component。definition 通过 `useFactorySlot(name, fallback)` 读取该选择。
|
||||
设计者认为组件或装配可复用时,即使当前只有一个调用方,也可以选择 Component Factory;互不相关的父级、不同的包、额外注入或局部 slot 都不是前提。一次性组件不必使用 Factory。在 `SlotFactoryMap` 中声明完整类型,通过 `ctx.slots.registerFactory()` 安装 definition,通过注入的 `renderFactorySlot()` 渲染 occurrences,并通过调用的 `slots` 选项选择每个已声明的局部 Component。definition 通过 `useFactorySlot(name, fallback)` 读取该选择。
|
||||
|
||||
Factory `children` 仍是普通全局 Slots 且必须与 `SlotMap` 匹配,而局部 `slots` 为每个 occurrence 选择一个 Component。occurrence 继承其渲染位置的 scope;`renderFactorySlot()` 不接受 Session identity。共享 Store handle 使用普通 scope 解析。Store factory 保持 lazy,直到 occurrence 首次物化时才为该渲染位置创建一个 handle;若持久化 Store spec 会让 persistence key 在 occurrences 之间冲突,renderer 会拒绝它。
|
||||
|
||||
|
||||
@@ -27,8 +27,8 @@
|
||||
en: 9eab3bfbaf98c987
|
||||
zh: 54e7e141dae5c9e8
|
||||
/deepseek-ai-dsh-client-ui-workspace/use-this-package/managing-sessions:
|
||||
en: cafc87e8e0ac4058
|
||||
zh: 4c35bc5bfa24ba6c
|
||||
en: e96b714aeb6dcd03
|
||||
zh: 75b63aa2cafbb57a
|
||||
/deepseek-ai-dsh-client-ui-workspace/use-this-package/pending-interactions:
|
||||
en: 9fb88260380bf093
|
||||
zh: 3bace2b96ecd4a82
|
||||
@@ -42,8 +42,8 @@
|
||||
en: 868904dbfb5713f8
|
||||
zh: 225906bfef7398bf
|
||||
/deepseek-ai-dsh-client-ui-workspace/understand-the-implementation/session-row-actions:
|
||||
en: a3b80d0e844d2929
|
||||
zh: 85fe5dfb2968b491
|
||||
en: 24d196702ca9a5a0
|
||||
zh: 351b4896a0217ac1
|
||||
/deepseek-ai-dsh-client-ui-workspace/understand-the-implementation/session-row-actions/packaged-client-plugin:
|
||||
en: 36934671b80b11ae
|
||||
zh: 8e0aea6162e35e77
|
||||
|
||||
@@ -51,13 +51,15 @@ Collapsed search is one header action beside the view and add actions: activatin
|
||||
|
||||
### Managing sessions
|
||||
|
||||
The Session row's Rename action opens a dialog prefilled with the row's display title; confirming an unchanged title is deliberately allowed — it pins the current automatic title against regeneration. Double-clicking a title also opens Rename; for an unarchived Session, the preceding clicks open its conversation. Rename uses a temporary `workspaceOperation` reference and awaits its initial history opening. The row's Fork action reads ordinary cold history normally. When the Host reports that source migration is required, an app-wide Toast offers to open that Session; the action only navigates and does not retry fork. A successful fork uses the source's last completed turn and increments the inherited persisted title through Session Controller without retaining the child, opening its history, or changing selection. Workspace Delete opens a confirmation that states the retention boundary; success removes the group while its Sessions remain under Ungrouped. Pin, Rename, Fork, and Archive are themselves entries of the `sidebar.workspaces.session.menu.item` list (pin and archive also of `sidebar.workspaces.session.row.action`), so a client plugin's action takes whatever position its `order` gives it.
|
||||
The final built-in item in a Session row's "..." menu is Copy Session ID. It closes the menu and copies the complete ID directly, without opening a dialog. Clipboard success or failure appears in the global toast; a failed copy can be retried from the menu. Copying does not retain the Session, load its history, or call the Host.
|
||||
|
||||
The Session row's Rename action opens a dialog prefilled with the row's display title; confirming an unchanged title is deliberately allowed — it pins the current automatic title against regeneration. Double-clicking a title also opens Rename; for an unarchived Session, the preceding clicks open its conversation. Rename uses a temporary `workspaceOperation` reference and awaits its initial history opening. The row's Fork action reads ordinary cold history normally. When the Host reports that source migration is required, an app-wide Toast offers to open that Session; the action only navigates and does not retry fork. A successful fork uses the source's last completed turn and increments the inherited persisted title through Session Controller without retaining the child, opening its history, or changing selection. Workspace Delete opens a confirmation that states the retention boundary; success removes the group while its Sessions remain under Ungrouped. Pin, Rename, Fork, Archive, and Copy Session ID are themselves entries of the `sidebar.workspaces.session.menu.item` list (pin and archive also of `sidebar.workspaces.session.row.action`), so a client plugin's action takes whatever position its `order` gives it.
|
||||
|
||||
Archive commits without a confirmation dialog for a quiet Session and retains the Session's account position. A Session with running work is the one case that asks first: the Host refuses the plain archive and names that work, and the sidebar opens a stop-and-archive dialog listing it by family — the turn in progress, running subagents, background jobs, scheduled reminders, each with its labels — with the restore path stated; confirming asks the Host to stop the work the way the stop button does and archives once the archive set is durable, while the stops settle in the background, and cancelling leaves the Session running and visible. View options control visibility through one explicit three-way choice: Hide archived (the default) hides archived Sessions, All conversations (show archived) includes them, and Archived only hides ordinary Sessions and drops Workspaces without an archived Session; in tree grouping, children of a dropped Workspace nest under the nearest shown ancestor. Visible archived rows are grayed and carry an accessible explanation that they cannot be opened until restored; Rename, Fork, and Unarchive remain available. A successful archive shows a notice with an undo action and — while archived rows are hidden — a "filter archived sessions" action that switches the filter to All conversations (show archived); a stop-and-archive shows the same notice under its own wording, and undo restores the Session without resuming the stopped work. Unarchive removes the archive mark without restoring a pin or changing the saved position. An empty list shows a centered glyph-over-text placeholder; the Archived-only view names its own emptiness (No archived sessions yet) and adds a View other sessions text action that switches the filter back to Hide archived.
|
||||
|
||||
Session update times use the tertiary label color, including on archived rows. A Session title wider than its row is clipped with an ellipsis at rest. Hovering the row scrolls the title to its far edge — the incremented title of a fork, for example — and reveals it without the ellipsis; leaving the row returns the title to its start.
|
||||
|
||||
The keyboard reference exposes New Session, Search sessions, Add workspace, Rename session, Fork session, and Archive session. Desktop defaults use the platform's primary modifier, with Mod+K for search; Windows and macOS Web use the [shortcut service’s platform defaults](../shortcuts/README.md); Linux Web leaves these commands unbound until configured. Button tooltips and Session row menus display the effective bindings. Clicking a menu item targets that row; pressing its shortcut targets the main Session. Desktop and Windows/macOS Web rename use Mod+Alt+G, leaving Mod+Shift+R to browser reload. Rename requires a nonblank main Conversation with no modal obscuring it; a retained Session behind another main panel is unavailable. Other Windows and macOS Desktop bindings also execute from terminal input and modal dialogs; other environments follow the command's region and modal restrictions. Search and rename requests belong to this package; input drafts remain in the browser. The directory picker rejects another open while selection or Workspace adoption is pending. Fork captures the retained main-view Session, for which navigation has requested history opening, and keeps automatic migration. It uses the row action's Host operation to select its last completed turn, without loading older Client history. Missing or blank Sessions are unavailable; the Host rejects a source with no completed turn. A rejected shortcut fork preserves the current selection, displays a localized notification, and can be retried; unexpected failures also retain diagnostic logging.
|
||||
The keyboard reference exposes New Session, Search sessions, Add workspace, Rename session, Fork session, and Archive session. Desktop defaults use the platform's primary modifier, with Mod+K for search; Windows and macOS Web use the [shortcut service’s platform defaults](../shortcuts/README.md); Linux Web leaves these commands unbound until configured. Button tooltips and Session row menus display the effective bindings. Clicking a menu item targets that row; pressing its shortcut targets the main Session. Desktop and Windows/macOS Web rename use Mod+Alt+G, leaving Mod+Shift+R to browser reload. Rename requires a nonblank main Conversation with no modal obscuring it; a retained Session behind another main panel is unavailable. Other Windows and macOS Desktop bindings also execute from terminal input and modal dialogs; other environments follow the command's region and modal restrictions. Search and rename requests belong to this package; input drafts remain in the browser. The directory picker rejects another open while selection or Workspace adoption is pending. Fork captures the retained main-view Session, for which navigation has requested history opening, and keeps automatic migration. It uses the row action's Host operation to select its last completed turn, without loading older Client history. Missing or blank Sessions are unavailable; the Host rejects a source with no completed turn. A rejected shortcut fork preserves the current selection, displays a localized notification, and can be retried; unexpected failures also retain diagnostic logging. Its notification shares the frame-wide Workspace notice channel: only the latest notice remains visible, and removing the browsing region does not dismiss it.
|
||||
|
||||
### Pending interactions
|
||||
|
||||
@@ -97,10 +99,12 @@ Each registration declares a **directory-flow child hole** (`single` kind: `conv
|
||||
|
||||
### Session row actions
|
||||
|
||||
The Session row's "..." menu and its hover buttons are two `list` slots declared by the WorkspaceBrowser entry: `sidebar.workspaces.session.menu.item` and `sidebar.workspaces.session.row.action`. Every menu row and every hover button is an entry, this package's own actions included: `apply` registers `pin` (menu 100, button 200), `rename` (200), `fork` (300), and `archive` (menu 400, button 100) the way a client plugin registers its actions, so a plugin action lands wherever its `order` says, and reusing a shipped id at another `priority` shadows that action.
|
||||
The Session row's "..." menu and its hover buttons are two `list` slots declared by the WorkspaceBrowser entry: `sidebar.workspaces.session.menu.item` and `sidebar.workspaces.session.row.action`. Every menu row and every hover button is an entry, this package's own actions included: `apply` registers `pin` (menu 100, button 200), `rename` (200), `fork` (300), `archive` (menu 400, button 100), and `session-id` (450) the way a client plugin registers its actions, so a plugin action lands wherever its `order` says, and reusing a shipped id at another `priority` shadows that action.
|
||||
|
||||
An entry receives only the row identity (`sessionId`, `displayTitle`) and owns everything else. It reads the Host state it cares about through its own injected hooks (the pin and archive sets, as Sets derived once per Workspace snapshot), decides its own visibility (pin renders nothing on an archived row, because the Host keeps the two sets exclusive), carries its whole behavior in its registration's `inject` face (a pin also fronts the Session in its saved orders; an archive raises the notice), and raises its own surfaces: the rename dialog, the stop-and-archive dialog, and the row-action notice are this package's `shell.overlay` entries, fed by the requests the actions inject. A menu entry renders one `role="menuitem"` button (this package's rows use `MenuItemButton` from ui-primitives, which adds the host styling and `separatorBefore` for a group start; the hairline comes and goes with the row) and dismisses the menu through the slot-level `useMenuOpenState` hook, the menu's own open state bound from the row's render occurrence; a hover button entry renders one icon button, and the strip keeps its clicks from opening the row. The browser passes no action callbacks to its rows; its remaining verbs are the search results' restore button and the title double-click, which raises the same rename request.
|
||||
|
||||
The existing notice overlay dispatches `workspace.toast` by notice kind. Keyed registrations inject localized display mappings and their own actions; only archive notices subscribe to the viewing filter. They render the package-local `workspace.toast.content` Factory, which reuses the Toast primitive once for all presentations. The existing notice state, display sequence, latest-notice replacement, and dismissal remain shared; locale or filter changes do not restart the same notice's timer.
|
||||
|
||||
#### Packaged client plugin
|
||||
|
||||
Declare `ui-workspace`, `ui-slots`, `ui-renderer`, `client-locale`, and `ui-primitives` as browser/type development dependencies according to the Client dependency policy. The type-only `ui-workspace/client` import loads this package's `SlotMap` declaration; without it, an independently compiled plugin does not know the slot keys. Keep the Component at module scope and own visible copy in the contributing package's locale namespace.
|
||||
|
||||
@@ -51,13 +51,15 @@ kind: "package-reference"
|
||||
|
||||
### 管理会话
|
||||
|
||||
Session 行内的 Rename 操作打开一个以该行显示标题预填的对话框;确认未修改的标题是有意允许的——这正是把当前自动标题钉住、不再被重新生成覆盖的手势。双击标题也会打开 Rename;对于未归档 Session,先发生的点击会打开其对话。Rename 使用临时 `workspaceOperation` reference,并等待首次历史打开。行内 Fork 正常读取普通冷历史。Host 报告源会话需要迁移时,应用级 Toast 提供打开该会话的操作;该操作仅导航,不重试 fork。成功的 fork 在源会话最后一个已完成轮次处创建分支,通过 Session Controller 递增继承的持久化标题,不 retain 子会话、不打开其历史,也不改变选择。Workspace 行内的 Delete 操作会打开确认框,说明保留边界;成功后该分组被移除,其 Session 则留在 Ungrouped 下。Pin、Rename、Fork、Archive 本身就是 `sidebar.workspaces.session.menu.item` 列表的条目(pin 与 archive 同时也是 `sidebar.workspaces.session.row.action` 的条目),因此客户端插件的 action 由其 `order` 决定落在哪个位置。
|
||||
Session 行“...”菜单的最后一个内置项为“复制 Session ID”。点击后关闭菜单并直接复制完整 ID,不打开对话框。复制成功或失败通过全局提示反馈;失败时可从菜单重试。复制不会 retain 会话、加载历史或调用 Host。
|
||||
|
||||
Session 行内的 Rename 操作打开一个以该行显示标题预填的对话框;确认未修改的标题是有意允许的——这正是把当前自动标题钉住、不再被重新生成覆盖的手势。双击标题也会打开 Rename;对于未归档 Session,先发生的点击会打开其对话。Rename 使用临时 `workspaceOperation` reference,并等待首次历史打开。行内 Fork 正常读取普通冷历史。Host 报告源会话需要迁移时,应用级 Toast 提供打开该会话的操作;该操作仅导航,不重试 fork。成功的 fork 在源会话最后一个已完成轮次处创建分支,通过 Session Controller 递增继承的持久化标题,不 retain 子会话、不打开其历史,也不改变选择。Workspace 行内的 Delete 操作会打开确认框,说明保留边界;成功后该分组被移除,其 Session 则留在 Ungrouped 下。Pin、Rename、Fork、Archive 和复制 Session ID 本身就是 `sidebar.workspaces.session.menu.item` 列表的条目(pin 与 archive 同时也是 `sidebar.workspaces.session.row.action` 的条目),因此客户端插件的 action 由其 `order` 决定落在哪个位置。
|
||||
|
||||
对静止的 Session,Archive 不经确认对话框直接提交,并保留 Session 的记账位置。仍有工作在跑的 Session 是唯一会先询问的情形:Host 拒绝普通归档并列出这些工作,侧栏随即打开"停止并归档"对话框,按族列出——进行中的回合、运行中的子代理、后台任务、定时提醒,各带名称——并写明恢复路径;确认后请 Host 按停止按钮同样的方式停止这些工作,归档集合持久化后即完成归档,停止在后台收敛;取消则让 Session 继续运行并保持可见。视图选项以一组显式三选一控制显隐:隐藏已归档(默认项)隐藏已归档 Session,全部对话(显示已归档)将其纳入列表,仅显示已归档则隐藏普通 Session,并丢弃没有归档 Session 的 Workspace;树形分组下,被丢弃 Workspace 的子级挂到最近一个仍显示的祖先下。可见的归档行置灰,并提供无障碍说明,告知取消归档后才能打开;Rename、Fork 与取消归档仍然可用。归档成功后的提示提供"撤销"动作,并在归档行仍被隐藏时附带"筛选已归档会话"动作,后者直接把筛选切到全部对话(显示已归档);停止并归档显示同样的提示但措辞不同,撤销只恢复 Session,不会让被停止的工作继续。取消归档移除归档标记,但不恢复置顶,也不改变保存的位置。列表为空时显示居中的"图标在上、文字在下"占位;仅显示已归档视图用自己的文案(暂无已归档会话),并附"查看其他会话"文字按钮,点击把筛选切回隐藏已归档。
|
||||
|
||||
会话更新时间使用 tertiary 文本色,包括已归档行。标题宽于所在行时,静止状态以省略号裁切。把指针停在行上,标题会滚动到远端——例如 fork 递增后的标题——并在揭示时不显示省略号;指针离开后标题回到开头。
|
||||
|
||||
快捷键速查提供新建会话、搜索会话、添加工作区、重命名会话、分叉会话和归档会话。桌面默认使用平台的主修饰键,搜索为 Mod+K;Windows 和 macOS Web 使用[快捷键服务的平台默认值](../shortcuts/README.zh.md);Linux Web 在用户配置前不绑定这些命令。按钮提示和会话行菜单显示当前有效绑定。点击菜单项操作该行,按快捷键操作主会话。Desktop 和 Windows/macOS Web 的重命名均使用 Mod+Alt+G,将 Mod+Shift+R 留给浏览器刷新。重命名要求主区域正在显示非空会话,且没有模态对话框遮挡;切换到其他主面板后,后台保留的会话不可作为重命名目标。其他 Windows 和 macOS Desktop 绑定也可从终端输入区域和模态对话框中执行;其他环境遵循命令的区域和模态限制。搜索和重命名的打开请求归本包管理,输入草稿保留在浏览器中。目录选择或工作区接纳尚未结束时,目录选择器拒绝重复打开。分叉捕获主视图已持有并发起历史打开的会话,保留自动迁移;它使用与行菜单相同的 Host 操作选择最近已完成轮次,不读取更早的 Client 历史。没有会话或会话为空时不可用;没有已完成轮次的源会话由 Host 拒绝。快捷键分叉被拒绝时保留当前选择、显示本地化提示,并允许重试;非预期失败还会保留诊断日志。
|
||||
快捷键速查提供新建会话、搜索会话、添加工作区、重命名会话、分叉会话和归档会话。桌面默认使用平台的主修饰键,搜索为 Mod+K;Windows 和 macOS Web 使用[快捷键服务的平台默认值](../shortcuts/README.zh.md);Linux Web 在用户配置前不绑定这些命令。按钮提示和会话行菜单显示当前有效绑定。点击菜单项操作该行,按快捷键操作主会话。Desktop 和 Windows/macOS Web 的重命名均使用 Mod+Alt+G,将 Mod+Shift+R 留给浏览器刷新。重命名要求主区域正在显示非空会话,且没有模态对话框遮挡;切换到其他主面板后,后台保留的会话不可作为重命名目标。其他 Windows 和 macOS Desktop 绑定也可从终端输入区域和模态对话框中执行;其他环境遵循命令的区域和模态限制。搜索和重命名的打开请求归本包管理,输入草稿保留在浏览器中。目录选择或工作区接纳尚未结束时,目录选择器拒绝重复打开。分叉捕获主视图已持有并发起历史打开的会话,保留自动迁移;它使用与行菜单相同的 Host 操作选择最近已完成轮次,不读取更早的 Client 历史。没有会话或会话为空时不可用;没有已完成轮次的源会话由 Host 拒绝。快捷键分叉被拒绝时保留当前选择、显示本地化提示,并允许重试;非预期失败还会保留诊断日志。该提示共用应用级 Workspace 通知通道:只显示最新提示,移除浏览区域不会关闭它。
|
||||
|
||||
### 待处理交互
|
||||
|
||||
@@ -97,10 +99,12 @@ Workspace 和 Session 的启动基线均就绪后,空安装环境调用 `works
|
||||
|
||||
### Session 行 action
|
||||
|
||||
Session 行的 "..." 菜单和行尾悬停按钮是 WorkspaceBrowser 注册项声明的两个 `list` slot:`sidebar.workspaces.session.menu.item` 与 `sidebar.workspaces.session.row.action`。每一个菜单行、每一个悬停按钮都是条目,本包自己的 action 也不例外:`apply` 以客户端插件注册自己 action 的同一方式注册 `pin`(菜单 100、按钮 200)、`rename`(200)、`fork`(300)、`archive`(菜单 400、按钮 100),因此插件 action 落在其 `order` 所指的位置,以另一个 `priority` 复用内置 id 则遮蔽该 action。
|
||||
Session 行的 "..." 菜单和行尾悬停按钮是 WorkspaceBrowser 注册项声明的两个 `list` slot:`sidebar.workspaces.session.menu.item` 与 `sidebar.workspaces.session.row.action`。每一个菜单行、每一个悬停按钮都是条目,本包自己的 action 也不例外:`apply` 以客户端插件注册自己 action 的同一方式注册 `pin`(菜单 100、按钮 200)、`rename`(200)、`fork`(300)、`archive`(菜单 400、按钮 100)和 `session-id`(450),因此插件 action 落在其 `order` 所指的位置,以另一个 `priority` 复用内置 id 则遮蔽该 action。
|
||||
|
||||
条目只接收行身份(`sessionId`、`displayTitle`),其余一切自己负责:用自己注入的 hook 读自己关心的 Host 状态(置顶与归档集合,以每次 Workspace 快照只派生一次的 Set 形式),自己决定是否显示(Host 规定归档与置顶互斥,所以 pin 在归档行上不渲染),整套行为放在注册项自己的 `inject` face 里(置顶成功后顺带把会话推到保存顺序最前,归档成功后发提示),浮层也自己带——重命名对话框、停止并归档对话框和行 action 的提示是本包注册在 `shell.overlay` 的条目,由 action 注入的请求驱动。菜单条目渲染一个 `role="menuitem"` 的按钮(本包自己的行用 ui-primitives 的 `MenuItemButton`,它带宿主样式,开启新分组的行加 `separatorBefore`,分隔线随行一起出现和消失),并通过 slot 级 `useMenuOpenState` hook(菜单自身的打开状态,从该行的渲染出现处绑定)关闭菜单;悬停按钮条目渲染一个图标按钮,按钮条会拦住点击、不让它打开该行。browser 不再向行传任何 action 回调,它剩下的动作只有搜索结果里的恢复按钮和标题双击,后者发出的是同一个重命名请求。
|
||||
|
||||
现有通知浮层按通知 kind 分派 `workspace.toast`。各 keyed 注册注入本地化展示映射与自己的操作,只有归档通知订阅查看筛选状态。它们渲染包内的 `workspace.toast.content` Factory,所有展示共用一处 Toast primitive。现有通知状态、显示序号、最新提示替换及关闭逻辑仍共享;语言或筛选变化不会重新启动同一条提示的计时。
|
||||
|
||||
#### 打包客户端插件
|
||||
|
||||
按照 Client 依赖规则,将 `ui-workspace`、`ui-slots`、`ui-renderer`、`client-locale` 与 `ui-primitives` 声明为浏览器/类型开发依赖。纯类型的 `ui-workspace/client` import 会加载本包的 `SlotMap` 声明;缺少该 import 时,独立编译的插件不会知道这些 slot key。Component 保持模块级稳定身份;用户可见文案由贡献包自己的 locale namespace 持有。
|
||||
|
||||
@@ -26,8 +26,8 @@
|
||||
* row of a Session's "..." menu is an entry of
|
||||
* `sidebar.workspaces.session.menu.item`, and every hover button at the row's
|
||||
* end is an entry of `sidebar.workspaces.session.row.action`. The shipped
|
||||
* actions — pin, rename, fork, archive — are ordinary entries this package
|
||||
* registers from `apply`, each carrying its own behavior in its own inject
|
||||
* actions — pin, rename, fork, archive, copy ID — are ordinary entries
|
||||
* registered from `apply`, each carrying its own behavior in its own inject
|
||||
* face and reading its own Host state through hooks that face injects, so a
|
||||
* client plugin's action lands beside them by `order` and needs nothing from
|
||||
* the browser beyond the row identity.
|
||||
@@ -53,6 +53,7 @@ import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { ShortcutCatalogEntry } from '@deepseek-ai/dsh-client-shortcuts/client'
|
||||
import type { WorkspaceShortcutState } from '../shortcuts.ts'
|
||||
import type { StartSessionOptions } from '../navigation.ts'
|
||||
import type {} from './toast.ts'
|
||||
import type { createWorkspaceViewStore } from '../stores.ts'
|
||||
|
||||
/**
|
||||
@@ -136,8 +137,8 @@ declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
/**
|
||||
* The rows of one Session's "..." menu, in ascending `order`. ui-workspace
|
||||
* registers the shipped rows here — `pin` (100), `rename` (200), `fork`
|
||||
* (300), `archive` (400) — so a plugin row is placed by its own `order`
|
||||
* among them. Use a package-namespaced `id`; reusing a shipped id at
|
||||
* (300), `archive` (400), and `session-id` (450) — so a plugin row is placed
|
||||
* by its own `order` among them. Use a package-namespaced `id`; reusing a shipped id at
|
||||
* another `priority` shadows that row. Each entry renders one
|
||||
* `role="menuitem"` `<button>` (the shipped rows use ui-primitives'
|
||||
* `MenuItemButton`, which adds the host styling and `separatorBefore`),
|
||||
@@ -149,14 +150,17 @@ declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
* return {
|
||||
* inject: ['slots'],
|
||||
* apply(ctx) {
|
||||
* const copyLabel = 'Copy Session ID' // Localize in the contributing package.
|
||||
* const copyLabel = 'Copy session title' // Localize in the contributing package.
|
||||
* ctx.slots.inject('sidebar.workspaces.session.menu.item', () => ctx.slots.register(
|
||||
* { name: 'sidebar.workspaces.session.menu.item', id: 'copy-session-id', order: 500 },
|
||||
* ({ sessionId, useMenuOpenState }) => {
|
||||
* { name: 'sidebar.workspaces.session.menu.item', id: 'copy-session-title', order: 500 },
|
||||
* ({ displayTitle, useMenuOpenState }) => {
|
||||
* const [, setMenuOpen] = useMenuOpenState()
|
||||
* return React.createElement(
|
||||
* 'button',
|
||||
* { type: 'button', role: 'menuitem', onClick: () => { setMenuOpen(false); void navigator.clipboard.writeText(sessionId) } },
|
||||
* {
|
||||
* type: 'button', role: 'menuitem',
|
||||
* onClick: () => { setMenuOpen(false); void navigator.clipboard.writeText(displayTitle) },
|
||||
* },
|
||||
* copyLabel,
|
||||
* )
|
||||
* },
|
||||
@@ -233,8 +237,6 @@ export type WorkspaceBrowserInjected = {
|
||||
closeAddWorkspace: () => void
|
||||
/** Publish directory interaction occupancy for command availability. */
|
||||
setDirectoryBusy: (busy: boolean) => void
|
||||
/** Dismiss the shortcut's fork-failure notification. */
|
||||
dismissForkError: () => void
|
||||
/**
|
||||
* Create a fresh Session, or preserve a reusable blank with explicit draft options.
|
||||
* Without an explicit Workspace, inherit the current Session Workspace,
|
||||
@@ -291,11 +293,14 @@ export type SessionRowActionProps<Injected extends object = object> =
|
||||
export type RowToast =
|
||||
| { kind: 'archived'; sessionId: SessionId }
|
||||
| { kind: 'stoppedAndArchived'; sessionId: SessionId }
|
||||
| { kind: 'sessionIdCopied' }
|
||||
| { kind: 'sessionIdCopyFailed' }
|
||||
| { kind: 'pinFailed' }
|
||||
| { kind: 'unpinFailed' }
|
||||
| { kind: 'archivedNotOpenable' }
|
||||
| { kind: 'defaultWorkspaceFailed' }
|
||||
| { kind: 'forkRequiresOpen'; sessionId: SessionId }
|
||||
| { kind: 'shortcutForkFailed'; reason: 'unavailable' | 'failed' }
|
||||
/**
|
||||
* An explicit New Session request that failed. `message` is untranslated:
|
||||
* a Host refusal as `code: message` — the stable code stays in the copy so
|
||||
@@ -392,6 +397,12 @@ export interface RenameSessionInjected {
|
||||
requestSessionRename: (sessionId: SessionId, currentTitle: string) => void
|
||||
}
|
||||
|
||||
/** Session ID action share; copying does not open the Session. */
|
||||
export interface SessionIdInjected {
|
||||
/** Copy the complete id and report acceptance or failure through the global toast. */
|
||||
copySessionId: (sessionId: SessionId) => Promise<void>
|
||||
}
|
||||
|
||||
/** A Session rename the rename action asked for; the dialog entry opens on it. */
|
||||
export interface SessionRenameTarget {
|
||||
/** Session to rename. */
|
||||
@@ -412,7 +423,7 @@ export interface SessionRenameDialogInjected {
|
||||
renameSession: (sessionId: SessionId, title: string) => Promise<void>
|
||||
}
|
||||
|
||||
/** Row toast share: the notice, dismissal, archive recovery, and explicit source-history opening. */
|
||||
/** Existing overlay share: the current notice and its dismissal. */
|
||||
export interface RowToastInjected {
|
||||
hooks: {
|
||||
/** The notice on display, or none. */
|
||||
@@ -420,6 +431,10 @@ export interface RowToastInjected {
|
||||
}
|
||||
/** Take the notice down. */
|
||||
dismissToast: () => void
|
||||
}
|
||||
|
||||
/** Business callbacks injected into their keyed Toast presentations. */
|
||||
export interface RowToastActions {
|
||||
/** Undo an archive from its notice. */
|
||||
undoArchive: (sessionId: SessionId) => void
|
||||
/** Switch the archived filter to "show" so the archived row is back in view. */
|
||||
@@ -442,16 +457,11 @@ export type SessionArchiveConfirmProps =
|
||||
& Omit<SessionArchiveConfirmInjected, 'hooks'>
|
||||
& PropsHooks<SessionArchiveConfirmInjected['hooks']>
|
||||
|
||||
/**
|
||||
* Props of the row toast entry in `shell.overlay`. The declared viewing store
|
||||
* carries the archived filter; the archived notice omits its filter action
|
||||
* when archived rows are already visible.
|
||||
*/
|
||||
/** Props of the existing overlay's keyed notice dispatcher. */
|
||||
export type RowToastProps =
|
||||
PropsRuntime<'shell.overlay'>
|
||||
& PropsLocale<'workspace'>
|
||||
& PropsStore<WorkspaceViewStoreHandle>
|
||||
& Omit<RowToastInjected, 'hooks'>
|
||||
& PropsRenderSlots<'workspace.toast'>
|
||||
& Pick<RowToastInjected, 'dismissToast'>
|
||||
& PropsHooks<RowToastInjected['hooks']>
|
||||
|
||||
/** Full browser props: shell owner share + viewing store + injected actions + the locale seat. */
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
/** Keyed Workspace notices and the shared Toast Factory's display data. */
|
||||
import type {
|
||||
FactoryComponentPropsOf, InjectFace, PropsLocale, PropsRenderFactories, PropsRuntime, PropsStore,
|
||||
} from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { RowToastState, WorkspaceViewStoreHandle } from './slots.ts'
|
||||
|
||||
/** Business key of one existing Workspace notice. */
|
||||
export type ToastKind = RowToastState['kind']
|
||||
/** Notice payload selected by the keyed registration. */
|
||||
export type ToastNotice<K extends ToastKind> = Extract<RowToastState, { kind: K }>
|
||||
/** Plain display fields consumed by the shared Factory. */
|
||||
export interface ToastDisplay {
|
||||
text: string
|
||||
tone: 'plain' | 'warning' | 'success'
|
||||
holdMs?: number
|
||||
actions?: readonly { label: string; prefix?: string; onClick: () => void }[]
|
||||
}
|
||||
/** Per-display identity and dismissal; neither changes when localized content updates. */
|
||||
export interface ToastOccurrence extends ToastDisplay {
|
||||
seq: number
|
||||
onDone: () => void
|
||||
}
|
||||
/** Pure localized display mapping owned by a keyed notice registration. */
|
||||
export interface ToastDisplayInjected<K extends ToastKind> {
|
||||
display: (notice: ToastNotice<K>, t: PropsLocale<'workspace'>['t'], dismiss: () => void) => ToastDisplay
|
||||
}
|
||||
/** Shared adapter props; each registration narrows its notice payload. */
|
||||
export type ToastEntryProps<P extends PropsRuntime<'workspace.toast'>> =
|
||||
P & PropsLocale<'workspace'> & PropsRenderFactories & InjectFace<{
|
||||
display: (notice: P, t: PropsLocale<'workspace'>['t'], dismiss: () => void) => ToastDisplay
|
||||
}>
|
||||
/** Archive adapters additionally read the existing viewing store. */
|
||||
export interface ArchiveToastInjected extends ToastDisplayInjected<'archived' | 'stoppedAndArchived'> {
|
||||
filterAction: (t: PropsLocale<'workspace'>['t'], dismiss: () => void) => NonNullable<ToastDisplay['actions']>[number]
|
||||
}
|
||||
/** Archive adapter props with its injected action and viewing-state seats. */
|
||||
export type ArchiveToastEntryProps =
|
||||
PropsRuntime<'workspace.toast', 'archived' | 'stoppedAndArchived'> & PropsLocale<'workspace'> & PropsRenderFactories
|
||||
& PropsStore<WorkspaceViewStoreHandle> & InjectFace<ArchiveToastInjected>
|
||||
|
||||
/** Complete props of the shared Workspace Toast Factory. */
|
||||
export type WorkspaceToastProps = FactoryComponentPropsOf<'workspace.toast.content'>
|
||||
|
||||
/** Owner operations available to every keyed Workspace notice. */
|
||||
export interface WorkspaceToastOwnerProps {
|
||||
/** Dismiss the displayed notice. */
|
||||
dismissToast: () => void
|
||||
}
|
||||
|
||||
declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
interface SlotMap {
|
||||
/** Workspace notices selected by their existing business discriminator. */
|
||||
'workspace.toast': {
|
||||
kind: 'keyed'
|
||||
scope: 'root'
|
||||
owner: WorkspaceToastOwnerProps
|
||||
keyProps: { [K in ToastKind]: ToastNotice<K> }
|
||||
}
|
||||
}
|
||||
interface SlotFactoryMap {
|
||||
/** Shared Toast presentation; business registrations supply only display data and callbacks. */
|
||||
'workspace.toast.content': { scope: 'root'; props: ToastOccurrence }
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,8 @@
|
||||
* own `single` directory-flow child hole for the composed picker package's
|
||||
* client half. WorkspaceBrowser additionally declares the two Session row
|
||||
* action lists, and this apply registers the shipped actions — pin, rename,
|
||||
* fork, archive — into them the way any client plugin would, each with its
|
||||
* own behavior, plus the rename dialog and the row-action notice into
|
||||
* fork, archive, copy ID — into them the way any client plugin would, each
|
||||
* with its own behavior, plus the dialogs and the row-action notice into
|
||||
* `shell.overlay` (see the contract module doc). It also declares two
|
||||
* Session-row seats: the leading decoration a row renders only while its own
|
||||
* primary state is idle, and the section the row's hover card renders between
|
||||
@@ -23,6 +23,7 @@ import type {
|
||||
IWorkspaces, SessionActivity, WorkspaceArchiveError, WorkspaceSnapshot,
|
||||
} from '@deepseek-ai/dsh-api-workspace-controller/client'
|
||||
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
|
||||
import { writeClipboard } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { HostObservable, SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
// Type-only: pulls the Controller service merges.
|
||||
@@ -39,7 +40,7 @@ import {
|
||||
type ArchiveSessionInjected, type ForkSessionInjected, menuOpenStateFactory, type PinSessionInjected,
|
||||
type SessionArchiveConfirmInjected, type SessionArchiveConfirmRequest,
|
||||
type RenameSessionInjected, type RowToast, type RowToastInjected, type RowToastState, type SessionRenameDialogInjected,
|
||||
type WorkspaceBrowserInjected, type WorkspacePickerInjected,
|
||||
type SessionIdInjected, type WorkspaceBrowserInjected, type WorkspacePickerInjected,
|
||||
} from './contract/slots.ts'
|
||||
import { createWorkspaceShortcutControls, installWorkspaceShortcuts } from './shortcuts.ts'
|
||||
import { UiWorkspaceService } from './navigation.ts'
|
||||
@@ -51,6 +52,8 @@ import { ForkSessionMenuItem } from './session-actions/ForkSession.tsx'
|
||||
import { PinSessionMenuItem, PinSessionRowButton } from './session-actions/PinSession.tsx'
|
||||
import { RenameSessionMenuItem, SessionRenameDialog } from './session-actions/RenameSession.tsx'
|
||||
import { RowActionToast } from './session-actions/RowActionToast.tsx'
|
||||
import { registerToasts } from './toast/register.ts'
|
||||
import { SessionIdMenuItem } from './session-actions/SessionId.tsx'
|
||||
import { WorkspacePicker } from './WorkspacePicker.tsx'
|
||||
import { en, zh, type WorkspaceKey } from './locales.ts'
|
||||
|
||||
@@ -198,7 +201,8 @@ export function apply(ctx: Context): void {
|
||||
},
|
||||
unarchiveSession,
|
||||
})
|
||||
installWorkspaceShortcuts(ctx, uiWorkspace, shortcutControls, archiveInjected().archiveSession)
|
||||
installWorkspaceShortcuts(ctx, uiWorkspace, shortcutControls, archiveInjected().archiveSession,
|
||||
(reason) => { notify({ kind: 'shortcutForkFailed', reason }) })
|
||||
const archiveConfirmInjected = (): SessionArchiveConfirmInjected => ({
|
||||
hooks: { archiveRequest },
|
||||
settleSessionArchive: () => { archiveRequest.set(null) },
|
||||
@@ -219,24 +223,33 @@ export function apply(ctx: Context): void {
|
||||
})
|
||||
},
|
||||
})
|
||||
const sessionIdInjected = (): SessionIdInjected => ({
|
||||
copySessionId: async (sessionId) => {
|
||||
const copied = await writeClipboard(sessionId)
|
||||
notify({ kind: copied ? 'sessionIdCopied' : 'sessionIdCopyFailed' })
|
||||
},
|
||||
})
|
||||
const renameInjected = (): RenameSessionInjected => ({ requestSessionRename })
|
||||
const renameDialogInjected = (): SessionRenameDialogInjected => ({
|
||||
hooks: { renameRequest },
|
||||
settleSessionRename: shortcutControls.closeRename,
|
||||
renameSession,
|
||||
})
|
||||
const rowToastInjected = (): RowToastInjected => ({
|
||||
hooks: { toast: rowToast },
|
||||
dismissToast: () => { rowToast.set(null) },
|
||||
const toastActions = {
|
||||
undoArchive: unarchiveSession,
|
||||
showArchived: () => { viewInstance.actions.setArchivedFilter('show') },
|
||||
openForkSource: (sessionId) => {
|
||||
openForkSource: (sessionId: SessionId) => {
|
||||
if (workspaces.list.getSnapshot().archivedSessionIds.includes(sessionId)) {
|
||||
notify({ kind: 'archivedNotOpenable' })
|
||||
return
|
||||
}
|
||||
openSession(sessionId)
|
||||
},
|
||||
}
|
||||
registerToasts(ctx, viewStore, toastActions)
|
||||
const rowToastInjected = (): Pick<RowToastInjected, 'hooks' | 'dismissToast'> => ({
|
||||
hooks: { toast: rowToast },
|
||||
dismissToast: () => { rowToast.set(null) },
|
||||
})
|
||||
const browserInjected = (): WorkspaceBrowserInjected => ({
|
||||
// Explicit group actions keep their target; unscoped New Session inherits
|
||||
@@ -258,7 +271,6 @@ export function apply(ctx: Context): void {
|
||||
requestAddWorkspace: shortcutControls.add,
|
||||
closeAddWorkspace: shortcutControls.closeAdd,
|
||||
setDirectoryBusy: shortcutControls.directoryBusy,
|
||||
dismissForkError: shortcutControls.dismissForkError,
|
||||
hooks: { directoryFlow: browserFlowSource, hostInfo, workspaceShortcuts: shortcutControls.state, shortcuts: ctx.shortcuts.catalog },
|
||||
})
|
||||
const pickerInjected = (): WorkspacePickerInjected => ({
|
||||
@@ -290,13 +302,13 @@ export function apply(ctx: Context): void {
|
||||
))
|
||||
// The shipped row actions take the same route as a plugin's: `slots.inject`
|
||||
// waits for the browser registration above to declare each list, and the
|
||||
// entries leave with it. Orders step by 100 so a plugin entry can land
|
||||
// between them.
|
||||
// entries leave with it. Explicit orders leave room for plugin entries.
|
||||
ctx.slots.inject('sidebar.workspaces.session.menu.item', function* () {
|
||||
yield ctx.slots.register({ name: 'sidebar.workspaces.session.menu.item', id: 'pin', order: 100, locale: NS, inject: pinInjected }, PinSessionMenuItem)
|
||||
yield ctx.slots.register({ name: 'sidebar.workspaces.session.menu.item', id: 'rename', order: 200, locale: NS, inject: renameInjected }, RenameSessionMenuItem)
|
||||
yield ctx.slots.register({ name: 'sidebar.workspaces.session.menu.item', id: 'fork', order: 300, locale: NS, inject: forkInjected }, ForkSessionMenuItem)
|
||||
yield ctx.slots.register({ name: 'sidebar.workspaces.session.menu.item', id: 'archive', order: 400, locale: NS, inject: archiveInjected }, ArchiveSessionMenuItem)
|
||||
yield ctx.slots.register({ name: 'sidebar.workspaces.session.menu.item', id: 'session-id', order: 450, locale: NS, inject: sessionIdInjected }, SessionIdMenuItem)
|
||||
})
|
||||
ctx.slots.inject('sidebar.workspaces.session.row.action', function* () {
|
||||
yield ctx.slots.register({ name: 'sidebar.workspaces.session.row.action', id: 'archive', order: 100, locale: NS, inject: archiveInjected }, ArchiveSessionRowButton)
|
||||
@@ -311,10 +323,9 @@ export function apply(ctx: Context): void {
|
||||
yield ctx.slots.register({
|
||||
name: 'shell.overlay', id: 'workspace.session-archive', locale: NS, inject: archiveConfirmInjected,
|
||||
}, SessionArchiveConfirmDialog)
|
||||
// The toast shares the browser's viewing store: it reads the archived
|
||||
// filter to drop the archived notice's filter action once rows are visible.
|
||||
yield ctx.slots.register({
|
||||
name: 'shell.overlay', id: 'workspace.row-toast', locale: NS, store: viewStore, inject: rowToastInjected,
|
||||
name: 'shell.overlay', id: 'workspace.row-toast', inject: rowToastInjected,
|
||||
children: { 'workspace.toast': { kind: 'keyed', scope: 'root' } },
|
||||
}, RowActionToast)
|
||||
})
|
||||
ctx.slots.inject('conversation.hero.workspace', () => ctx.slots.register(
|
||||
|
||||
@@ -63,6 +63,9 @@ export const zh = {
|
||||
'menu.unarchiveSession': '取消归档',
|
||||
'menu.pinSession': '置顶会话',
|
||||
'menu.unpinSession': '取消置顶',
|
||||
'menu.sessionId': '复制 Session ID',
|
||||
'toast.sessionIdCopied': 'Session ID 已复制',
|
||||
'toast.sessionIdCopyFailed': '复制失败,请重试',
|
||||
'row.archived': '已归档',
|
||||
'row.pinned': '已置顶',
|
||||
'toast.archivedNotOpenable': '已归档对话暂时无法查看,请取消归档后查看',
|
||||
@@ -186,6 +189,9 @@ export const en = {
|
||||
'menu.unarchiveSession': 'Unarchive session',
|
||||
'menu.pinSession': 'Pin session',
|
||||
'menu.unpinSession': 'Unpin session',
|
||||
'menu.sessionId': 'Copy Session ID',
|
||||
'toast.sessionIdCopied': 'Session ID copied',
|
||||
'toast.sessionIdCopyFailed': 'Copy failed. Try again.',
|
||||
'row.archived': 'Archived',
|
||||
'row.pinned': 'Pinned',
|
||||
'toast.archivedNotOpenable': 'Archived sessions cannot be opened. Unarchive it to view.',
|
||||
|
||||
@@ -21,7 +21,7 @@ import {
|
||||
IconChevronsUpDownOutlineRegular, IconClockOutlineRegular, IconCloseFillRegular,
|
||||
IconFlatListOutlineRegular, IconFolderCloseRegular, IconProjectAddOutlineRegular,
|
||||
IconQueueOutlineRegular, IconSearchOutlineRegular, IconSlidersTwoOutlineRegular,
|
||||
IconWorkspaceTreeOutlineRegular, Menu, Modal, Toast, Tooltip,
|
||||
IconWorkspaceTreeOutlineRegular, Menu, Modal, Tooltip,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type {
|
||||
SessionListState, SessionSearchResultItem,
|
||||
@@ -861,7 +861,6 @@ export function WorkspaceBrowser({
|
||||
requestAddWorkspace,
|
||||
closeAddWorkspace,
|
||||
setDirectoryBusy,
|
||||
dismissForkError,
|
||||
renderSlot,
|
||||
t,
|
||||
}: WorkspaceBrowserProps) {
|
||||
@@ -1479,9 +1478,6 @@ export function WorkspaceBrowser({
|
||||
{deleting && <div className={css.deleteStatus} role="status">{t('delete.pending')}</div>}
|
||||
{deleteError !== null && <div className={css.renameError} role="alert">{deleteError}</div>}
|
||||
</Modal>
|
||||
{shortcutState.forkError !== null && <Toast key={shortcutState.forkError.seq}
|
||||
text={t(shortcutState.forkError.reason === 'unavailable' ? 'shortcut.noCompletedTurn' : 'shortcut.forkFailed')}
|
||||
onDone={dismissForkError} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,92 +1,14 @@
|
||||
/**
|
||||
* 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 { assertNever } from '@deepseek-ai/dsh-util-values'
|
||||
import type { RowToastProps, RowToastState } from '../contract/slots.ts'
|
||||
/** The existing overlay dispatches the latest Workspace notice to its keyed presentation. */
|
||||
import type { RowToastProps } from '../contract/slots.ts'
|
||||
import type {} from '../contract/toast.ts'
|
||||
|
||||
/**
|
||||
* Hold for the notices that take longer to read than a one-line warning: the
|
||||
* archive and fork recovery actions, and a refused Session creation quoting the Host's reason.
|
||||
* Dispatch the current notice without interpreting its business payload.
|
||||
* @param props - Current notice, dismissal, and the declared keyed renderer.
|
||||
* @returns The selected notice presentation, or nothing.
|
||||
*/
|
||||
const LONG_TOAST_HOLD_MS = 6000
|
||||
|
||||
/**
|
||||
* Render an operation notice, retaining recovery actions for six seconds.
|
||||
* @param props - notice and viewing sources, dismissal and recovery callbacks, and localized copy.
|
||||
* @returns the notice on display, or null.
|
||||
*/
|
||||
export function RowActionToast({ useToast, useStore, dismissToast, undoArchive, showArchived, openForkSource, t }: RowToastProps) {
|
||||
const toast = useToast(current => current)
|
||||
const archivedRowsVisible = useStore(state => (state.archivedFilter ?? 'default') !== 'default')
|
||||
if (toast === null) return null
|
||||
if (toast.kind === 'forkRequiresOpen') {
|
||||
return (
|
||||
<Toast
|
||||
key={`toast-${String(toast.seq)}`}
|
||||
text={t('toast.forkRequiresOpen')}
|
||||
icon={<IconWarningOutlineRegular />}
|
||||
holdMs={LONG_TOAST_HOLD_MS}
|
||||
actions={[{
|
||||
label: t('toast.openForkSource'),
|
||||
onClick: () => { dismissToast(); openForkSource(toast.sessionId) },
|
||||
}]}
|
||||
onDone={dismissToast}
|
||||
/>
|
||||
)
|
||||
}
|
||||
if (toast.kind === 'archived' || toast.kind === 'stoppedAndArchived') {
|
||||
const { sessionId } = toast
|
||||
return (
|
||||
<Toast
|
||||
key={`toast-${String(toast.seq)}`}
|
||||
text={t(toast.kind === 'archived' ? 'toast.archived' : 'toast.stoppedAndArchived')}
|
||||
tone="success"
|
||||
holdMs={LONG_TOAST_HOLD_MS}
|
||||
actions={[
|
||||
{ label: t('toast.archivedUndo'), onClick: () => { dismissToast(); undoArchive(sessionId) } },
|
||||
...archivedRowsVisible ? [] : [
|
||||
{ prefix: t('toast.archivedOr'), label: t('toast.archivedFilter'), onClick: () => { dismissToast(); showArchived() } },
|
||||
],
|
||||
]}
|
||||
onDone={dismissToast}
|
||||
/>
|
||||
)
|
||||
}
|
||||
if (toast.kind === 'createFailed') {
|
||||
return (
|
||||
<Toast
|
||||
key={`toast-${String(toast.seq)}`}
|
||||
text={t('toast.createFailed', { message: toast.message })}
|
||||
icon={<IconWarningOutlineRegular />}
|
||||
holdMs={LONG_TOAST_HOLD_MS}
|
||||
onDone={dismissToast}
|
||||
/>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<Toast
|
||||
key={`toast-${String(toast.seq)}`}
|
||||
text={plainNoticeText(toast, t)}
|
||||
icon={<IconWarningOutlineRegular />}
|
||||
onDone={dismissToast}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
/** The copy of one plain warning, keyed by the notice kind the union closes over. */
|
||||
function plainNoticeText(
|
||||
toast: Exclude<RowToastState, { kind: 'archived' | 'stoppedAndArchived' | 'createFailed' | 'forkRequiresOpen' }>,
|
||||
t: RowToastProps['t'],
|
||||
): string {
|
||||
switch (toast.kind) {
|
||||
case 'pinFailed': return t('toast.pinFailed')
|
||||
case 'unpinFailed': return t('toast.unpinFailed')
|
||||
case 'defaultWorkspaceFailed': return t('defaultWorkspace.failed')
|
||||
case 'archivedNotOpenable': return t('toast.archivedNotOpenable')
|
||||
/* v8 ignore next 2 -- closed-union backstop; only reached if a notice kind is forged */
|
||||
default:
|
||||
return assertNever(toast)
|
||||
}
|
||||
export function RowActionToast({ useToast, dismissToast, renderSlot }: RowToastProps) {
|
||||
const notice = useToast(current => current)
|
||||
if (notice === null) return null
|
||||
return renderSlot('workspace.toast', { ...notice, dismissToast }, { entryKey: notice.kind })
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/** Copy the row's Session ID without opening its history. */
|
||||
import { IconCopyOutlineRegular, MenuItemButton } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { SessionIdInjected, SessionMenuItemProps } from '../contract/slots.ts'
|
||||
|
||||
/**
|
||||
* Copy the complete ID after dismissing the row menu.
|
||||
* @param props - Row identity, menu dismissal, clipboard action, and locale.
|
||||
* @returns The final built-in menu item.
|
||||
*/
|
||||
export function SessionIdMenuItem({ sessionId, useMenuOpenState, copySessionId, t }: SessionMenuItemProps<SessionIdInjected>) {
|
||||
const [, setMenuOpen] = useMenuOpenState()
|
||||
return (
|
||||
<MenuItemButton icon={<IconCopyOutlineRegular />} onSelect={() => {
|
||||
setMenuOpen(false)
|
||||
void copySessionId(sessionId)
|
||||
}}>
|
||||
{t('menu.sessionId')}
|
||||
</MenuItemButton>
|
||||
)
|
||||
}
|
||||
@@ -13,7 +13,6 @@ export interface WorkspaceShortcutState {
|
||||
readonly addRequested: boolean
|
||||
readonly directoryBusy: boolean
|
||||
readonly renameTarget: { readonly sessionId: SessionId; readonly currentTitle: string } | null
|
||||
readonly forkError: { readonly reason: 'unavailable' | 'failed'; readonly seq: number } | null
|
||||
}
|
||||
|
||||
interface WorkspaceShortcutControls {
|
||||
@@ -24,8 +23,6 @@ interface WorkspaceShortcutControls {
|
||||
directoryBusy: (busy: boolean) => void
|
||||
rename: (sessionId: SessionId, currentTitle: string) => void
|
||||
closeRename: () => void
|
||||
forkFailed: (reason: 'unavailable' | 'failed') => void
|
||||
dismissForkError: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -34,9 +31,8 @@ interface WorkspaceShortcutControls {
|
||||
*/
|
||||
export function createWorkspaceShortcutControls(): WorkspaceShortcutControls {
|
||||
const state = createSnapshotStore<WorkspaceShortcutState>({
|
||||
searchRequest: 0, addRequested: false, directoryBusy: false, renameTarget: null, forkError: null,
|
||||
searchRequest: 0, addRequested: false, directoryBusy: false, renameTarget: null,
|
||||
})
|
||||
let forkErrorSeq = 0
|
||||
return {
|
||||
state,
|
||||
search: () => { state.set({ ...state.getSnapshot(), searchRequest: state.getSnapshot().searchRequest + 1 }) },
|
||||
@@ -47,11 +43,6 @@ export function createWorkspaceShortcutControls(): WorkspaceShortcutControls {
|
||||
state.set({ ...state.getSnapshot(), renameTarget: { sessionId, currentTitle } })
|
||||
},
|
||||
closeRename: () => { state.set({ ...state.getSnapshot(), renameTarget: null }) },
|
||||
forkFailed: (reason) => {
|
||||
forkErrorSeq += 1
|
||||
state.set({ ...state.getSnapshot(), forkError: { reason, seq: forkErrorSeq } })
|
||||
},
|
||||
dismissForkError: () => { state.set({ ...state.getSnapshot(), forkError: null }) },
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,12 +53,14 @@ export function createWorkspaceShortcutControls(): WorkspaceShortcutControls {
|
||||
* @param navigation - session creation and forking from the pointer controls' navigation service.
|
||||
* @param controls - browser-owned opening requests.
|
||||
* @param archiveSession - shared archive action, including running-work confirmation and notices.
|
||||
* @param reportForkFailure - publish a classified failure through the frame-wide notice channel.
|
||||
*/
|
||||
export function installWorkspaceShortcuts(
|
||||
ctx: Context,
|
||||
navigation: Pick<UiWorkspace, 'startSession' | 'forkSession'>,
|
||||
controls: ReturnType<typeof createWorkspaceShortcutControls>,
|
||||
archiveSession: (sessionId: SessionId) => void,
|
||||
reportForkFailure: (reason: 'unavailable' | 'failed') => void,
|
||||
): void {
|
||||
const t = ctx.locale.bind('workspace')
|
||||
const current = () => Object.values(ctx.sessions.list.getSnapshot().byId)
|
||||
@@ -110,7 +103,7 @@ export function installWorkspaceShortcuts(
|
||||
// Client plugin bundles do not share error-class identity.
|
||||
const unavailable = error instanceof Error && error.name === 'SessionForkError'
|
||||
&& (error as SessionForkError).rpcError.code === 'session/fork-unavailable'
|
||||
controls.forkFailed(unavailable ? 'unavailable' : 'failed')
|
||||
reportForkFailure(unavailable ? 'unavailable' : 'failed')
|
||||
if (!unavailable) console.warn('session fork rejected:', error)
|
||||
})
|
||||
} }
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
/** One presentation Factory and the adapters for keyed Workspace notices. */
|
||||
import { IconWarningOutlineRegular, Toast } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { ArchiveToastEntryProps, ToastEntryProps, WorkspaceToastProps } from '../contract/toast.ts'
|
||||
|
||||
/**
|
||||
* Render one notice using the shared Factory.
|
||||
* @param props - Keyed payload, injected display mapping, locale, and Factory renderer.
|
||||
* @returns The shared Toast occurrence.
|
||||
*/
|
||||
export function ToastEntry<P extends PropsRuntime<'workspace.toast'>>(props: ToastEntryProps<P>) {
|
||||
const { dismissToast, display, t, renderFactorySlot, seq } = props
|
||||
return renderFactorySlot('workspace.toast.content', { ...display(props, t, dismissToast), seq, onDone: dismissToast })
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep the archive filter action reactive without subscribing unrelated notices.
|
||||
* @param props - Archive notice, display mapping, and the existing viewing store.
|
||||
* @returns The shared Toast occurrence with its current actions.
|
||||
*/
|
||||
export function ArchiveToastEntry(props: ArchiveToastEntryProps) {
|
||||
const { dismissToast, display, filterAction, useStore, t, renderFactorySlot, seq } = props
|
||||
const archivedVisible = useStore(state => (state.archivedFilter ?? 'default') !== 'default')
|
||||
const fields = display(props, t, dismissToast)
|
||||
return renderFactorySlot('workspace.toast.content', {
|
||||
...fields,
|
||||
actions: [...fields.actions ?? [], ...archivedVisible ? [] : [filterAction(t, dismissToast)]],
|
||||
seq,
|
||||
onDone: dismissToast,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Present plain display data with the shared primitive's timing and portal.
|
||||
* @param props - Localized display fields, display identity, and dismissal.
|
||||
* @returns One Toast, remounted only for a new display identity.
|
||||
*/
|
||||
export function WorkspaceToast({ seq, text, tone, holdMs, actions, onDone }: WorkspaceToastProps) {
|
||||
return <Toast key={seq} text={text} onDone={onDone}
|
||||
{...tone === 'success' ? { tone: 'success' as const } : {}}
|
||||
{...tone === 'warning' ? { icon: <IconWarningOutlineRegular /> } : {}}
|
||||
{...holdMs === undefined ? {} : { holdMs }}
|
||||
{...actions === undefined ? {} : { actions }} />
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/** Business-owned mappings into the keyed Workspace Toast slot. */
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { RowToastActions, WorkspaceViewStoreHandle } from '../contract/slots.ts'
|
||||
import type { ArchiveToastInjected, ToastDisplayInjected } from '../contract/toast.ts'
|
||||
import { ArchiveToastEntry, ToastEntry, WorkspaceToast } from './Toast.tsx'
|
||||
|
||||
/** Register notice presentations with their business-owned display fields and actions.
|
||||
* @param ctx - Workspace plugin context.
|
||||
* @param viewStore - Viewing store, read only by archive notices.
|
||||
* @param actions - Archive and source-opening callbacks.
|
||||
*/
|
||||
export function registerToasts(
|
||||
ctx: Context,
|
||||
viewStore: WorkspaceViewStoreHandle,
|
||||
actions: Pick<RowToastActions, 'undoArchive' | 'showArchived' | 'openForkSource'>,
|
||||
): void {
|
||||
const archiveFilterAction: ArchiveToastInjected['filterAction'] = (t, dismiss) => ({
|
||||
prefix: t('toast.archivedOr'), label: t('toast.archivedFilter'),
|
||||
onClick: () => { dismiss(); actions.showArchived() },
|
||||
})
|
||||
ctx.slots.registerFactory({ name: 'workspace.toast.content', scope: 'root' }, WorkspaceToast)
|
||||
ctx.slots.inject('workspace.toast', function* () {
|
||||
yield ctx.slots.register({
|
||||
name: 'workspace.toast', key: 'sessionIdCopied', locale: 'workspace',
|
||||
inject: (): ToastDisplayInjected<'sessionIdCopied'> => ({
|
||||
display: (_notice, t) => ({ text: t('toast.sessionIdCopied'), tone: 'success' }),
|
||||
}),
|
||||
}, ToastEntry<PropsRuntime<'workspace.toast', 'sessionIdCopied'>>)
|
||||
yield ctx.slots.register({
|
||||
name: 'workspace.toast', key: 'sessionIdCopyFailed', locale: 'workspace',
|
||||
inject: (): ToastDisplayInjected<'sessionIdCopyFailed'> => ({
|
||||
display: (_notice, t) => ({ text: t('toast.sessionIdCopyFailed'), tone: 'warning' }),
|
||||
}),
|
||||
}, ToastEntry<PropsRuntime<'workspace.toast', 'sessionIdCopyFailed'>>)
|
||||
yield ctx.slots.register({
|
||||
name: 'workspace.toast', key: 'pinFailed', locale: 'workspace',
|
||||
inject: (): ToastDisplayInjected<'pinFailed'> => ({
|
||||
display: (_notice, t) => ({ text: t('toast.pinFailed'), tone: 'warning' }),
|
||||
}),
|
||||
}, ToastEntry<PropsRuntime<'workspace.toast', 'pinFailed'>>)
|
||||
yield ctx.slots.register({
|
||||
name: 'workspace.toast', key: 'unpinFailed', locale: 'workspace',
|
||||
inject: (): ToastDisplayInjected<'unpinFailed'> => ({
|
||||
display: (_notice, t) => ({ text: t('toast.unpinFailed'), tone: 'warning' }),
|
||||
}),
|
||||
}, ToastEntry<PropsRuntime<'workspace.toast', 'unpinFailed'>>)
|
||||
yield ctx.slots.register({
|
||||
name: 'workspace.toast', key: 'archivedNotOpenable', locale: 'workspace',
|
||||
inject: (): ToastDisplayInjected<'archivedNotOpenable'> => ({
|
||||
display: (_notice, t) => ({ text: t('toast.archivedNotOpenable'), tone: 'warning' }),
|
||||
}),
|
||||
}, ToastEntry<PropsRuntime<'workspace.toast', 'archivedNotOpenable'>>)
|
||||
yield ctx.slots.register({
|
||||
name: 'workspace.toast', key: 'defaultWorkspaceFailed', locale: 'workspace',
|
||||
inject: (): ToastDisplayInjected<'defaultWorkspaceFailed'> => ({
|
||||
display: (_notice, t) => ({ text: t('defaultWorkspace.failed'), tone: 'warning' }),
|
||||
}),
|
||||
}, ToastEntry<PropsRuntime<'workspace.toast', 'defaultWorkspaceFailed'>>)
|
||||
yield ctx.slots.register({
|
||||
name: 'workspace.toast', key: 'shortcutForkFailed', locale: 'workspace',
|
||||
inject: (): ToastDisplayInjected<'shortcutForkFailed'> => ({
|
||||
display: (notice, t) => ({
|
||||
text: t(notice.reason === 'unavailable' ? 'shortcut.noCompletedTurn' : 'shortcut.forkFailed'), tone: 'plain',
|
||||
}),
|
||||
}),
|
||||
}, ToastEntry<PropsRuntime<'workspace.toast', 'shortcutForkFailed'>>)
|
||||
yield ctx.slots.register({
|
||||
name: 'workspace.toast', key: 'createFailed', locale: 'workspace',
|
||||
inject: (): ToastDisplayInjected<'createFailed'> => ({
|
||||
display: (notice, t) => ({ text: t('toast.createFailed', { message: notice.message }), tone: 'warning', holdMs: 6000 }),
|
||||
}),
|
||||
}, ToastEntry<PropsRuntime<'workspace.toast', 'createFailed'>>)
|
||||
yield ctx.slots.register({
|
||||
name: 'workspace.toast', key: 'forkRequiresOpen', locale: 'workspace',
|
||||
inject: (): ToastDisplayInjected<'forkRequiresOpen'> => ({
|
||||
display: (notice, t, dismiss) => ({
|
||||
text: t('toast.forkRequiresOpen'), tone: 'warning', holdMs: 6000,
|
||||
actions: [{ label: t('toast.openForkSource'), onClick: () => { dismiss(); actions.openForkSource(notice.sessionId) } }],
|
||||
}),
|
||||
}),
|
||||
}, ToastEntry<PropsRuntime<'workspace.toast', 'forkRequiresOpen'>>)
|
||||
yield ctx.slots.register({
|
||||
name: 'workspace.toast', key: 'archived', locale: 'workspace', store: viewStore,
|
||||
inject: (): ArchiveToastInjected => ({
|
||||
display: (notice, t, dismiss) => ({
|
||||
text: t('toast.archived'), tone: 'success', holdMs: 6000,
|
||||
actions: [{ label: t('toast.archivedUndo'), onClick: () => { dismiss(); actions.undoArchive(notice.sessionId) } }],
|
||||
}),
|
||||
filterAction: archiveFilterAction,
|
||||
}),
|
||||
}, ArchiveToastEntry)
|
||||
yield ctx.slots.register({
|
||||
name: 'workspace.toast', key: 'stoppedAndArchived', locale: 'workspace', store: viewStore,
|
||||
inject: (): ArchiveToastInjected => ({
|
||||
display: (notice, t, dismiss) => ({
|
||||
text: t('toast.stoppedAndArchived'), tone: 'success', holdMs: 6000,
|
||||
actions: [{ label: t('toast.archivedUndo'), onClick: () => { dismiss(); actions.undoArchive(notice.sessionId) } }],
|
||||
}),
|
||||
filterAction: archiveFilterAction,
|
||||
}),
|
||||
}, ArchiveToastEntry)
|
||||
})
|
||||
}
|
||||
@@ -8,7 +8,8 @@ import { SessionForkError } from '@deepseek-ai/dsh-api-session-controller/client
|
||||
import type { WorkspaceId, WorkspaceSnapshot, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client'
|
||||
import type { StoredEntry } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { PropsRenderSlots, StoredEntry } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { ShortcutCommand } from '@deepseek-ai/dsh-client-shortcuts/client'
|
||||
import { RemoteError, TestRemote } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
|
||||
import { apply, inject } from '@deepseek-ai/dsh-client-ui-workspace/client'
|
||||
@@ -16,7 +17,7 @@ import type { WorkspaceBrowserInjected, WorkspacePickerInjected } from '@deepsee
|
||||
import {
|
||||
type ArchiveSessionInjected, type ForkSessionInjected, menuOpenStateFactory, type PinSessionInjected,
|
||||
type RenameSessionInjected, type RowToastInjected, type SessionArchiveConfirmInjected, type SessionRenameDialogInjected,
|
||||
type WorkspaceViewStoreHandle,
|
||||
type SessionIdInjected, type WorkspaceViewStoreHandle,
|
||||
} from '../src/client/contract/slots.ts'
|
||||
import { WorkspaceBrowser } from '../src/client/rows/WorkspaceBrowser.tsx'
|
||||
import { ArchiveSessionMenuItem, ArchiveSessionRowButton, SessionArchiveConfirmDialog } from '../src/client/session-actions/ArchiveSession.tsx'
|
||||
@@ -24,6 +25,8 @@ import { ForkSessionMenuItem } from '../src/client/session-actions/ForkSession.t
|
||||
import { PinSessionMenuItem, PinSessionRowButton } from '../src/client/session-actions/PinSession.tsx'
|
||||
import { RenameSessionMenuItem, SessionRenameDialog } from '../src/client/session-actions/RenameSession.tsx'
|
||||
import { RowActionToast } from '../src/client/session-actions/RowActionToast.tsx'
|
||||
import type { ArchiveToastInjected, ToastDisplayInjected } from '../src/client/contract/toast.ts'
|
||||
import { SessionIdMenuItem } from '../src/client/session-actions/SessionId.tsx'
|
||||
import { WorkspacePicker } from '../src/client/WorkspacePicker.tsx'
|
||||
import { FLAT_SESSION_ORDER_KEY } from '../src/client/stores.ts'
|
||||
import { UNGROUPED_KEY } from '../src/client/tree.ts'
|
||||
@@ -53,7 +56,14 @@ const workspaceState = (
|
||||
|
||||
async function bench() {
|
||||
const ctx = new Context()
|
||||
ctx.provide('shortcuts', { register: () => () => {}, catalog: createSnapshotStore([]) })
|
||||
const commands = new Map<string, ShortcutCommand>()
|
||||
ctx.provide('shortcuts', {
|
||||
register: (command: ShortcutCommand) => {
|
||||
commands.set(command.id, command)
|
||||
return () => { commands.delete(command.id) }
|
||||
},
|
||||
catalog: createSnapshotStore([]),
|
||||
})
|
||||
ctx.provide('uiConversation', {})
|
||||
await ctx.plugin(SlotRegistry).await()
|
||||
const create = vi.fn(async (input: { name: string } | { path: string }) => ({
|
||||
@@ -148,7 +158,7 @@ async function bench() {
|
||||
locale.setLocale('zh')
|
||||
ctx.provide('locale', locale)
|
||||
return {
|
||||
ctx, slots: ctx.get('slots') as SlotRegistry, locale, create, rename,
|
||||
ctx, slots: ctx.get('slots') as SlotRegistry, locale, create, rename, commands,
|
||||
retain, using, selectPanel, search, renameSession, binding, fork, pickDirectory, pinSession, unpinSession,
|
||||
workspacesSubscribe, initializeDefault, history, scope, sessionOf,
|
||||
setWorkspaces: (snapshot: WorkspaceSnapshot): void => { workspaceSnapshot = snapshot },
|
||||
@@ -170,6 +180,11 @@ function declare(slots: SlotRegistry, ...names: HoleName[]): () => void {
|
||||
return slots.register({ name: 'root', children } as never, () => null)
|
||||
}
|
||||
|
||||
/** Own the sidebar declaration independently of the frame-wide overlay in lifecycle tests. */
|
||||
function SidebarDeclarationOwner({ renderSlot }: PropsRenderSlots<'sidebar.workspaces'>) {
|
||||
return renderSlot('sidebar.workspaces', { wide: true, expandSidebar: () => {} })
|
||||
}
|
||||
|
||||
/** The one entry registered under `id` in a list. */
|
||||
function entry(slots: SlotRegistry, key: RowListName, id: string): StoredEntry {
|
||||
const found = slots.entries(key).find(candidate => candidate.options.id === id)
|
||||
@@ -234,7 +249,7 @@ describe('ui-workspace apply', () => {
|
||||
await Promise.resolve()
|
||||
expect(after.slots.entries('conversation.hero.workspace')[0]!.component).toBe(WorkspacePicker)
|
||||
// The row actions follow the browser's own declaration, whenever it lands.
|
||||
expect(after.slots.entries(MENU_ITEM)).toHaveLength(4)
|
||||
expect(after.slots.entries(MENU_ITEM)).toHaveLength(5)
|
||||
expect(after.slots.entries(ROW_ACTION)).toHaveLength(2)
|
||||
expect(after.slots.entries('shell.overlay')).toHaveLength(3)
|
||||
})
|
||||
@@ -257,6 +272,7 @@ describe('ui-workspace apply', () => {
|
||||
['rename', 200, RenameSessionMenuItem, 'workspace'],
|
||||
['fork', 300, ForkSessionMenuItem, 'workspace'],
|
||||
['archive', 400, ArchiveSessionMenuItem, 'workspace'],
|
||||
['session-id', 450, SessionIdMenuItem, 'workspace'],
|
||||
])
|
||||
expect(rows(ROW_ACTION)).toEqual([
|
||||
['archive', 100, ArchiveSessionRowButton, 'workspace'],
|
||||
@@ -265,17 +281,22 @@ describe('ui-workspace apply', () => {
|
||||
expect(rows('shell.overlay')).toEqual([
|
||||
['workspace.session-rename', undefined, SessionRenameDialog, 'workspace'],
|
||||
['workspace.session-archive', undefined, SessionArchiveConfirmDialog, 'workspace'],
|
||||
['workspace.row-toast', undefined, RowActionToast, 'workspace'],
|
||||
['workspace.row-toast', undefined, RowActionToast, undefined],
|
||||
])
|
||||
// The browser and the row toast declare the same viewing-store handle,
|
||||
// which hands out one instance: the browser's injected callbacks write
|
||||
// view state through it and the toast reads the archived filter from it.
|
||||
// The row actions and the other overlay surfaces declare none.
|
||||
// Only archive notice entries share the browser's viewing store.
|
||||
const browser = b.slots.entries('sidebar.workspaces')[0]!
|
||||
expect(browser.store).toBeDefined()
|
||||
expect(viewInstance(b.slots)).toBe(viewInstance(b.slots))
|
||||
const rowToastEntry = entry(b.slots, 'shell.overlay', 'workspace.row-toast')
|
||||
expect(rowToastEntry.store).toBe(browser.store)
|
||||
expect(rowToastEntry.store).toBeUndefined()
|
||||
expect(b.slots.entries('workspace.toast').map(row => row.options.key)).toEqual([
|
||||
'sessionIdCopied', 'sessionIdCopyFailed', 'pinFailed', 'unpinFailed', 'archivedNotOpenable',
|
||||
'defaultWorkspaceFailed', 'shortcutForkFailed', 'createFailed', 'forkRequiresOpen', 'archived', 'stoppedAndArchived',
|
||||
])
|
||||
for (const registration of b.slots.entries('workspace.toast')) {
|
||||
expect(registration.locale).toBe('workspace')
|
||||
expect(registration.store).toBe(['archived', 'stoppedAndArchived'].includes(String(registration.options.key)) ? browser.store : undefined)
|
||||
}
|
||||
for (const registration of [...b.slots.entries(MENU_ITEM), ...b.slots.entries(ROW_ACTION), ...b.slots.entries('shell.overlay')]) {
|
||||
if (registration === rowToastEntry) continue
|
||||
expect(registration.store).toBeUndefined()
|
||||
@@ -287,6 +308,77 @@ describe('ui-workspace apply', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it.each([true, false])('copies an ID directly without loading its Session (clipboard accepted: %s)', async (accepted) => {
|
||||
const b = await bench()
|
||||
onTestFinished(() => b.ctx.fiber.dispose())
|
||||
declare(b.slots, 'sidebar.workspaces', 'shell.overlay')
|
||||
await b.ctx.plugin({ inject: [...inject], apply }).await()
|
||||
const action = faceOf(entry(b.slots, MENU_ITEM, 'session-id')) as SessionIdInjected
|
||||
const toast = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected
|
||||
const writeText = vi.fn(async () => {
|
||||
if (!accepted) throw new Error('clipboard denied')
|
||||
})
|
||||
vi.stubGlobal('navigator', { clipboard: { writeText } })
|
||||
onTestFinished(() => { vi.unstubAllGlobals() })
|
||||
await action.copySessionId(sid('cold-session'))
|
||||
expect(writeText).toHaveBeenCalledExactlyOnceWith('cold-session')
|
||||
expect(toast.hooks.toast.getSnapshot()).toMatchObject({ kind: accepted ? 'sessionIdCopied' : 'sessionIdCopyFailed' })
|
||||
expect(b.retain).not.toHaveBeenCalled()
|
||||
expect(b.using).not.toHaveBeenCalled()
|
||||
expect(b.binding).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('publishes shortcut fork failures through the same latest-notice source as row actions', async () => {
|
||||
const b = await bench()
|
||||
onTestFinished(() => b.ctx.fiber.dispose())
|
||||
declare(b.slots, 'shell.overlay')
|
||||
const removeBrowser = b.slots.register({
|
||||
name: 'shell.overlay', id: 'test-sidebar-owner',
|
||||
children: { 'sidebar.workspaces': { kind: 'single', scope: 'root' } },
|
||||
}, SidebarDeclarationOwner)
|
||||
await b.ctx.plugin({ inject: [...inject], apply }).await()
|
||||
b.setSessions(sessionState([{ ...summary('source', 1), retainedBy: { mainView: 1 } }]))
|
||||
const browser = faceOf(b.slots.entries('sidebar.workspaces')[0]!) as WorkspaceBrowserInjected
|
||||
const toast = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected
|
||||
const warning = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
onTestFinished(() => { warning.mockRestore() })
|
||||
const invoke = () => {
|
||||
const resolution = b.commands.get('session.fork')!.resolve({ region: 'page', modal: null, target: null })
|
||||
if (resolution.status !== 'handled') throw new Error('the source must be available')
|
||||
resolution.run()
|
||||
}
|
||||
|
||||
browser.notifyArchivedNotOpenable()
|
||||
expect(toast.hooks.toast.getSnapshot()).toMatchObject({ kind: 'archivedNotOpenable' })
|
||||
b.fork.mockRejectedValueOnce(new SessionForkError(
|
||||
new RemoteError('session/fork-unavailable', 'no completed turn', { sessionId: sid('source') }), sid('source'),
|
||||
))
|
||||
invoke()
|
||||
await vi.waitFor(() => {
|
||||
expect(toast.hooks.toast.getSnapshot()).toMatchObject({ kind: 'shortcutForkFailed', reason: 'unavailable' })
|
||||
})
|
||||
expect(b.fork).toHaveBeenCalledExactlyOnceWith({ sessionId: sid('source'), increaseTitle: true })
|
||||
expect(warning).not.toHaveBeenCalled()
|
||||
const unavailable = toast.hooks.toast.getSnapshot()
|
||||
b.fork.mockRejectedValueOnce(new Error('connection closed'))
|
||||
invoke()
|
||||
await vi.waitFor(() => {
|
||||
expect(toast.hooks.toast.getSnapshot()).toMatchObject({ kind: 'shortcutForkFailed', reason: 'failed' })
|
||||
})
|
||||
expect(toast.hooks.toast.getSnapshot()).not.toBe(unavailable)
|
||||
expect(warning).toHaveBeenCalledExactlyOnceWith('session fork rejected:', expect.any(Error))
|
||||
const failure = toast.hooks.toast.getSnapshot()
|
||||
removeBrowser()
|
||||
expect(b.slots.entries('sidebar.workspaces')).toEqual([])
|
||||
expect(entry(b.slots, 'shell.overlay', 'workspace.row-toast').component).toBe(RowActionToast)
|
||||
expect(toast.hooks.toast.getSnapshot()).toBe(failure)
|
||||
browser.notifyArchivedNotOpenable()
|
||||
expect(toast.hooks.toast.getSnapshot()).toMatchObject({ kind: 'archivedNotOpenable' })
|
||||
toast.dismissToast()
|
||||
expect(toast.hooks.toast.getSnapshot()).toBeNull()
|
||||
expect(browser).not.toHaveProperty('dismissForkError')
|
||||
})
|
||||
|
||||
it('derives the pinned and archived Sets from the Workspace snapshot, rebuilt only when it changes', async () => {
|
||||
const b = await bench()
|
||||
b.setWorkspaces(workspaceState([workspace('alpha', ['one', 'two'])], [sid('two')], [sid('one')]))
|
||||
@@ -472,17 +564,19 @@ describe('ui-workspace apply', () => {
|
||||
unsubscribe()
|
||||
|
||||
expect(view.getSnapshot().archivedFilter).toBe('default')
|
||||
toast.showArchived()
|
||||
const archived = b.slots.entries('workspace.toast').find(row => row.options.key === 'archived')!
|
||||
const archiveDisplay = faceOf(archived) as ArchiveToastInjected
|
||||
archiveDisplay.filterAction(b.locale.bind('workspace'), toast.dismissToast).onClick()
|
||||
expect(view.getSnapshot().archivedFilter).toBe('show')
|
||||
|
||||
toast.undoArchive(sid('one'))
|
||||
archiveDisplay.display({ kind: 'archived', sessionId: sid('one'), seq: 1 }, b.locale.bind('workspace'), toast.dismissToast).actions![0]!.onClick()
|
||||
expect(unarchiveSession).toHaveBeenCalledWith('one')
|
||||
// A rejected undo is a console diagnostic.
|
||||
const rejection = new Error('unarchive exploded')
|
||||
unarchiveSession.mockRejectedValueOnce(rejection)
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
try {
|
||||
toast.undoArchive(sid('two'))
|
||||
archiveDisplay.display({ kind: 'archived', sessionId: sid('two'), seq: 2 }, b.locale.bind('workspace'), toast.dismissToast).actions![0]!.onClick()
|
||||
await vi.waitFor(() => { expect(warn).toHaveBeenCalledWith('session unarchive rejected:', rejection) })
|
||||
} finally {
|
||||
warn.mockRestore()
|
||||
@@ -594,7 +688,8 @@ describe('ui-workspace apply', () => {
|
||||
expect(b.retain).not.toHaveBeenCalled()
|
||||
expect(b.selectPanel).not.toHaveBeenCalled()
|
||||
toast.dismissToast()
|
||||
toast.openForkSource(sid('source'))
|
||||
;(faceOf(b.slots.entries('workspace.toast').find(row => row.options.key === 'forkRequiresOpen')!) as ToastDisplayInjected<'forkRequiresOpen'>)
|
||||
.display({ kind: 'forkRequiresOpen', sessionId: sid('source'), seq: 1 }, b.locale.bind('workspace'), toast.dismissToast).actions![0]!.onClick()
|
||||
expect(b.retain).toHaveBeenCalledExactlyOnceWith('source', { source: 'mainView' })
|
||||
expect(b.selectPanel).toHaveBeenCalledExactlyOnceWith(null)
|
||||
expect(b.fork).toHaveBeenCalledOnce()
|
||||
@@ -621,7 +716,8 @@ describe('ui-workspace apply', () => {
|
||||
if (timing === 'after the notice') b.setWorkspaces(workspaceState([], [sid('source')]))
|
||||
|
||||
toast.dismissToast()
|
||||
toast.openForkSource(sid('source'))
|
||||
;(faceOf(b.slots.entries('workspace.toast').find(row => row.options.key === 'forkRequiresOpen')!) as ToastDisplayInjected<'forkRequiresOpen'>)
|
||||
.display({ kind: 'forkRequiresOpen', sessionId: sid('source'), seq: 1 }, b.locale.bind('workspace'), toast.dismissToast).actions![0]!.onClick()
|
||||
|
||||
expect(toast.hooks.toast.getSnapshot()).toEqual({ kind: 'archivedNotOpenable', seq: 2 })
|
||||
expect(b.retain).not.toHaveBeenCalled()
|
||||
@@ -764,7 +860,7 @@ describe('ui-workspace apply', () => {
|
||||
declare(b.slots, 'sidebar.workspaces', 'conversation.hero.workspace', 'conversation.empty.workspace', 'shell.overlay')
|
||||
const fiber = b.ctx.plugin({ inject: [...inject], apply })
|
||||
await fiber.await()
|
||||
expect(b.slots.entries(MENU_ITEM)).toHaveLength(4)
|
||||
expect(b.slots.entries(MENU_ITEM)).toHaveLength(5)
|
||||
expect(b.slots.entries(ROW_ACTION)).toHaveLength(2)
|
||||
expect(b.slots.entries('shell.overlay')).toHaveLength(3)
|
||||
await fiber.dispose()
|
||||
@@ -776,5 +872,7 @@ describe('ui-workspace apply', () => {
|
||||
expect(b.slots.entries(MENU_ITEM)).toHaveLength(0)
|
||||
expect(b.slots.entries(ROW_ACTION)).toHaveLength(0)
|
||||
expect(b.slots.entries('shell.overlay')).toHaveLength(0)
|
||||
expect(b.slots.entries('workspace.toast')).toHaveLength(0)
|
||||
expect(b.slots.snapshot('factory:workspace.toast.content')).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -14,7 +14,7 @@ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
|
||||
* (session.spec.ts#rename), the entries' own arms with
|
||||
* session-actions.client.spec, the row's list rendering with rows.client.spec.
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest'
|
||||
import { act, cleanup, fireEvent, waitFor, within } from '@testing-library/react'
|
||||
import type { ISession } from '@deepseek-ai/dsh-api-session-controller/client'
|
||||
import type { WorkspaceId } from '@deepseek-ai/dsh-api-workspace-controller/client'
|
||||
@@ -111,7 +111,7 @@ describe('session rename through the assembled browser', () => {
|
||||
},
|
||||
)
|
||||
}
|
||||
// `order` places plugin rows after the shipped rows (100/200/300/400)
|
||||
// `order` places plugin rows after the shipped rows (100/200/300/400/450)
|
||||
// even when the later registration has the lower shadowing priority
|
||||
// assigned to dynamic browser packages; the first plugin row opens the
|
||||
// plugin group with a hairline.
|
||||
@@ -123,7 +123,7 @@ describe('session rename through the assembled browser', () => {
|
||||
const trigger = within(row as HTMLElement).getByLabelText('会话“Persisted title”的操作')
|
||||
fireEvent.click(trigger)
|
||||
expect(view.getAllByRole('menuitem').map(item => item.textContent)).toEqual([
|
||||
'置顶会话', '重命名', '分叉会话', '归档会话', 'Export action', 'Last action',
|
||||
'置顶会话', '重命名', '分叉会话', '归档会话', '复制 Session ID', 'Export action', 'Last action',
|
||||
])
|
||||
expect(view.getAllByRole('separator')).toHaveLength(1)
|
||||
const last = view.getByRole('menuitem', { name: 'Last action' })
|
||||
@@ -140,6 +140,18 @@ describe('session rename through the assembled browser', () => {
|
||||
expect(view.queryByRole('menu')).toBeNull()
|
||||
await act(async () => { await Promise.resolve() })
|
||||
expect(document.activeElement).toBe(trigger)
|
||||
const writeText = vi.fn(async () => {})
|
||||
const clipboard = Object.getOwnPropertyDescriptor(navigator, 'clipboard')
|
||||
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } })
|
||||
onTestFinished(() => {
|
||||
if (clipboard === undefined) Reflect.deleteProperty(navigator, 'clipboard')
|
||||
else Object.defineProperty(navigator, 'clipboard', clipboard)
|
||||
})
|
||||
fireEvent.click(trigger)
|
||||
fireEvent.click(view.getByRole('menuitem', { name: '复制 Session ID' }))
|
||||
expect(view.queryByRole('menu')).toBeNull()
|
||||
expect(writeText).toHaveBeenCalledExactlyOnceWith(SID)
|
||||
await view.findByText('Session ID 已复制')
|
||||
await runtime.dispose()
|
||||
})
|
||||
|
||||
|
||||
@@ -1,22 +1,25 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* The shipped Session row actions rendered directly with hand-built props:
|
||||
* the pin, rename, fork, and archive menu rows, the archive and pin hover
|
||||
* buttons, and the two `shell.overlay` surfaces they raise (rename dialog,
|
||||
* row notice). Every action reads its own injected hooks and calls its own
|
||||
* injected callbacks; what those callbacks do is apply.client.spec's
|
||||
* the menu rows, hover buttons, dialogs, and global notices. Every action
|
||||
* reads its own injected hooks and calls its own injected callbacks;
|
||||
* what those callbacks do is apply.client.spec's
|
||||
* subject. The browser and the slot machinery stay out; the assembled
|
||||
* chain lives in rename-assembly.client.spec.
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest'
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import type { SessionListState, SessionSummary } from '@deepseek-ai/dsh-api-session-controller/client'
|
||||
import type { WorkspaceId, WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client'
|
||||
import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
|
||||
import type { GlobalStandardProps, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import type { GlobalStandardProps, PropsLocale, PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import { bindSnapshotSelector, makeTranslate, SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
|
||||
import { registerToasts } from '../src/client/toast/register.ts'
|
||||
import { ArchiveToastEntry } from '../src/client/toast/Toast.tsx'
|
||||
import type { ArchiveToastEntryProps } from '../src/client/contract/toast.ts'
|
||||
import { en as commonEn } from '@deepseek-ai/dsh-client-locale/src/locales/en.ts'
|
||||
import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts'
|
||||
import type {
|
||||
@@ -30,6 +33,7 @@ import { ForkSessionMenuItem } from '../src/client/session-actions/ForkSession.t
|
||||
import { PinSessionMenuItem, PinSessionRowButton } from '../src/client/session-actions/PinSession.tsx'
|
||||
import { RenameSessionMenuItem, SessionRenameDialog } from '../src/client/session-actions/RenameSession.tsx'
|
||||
import { RowActionToast } from '../src/client/session-actions/RowActionToast.tsx'
|
||||
import { SessionIdMenuItem } from '../src/client/session-actions/SessionId.tsx'
|
||||
import { createWorkspaceViewStore } from '../src/client/stores.ts'
|
||||
import { en, zh } from '../src/client/locales.ts'
|
||||
import { ShortcutRegistry } from '../../shortcuts/src/client/registry.ts'
|
||||
@@ -109,6 +113,19 @@ function callOrder(fn: { mock: { invocationCallOrder: readonly number[] } }, nth
|
||||
return fn.mock.invocationCallOrder[nth] ?? Number.POSITIVE_INFINITY
|
||||
}
|
||||
|
||||
describe('Session ID action', () => {
|
||||
it.each([t, tEn])('dismisses the menu before copying the complete row ID', (translate) => {
|
||||
const { state, setMenuOpen } = openMenu()
|
||||
const sessionId = sid('session-c4421b66-252e-44c0-80ed-6e320abeba25')
|
||||
const copySessionId = vi.fn(async () => {})
|
||||
render(<SessionIdMenuItem {...menuRow(state)} sessionId={sessionId} t={translate} copySessionId={copySessionId} />)
|
||||
fireEvent.click(screen.getByRole('menuitem', { name: translate('menu.sessionId') }))
|
||||
expect(setMenuOpen).toHaveBeenCalledWith(false)
|
||||
expect(copySessionId).toHaveBeenCalledExactlyOnceWith(sessionId)
|
||||
expect(callOrder(setMenuOpen)).toBeLessThan(callOrder(copySessionId))
|
||||
})
|
||||
})
|
||||
|
||||
describe('pin action', () => {
|
||||
/** The pin share over fixed membership: the bound Set hooks and the two callbacks the entries call. */
|
||||
const pinShare = (pinned: readonly string[] = [], archived: readonly string[] = []) => ({
|
||||
@@ -488,9 +505,28 @@ declare module '@deepseek-ai/dsh-workspace/types' {
|
||||
}
|
||||
}
|
||||
|
||||
function ToastFrame({ renderSlot }: PropsRenderSlots<'shell.overlay'>) {
|
||||
return renderSlot('shell.overlay', {})
|
||||
}
|
||||
|
||||
describe('RowActionToast', () => {
|
||||
it('adds the archive filter action when the display mapping supplies no actions', () => {
|
||||
const instance = createWorkspaceViewStore().create()
|
||||
const dismissToast = vi.fn()
|
||||
const showArchived = vi.fn()
|
||||
const filter = { label: 'Show archived', onClick: showArchived }
|
||||
const renderFactorySlot = vi.fn<ArchiveToastEntryProps['renderFactorySlot']>(() => null)
|
||||
render(<ArchiveToastEntry {...standard} kind="archived" sessionId={ROW.sessionId} seq={1}
|
||||
t={t} useStore={bindSnapshotSelector(instance.store)} actions={instance.actions}
|
||||
dismissToast={dismissToast} renderFactorySlot={renderFactorySlot}
|
||||
display={() => ({ text: 'Archived', tone: 'success' })} filterAction={() => filter} />)
|
||||
expect(renderFactorySlot).toHaveBeenCalledWith('workspace.toast.content', {
|
||||
text: 'Archived', tone: 'success', actions: [filter], seq: 1, onDone: dismissToast,
|
||||
})
|
||||
})
|
||||
|
||||
/** The notice surface over a test-owned notice source; dismissal clears the notice the way apply does. */
|
||||
function toastSurface(
|
||||
async function toastSurface(
|
||||
viewState: { archivedFilter?: 'default' | 'show' | 'only' } = { archivedFilter: 'default' },
|
||||
translate = t,
|
||||
) {
|
||||
@@ -506,28 +542,59 @@ describe('RowActionToast', () => {
|
||||
const undoArchive = vi.fn()
|
||||
const showArchived = vi.fn()
|
||||
const openForkSource = vi.fn()
|
||||
render(
|
||||
<RowActionToast
|
||||
{...overlay}
|
||||
t={translate}
|
||||
useToast={bindSnapshotSelector(toast)}
|
||||
useStore={bindSnapshotSelector(view)}
|
||||
actions={instance.actions}
|
||||
dismissToast={dismissToast}
|
||||
undoArchive={undoArchive}
|
||||
showArchived={showArchived}
|
||||
openForkSource={openForkSource}
|
||||
/>,
|
||||
)
|
||||
const runtime = await SlotTestRuntime.create()
|
||||
onTestFinished(() => runtime.dispose())
|
||||
const locale = new LocaleRuntime(runtime.ctx)
|
||||
locale.setLocale(translate === tEn ? 'en' : 'zh')
|
||||
locale.register('workspace', { en, zh })
|
||||
runtime.ctx.provide('locale', locale)
|
||||
runtime.slots.installLocale(locale)
|
||||
await runtime.root.declare({ 'shell.overlay': { kind: 'list', scope: 'root' } }, ToastFrame)
|
||||
registerToasts(runtime.ctx, {
|
||||
...createWorkspaceViewStore(),
|
||||
create: () => ({
|
||||
...instance, store: view,
|
||||
getSnapshot: () => view.getSnapshot(),
|
||||
subscribe: listener => view.subscribe(listener),
|
||||
}),
|
||||
}, {
|
||||
undoArchive, showArchived, openForkSource,
|
||||
})
|
||||
runtime.slots.register({
|
||||
name: 'shell.overlay', id: 'workspace.row-toast',
|
||||
children: { 'workspace.toast': { kind: 'keyed', scope: 'root' } },
|
||||
inject: () => ({ hooks: { toast }, dismissToast }),
|
||||
}, RowActionToast)
|
||||
runtime.renderRoot()
|
||||
let seq = 0
|
||||
const notify = (notice: RowToast): void => {
|
||||
act(() => { toast.set({ ...notice, seq: ++seq }) })
|
||||
}
|
||||
return { dismissToast, undoArchive, showArchived, openForkSource, notify }
|
||||
return { dismissToast, undoArchive, showArchived, openForkSource, notify, locale, view }
|
||||
}
|
||||
|
||||
it('renders nothing without a notice', () => {
|
||||
toastSurface()
|
||||
it('updates locale and archive actions without restarting the same notice', async () => {
|
||||
const { notify, locale, view, dismissToast } = await toastSurface()
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
notify({ kind: 'archived', sessionId: sid('one') })
|
||||
const alert = screen.getByRole('alert')
|
||||
act(() => { vi.advanceTimersByTime(3000) })
|
||||
act(() => { locale.setLocale('en'); view.set({ ...view.getSnapshot(), archivedFilter: 'show' }) })
|
||||
expect(screen.getByRole('alert')).toBe(alert)
|
||||
expect(alert.textContent).toContain('Session archived')
|
||||
expect(screen.queryByRole('button', { name: 'filter archived sessions' })).toBeNull()
|
||||
act(() => { vi.advanceTimersByTime(3999) })
|
||||
expect(dismissToast).not.toHaveBeenCalled()
|
||||
act(() => { vi.advanceTimersByTime(1) })
|
||||
expect(dismissToast).toHaveBeenCalledOnce()
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('renders nothing without a notice', async () => {
|
||||
await toastSurface()
|
||||
expect(screen.queryByRole('alert')).toBeNull()
|
||||
expect(document.body.textContent).toBe('')
|
||||
})
|
||||
@@ -535,8 +602,8 @@ describe('RowActionToast', () => {
|
||||
it.each([
|
||||
['zh', t, '请先打开原会话完成迁移,再创建分支', '打开原会话'],
|
||||
['en', tEn, 'Open the original session to complete migration before creating a branch.', 'Open original session'],
|
||||
] as const)('keeps the %s fork notice after menu unmount and opens only on its action', (_locale, translate, message, action) => {
|
||||
const { dismissToast, openForkSource, notify } = toastSurface(undefined, translate)
|
||||
] as const)('keeps the %s fork notice after menu unmount and opens only on its action', async (_locale, translate, message, action) => {
|
||||
const { dismissToast, openForkSource, notify } = await toastSurface(undefined, translate)
|
||||
const { state, setMenuOpen } = openMenu()
|
||||
const forkSession = vi.fn((sessionId: SessionId) => { notify({ kind: 'forkRequiresOpen', sessionId }) })
|
||||
const menu = render(<ForkSessionMenuItem {...menuRow(state)} t={translate} forkSession={forkSession} />)
|
||||
@@ -558,16 +625,73 @@ describe('RowActionToast', () => {
|
||||
expect(screen.queryByRole('alert')).toBeNull()
|
||||
})
|
||||
|
||||
it('the stopped-and-archived notice offers the same undo and filter actions under its own wording', () => {
|
||||
const { undoArchive, notify } = toastSurface()
|
||||
it.each([t, tEn])('reports clipboard success and failure through the global toast', async (translate) => {
|
||||
const { notify } = await toastSurface(undefined, translate)
|
||||
notify({ kind: 'sessionIdCopied' })
|
||||
expect(screen.getByRole('alert').textContent).toBe(translate('toast.sessionIdCopied'))
|
||||
notify({ kind: 'sessionIdCopyFailed' })
|
||||
expect(screen.getByRole('alert').textContent).toBe(translate('toast.sessionIdCopyFailed'))
|
||||
})
|
||||
|
||||
it.each([t, tEn])('replaces other notices with plain shortcut fork failures and only keeps the latest', async (translate) => {
|
||||
const { dismissToast, notify } = await toastSurface(undefined, translate)
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
notify({ kind: 'archived', sessionId: sid('one') })
|
||||
act(() => { vi.advanceTimersByTime(1000) })
|
||||
notify({ kind: 'shortcutForkFailed', reason: 'unavailable' })
|
||||
const first = screen.getByRole('alert')
|
||||
expect(first.textContent).toBe(translate('shortcut.noCompletedTurn'))
|
||||
expect(first.querySelector('svg')).toBeNull()
|
||||
expect(first.querySelector('button')).toBeNull()
|
||||
act(() => { vi.advanceTimersByTime(3000) })
|
||||
expect(screen.getByRole('alert')).toBe(first)
|
||||
notify({ kind: 'shortcutForkFailed', reason: 'failed' })
|
||||
const retry = screen.getByRole('alert')
|
||||
expect(retry).not.toBe(first)
|
||||
expect(retry.textContent).toBe(translate('shortcut.forkFailed'))
|
||||
expect(retry.querySelector('svg')).toBeNull()
|
||||
act(() => { vi.advanceTimersByTime(3999) })
|
||||
expect(screen.getAllByRole('alert')).toEqual([retry])
|
||||
expect(dismissToast).not.toHaveBeenCalled()
|
||||
act(() => { vi.advanceTimersByTime(1) })
|
||||
expect(dismissToast).toHaveBeenCalledOnce()
|
||||
expect(screen.queryByRole('alert')).toBeNull()
|
||||
|
||||
notify({ kind: 'shortcutForkFailed', reason: 'failed' })
|
||||
act(() => { vi.advanceTimersByTime(1000) })
|
||||
notify({ kind: 'sessionIdCopied' })
|
||||
const latest = screen.getByRole('alert')
|
||||
expect(latest.textContent).toBe(translate('toast.sessionIdCopied'))
|
||||
act(() => { vi.advanceTimersByTime(3000) })
|
||||
expect(screen.getAllByRole('alert')).toEqual([latest])
|
||||
expect(dismissToast).toHaveBeenCalledOnce()
|
||||
act(() => { vi.advanceTimersByTime(1000) })
|
||||
expect(screen.queryByRole('alert')).toBeNull()
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('the stopped-and-archived notice offers the same undo and filter actions under its own wording', async () => {
|
||||
const { dismissToast, undoArchive, showArchived, notify } = await toastSurface()
|
||||
notify({ kind: 'stoppedAndArchived', sessionId: sid('one') })
|
||||
expect(screen.getByRole('alert').textContent).toBe('已停止并归档,可撤销或筛选已归档会话')
|
||||
fireEvent.click(screen.getByRole('button', { name: '撤销' }))
|
||||
expect(undoArchive).toHaveBeenCalledWith(sid('one'))
|
||||
expect(callOrder(dismissToast)).toBeLessThan(callOrder(undoArchive))
|
||||
|
||||
notify({ kind: 'stoppedAndArchived', sessionId: sid('two') })
|
||||
fireEvent.click(screen.getByRole('button', { name: '筛选已归档会话' }))
|
||||
expect(dismissToast).toHaveBeenCalledTimes(2)
|
||||
expect(showArchived).toHaveBeenCalledOnce()
|
||||
expect(callOrder(dismissToast, 1)).toBeLessThan(callOrder(showArchived))
|
||||
expect(undoArchive).toHaveBeenCalledOnce()
|
||||
expect(screen.queryByRole('alert')).toBeNull()
|
||||
})
|
||||
|
||||
it('the archived notice takes itself down, then undoes the archive or shows the archived rows', () => {
|
||||
const { dismissToast, undoArchive, showArchived, notify } = toastSurface()
|
||||
it('the archived notice takes itself down, then undoes the archive or shows the archived rows', async () => {
|
||||
const { dismissToast, undoArchive, showArchived, notify } = await toastSurface()
|
||||
notify({ kind: 'archived', sessionId: sid('one') })
|
||||
expect(screen.getByRole('alert').textContent).toBe('会话已归档,可撤销或筛选已归档会话')
|
||||
fireEvent.click(screen.getByRole('button', { name: '撤销' }))
|
||||
@@ -586,14 +710,14 @@ describe('RowActionToast', () => {
|
||||
expect(screen.queryByRole('alert')).toBeNull()
|
||||
})
|
||||
|
||||
it('treats a view without a persisted filter as the hidden default and keeps the filter action', () => {
|
||||
const { notify } = toastSurface({})
|
||||
it('treats a view without a persisted filter as the hidden default and keeps the filter action', async () => {
|
||||
const { notify } = await toastSurface({})
|
||||
notify({ kind: 'archived', sessionId: sid('one') })
|
||||
expect(screen.getByRole('alert').textContent).toBe('会话已归档,可撤销或筛选已归档会话')
|
||||
})
|
||||
|
||||
it.each(['show', 'only'] as const)('omits the filter action while the %s filter already shows archived rows', (archivedFilter) => {
|
||||
const { notify } = toastSurface({ archivedFilter })
|
||||
it.each(['show', 'only'] as const)('omits the filter action while the %s filter already shows archived rows', async (archivedFilter) => {
|
||||
const { notify } = await toastSurface({ archivedFilter })
|
||||
notify({ kind: 'archived', sessionId: sid('one') })
|
||||
expect(screen.getByRole('alert').textContent).toBe('会话已归档,可撤销')
|
||||
expect(screen.queryByRole('button', { name: '筛选已归档会话' })).toBeNull()
|
||||
@@ -605,10 +729,10 @@ describe('RowActionToast', () => {
|
||||
['unpinFailed', '取消置顶失败,请稍后重试'],
|
||||
['archivedNotOpenable', '已归档对话暂时无法查看,请取消归档后查看'],
|
||||
['defaultWorkspaceFailed', '无法创建默认工作区,请通过“选择工作区”选择文件夹'],
|
||||
] as const)('shows the %s warning and takes it down when its hold ends', (kind, text) => {
|
||||
] as const)('shows the %s warning and takes it down when its hold ends', async (kind, text) => {
|
||||
const { dismissToast, notify } = await toastSurface()
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
const { dismissToast, notify } = toastSurface()
|
||||
notify({ kind })
|
||||
const alert = screen.getByRole('alert')
|
||||
expect(alert.textContent).toBe(text)
|
||||
@@ -621,10 +745,10 @@ describe('RowActionToast', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('shows a refused creation with the Host reason and holds it as long as the archived notice', () => {
|
||||
it('shows a refused creation with the Host reason and holds it as long as the archived notice', async () => {
|
||||
const { dismissToast, notify } = await toastSurface()
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
const { dismissToast, notify } = toastSurface()
|
||||
notify({ kind: 'createFailed', message: 'agent-preset/invalid: agent-presets: preset "broken" failed to mount' })
|
||||
const alert = screen.getByRole('alert')
|
||||
expect(alert.textContent).toBe('新建会话失败:agent-preset/invalid: agent-presets: preset "broken" failed to mount')
|
||||
@@ -639,10 +763,10 @@ describe('RowActionToast', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('the archived notice holds longer than a plain notice, and a repeat restarts its hold', () => {
|
||||
it('the archived notice holds longer than a plain notice, and a repeat restarts its hold', async () => {
|
||||
const { dismissToast, notify } = await toastSurface()
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
const { dismissToast, notify } = toastSurface()
|
||||
notify({ kind: 'archived', sessionId: sid('one') })
|
||||
act(() => { vi.advanceTimersByTime(4000) })
|
||||
expect(screen.getByRole('alert')).toBeTruthy()
|
||||
|
||||
@@ -54,14 +54,16 @@ async function bench(runtime: 'web' | 'desktop' = 'desktop', platform: ShortcutP
|
||||
startSession: vi.fn(), forkSession: vi.fn(async () => 'fork-child' as SessionId), archiveSession: vi.fn(async (_sessionId: SessionId) => {}),
|
||||
}
|
||||
const controls = createWorkspaceShortcutControls()
|
||||
const reportForkFailure = vi.fn()
|
||||
const fiber = ctx.plugin((scoped) => {
|
||||
installWorkspaceShortcuts(scoped, navigation, controls, (id) => { void navigation.archiveSession(id) })
|
||||
installWorkspaceShortcuts(scoped, navigation, controls,
|
||||
(id) => { void navigation.archiveSession(id) }, reportForkFailure)
|
||||
})
|
||||
await fiber.await()
|
||||
const select = (id: string) => { list.set({ ...list.getSnapshot(), byId: {
|
||||
[sid('a')]: row('a', id === 'a'), [sid('b')]: row('b', id === 'b'),
|
||||
} }) }
|
||||
return { ctx, fiber, registry, commands, navigation, controls, list, directory, select, history, loadOlder, panelInfo }
|
||||
return { ctx, fiber, registry, commands, navigation, controls, reportForkFailure, list, directory, select, history, loadOlder, panelInfo }
|
||||
}
|
||||
|
||||
afterEach(() => { vi.restoreAllMocks() })
|
||||
@@ -188,12 +190,11 @@ describe('workspace shortcut ownership', () => {
|
||||
))
|
||||
const invoke = () => b.registry.dispatch(key('KeyF', { alt: true }), context, vi.fn())
|
||||
expect(invoke().status).toBe('handled')
|
||||
await vi.waitFor(() => { expect(b.controls.state.getSnapshot().forkError).toMatchObject({ reason: 'unavailable' }) })
|
||||
await vi.waitFor(() => { expect(b.reportForkFailure).toHaveBeenCalledExactlyOnceWith('unavailable') })
|
||||
expect(warning).not.toHaveBeenCalled()
|
||||
b.controls.dismissForkError()
|
||||
b.navigation.forkSession.mockRejectedValueOnce(new Error('connection closed'))
|
||||
expect(invoke().status).toBe('handled')
|
||||
await vi.waitFor(() => { expect(b.controls.state.getSnapshot().forkError).toMatchObject({ reason: 'failed' }) })
|
||||
await vi.waitFor(() => { expect(b.reportForkFailure).toHaveBeenNthCalledWith(2, 'failed') })
|
||||
expect(warning).toHaveBeenCalledOnce()
|
||||
b.list.set({ ...b.list.getSnapshot(), byId: { [sid('a')]: { ...row('a', true), running: true } } })
|
||||
expect(invoke().status).toBe('handled')
|
||||
|
||||
@@ -11,13 +11,12 @@ import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/c
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { MainPanelId } from '@deepseek-ai/dsh-client-ui-layout/client'
|
||||
import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts'
|
||||
import { en as commonEn } from '@deepseek-ai/dsh-client-locale/src/locales/en.ts'
|
||||
import type { DirectoryFlowOwnerProps, WorkspaceBrowserProps } from '../src/client/contract/slots.ts'
|
||||
import { createWorkspaceShortcutControls } from '../src/client/shortcuts.ts'
|
||||
import { createWorkspaceViewStore, FLAT_SESSION_ORDER_KEY } from '../src/client/stores.ts'
|
||||
import { UNGROUPED_KEY } from '../src/client/tree.ts'
|
||||
import { WorkspaceBrowser } from '../src/client/rows/WorkspaceBrowser.tsx'
|
||||
import { en, zh } from '../src/client/locales.ts'
|
||||
import { zh } from '../src/client/locales.ts'
|
||||
|
||||
// Every fixture carries the resource hook the resources plugin merges into GlobalStandardProps.
|
||||
const useResource = (() => ({ status: 'none' as const, value: undefined, failure: undefined, reload: () => {} })) as GlobalStandardProps['useResource']
|
||||
@@ -114,7 +113,6 @@ function mount(overrides: Partial<WorkspaceBrowserProps> = {}) {
|
||||
closeAddWorkspace: controls.closeAdd,
|
||||
setDirectoryBusy: controls.directoryBusy,
|
||||
requestSessionRename: controls.rename,
|
||||
dismissForkError: controls.dismissForkError,
|
||||
wide: true,
|
||||
expandSidebar: vi.fn(),
|
||||
useSessions: hook(sessionState([])),
|
||||
@@ -151,19 +149,6 @@ function rerender(b: ReturnType<typeof mount>, overrides: Partial<WorkspaceBrows
|
||||
}
|
||||
|
||||
describe('WorkspaceBrowser', () => {
|
||||
it.each([{ messages: en, common: commonEn }, { messages: zh, common: commonZh }])('shows localized fork failures and dismisses them', ({ messages, common }) => {
|
||||
const b = mount({ t: makeTranslate(messages, common) })
|
||||
act(() => { b.controls.forkFailed('unavailable') })
|
||||
const first = screen.getByRole('alert')
|
||||
expect(first.textContent).toBe(messages['shortcut.noCompletedTurn'])
|
||||
act(() => { b.controls.dismissForkError(); b.controls.forkFailed('unavailable') })
|
||||
expect(screen.getByRole('alert')).not.toBe(first)
|
||||
act(() => { b.controls.forkFailed('failed') })
|
||||
expect(screen.getByRole('alert').textContent).toBe(messages['shortcut.forkFailed'])
|
||||
act(() => { b.controls.dismissForkError() })
|
||||
expect(screen.queryByRole('alert')).toBeNull()
|
||||
})
|
||||
|
||||
it.each(['workspace', 'flat', 'ungrouped'] as const)('keeps %s recency independent of arrival order and saved manual positions', (mode) => {
|
||||
localStorage.clear()
|
||||
const preferences = createWorkspaceViewStore().create()
|
||||
|
||||
@@ -783,7 +783,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
],
|
||||
replaceRisk: 'shadows-shipped-ui',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.workspace.directoryFlow\', () => ctx.slots.register(\n { name: \'conversation.hero.workspace.directoryFlow\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-workspace/src/client/contract/slots.ts:118',
|
||||
source: 'packages/client/ui-workspace/src/client/contract/slots.ts:119',
|
||||
},
|
||||
{
|
||||
key: 'conversation.input.activity',
|
||||
@@ -3871,7 +3871,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
],
|
||||
replaceRisk: 'none',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'sidebar.session.row.hover\', () => ctx.slots.register(\n { name: \'sidebar.session.row.hover\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-workspace/src/client/contract/slots.ts:135',
|
||||
source: 'packages/client/ui-workspace/src/client/contract/slots.ts:136',
|
||||
},
|
||||
{
|
||||
key: 'sidebar.session.row.leading',
|
||||
@@ -3923,7 +3923,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
],
|
||||
replaceRisk: 'none',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'sidebar.session.row.leading\', () => ctx.slots.register(\n { name: \'sidebar.session.row.leading\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-workspace/src/client/contract/slots.ts:130',
|
||||
source: 'packages/client/ui-workspace/src/client/contract/slots.ts:131',
|
||||
},
|
||||
{
|
||||
key: 'sidebar.settings',
|
||||
@@ -4046,14 +4046,14 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
],
|
||||
replaceRisk: 'shadows-shipped-ui',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'sidebar.workspaces.directoryFlow\', () => ctx.slots.register(\n { name: \'sidebar.workspaces.directoryFlow\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-workspace/src/client/contract/slots.ts:120',
|
||||
source: 'packages/client/ui-workspace/src/client/contract/slots.ts:121',
|
||||
},
|
||||
{
|
||||
key: 'sidebar.workspaces.session.menu.item',
|
||||
kind: 'list',
|
||||
scope: 'root',
|
||||
summary: 'The rows of one Session\'s "..." menu, in ascending `order`.',
|
||||
doc: 'The rows of one Session\'s "..." menu, in ascending `order`. ui-workspace\nregisters the shipped rows here — `pin` (100), `rename` (200), `fork`\n(300), `archive` (400) — so a plugin row is placed by its own `order`\namong them. Use a package-namespaced `id`; reusing a shipped id at\nanother `priority` shadows that row. Each entry renders one\n`role="menuitem"` `<button>` (the shipped rows use ui-primitives\'\n`MenuItemButton`, which adds the host styling and `separatorBefore`),\ndecides its own visibility from its own state, and dismisses the menu\nthrough the injected `useMenuOpenState` hook after acting; the list\'s\nkeyboard walk and focus return read the DOM, so any such button joins\nthem. Labels come from the contributing package\'s locale namespace.',
|
||||
doc: 'The rows of one Session\'s "..." menu, in ascending `order`. ui-workspace\nregisters the shipped rows here — `pin` (100), `rename` (200), `fork`\n(300), `archive` (400), and `session-id` (450) — so a plugin row is placed\nby its own `order` among them. Use a package-namespaced `id`; reusing a shipped id at\nanother `priority` shadows that row. Each entry renders one\n`role="menuitem"` `<button>` (the shipped rows use ui-primitives\'\n`MenuItemButton`, which adds the host styling and `separatorBefore`),\ndecides its own visibility from its own state, and dismisses the menu\nthrough the injected `useMenuOpenState` hook after acting; the list\'s\nkeyboard walk and focus return read the DOM, so any such button joins\nthem. Labels come from the contributing package\'s locale namespace.',
|
||||
registerOptions: [
|
||||
{
|
||||
name: 'id',
|
||||
@@ -4098,10 +4098,11 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
'client-ui-workspace RenameSessionMenuItem id \'rename\'',
|
||||
'client-ui-workspace ForkSessionMenuItem id \'fork\'',
|
||||
'client-ui-workspace ArchiveSessionMenuItem id \'archive\'',
|
||||
'client-ui-workspace SessionIdMenuItem id \'session-id\'',
|
||||
],
|
||||
replaceRisk: 'none',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n const copyLabel = \'Copy Session ID\' // Localize in the contributing package.\n ctx.slots.inject(\'sidebar.workspaces.session.menu.item\', () => ctx.slots.register(\n { name: \'sidebar.workspaces.session.menu.item\', id: \'copy-session-id\', order: 500 },\n ({ sessionId, useMenuOpenState }) => {\n const [, setMenuOpen] = useMenuOpenState()\n return React.createElement(\n \'button\',\n { type: \'button\', role: \'menuitem\', onClick: () => { setMenuOpen(false); void navigator.clipboard.writeText(sessionId) } },\n copyLabel,\n )\n },\n ))\n },\n}',
|
||||
source: 'packages/client/ui-workspace/src/client/contract/slots.ts:167',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n const copyLabel = \'Copy session title\' // Localize in the contributing package.\n ctx.slots.inject(\'sidebar.workspaces.session.menu.item\', () => ctx.slots.register(\n { name: \'sidebar.workspaces.session.menu.item\', id: \'copy-session-title\', order: 500 },\n ({ displayTitle, useMenuOpenState }) => {\n const [, setMenuOpen] = useMenuOpenState()\n return React.createElement(\n \'button\',\n {\n type: \'button\', role: \'menuitem\',\n onClick: () => { setMenuOpen(false); void navigator.clipboard.writeText(displayTitle) },\n },\n copyLabel,\n )\n },\n ))\n },\n}',
|
||||
source: 'packages/client/ui-workspace/src/client/contract/slots.ts:171',
|
||||
},
|
||||
{
|
||||
key: 'sidebar.workspaces.session.row.action',
|
||||
@@ -4154,7 +4155,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
],
|
||||
replaceRisk: 'none',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'sidebar.workspaces.session.row.action\', () => ctx.slots.register(\n { name: \'sidebar.workspaces.session.row.action\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-workspace/src/client/contract/slots.ts:185',
|
||||
source: 'packages/client/ui-workspace/src/client/contract/slots.ts:189',
|
||||
},
|
||||
{
|
||||
key: 'tool.call.images',
|
||||
@@ -4354,5 +4355,55 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'tool.view.cordis\', () => ctx.slots.register(\n { name: \'tool.view.cordis\', key: \'<one key the owner dispatches>\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/extensions/ui-cordis/src/client/slots.ts:31',
|
||||
},
|
||||
{
|
||||
key: 'workspace.toast',
|
||||
kind: 'keyed',
|
||||
scope: 'root',
|
||||
summary: 'Workspace notices selected by their existing business discriminator.',
|
||||
doc: 'Workspace notices selected by their existing business discriminator.',
|
||||
registerOptions: [
|
||||
{
|
||||
name: 'key',
|
||||
requirement: 'required',
|
||||
type: 'string',
|
||||
doc: 'Your cell key: the entry renders where the owner dispatches this exact key. Registering an already-occupied key replaces that occupant.',
|
||||
},
|
||||
],
|
||||
ownerProps: [
|
||||
'/** Owner operations available to every keyed Workspace notice. */\nexport interface WorkspaceToastOwnerProps {\n /** Dismiss the displayed notice. */\n dismissToast: () => void\n}',
|
||||
],
|
||||
ownerPropsReferences: [
|
||||
'Workspace',
|
||||
],
|
||||
standardProps: [
|
||||
'useResource: UseResource',
|
||||
'useWorkspaces: SnapshotSelectorHook<WorkspaceSnapshot>',
|
||||
'usePanelInfo: UsePanelInfo',
|
||||
'useSessions: UseSessions',
|
||||
'useSessionStatus: UseSessionStatus',
|
||||
'useSessionRetainInfo: UseSessionRetainInfo',
|
||||
'useWorkspaces: SnapshotSelectorHook<WorkspaceSnapshot>',
|
||||
],
|
||||
keyDomain: 'fixed by the owner\'s key table { [K in ToastKind]: ToastNotice<K> }, already taken: archived, archivedNotOpenable, createFailed, defaultWorkspaceFailed, forkRequiresOpen, pinFailed, sessionIdCopied, sessionIdCopyFailed, shortcutForkFailed, stoppedAndArchived, unpinFailed',
|
||||
hookContext: '',
|
||||
slotInject: '',
|
||||
declaredBy: 'an entry in \'shell.overlay\' (client-ui-workspace), so it exists while that entry is mounted',
|
||||
occupants: [
|
||||
'client-ui-workspace ToastEntry<PropsRuntime<\'workspace.toast\', \'sessionIdCopi… key \'sessionIdCopied\'',
|
||||
'client-ui-workspace ToastEntry<PropsRuntime<\'workspace.toast\', \'sessionIdCopy… key \'sessionIdCopyFailed\'',
|
||||
'client-ui-workspace ToastEntry<PropsRuntime<\'workspace.toast\', \'pinFailed\'>> key \'pinFailed\'',
|
||||
'client-ui-workspace ToastEntry<PropsRuntime<\'workspace.toast\', \'unpinFailed\'>> key \'unpinFailed\'',
|
||||
'client-ui-workspace ToastEntry<PropsRuntime<\'workspace.toast\', \'archivedNotOp… key \'archivedNotOpenable\'',
|
||||
'client-ui-workspace ToastEntry<PropsRuntime<\'workspace.toast\', \'defaultWorksp… key \'defaultWorkspaceFailed\'',
|
||||
'client-ui-workspace ToastEntry<PropsRuntime<\'workspace.toast\', \'shortcutForkF… key \'shortcutForkFailed\'',
|
||||
'client-ui-workspace ToastEntry<PropsRuntime<\'workspace.toast\', \'createFailed\'>> key \'createFailed\'',
|
||||
'client-ui-workspace ToastEntry<PropsRuntime<\'workspace.toast\', \'forkRequiresO… key \'forkRequiresOpen\'',
|
||||
'client-ui-workspace ArchiveToastEntry key \'archived\'',
|
||||
'client-ui-workspace ArchiveToastEntry key \'stoppedAndArchived\'',
|
||||
],
|
||||
replaceRisk: 'shadows-shipped-ui',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'workspace.toast\', () => ctx.slots.register(\n { name: \'workspace.toast\', key: \'<one key the owner dispatches>\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-workspace/src/client/contract/toast.ts:53',
|
||||
},
|
||||
]
|
||||
/* jscpd:ignore-end */
|
||||
@@ -9,8 +9,8 @@
|
||||
en: 7a12adba4e7766e3
|
||||
zh: f6d5c8374f4512c8
|
||||
/deepseek-ai-dsh-workspace/summary:
|
||||
en: 58d66b238882b849
|
||||
zh: a427930afd293c6b
|
||||
en: 30aea62cabd8e8a8
|
||||
zh: b22b30ef08fd4713
|
||||
/deepseek-ai-dsh-workspace/table-of-contents:
|
||||
en: d152484eb41ac6b4
|
||||
zh: 09388d293f9be9cb
|
||||
@@ -30,8 +30,8 @@
|
||||
en: 217475057b6506ed
|
||||
zh: be2312a29499c203
|
||||
/deepseek-ai-dsh-workspace/use-this-package/grouping-sessions-under-a-project:
|
||||
en: 510be21d012de28c
|
||||
zh: fdcb05447d6ba93c
|
||||
en: 5a68da22516a6a3c
|
||||
zh: a229d57acdab882c
|
||||
/deepseek-ai-dsh-workspace/use-this-package/hiding-and-restoring-sessions-and-removing-projects:
|
||||
en: 7b298aa5c48501d4
|
||||
zh: 8ffeec728c1c13fe
|
||||
@@ -39,8 +39,8 @@
|
||||
en: 447ced401b3b14a8
|
||||
zh: 3ce2105605223945
|
||||
/deepseek-ai-dsh-workspace/understand-the-implementation/design-philosophy:
|
||||
en: e8ff536e19566447
|
||||
zh: 53ba4c15f10c1549
|
||||
en: e969314497b99389
|
||||
zh: 82eafc832617a1eb
|
||||
/deepseek-ai-dsh-workspace/understand-the-implementation/api-behavior:
|
||||
en: 69327adb9ea52680
|
||||
zh: fa32eea5019c7abb
|
||||
@@ -75,8 +75,8 @@
|
||||
en: 524afbded27fb06b
|
||||
zh: 9dcf8539495e9c68
|
||||
/deepseek-ai-dsh-workspace/known-limitations-and-deferred-work:
|
||||
en: 85694227357bbd7c
|
||||
zh: 16ad935226c51022
|
||||
en: 1a9c71a3dbfc4506
|
||||
zh: 87b57414053f4d00
|
||||
/deepseek-ai-dsh-workspace/known-limitations-and-deferred-work/dev-note:
|
||||
en: ac1d08360a93382b
|
||||
zh: 6c58749bae9a6e65
|
||||
|
||||
@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
|
||||
|
||||
## Summary
|
||||
|
||||
Use this package to keep an ordered, persistent list of project directories and the sessions run in each directory. Hosts can build project sidebars, hide sessions from grouping without deleting their histories, and remove projects without deleting folders, files, or sessions. Re-adding a removed directory creates a fresh project, while sessions whose directories cannot be validated remain ungrouped. Choose it for GUI or host workflows that need durable project grouping; it is invisible to models and adds no prompt or request-context cost, but requires session persistence and storage backends.
|
||||
Use this package to keep an ordered, persistent list of project directories and the sessions run in each directory. Hosts can build project sidebars, hide sessions from grouping without deleting their histories, and remove projects without deleting folders, files, or sessions. Re-adding a removed directory creates a fresh project; an existing project's sessions stay grouped when its directory disappears. Choose it for GUI or host workflows that need durable project grouping; it is invisible to models and adds no prompt or request-context cost, but requires session persistence and storage backends.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
@@ -70,7 +70,7 @@ The first successful registration records its identity durably. Repeated calls r
|
||||
|
||||
### 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.
|
||||
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 new session must have a recorded directory that resolves to the project's directory. Already-accounted sessions keep their project and order when their fully qualified recorded path is missing, including a dangling symlink; renaming or reordering the project does not remove that ownership. Missing headers, invalid recorded paths, existing mismatched directories, and filesystem failures other than ENOENT remain excluded. Keeping ownership does not recreate the directory or relax new-session attachment, so a fork can still fail to attach while the directory is missing.
|
||||
|
||||
### Hiding and restoring sessions, and removing projects
|
||||
|
||||
@@ -91,7 +91,7 @@ This section explains the design decisions behind the feature and points at the
|
||||
### Design philosophy
|
||||
|
||||
- **One record per canonical path.** `fs.realpath` is the single uniqueness canon: paths are stored canonicalized, so a symlink to an owned directory collides, and uniqueness is string equality of canonical paths.
|
||||
- **Membership is ownership plus a live cwd fact.** The record's ordered `sessionIds` is the ownership truth; the startup header index validates it, and `sessionIds` filters on read while the next mutation prunes durably.
|
||||
- **Membership starts from the recorded account.** The header index validates ordered `sessionIds`; missing-directory candidates retain their account, while other invalid candidates are filtered on read and pruned by the next mutation. The strict canonical-path index used for history bootstrap includes existing directories only.
|
||||
- **Header-only reads.** Bootstrap and attach validation read `SessionHeader` fields only; event bodies are never loaded.
|
||||
- **Two-write mutations with an explicit marker.** Create and delete persist a `pendingMutation` marker before the record/order pair can diverge, so startup completes exactly the interrupted operation and unmarked divergence fails loud as corruption.
|
||||
- **Serialized writes.** Registry operations run on one operation chain; entity mutations go through `table.update` on the domain write chain, stamping `updatedAt` and deciding membership at their chain slot.
|
||||
@@ -166,7 +166,7 @@ Independent of live requests: the package never touches a request prefix, so it
|
||||
These limits define when the project list is a poor fit or needs special operational care. They are current package constraints, not a task backlog.
|
||||
|
||||
- **Removal never deletes data** — removing a project leaves its folder, files, and session histories in place; those sessions become ungrouped, and session deletion or folder removal are separate, absent capabilities.
|
||||
- **A session joins only with a recorded directory** — a session belongs to a project only when its record carries a directory that resolves to the project's path; sessions without one stay ungrouped, and a session from another directory cannot be moved in.
|
||||
- **Missing paths retain recorded ownership, not verified symlink history** — a removed symlink and an incorrect but missing absolute cwd cannot be distinguished from existing records; both preserve an already-accounted id. No unaccounted session is assigned by this exception, and an account already removed from storage is not reconstructed.
|
||||
- **External changes are seen late** — if another process deletes or damages a directory, the project reflects it only at the next refresh or restart.
|
||||
- **Archive and unarchive enforce different session checks** — a restore only drops an id from the archive set, so an entry whose session is gone still unarchives and leaves no unknown referent; a restore of an id that is not archived resolves without writing, while `archiveSession` rejects a session that is neither live nor persisted.
|
||||
- **The activity check and the archive write are not one atomic step** — a turn that starts between the providers' answer and the durable write is hidden while running, and every model step whose `agent/pre-step` precedes the write still runs with its tool calls; the API Session Controller's gate ends the first step proposed after the write as `blocked`, so the exposure is bounded by that write's latency, in practice one model step.
|
||||
|
||||
@@ -9,7 +9,7 @@ kind: "package-reference"
|
||||
|
||||
## 概述
|
||||
|
||||
使用此包可以维护一个有序、持久的项目目录列表,以及在每个目录中运行的会话。宿主可以构建项目侧边栏、在不删除历史的情况下把会话从分组中隐藏,并在不删除文件夹、文件或会话的情况下移除项目。重新添加已移除的目录会创建一个全新项目,而目录无法校验的会话会保持 Ungrouped。需要持久项目分组的 GUI 或宿主工作流适合使用它;它对模型不可见,不增加提示词或请求上下文成本,但需要会话持久化与存储后端。
|
||||
使用此包可以维护一个有序、持久的项目目录列表,以及在每个目录中运行的会话。宿主可以构建项目侧边栏、在不删除历史的情况下把会话从分组中隐藏,并在不删除文件夹、文件或会话的情况下移除项目。重新添加已移除的目录会创建一个全新项目;已有项目的目录消失时,其会话仍保持原分组。需要持久项目分组的 GUI 或宿主工作流适合使用它;它对模型不可见,不增加提示词或请求上下文成本,但需要会话持久化与存储后端。
|
||||
|
||||
## 目录
|
||||
|
||||
@@ -70,7 +70,7 @@ ctx.workspaceRegistry.list() // shows the project, newest first
|
||||
|
||||
### 将会话归入项目
|
||||
|
||||
会话加入它运行目录所在的项目:在项目目录中创建会话,它就会出现在该项目下,新到旧排列。一个会话只能属于一个项目。目录无法校验的会话——没有记录目录,或目录被移动、删除——无法加入,保持 Ungrouped。
|
||||
会话加入它运行目录所在的项目:在项目目录中创建会话,它就会出现在该项目下,新到旧排列。一个会话只能属于一个项目。新会话必须记录可解析为项目目录的工作目录。已记账会话的完整绝对路径缺失时(包括悬空符号链接),仍保留原项目与顺序;重命名或排序项目不会移除该归属。头部缺失、无效记录路径、现存但不匹配的目录,以及 ENOENT 以外的文件系统错误仍会被排除。保留归属不会重建目录,也不放宽新会话挂接要求,因此目录缺失时 Fork 仍可能挂接失败。
|
||||
|
||||
### 隐藏、恢复会话与移除项目
|
||||
|
||||
@@ -91,7 +91,7 @@ Workspace 注册不意味着拥有其目录。未来的破坏性文件系统操
|
||||
### 设计理念
|
||||
|
||||
- **每个规范路径一条记录。** `fs.realpath` 是唯一的一套唯一性规范:路径以规范化形式存储,因此指向已有记录目录的符号链接会与之冲突,唯一性即规范路径的字符串相等。
|
||||
- **成员资格是所有权加实时 cwd 事实。** 记录的 `sessionIds` 顺序是所有权真源;启动时的头部索引校验它,`sessionIds` 在读取时过滤,下一次变更会持久化剪除无效项。
|
||||
- **成员资格以已记录的归属为起点。** 头部索引校验有序的 `sessionIds`;目录缺失的候选保留归属,其他无效候选在读取时过滤,并在下一次变更时剪除。历史引导使用的严格规范路径索引只包含现存目录。
|
||||
- **仅读取头部。** 引导与 attach 校验只读取 `SessionHeader` 字段;事件正文绝不加载。
|
||||
- **两次写入的变更带显式标记。** 创建与删除在记录/顺序对可能分叉之前先持久化 `pendingMutation` 标记,因此启动只补全被中断的操作,未标记的分叉作为损坏明确报错。
|
||||
- **串行化写入。** 注册表操作跑在同一条操作链上;实体变更通过领域写链上的 `table.update` 执行,写入 `updatedAt`,并在其所在的链位置决定成员资格。
|
||||
@@ -167,7 +167,7 @@ Workspace 注册不意味着拥有其目录。未来的破坏性文件系统操
|
||||
这些限制说明项目列表何时不合适,或何时需要特别的运维注意。它们是当前包约束,不是任务积压。
|
||||
|
||||
- **移除绝不删除数据**——移除项目会保留其文件夹、文件与会话历史;这些会话变成 Ungrouped,而会话删除与文件夹移除是彼此独立且尚未提供的功能。
|
||||
- **只有带记录目录的会话才能加入**——只有记录中带有可解析为项目路径的目录的会话才属于项目;没有目录的会话保持 Ungrouped,来自其他目录的会话无法移入。
|
||||
- **路径缺失时保留记录归属,而非重新验证符号链接历史**——现有记录无法区分被移除的符号链接与错误但不存在的绝对 cwd;两者均保留已记账 id。此例外不吸收未记账会话,也不重建已经从存储中删除的归属。
|
||||
- **外部变更延迟可见**——如果另一进程删除或损坏目录,项目只能在下次刷新或重启后反映出来。
|
||||
- **归档与取消归档执行不同的会话校验**——恢复只是从归档集合中移除 id,因此会话已不存在的条目仍能取消归档,也不会留下未知引用;对未归档 id 执行恢复不写盘即完成,而 `archiveSession` 会拒绝既非实时也未持久化的会话。
|
||||
- **活动检查与归档写入不是一个原子步骤**——在提供方作答与持久化写入之间开始的回合会在隐藏状态下运行,`agent/pre-step` 先于该写入的每个模型步连同其工具调用照常执行;API Session Controller 的门禁把写入之后提出的第一步以 `blocked` 收口,因此暴露面以该写入的时延为界,实际上是一个模型步。
|
||||
|
||||
@@ -39,12 +39,13 @@ export interface WorkspaceEntityHost {
|
||||
table(): KvTable<WorkspaceId, WorkspaceRecord>
|
||||
|
||||
/**
|
||||
* Read a session's canonical directory from the registry's header index.
|
||||
* @param id - Session whose indexed path is requested.
|
||||
* @returns the canonical directory, or `undefined` when the header is
|
||||
* missing or its cwd cannot identify an existing directory.
|
||||
* Validate an already-accounted session, preserving ownership when its fully
|
||||
* qualified cwd cannot resolve because a path component is missing.
|
||||
* @param id - Session already present in this workspace's candidate account.
|
||||
* @param path - Workspace's stored canonical directory.
|
||||
* @returns whether the candidate remains a member.
|
||||
*/
|
||||
sessionPath(id: SessionId): string | undefined
|
||||
candidateMatches(id: SessionId, path: string): boolean
|
||||
|
||||
/**
|
||||
* Read one stored session header for attach validation.
|
||||
@@ -99,7 +100,7 @@ export class WorkspaceEntity implements Workspace {
|
||||
}
|
||||
|
||||
get sessionIds(): readonly SessionId[] {
|
||||
return this.record.sessionIds.filter(id => this.host.sessionPath(id) === this.record.path)
|
||||
return this.record.sessionIds.filter(id => this.host.candidateMatches(id, this.record.path))
|
||||
}
|
||||
|
||||
async setTitle(title: string): Promise<void> {
|
||||
@@ -190,7 +191,7 @@ export class WorkspaceEntity implements Workspace {
|
||||
/**
|
||||
* The single write path: run `fn` on the domain write chain via
|
||||
* `table.update`, stamping `updatedAt` and pruning candidates that no
|
||||
* longer pass the id-plus-canonical-cwd membership check, then swap the
|
||||
* longer pass the candidate membership check, then swap the
|
||||
* snapshot.
|
||||
*
|
||||
* `fn` sees the value current at its chain slot, so membership decisions
|
||||
@@ -205,7 +206,7 @@ export class WorkspaceEntity implements Workspace {
|
||||
next = await this.host.table().update(this.id, (current) => {
|
||||
const changed = fn(current)
|
||||
const sessionIds = changed.sessionIds.filter(
|
||||
id => this.host.sessionPath(id) === changed.path,
|
||||
id => this.host.candidateMatches(id, changed.path),
|
||||
)
|
||||
if (changed === current && sessionIds.length === current.sessionIds.length) {
|
||||
throw unchangedSentinel
|
||||
|
||||
@@ -176,15 +176,17 @@ export class WorkspaceRegistry extends Service {
|
||||
private readonly entities = new Map<WorkspaceId, WorkspaceEntity>()
|
||||
private readonly headers = new Map<SessionId, SessionHeader>()
|
||||
private readonly sessionPaths = new Map<SessionId, string>()
|
||||
private readonly missingSessionPaths = new Set<SessionId>()
|
||||
private readonly invalidSessionPaths = new Map<SessionId, string>()
|
||||
private operationTail: Promise<void> = Promise.resolve()
|
||||
|
||||
private readonly host: WorkspaceEntityHost = {
|
||||
table: () => this.requireTable(),
|
||||
sessionPath: id => this.sessionPaths.get(id),
|
||||
candidateMatches: (id, path) => this.sessionPaths.get(id) === path || this.missingSessionPaths.has(id),
|
||||
readSessionHeader: id => this.readSessionHeader(id),
|
||||
rememberSessionPath: (id, path) => {
|
||||
this.sessionPaths.set(id, path)
|
||||
this.missingSessionPaths.delete(id)
|
||||
this.invalidSessionPaths.delete(id)
|
||||
},
|
||||
}
|
||||
@@ -793,6 +795,7 @@ export class WorkspaceRegistry extends Service {
|
||||
private async replaceHeaderIndex(headers: readonly SessionHeader[]): Promise<void> {
|
||||
this.headers.clear()
|
||||
this.sessionPaths.clear()
|
||||
this.missingSessionPaths.clear()
|
||||
this.invalidSessionPaths.clear()
|
||||
await this.indexHeaders(headers)
|
||||
}
|
||||
@@ -804,6 +807,7 @@ export class WorkspaceRegistry extends Service {
|
||||
private async indexHeader(header: SessionHeader): Promise<void> {
|
||||
this.headers.set(header.id, header)
|
||||
this.sessionPaths.delete(header.id)
|
||||
this.missingSessionPaths.delete(header.id)
|
||||
if (header.cwd === undefined) {
|
||||
this.invalidSessionPaths.set(header.id, 'header has no cwd')
|
||||
return
|
||||
@@ -816,7 +820,11 @@ export class WorkspaceRegistry extends Service {
|
||||
}
|
||||
this.sessionPaths.set(header.id, path)
|
||||
this.invalidSessionPaths.delete(header.id)
|
||||
} catch {
|
||||
} catch (error) {
|
||||
if (fullyQualifiedWorkspacePath(header.cwd)
|
||||
&& error instanceof Error && 'code' in error && error.code === 'ENOENT') {
|
||||
this.missingSessionPaths.add(header.id)
|
||||
}
|
||||
this.invalidSessionPaths.set(header.id, `cwd '${header.cwd}' does not resolve`)
|
||||
}
|
||||
}
|
||||
@@ -837,8 +845,8 @@ export class WorkspaceRegistry extends Service {
|
||||
for (const entity of this.entities.values()) {
|
||||
const record = this.requireTable().get(entity.id) as WorkspaceRecord
|
||||
for (const sessionId of record.sessionIds) {
|
||||
if (this.host.candidateMatches(sessionId, record.path)) continue
|
||||
const path = this.sessionPaths.get(sessionId)
|
||||
if (path === record.path) continue
|
||||
const reason = this.invalidSessionPaths.get(sessionId)
|
||||
?? (this.headers.has(sessionId)
|
||||
? `canonical cwd '${path}' differs from workspace path '${record.path}'`
|
||||
|
||||
@@ -56,9 +56,10 @@ export interface SessionActivity {
|
||||
|
||||
/**
|
||||
* One workspace: a stable id over an existing directory, a display title, and
|
||||
* an ordered candidate account of sessions. Membership requires both an id in
|
||||
* that account and a session header whose canonical cwd equals the workspace
|
||||
* path. Consumers only see this interface; the implementation stays private.
|
||||
* an ordered candidate account of sessions. Membership validates header cwd
|
||||
* against the workspace path, but preserves an existing account when its
|
||||
* fully qualified cwd is missing. Consumers only see this interface; the
|
||||
* implementation stays private.
|
||||
*/
|
||||
export interface Workspace {
|
||||
/** Stable record id (generated uuid). */
|
||||
@@ -85,8 +86,11 @@ export interface Workspace {
|
||||
* prepended at attach, explicit reordering goes through
|
||||
* `insertSessionBefore`, and activity never reorders. The durable candidate
|
||||
* account is filtered synchronously: missing headers, invalid cwd values,
|
||||
* and canonical cwd mismatches are never returned. A subsequent workspace
|
||||
* mutation prunes those filtered candidates durably.
|
||||
* and canonical cwd mismatches are never returned. A fully qualified cwd
|
||||
* whose realpath or directory stat fails with ENOENT preserves an existing
|
||||
* candidate, including a dangling symlink; other filesystem failures do not.
|
||||
* A subsequent mutation prunes filtered candidates, not missing-directory
|
||||
* candidates. This does not admit new sessions or recreate directories.
|
||||
*/
|
||||
readonly sessionIds: readonly SessionId[]
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { z } from 'zod'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest'
|
||||
import { mkdir, mkdtemp, realpath, rm, symlink, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { basename, join, relative } from 'node:path'
|
||||
@@ -21,6 +21,7 @@ import WorkspaceRegistry, {
|
||||
} from '../src/index.ts'
|
||||
import type { WorkspaceDomainState, WorkspaceRecord } from '../src/index.ts'
|
||||
import { defaultWorkspaceTitle, fullyQualifiedWorkspacePath } from '../src/paths.ts'
|
||||
import * as workspacePaths from '../src/paths.ts'
|
||||
|
||||
const DOMAIN_VERSION = 2
|
||||
|
||||
@@ -764,6 +765,150 @@ describe('Workspace session ordering', () => {
|
||||
})
|
||||
|
||||
describe('header-validated membership projection', () => {
|
||||
it('preserves owned sessions and manual order after directory removal and restart', async () => {
|
||||
const dir = await makeDir('removed-owned')
|
||||
const sessions = [header('first', dir), header('second', dir)]
|
||||
const initial = await harness()
|
||||
onTestFinished(() => initial.ctx.fiber.dispose())
|
||||
initial.setSessions(sessions)
|
||||
const workspace = await initial.registry.create(dir)
|
||||
await workspace.attachSession(SessionId('first'))
|
||||
await workspace.attachSession(SessionId('second'))
|
||||
await initial.ctx.fiber.dispose()
|
||||
await rm(dir, { recursive: true })
|
||||
|
||||
const restarted = await harness({ pool: initial.pool, sessions: [...sessions, header('unowned', dir)] })
|
||||
onTestFinished(() => restarted.ctx.fiber.dispose())
|
||||
const restored = restarted.registry.get(workspace.id)!
|
||||
expect(restored.sessionIds).toEqual(['second', 'first'])
|
||||
expect(await restored.status()).toBe('missing-dir')
|
||||
await restored.setTitle('Still owned')
|
||||
await restored.insertSessionBefore(SessionId('first'), SessionId('second'))
|
||||
expect(storedRecord(initial.pool, workspace.id).sessionIds).toEqual(['first', 'second'])
|
||||
await expect(restored.attachSession(SessionId('unowned'))).rejects.toThrow(/does not resolve/)
|
||||
expect(restored.sessionIds).toEqual(['first', 'second'])
|
||||
await restarted.ctx.fiber.dispose()
|
||||
|
||||
const again = await harness({ pool: initial.pool, sessions })
|
||||
onTestFinished(() => again.ctx.fiber.dispose())
|
||||
expect(again.registry.get(workspace.id)!.sessionIds).toEqual(['first', 'second'])
|
||||
})
|
||||
|
||||
it('preserves an owned session when its symlink target disappears without bootstrapping missing paths', async () => {
|
||||
const target = await makeDir('removed-symlink-target')
|
||||
const alias = join(base, 'removed-symlink-alias')
|
||||
await symlink(target, alias, 'junction')
|
||||
const sessions = [header('linked', alias)]
|
||||
const initial = await harness()
|
||||
onTestFinished(() => initial.ctx.fiber.dispose())
|
||||
initial.setSessions(sessions)
|
||||
const workspace = await initial.registry.create(target)
|
||||
await workspace.attachSession(SessionId('linked'))
|
||||
await initial.ctx.fiber.dispose()
|
||||
await rm(target, { recursive: true })
|
||||
|
||||
const restarted = await harness({ pool: initial.pool, sessions })
|
||||
onTestFinished(() => restarted.ctx.fiber.dispose())
|
||||
expect(restarted.registry.get(workspace.id)!.sessionIds).toEqual(['linked'])
|
||||
const fresh = await harness({ sessions })
|
||||
onTestFinished(() => fresh.ctx.fiber.dispose())
|
||||
expect(fresh.registry.list()).toEqual([])
|
||||
})
|
||||
|
||||
it('preserves an owned session when the directory disappears between realpath and stat', async () => {
|
||||
const dir = await makeDir('stat-missing')
|
||||
const id = WorkspaceId('stat-missing-workspace')
|
||||
const pool = storedPool([[id, record(dir, ['kept'])]], { initialized: true, workspaceIds: [id] })
|
||||
const normalize = workspacePaths.realpathNormalize
|
||||
const spy = vi.spyOn(workspacePaths, 'realpathNormalize').mockImplementation(async (path) => {
|
||||
const canonical = await normalize(path)
|
||||
if (path === dir) await rm(dir, { recursive: true })
|
||||
return canonical
|
||||
})
|
||||
onTestFinished(() => { spy.mockRestore() })
|
||||
const result = await harness({ pool, sessions: [header('kept', dir)] })
|
||||
onTestFinished(() => result.ctx.fiber.dispose())
|
||||
expect(result.registry.get(id)!.sessionIds).toEqual(['kept'])
|
||||
})
|
||||
|
||||
it.each(['EACCES', 'ELOOP', 'ENOTDIR'])('does not preserve candidates after a %s path failure', async (code) => {
|
||||
const dir = await makeDir(`path-error-${code}`)
|
||||
const id = WorkspaceId(`path-error-${code}`)
|
||||
const pool = storedPool([[id, record(dir, ['invalid'])]], { initialized: true, workspaceIds: [id] })
|
||||
const spy = vi.spyOn(workspacePaths, 'realpathNormalize').mockRejectedValue(Object.assign(new Error(code), { code }))
|
||||
onTestFinished(() => { spy.mockRestore() })
|
||||
const result = await harness({ pool, sessions: [header('invalid', dir)] })
|
||||
onTestFinished(() => result.ctx.fiber.dispose())
|
||||
const workspace = result.registry.get(id)!
|
||||
expect(workspace.sessionIds).toEqual([])
|
||||
await workspace.setTitle('Pruned')
|
||||
expect(storedRecord(pool, id).sessionIds).toEqual([])
|
||||
})
|
||||
|
||||
it('clears the missing-path exemption when a later header index resolves elsewhere or becomes invalid', async () => {
|
||||
const dir = await makeDir('reindexed-missing')
|
||||
const elsewhere = await makeDir('reindexed-elsewhere')
|
||||
const id = WorkspaceId('reindexed-workspace')
|
||||
const pool = storedPool([[id, record(dir, ['kept'])]], { initialized: true, workspaceIds: [id] })
|
||||
await rm(dir, { recursive: true })
|
||||
const result = await harness({ pool, sessions: [header('kept', dir)] })
|
||||
onTestFinished(() => result.ctx.fiber.dispose())
|
||||
const workspace = result.registry.get(id)!
|
||||
expect(workspace.sessionIds).toEqual(['kept'])
|
||||
result.setSessions([header('kept', elsewhere), header('trigger-one', elsewhere)])
|
||||
await result.registry.pinSession(SessionId('trigger-one'))
|
||||
expect(workspace.sessionIds).toEqual([])
|
||||
result.setSessions([header('kept', dir), header('trigger-two', elsewhere)])
|
||||
await result.registry.pinSession(SessionId('trigger-two'))
|
||||
expect(workspace.sessionIds).toEqual(['kept'])
|
||||
result.setSessions([header('kept'), header('trigger-three', elsewhere)])
|
||||
await result.registry.pinSession(SessionId('trigger-three'))
|
||||
expect(workspace.sessionIds).toEqual([])
|
||||
await workspace.setTitle('Pruned')
|
||||
expect(storedRecord(pool, id).sessionIds).toEqual([])
|
||||
})
|
||||
|
||||
it('filters absent headers and invalid cwd facts while retaining only missing-directory candidates', async () => {
|
||||
const dir = await makeDir('candidate-validation')
|
||||
const elsewhere = await makeDir('candidate-elsewhere')
|
||||
const missing = join(base, 'candidate-missing')
|
||||
const file = join(base, 'candidate-file')
|
||||
await writeFile(file, 'not a directory')
|
||||
const id = WorkspaceId('candidate-validation')
|
||||
const pool = storedPool(
|
||||
[[id, record(dir, ['missing-dir', 'no-header', 'no-cwd', 'relative', 'file', 'elsewhere'])]],
|
||||
{ initialized: true, workspaceIds: [id] },
|
||||
)
|
||||
const result = await harness({
|
||||
pool,
|
||||
sessions: [
|
||||
header('missing-dir', missing), header('no-cwd'), header('relative', 'relative-missing'),
|
||||
header('file', file), header('elsewhere', elsewhere), header('unowned', missing),
|
||||
],
|
||||
})
|
||||
onTestFinished(() => result.ctx.fiber.dispose())
|
||||
const workspace = result.registry.get(id)!
|
||||
expect(workspace.sessionIds).toEqual(['missing-dir'])
|
||||
await workspace.setTitle('Validated')
|
||||
expect(storedRecord(pool, id).sessionIds).toEqual(['missing-dir'])
|
||||
})
|
||||
|
||||
it('can detach and reattach a missing-directory candidate after the directory is restored', async () => {
|
||||
const dir = await makeDir('reattach-restored')
|
||||
const id = WorkspaceId('reattach-restored')
|
||||
const pool = storedPool([[id, record(dir, ['restored'])]], { initialized: true, workspaceIds: [id] })
|
||||
await rm(dir, { recursive: true })
|
||||
const result = await harness({ pool, sessions: [header('restored', dir)] })
|
||||
onTestFinished(() => result.ctx.fiber.dispose())
|
||||
const workspace = result.registry.get(id)!
|
||||
await workspace.detachSession(SessionId('restored'))
|
||||
expect(workspace.sessionIds).toEqual([])
|
||||
await mkdir(dir)
|
||||
await workspace.attachSession(SessionId('restored'))
|
||||
expect(workspace.sessionIds).toEqual(['restored'])
|
||||
expect(await workspace.status()).toBe('ok')
|
||||
})
|
||||
|
||||
it('requires both candidate id and matching canonical cwd without re-reading on list()', async () => {
|
||||
const owned = await makeDir('owned')
|
||||
const elsewhere = await makeDir('projection-elsewhere')
|
||||
|
||||
Reference in new issue
Block a user