From 5ec3353af2be73c6773ae3ce917d547f0ea5cd3a Mon Sep 17 00:00:00 2001 From: _Kerman Date: Sun, 20 Sep 2026 20:42:50 +0800 Subject: [PATCH] refactor(workspace): reuse toast for default initialization failures --- apps/web/tests/default-workspace.e2e.ts | 14 ++-- .../default-workspace/failure.expected.md | 7 +- packages/client/ui-workspace/README.i18n.yaml | 4 +- packages/client/ui-workspace/README.md | 2 +- packages/client/ui-workspace/README.zh.md | 2 +- .../src/client/WorkspacePicker.tsx | 48 ++++--------- .../ui-workspace/src/client/contract/slots.ts | 9 +-- .../client/ui-workspace/src/client/index.ts | 13 ++-- .../client/ui-workspace/src/client/locales.ts | 8 +-- .../ui-workspace/src/client/navigation.ts | 20 +++--- .../client/session-actions/RowActionToast.tsx | 13 ++-- .../ui-workspace/tests/apply.client.spec.ts | 20 +++++- .../tests/session-actions.client.spec.tsx | 1 + .../tests/workspace-picker.client.spec.tsx | 35 +--------- .../tests/workspaces-service.client.spec.ts | 69 ++++++++++++------- 15 files changed, 114 insertions(+), 151 deletions(-) diff --git a/apps/web/tests/default-workspace.e2e.ts b/apps/web/tests/default-workspace.e2e.ts index d3b6db624d..d27f430fd3 100644 --- a/apps/web/tests/default-workspace.e2e.ts +++ b/apps/web/tests/default-workspace.e2e.ts @@ -81,16 +81,14 @@ describe.skipIf(MODE === 'record')('web e2e: default Workspace', () => { try { await page.goto(scaffold.authenticatedUrl) const input = page.locator('[data-composer-input][contenteditable="true"]').first() - const modal = page.getByRole('dialog', { name: '无法创建默认工作区' }) - await modal.waitFor() + const notice = page.getByRole('alert').filter({ hasText: '无法创建默认工作区' }) + await notice.waitFor() expect(scaffold.ctx.workspaceRegistry.list()).toEqual([]) expect(scaffold.ctx.sessions.list()).toEqual([]) - await compareOrRefreshGolden(FAILURE_EXPECTED, await modal.ariaSnapshot(), MODE) - await modal.getByRole('button', { name: '取消', exact: true }).click() + await compareOrRefreshGolden(FAILURE_EXPECTED, await notice.ariaSnapshot(), MODE) + expect(await page.getByRole('dialog').count()).toBe(0) expect(await input.count()).toBe(0) - await page.reload() - await modal.waitFor() - await modal.getByRole('button', { name: '选择文件夹', exact: true }).click() + await page.getByRole('button', { name: '选择工作区', exact: true }).click() const picker = page.getByRole('dialog', { name: '选择工作区目录' }) await picker.waitFor() await picker.getByRole('button', { name: '编辑路径', exact: true }).click() @@ -126,7 +124,7 @@ describe.skipIf(MODE === 'record')('web e2e: default Workspace', () => { await page.goto(scaffold.authenticatedUrl) expect((await attempted).ok()).toBe(true) await page.getByRole('button', { name: 'Choose workspace', exact: true }).waitFor() - expect(await page.getByRole('dialog', { name: 'Unable to create default workspace' }).count()).toBe(0) + expect(await page.getByRole('alert').filter({ hasText: 'Unable to create default workspace' }).count()).toBe(0) expect(await page.locator('[data-composer-input][contenteditable="true"]').count()).toBe(0) expect(scaffold.ctx.workspaceRegistry.list()).toEqual([]) expect(scaffold.ctx.sessions.list()).toEqual([]) diff --git a/apps/web/tests/expected/default-workspace/failure.expected.md b/apps/web/tests/expected/default-workspace/failure.expected.md index 6944d1cf14..c9624749f0 100644 --- a/apps/web/tests/expected/default-workspace/failure.expected.md +++ b/apps/web/tests/expected/default-workspace/failure.expected.md @@ -1,6 +1 @@ -- dialog "无法创建默认工作区": - - heading "无法创建默认工作区" [level=2] - - button "关闭" - - text: 请选择一个文件夹后重试 - - button "取消" - - button "选择文件夹" +- alert: 无法创建默认工作区,请通过“选择工作区”选择文件夹 diff --git a/packages/client/ui-workspace/README.i18n.yaml b/packages/client/ui-workspace/README.i18n.yaml index 4af8adc8d4..2f176f2329 100644 --- a/packages/client/ui-workspace/README.i18n.yaml +++ b/packages/client/ui-workspace/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-workspace/README.md -README.md: 768c66503af70d0b587b25c09aa8412b0a647439 -README.zh.md: 25df6f8e6a2ec0a001d784c7bde18e454e9d706f +README.md: bf67f12f15f634a29dc05744c079255723ae2a62 +README.zh.md: e57700d983b31872383fc4b26f9b5b080d66ba6c diff --git a/packages/client/ui-workspace/README.md b/packages/client/ui-workspace/README.md index 768c66503a..bf67f12f15 100644 --- a/packages/client/ui-workspace/README.md +++ b/packages/client/ui-workspace/README.md @@ -69,7 +69,7 @@ The value is intentionally best effort for cold Sessions. An identity-matching u New Session tries to acquire the first eligible blank in catalog order; startup restoration tries the saved blank. If that writer is held, navigation creates a new Session without trying other blanks. Other acquisition failures abort the request and are currently reported only to the console. Released blanks retain their slash-command state when reused. Later navigation cancels a pending startup selection. -Once both Workspace and Session startup baselines are ready, an empty installation calls `workspaces.initializeDefault` and creates or reuses its blank Session. The composer becomes editable when that Session is selected; no message is submitted automatically. Later navigation or owner disposal prevents startup from selecting its result. Ineligible first use leaves the folder picker available without an error. Preparation failure offers Cancel or Choose folder through the existing picker, and is not retried until the next startup. A successfully registered Workspace remains available when Session creation or later submission fails. +Once both Workspace and Session startup baselines are ready, an empty installation calls `workspaces.initializeDefault` and creates or reuses its blank Session. The composer becomes editable when that Session is selected; no message is submitted automatically. Later navigation or owner disposal prevents startup from selecting its result. Ineligible first use leaves the folder picker available without an error. Default Workspace creation failure shows a transient notice directing the user to Choose workspace, and is not retried until the next startup. Session creation failures use the ordinary restoration error handling. The registered Workspace remains available if Session creation or later submission fails. The Client chooses the initial directory name and title from its language at startup: Chinese uses `默认工作区`, English uses `Default workspace`, and other languages use directory `default-workspace` with title `Default workspace`. The request retains those names during initialization. A successfully initialized Workspace keeps its directory and title across language changes. diff --git a/packages/client/ui-workspace/README.zh.md b/packages/client/ui-workspace/README.zh.md index 25df6f8e6a..e57700d983 100644 --- a/packages/client/ui-workspace/README.zh.md +++ b/packages/client/ui-workspace/README.zh.md @@ -69,7 +69,7 @@ Session 行渲染运行时的实时 `pendingInteraction` 分类:审批显示** 新建会话尝试获取列表中第一个符合条件的空白会话;启动恢复尝试已保存的空白会话。若该写锁被占用,导航直接新建 Session,不再尝试其他空白会话。其他获取错误会中止请求,目前只报告到控制台。已释放的空白会话被复用时保留 slash 命令状态。后续导航会取消尚未完成的启动选择。 -Workspace 和 Session 的启动基线均就绪后,空安装环境调用 `workspaces.initializeDefault`,创建或复用其空白 Session。选中该 Session 后输入框才可编辑,不会自动提交消息。后续导航或所属上下文销毁会阻止启动流程选中其结果。不符合首次使用条件时仍可选择文件夹,不显示错误。准备失败时通过现有选择器提供取消或选择文件夹操作,直到下次启动才重试。登记成功的工作区在 Session 创建或后续提交失败时仍然保留。 +Workspace 和 Session 的启动基线均就绪后,空安装环境调用 `workspaces.initializeDefault`,创建或复用其空白 Session。选中该 Session 后输入框才可编辑,不会自动提交消息。后续导航或所属上下文销毁会阻止启动流程选中其结果。不符合首次使用条件时仍可选择文件夹,不显示错误。默认工作区创建失败时显示短暂提示,引导用户通过“选择工作区”选择文件夹,直到下次启动才重试。Session 创建失败沿用普通的恢复错误处理。登记成功的工作区在 Session 创建或后续提交失败时仍然保留。 Client 在启动时按其语言选择初始目录名和标题:中文使用 `默认工作区`,英文使用 `Default workspace`,其他语言使用目录 `default-workspace` 和标题 `Default workspace`。初始化过程中保留请求中的名称。成功初始化的工作区在切换语言后保留原目录和标题。 diff --git a/packages/client/ui-workspace/src/client/WorkspacePicker.tsx b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx index 42e177afce..b74e3689dc 100644 --- a/packages/client/ui-workspace/src/client/WorkspacePicker.tsx +++ b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx @@ -231,45 +231,21 @@ export function WorkspacePicker({ onClose, createWorkspace, useDirectoryFlow, - useDefaultFailure, - dismissDefaultFailure, renderSlot, t, }: WorkspacePickerProps) { - const failed = useDefaultFailure(value => value) - const flowAvailable = useDirectoryFlow(value => value) - const [recovering, setRecovering] = useState(false) return ( - <> - renderSlot('conversation.hero.workspace.directoryFlow', owner)} - selectedId={selectedId} - onPick={onPick} - onClose={() => { setRecovering(false); onClose() }} - /> - - - - - )} - > - {t('defaultWorkspace.retry')} - - + renderSlot('conversation.hero.workspace.directoryFlow', owner)} + selectedId={selectedId} + onPick={onPick} + onClose={onClose} + /> ) } diff --git a/packages/client/ui-workspace/src/client/contract/slots.ts b/packages/client/ui-workspace/src/client/contract/slots.ts index b878e24986..36ab1850d4 100644 --- a/packages/client/ui-workspace/src/client/contract/slots.ts +++ b/packages/client/ui-workspace/src/client/contract/slots.ts @@ -238,12 +238,13 @@ export type SessionRowActionProps = & PropsLocale<'workspace'> & InjectFace -/** One transient notice a row action raises; the overlay toast entry renders it. */ +/** One transient Workspace notice rendered by the overlay toast entry. */ export type RowToast = | { kind: 'archived'; sessionId: SessionId } | { kind: 'pinFailed' } | { kind: 'unpinFailed' } | { kind: 'archivedNotOpenable' } + | { kind: 'defaultWorkspaceFailed' } /** The notice on display; `seq` keys remounts so a repeated notice restarts its hold. */ export type RowToastState = RowToast & { seq: number } @@ -364,12 +365,6 @@ export type WorkspaceBrowserProps = * supplies the implicit index signature required by the registry. */ export type WorkspacePickerInjected = DirectoryPickingInjected & { - /** Dismiss the startup failure before choosing a directory manually. */ - dismissDefaultFailure: () => void - hooks: { - /** Whether first-use startup failed to prepare a Workspace and Session. */ - defaultFailure: HostObservable - } /** Adopt a picked host directory as a real Workspace before targeting a Session. */ createWorkspace: (input: { path: string }) => Promise } diff --git a/packages/client/ui-workspace/src/client/index.ts b/packages/client/ui-workspace/src/client/index.ts index 8d96c65d77..7c821033d6 100644 --- a/packages/client/ui-workspace/src/client/index.ts +++ b/packages/client/ui-workspace/src/client/index.ts @@ -103,8 +103,13 @@ export function apply(ctx: Context): void { const viewHandle = createWorkspaceViewStore() const viewInstance = viewHandle.create() const viewStore: typeof viewHandle = { ...viewHandle, create: () => viewInstance } + const rowToast = createSnapshotStore(null) + let toastSeq = 0 + const notify = (toast: RowToast): void => { rowToast.set({ ...toast, seq: ++toastSeq }) } const uiWorkspace = new UiWorkspaceService( - ctx, ctx.remote.directoryPicker, workspaces, sessions, viewInstance.actions) + ctx, ctx.remote.directoryPicker, workspaces, sessions, viewInstance.actions, + () => { notify({ kind: 'defaultWorkspaceFailed' }) }, + ) ctx.slots.provideRoot({ hooks: { workspaces: workspaces.list } }) ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'ui-workspace: dictionaries') @@ -137,9 +142,6 @@ export function apply(ctx: Context): void { // writes through its own injected callback and the surface reads through // its bound hook. const renameRequest = createSnapshotStore(null) - const rowToast = createSnapshotStore(null) - let toastSeq = 0 - const notify = (toast: RowToast): void => { rowToast.set({ ...toast, seq: ++toastSeq }) } const requestSessionRename = (sessionId: SessionId, currentTitle: string): void => { renameRequest.set({ sessionId, currentTitle }) } @@ -219,8 +221,7 @@ export function apply(ctx: Context): void { }) const pickerInjected = (): WorkspacePickerInjected => ({ createWorkspace: input => workspaces.create(input), - dismissDefaultFailure: () => { uiWorkspace.defaultFailure.set(false) }, - hooks: { directoryFlow: pickerFlowSource, defaultFailure: uiWorkspace.defaultFailure }, + hooks: { directoryFlow: pickerFlowSource }, }) // Each registration declares its owned children in the same call; slot // injection follows both the owner and declaration HMR lifetimes. diff --git a/packages/client/ui-workspace/src/client/locales.ts b/packages/client/ui-workspace/src/client/locales.ts index d926ce987f..3ecc46741f 100644 --- a/packages/client/ui-workspace/src/client/locales.ts +++ b/packages/client/ui-workspace/src/client/locales.ts @@ -6,10 +6,8 @@ /** Simplified Chinese dictionary (the key-set source of truth). */ export const zh = { - 'defaultWorkspace.failed': '无法创建默认工作区', + 'defaultWorkspace.failed': '无法创建默认工作区,请通过“选择工作区”选择文件夹', 'defaultWorkspace.title': '默认工作区', - 'defaultWorkspace.retry': '请选择一个文件夹后重试', - 'defaultWorkspace.choose': '选择文件夹', 'group.ungrouped': '未分组', 'session.new': '新会话', 'section.workspaces': '工作区', @@ -103,10 +101,8 @@ export type WorkspaceKey = keyof typeof zh /** English dictionary, checked complete against the zh key set. */ export const en = { - 'defaultWorkspace.failed': 'Unable to create default workspace', + 'defaultWorkspace.failed': 'Unable to create default workspace. Use Choose workspace to select a folder.', 'defaultWorkspace.title': 'Default workspace', - 'defaultWorkspace.retry': 'Please choose a folder and try again', - 'defaultWorkspace.choose': 'Choose folder', 'group.ungrouped': 'Ungrouped', 'session.new': 'New Session', 'section.workspaces': 'Workspaces', diff --git a/packages/client/ui-workspace/src/client/navigation.ts b/packages/client/ui-workspace/src/client/navigation.ts index b21cf06f15..13c12651fd 100644 --- a/packages/client/ui-workspace/src/client/navigation.ts +++ b/packages/client/ui-workspace/src/client/navigation.ts @@ -120,8 +120,6 @@ export class DirectoryBrowseError extends Error { /** Implements Workspace archive and directory UI operations. */ class UiWorkspaceService extends Service implements UiWorkspace { - /** Startup failure awaiting dismissal or explicit directory selection. */ - readonly defaultFailure = createSnapshotStore(false) private readonly connecting = new Map>() private readonly lifetime = new AbortController() private readonly selection = createSnapshotStore( @@ -135,6 +133,7 @@ class UiWorkspaceService extends Service implements UiWorkspace { * @param workspaces - pure Workspace Controller. * @param sessions - pure Session Controller. * @param view - the browser's viewing-store write set (one instance shared with its registration). + * @param notifyDefaultFailure - show the startup creation failure through the Workspace notice channel. */ constructor( ctx: Context, @@ -142,6 +141,7 @@ class UiWorkspaceService extends Service implements UiWorkspace { private readonly workspaces: IWorkspaces, private readonly sessions: ISessions, private readonly view: Pick, + private readonly notifyDefaultFailure: () => void, ) { super(ctx, 'uiWorkspace') ctx.effect(() => { @@ -324,28 +324,28 @@ class UiWorkspaceService extends Service implements UiWorkspace { && !workspaces.archivedSessionIds.includes(summary.id)) { sessionId = await this.reuseBlank(workspace.workspaceId, summary.id) } - const target = workspace?.workspaceId ?? recentWorkspace(workspaces.items, sessions.byId) - if (sessionId === undefined && target !== undefined) sessionId = await this.connectWorkspace(target) + let target = workspace?.workspaceId ?? recentWorkspace(workspaces.items, sessions.byId) if (target === undefined && workspaces.items.length === 0 && sessions.ids.length === 0) { - sessionId = await this.initializeDefaultWorkspace(navigation) + const prepared = await this.initializeDefaultWorkspace(navigation) + if (navigation.aborted) return + target = prepared?.workspaceId } + if (sessionId === undefined && target !== undefined) sessionId = await this.connectWorkspace(target) if (sessionId !== undefined && !navigation.aborted) { this.replaceMain(sessionId, navigation, 'preserve') } } - private async initializeDefaultWorkspace(signal: AbortSignal): Promise { + private async initializeDefaultWorkspace(signal: AbortSignal): Promise { const language = this.ctx.locale.getSnapshot().active.toLowerCase().split('-')[0] const title = (language === 'zh' ? zh : en)['defaultWorkspace.title'] try { - const workspace = await this.workspaces.initializeDefault({ + return await this.workspaces.initializeDefault({ directoryName: language === 'zh' || language === 'en' ? title : 'default-workspace', title, }, signal) - if (workspace === undefined || signal.aborted) return undefined - return await this.connectWorkspace(workspace.workspaceId) } catch (_error: unknown) { - if (!signal.aborted) this.defaultFailure.set(true) + if (!signal.aborted) this.notifyDefaultFailure() return undefined } } diff --git a/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx b/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx index f000fc4b4a..c5a3caccc6 100644 --- a/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx +++ b/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx @@ -1,8 +1,6 @@ /** - * The `shell.overlay` entry that shows the row actions' notices: the archived - * notice with its undo and "show archived" actions, pin failures, and the - * browser's "archived rows cannot be opened" notice. One notice at a time; - * a parent rerender does not extend its hold. + * The `shell.overlay` entry for Workspace and Session notices. + * One notice is visible at a time; a parent rerender does not extend its hold. */ import { IconWarningOutlineRegular, Toast } from '@deepseek-ai/dsh-client-ui-primitives' import type { RowToastProps } from '../contract/slots.ts' @@ -11,9 +9,9 @@ import type { RowToastProps } from '../contract/slots.ts' const ARCHIVED_TOAST_HOLD_MS = 6000 /** - * Render the row actions' current notice: the archived notice with its undo + * Render the current notice: the archived notice with its undo * and show-archived actions on a 6 s hold, or a plain warning for a failed - * pin or an archived row that was clicked. + * pin, an archived row that was clicked, or default Workspace creation. * @param props - the notice hook, its dismissal, the two archived-notice actions, and the locale seat. * @returns the notice on display, or null. */ @@ -38,7 +36,8 @@ export function RowActionToast({ useToast, dismissToast, undoArchive, showArchiv } const text = toast.kind === 'pinFailed' ? t('toast.pinFailed') - : toast.kind === 'unpinFailed' ? t('toast.unpinFailed') : t('toast.archivedNotOpenable') + : toast.kind === 'unpinFailed' ? t('toast.unpinFailed') + : toast.kind === 'defaultWorkspaceFailed' ? t('defaultWorkspace.failed') : t('toast.archivedNotOpenable') return ( () => {} const workspacesSubscribe = vi.fn(subscribe) + const initializeDefault = vi.fn(async (): Promise => undefined) ctx.provide('workspaces', { list: { getSnapshot: () => workspaceSnapshot, subscribe: workspacesSubscribe }, create, + initializeDefault, rename, delete: vi.fn(async () => undefined), insertBefore: vi.fn(async () => undefined), @@ -128,7 +130,7 @@ async function bench() { return { ctx, slots: ctx.get('slots') as SlotRegistry, locale, create, rename, retain, using, selectPanel, search, renameSession, binding, fork, pickDirectory, pinSession, unpinSession, - workspacesSubscribe, + workspacesSubscribe, initializeDefault, setWorkspaces: (snapshot: WorkspaceSnapshot): void => { workspaceSnapshot = snapshot }, setSessions: (snapshot: SessionListState): void => { sessionSnapshot = snapshot }, } @@ -182,6 +184,20 @@ describe('ui-workspace apply', () => { ]) }) + it('reports a default Workspace creation failure through the shared notice overlay', async () => { + const b = await bench() + onTestFinished(() => b.ctx.fiber.dispose()) + b.initializeDefault.mockRejectedValueOnce(new Error('denied')) + declare(b.slots, 'shell.overlay') + await b.ctx.plugin({ inject: [...inject], apply }).await() + const face = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected + await vi.waitFor(() => { + expect(face.hooks.toast.getSnapshot()).toMatchObject({ kind: 'defaultWorkspaceFailed' }) + }) + face.dismissToast() + expect(face.hooks.toast.getSnapshot()).toBeNull() + }) + it('registers browser and pickers for declarations arriving before or after apply', async () => { const before = await bench() declare(before.slots, 'sidebar.workspaces') diff --git a/packages/client/ui-workspace/tests/session-actions.client.spec.tsx b/packages/client/ui-workspace/tests/session-actions.client.spec.tsx index ce5cb47dda..c7e3b1150d 100644 --- a/packages/client/ui-workspace/tests/session-actions.client.spec.tsx +++ b/packages/client/ui-workspace/tests/session-actions.client.spec.tsx @@ -387,6 +387,7 @@ describe('RowActionToast', () => { ['pinFailed', '置顶失败,请稍后重试'], ['unpinFailed', '取消置顶失败,请稍后重试'], ['archivedNotOpenable', '已归档对话暂时无法查看,请取消归档后查看'], + ['defaultWorkspaceFailed', '无法创建默认工作区,请通过“选择工作区”选择文件夹'], ] as const)('shows the %s warning and takes it down when its hold ends', (kind, text) => { vi.useFakeTimers() try { diff --git a/packages/client/ui-workspace/tests/workspace-picker.client.spec.tsx b/packages/client/ui-workspace/tests/workspace-picker.client.spec.tsx index e72d523668..9ff0181207 100644 --- a/packages/client/ui-workspace/tests/workspace-picker.client.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-picker.client.spec.tsx @@ -1,7 +1,6 @@ // @vitest-environment jsdom import type { GlobalStandardProps } from '@deepseek-ai/dsh-client-ui-slots' import { afterEach, describe, expect, it, vi } from 'vitest' -import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' import type { SessionListState } from '@deepseek-ai/dsh-api-session-controller/client' import type { @@ -89,19 +88,14 @@ function mount( items: readonly WorkspaceView[] = [workspace('alpha', 'Alpha')], createWorkspace = vi.fn(), occupancy = occupancySource(), - options: { defaultFailure?: boolean; open?: boolean } = {}, ) { - const failure = createSnapshotStore(options.defaultFailure ?? false) - const useDefaultFailure = bindSnapshotSelector(failure) - const dismissDefaultFailure = vi.fn(() => { failure.set(false) }) const onPick = vi.fn() const onClose = vi.fn() const anchorRef = anchor() const { probe, renderSlot } = flowProbe() const renderPicker = (nextItems: readonly WorkspaceView[]) => ( { view.rerender(renderPicker(nextItems)) }, } } @@ -226,7 +220,6 @@ describe('WorkspacePicker', () => { const { renderSlot } = flowProbe() render( undefined} @@ -245,7 +238,6 @@ describe('WorkspacePicker', () => { const { renderSlot } = flowProbe() render( undefined} @@ -329,26 +321,3 @@ describe('WorkspacePicker', () => { expect(screen.queryByRole('menuitem', { name: '添加工作区…' })).toBeNull() }) }) - -describe('default Workspace startup recovery', () => { - it('dismisses the failure without opening the directory flow', () => { - const b = mount([], vi.fn(), occupancySource(), { defaultFailure: true, open: false }) - expect(screen.getByRole('dialog', { name: '无法创建默认工作区' })).toBeTruthy() - expect(b.probe.owner?.open).toBe(false) - fireEvent.click(screen.getByRole('button', { name: '取消' })) - expect(b.dismissDefaultFailure).toHaveBeenCalledOnce() - expect(screen.queryByRole('dialog', { name: '无法创建默认工作区' })).toBeNull() - expect(b.probe.owner?.open).toBe(false) - }) - - it('opens the composed directory flow from the startup failure', async () => { - const create = vi.fn(async () => workspace('chosen')) - const b = mount([], create, occupancySource(), { defaultFailure: true, open: false }) - fireEvent.click(screen.getByRole('button', { name: '选择文件夹' })) - expect(b.dismissDefaultFailure).toHaveBeenCalledOnce() - expect(b.probe.owner?.open).toBe(true) - await act(async () => { b.probe.owner!.onPicked('/chosen') }) - expect(create).toHaveBeenCalledExactlyOnceWith({ path: '/chosen' }) - expect(b.onPick).toHaveBeenCalledExactlyOnceWith(wid('chosen')) - }) -}) diff --git a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts index 4f9cd973b8..8efdb0af95 100644 --- a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts +++ b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts @@ -294,14 +294,16 @@ function bench(options: BenchOptions = {}) { options.configureWorkspaces?.(workspaces) options.configureSessions?.(sessions) const view = createWorkspaceViewStore().create() + const notifyDefaultFailure = vi.fn() const uiWorkspace = new UiWorkspaceService( ctx, directoryPicker.remote, workspaces, sessions, view.actions, + notifyDefaultFailure, ) - return { ctx, directoryPicker, sessions, uiWorkspace, workspaces, layout, selectPanel, view } + return { ctx, directoryPicker, sessions, uiWorkspace, workspaces, layout, selectPanel, view, notifyDefaultFailure } } describe('UiWorkspaceService', () => { @@ -326,10 +328,10 @@ describe('UiWorkspaceService', () => { }) expect(b.workspaces.initializeDefault).toHaveBeenCalledExactlyOnceWith({ directoryName, title }, expect.any(AbortSignal)) expect(b.sessions.create).toHaveBeenCalledWith({ workspaceId: wid('default') }) - expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(false) + expect(b.notifyDefaultFailure).not.toHaveBeenCalled() }) - it('leaves an ineligible empty installation without a Session or failure dialog', async () => { + it('leaves an ineligible empty installation without a Session or failure notice', async () => { const b = bench({ workspaces: workspaceState(), sessions: sessionState() }) await setImmediate() b.workspaces.list.set(workspaceState()) @@ -337,7 +339,7 @@ describe('UiWorkspaceService', () => { await setImmediate() expect(b.workspaces.initializeDefault).toHaveBeenCalledOnce() expect(b.sessions.create).not.toHaveBeenCalled() - expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(false) + expect(b.notifyDefaultFailure).not.toHaveBeenCalled() }) it('requires explicit selection when the startup Session list contains history', async () => { @@ -351,13 +353,12 @@ describe('UiWorkspaceService', () => { const b = bench({ workspaces: workspaceState(), sessions: sessionState(), configureWorkspaces: (workspaces) => { workspaces.initializeDefault.mockRejectedValueOnce(new Error('denied')) } }) - await vi.waitFor(() => { expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(true) }) - b.uiWorkspace.defaultFailure.set(false) + await vi.waitFor(() => { expect(b.notifyDefaultFailure).toHaveBeenCalledOnce() }) b.workspaces.list.set(workspaceState()) await setImmediate() expect(b.workspaces.initializeDefault).toHaveBeenCalledOnce() expect(b.sessions.create).not.toHaveBeenCalled() - expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(false) + expect(b.notifyDefaultFailure).toHaveBeenCalledOnce() }) it.each(['session', 'panel', 'disposal'] as const)('cancels startup directory preparation after %s navigation', async (kind) => { @@ -373,27 +374,43 @@ describe('UiWorkspaceService', () => { await setImmediate() expect(b.sessions.create).not.toHaveBeenCalled() expect(b.sessions.retain.mock.calls.map(args => args[0])).toEqual(kind === 'session' ? [sid('manual')] : []) - expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(false) + expect(b.notifyDefaultFailure).not.toHaveBeenCalled() }) - it('retains a prepared Workspace when its Session fails and suppresses a superseded failure', async () => { - for (const superseded of [false, true]) { - const created = Promise.withResolvers() - const b = bench({ workspaces: workspaceState(), sessions: sessionState(), configureWorkspaces: (workspaces) => { - workspaces.initializeDefault.mockImplementationOnce(async () => { - const item = workspace('default') - workspaces.list.set(workspaceState([item])) - return item - }) - }, configureSessions: (sessions) => { sessions.create.mockReturnValueOnce(created.promise) } }) - await vi.waitFor(() => { expect(b.sessions.create).toHaveBeenCalledOnce() }) - if (superseded) b.layout.selectPanel('other-panel' as MainPanelId) - created.reject(new Error('session failed')) - await setImmediate() - expect(b.workspaces.list.getSnapshot().items).toEqual([workspace('default')]) - expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(!superseded) - expect(b.sessions.retain).not.toHaveBeenCalled() - } + it.each(['session', 'panel', 'disposal'] as const)('suppresses a startup directory failure after %s navigation', async (kind) => { + const pending = Promise.withResolvers() + const b = bench({ workspaces: workspaceState(), sessions: sessionState(), configureWorkspaces: (workspaces) => { + workspaces.initializeDefault.mockReturnValueOnce(pending.promise) + } }) + if (kind === 'session') b.uiWorkspace.openSession(sid('manual')) + else if (kind === 'panel') b.layout.selectPanel('other-panel' as MainPanelId) + else await b.ctx.fiber.dispose() + pending.reject(new Error('late failure')) + await setImmediate() + expect(b.sessions.create).not.toHaveBeenCalled() + expect(b.notifyDefaultFailure).not.toHaveBeenCalled() + }) + + it.each([false, true])('reports Session failure without a directory error and retains the Workspace (superseded: %s)', async (superseded) => { + const warning = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const created = Promise.withResolvers() + const b = bench({ workspaces: workspaceState(), sessions: sessionState(), configureWorkspaces: (workspaces) => { + workspaces.initializeDefault.mockImplementationOnce(async () => { + const item = workspace('default') + workspaces.list.set(workspaceState([item])) + return item + }) + }, configureSessions: (sessions) => { sessions.create.mockReturnValueOnce(created.promise) } }) + await vi.waitFor(() => { expect(b.sessions.create).toHaveBeenCalledOnce() }) + if (superseded) b.layout.selectPanel('other-panel' as MainPanelId) + const failure = new Error('session failed') + created.reject(failure) + await vi.waitFor(() => { + expect(warning).toHaveBeenCalledExactlyOnceWith('initial Session restoration failed:', failure) + }) + expect(b.workspaces.list.getSnapshot().items).toEqual([workspace('default')]) + expect(b.notifyDefaultFailure).not.toHaveBeenCalled() + expect(b.sessions.retain).not.toHaveBeenCalled() }) it('retains an explicit main target before revealing its Conversation', () => {