fix(web): report a refused new session through the Workspace notice

An explicit New Session (sidebar and header buttons, the workspace row
button, and the hero workspace pick) whose `session.create` the Host
refuses — for example a default preset whose composition names a
plugin that no longer resolves (`agent-preset/invalid`) — was only
logged with `console.warn`, so the click looked like it did nothing.

`openWorkspace` now shows the failure through the shared Workspace
notice as a `createFailed` toast quoting the Host's stable code and
message on the long hold, then rethrows as before. Startup restoration
does not go through `openWorkspace` and stays console-only.
This commit is contained in:
Yichen Jiang committed 2026-09-20 22:40:00 +08:00
1 parent 27fa7ed9ff
commit 93ad804bf1
11 files changed
+129 -29

No files matched your search

@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/client/ui-workspace/README.md
README.md: 92e2f231ec2e25aa1716f03338a980f2c2269d16
README.zh.md: e490c4ebe63a0e11e1892d8bc02693ab63d12277
README.md: d4396fd07a05791285f44a01a6cfb17aeac1ebe9
README.zh.md: 31dca87e21c620271f5fe7307f07f9f437247742
+1 -1
View File
@@ -69,7 +69,7 @@ The value is intentionally best effort for cold Sessions. An identity-matching u
Navigation and startup restoration obtain the selected Session's projections from its `follow`; neither issues a separate projection refresh for that Session or its parent.
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.
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: an explicit New Session or hero Workspace pick shows the failure as a transient notice quoting the Host's code and message (for example a preset that fails to mount), while startup restoration reports only to the console. Released blanks retain their slash-command state when reused. Later navigation cancels a pending startup selection.
Once both Workspace and Session startup baselines are ready, an empty installation calls `workspaces.initializeDefault` and creates or reuses its blank Session. The composer becomes editable when that Session is selected; no message is submitted automatically. Later navigation or owner disposal prevents startup from selecting its result. Ineligible first use leaves the folder picker available without an error. Default Workspace creation failure shows a transient notice directing the user to Choose workspace, and is not retried until the next startup. Session creation failures use the ordinary restoration error handling. The registered Workspace remains available if Session creation or later submission fails.
+1 -1
View File
@@ -69,7 +69,7 @@ Session 行渲染运行时的实时 `pendingInteraction` 分类:审批显示**
导航和启动恢复通过所选 Session 的 `follow` 获取投影,不会另行刷新该 Session 或其父会话的投影。
新建会话尝试获取列表中第一个符合条件的空白会话;启动恢复尝试已保存的空白会话。若该写锁被占用,导航直接新建 Session,不再尝试其他空白会话。其他获取错误会中止请求,目前只报告到控制台。已释放的空白会话被复用时保留 slash 命令状态。后续导航会取消尚未完成的启动选择。
新建会话尝试获取列表中第一个符合条件的空白会话;启动恢复尝试已保存的空白会话。若该写锁被占用,导航直接新建 Session,不再尝试其他空白会话。其他获取错误会中止请求:显式新建会话或在 hero 中选择工作区时,失败以短暂提示展示,引用 Host 的错误码和消息(例如 preset 挂载失败);启动恢复仍只报告到控制台。已释放的空白会话被复用时保留 slash 命令状态。后续导航会取消尚未完成的启动选择。
Workspace 和 Session 的启动基线均就绪后,空安装环境调用 `workspaces.initializeDefault`,创建或复用其空白 Session。选中该 Session 后输入框才可编辑,不会自动提交消息。后续导航或所属上下文销毁会阻止启动流程选中其结果。不符合首次使用条件时仍可选择文件夹,不显示错误。默认工作区创建失败时显示短暂提示,引导用户通过“选择工作区”选择文件夹,直到下次启动才重试。Session 创建失败沿用普通的恢复错误处理。登记成功的工作区在 Session 创建或后续提交失败时仍然保留。
@@ -245,6 +245,8 @@ export type RowToast =
| { kind: 'unpinFailed' }
| { kind: 'archivedNotOpenable' }
| { kind: 'defaultWorkspaceFailed' }
/** An explicit New Session request the Host refused; `message` is the failure in the Host's own words, untranslated. */
| { kind: 'createFailed'; message: string }
/** The notice on display; `seq` keys remounts so a repeated notice restarts its hold. */
export type RowToastState = RowToast & { seq: number }
@@ -107,8 +107,7 @@ export function apply(ctx: Context): void {
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,
() => { notify({ kind: 'defaultWorkspaceFailed' }) },
ctx, ctx.remote.directoryPicker, workspaces, sessions, viewInstance.actions, notify,
)
ctx.slots.provideRoot({ hooks: { workspaces: workspaces.list } })
ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'ui-workspace: dictionaries')
@@ -62,6 +62,7 @@ export const zh = {
'toast.archivedFilter': '筛选已归档会话',
'toast.pinFailed': '置顶失败,请稍后重试',
'toast.unpinFailed': '取消置顶失败,请稍后重试',
'toast.createFailed': '新建会话失败:{message}',
'sessions.count.one': '{n} 个会话',
'sessions.count.other': '{n} 个会话',
'actions.workspace.aria': '工作区“{name}”的操作',
@@ -157,6 +158,7 @@ export const en = {
'toast.archivedFilter': 'filter archived sessions',
'toast.pinFailed': 'Pin failed. Try again later.',
'toast.unpinFailed': 'Unpin failed. Try again later.',
'toast.createFailed': 'New session failed: {message}',
'sessions.count.one': '{n} session',
'sessions.count.other': '{n} sessions',
'actions.workspace.aria': 'Workspace actions for {name}',
@@ -17,6 +17,7 @@ import type {
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import type {} from '@deepseek-ai/dsh-client-ui-layout/client'
import type {} from '@deepseek-ai/dsh-client-locale/client'
import type { RowToast } from './contract/slots.ts'
import { en, zh } from './locales.ts'
import { pinOrderAccounts, pinOrderSource } from './pin-order.ts'
import type { WorkspaceViewStoreActions } from './stores.ts'
@@ -38,6 +39,7 @@ export interface UiWorkspace {
* @param workspaceId - target Workspace.
* @param beforeOpen - optional synchronous preparation for the selected Session, skipped after supersession.
* @returns completion; a superseded request may create a Session but does not open it.
* @throws when the Session cannot be created; the failure is also shown through the Workspace notice.
*/
openWorkspace(workspaceId: WorkspaceId, beforeOpen?: (sessionId: SessionId) => void): Promise<void>
/**
@@ -53,7 +55,8 @@ export interface UiWorkspace {
*/
connectWorkspace(workspaceId: WorkspaceId): Promise<SessionId>
/**
* Start a New Session flow and navigate to its Session.
* Start a New Session flow and navigate to its Session; a creation the Host
* refuses is shown through the Workspace notice and leaves the selection as it was.
* @param workspaceId - explicit target; absent inherits the current or most recent Workspace.
*/
startSession(workspaceId?: WorkspaceId): void
@@ -133,7 +136,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.
* @param notify - show one notice through the Workspace notice channel.
*/
constructor(
ctx: Context,
@@ -141,7 +144,7 @@ class UiWorkspaceService extends Service implements UiWorkspace {
private readonly workspaces: IWorkspaces,
private readonly sessions: ISessions,
private readonly view: Pick<WorkspaceViewStoreActions, 'pinSessionOrder'>,
private readonly notifyDefaultFailure: () => void,
private readonly notify: (toast: RowToast) => void,
) {
super(ctx, 'uiWorkspace')
ctx.effect(() => {
@@ -187,9 +190,7 @@ class UiWorkspaceService extends Service implements UiWorkspace {
try {
return await this.sessions.create({ workspaceId, sessionId })
} catch (error: unknown) {
// Client plugin bundles do not share error-class identity.
if (!(error instanceof Error) || error.name !== 'SessionCreateError'
|| (error as SessionCreateError).rpcError.code !== 'session/writer-held') throw error
if (sessionCreateErrorOf(error)?.rpcError.code !== 'session/writer-held') throw error
return this.sessions.create({ workspaceId })
}
}
@@ -200,7 +201,15 @@ class UiWorkspaceService extends Service implements UiWorkspace {
async openWorkspace(workspaceId: WorkspaceId, beforeOpen?: (sessionId: SessionId) => void): Promise<void> {
const navigation = AbortSignal.any([this.ctx.layout.beginNavigation(), this.lifetime.signal])
const sessionId = await this.connectWorkspace(workspaceId)
let sessionId: SessionId
try {
sessionId = await this.connectWorkspace(workspaceId)
} catch (error: unknown) {
// The user asked for this Session, so the refusal is theirs to read;
// startup restoration goes through connectWorkspace directly and stays quiet.
this.notify({ kind: 'createFailed', message: creationFailureMessage(error) })
throw error
}
if (navigation.aborted) return
this.replaceMain(sessionId, navigation, 'reveal', beforeOpen)
}
@@ -344,7 +353,7 @@ class UiWorkspaceService extends Service implements UiWorkspace {
title,
}, signal)
} catch (_error: unknown) {
if (!signal.aborted) this.notifyDefaultFailure()
if (!signal.aborted) this.notify({ kind: 'defaultWorkspaceFailed' })
return undefined
}
}
@@ -400,6 +409,24 @@ class UiWorkspaceService extends Service implements UiWorkspace {
}
/**
* The Session Controller's creation failure `error` is, or undefined. Client
* plugin bundles do not share error-class identity, so the name decides.
*/
function sessionCreateErrorOf(error: unknown): SessionCreateError | undefined {
return error instanceof Error && error.name === 'SessionCreateError' ? error as SessionCreateError : undefined
}
/**
* The words a failed Session creation is reported in: a Host refusal keeps its
* stable code and message; any other failure keeps its own message.
*/
function creationFailureMessage(error: unknown): string {
const refused = sessionCreateErrorOf(error)
if (refused !== undefined) return `${refused.rpcError.code}: ${refused.rpcError.message}`
return error instanceof Error ? error.message : String(error)
}
/** Stable tie-breaking follows Host Workspace order. */
function recentWorkspace(
workspaces: readonly WorkspaceView[],
@@ -5,12 +5,17 @@
import { IconWarningOutlineRegular, Toast } from '@deepseek-ai/dsh-client-ui-primitives'
import type { RowToastProps } from '../contract/slots.ts'
/** Hold for the actionable archived notice: two buttons need a longer read-and-react window than a plain notice. */
const ARCHIVED_TOAST_HOLD_MS = 6000
/**
* Hold for the notices that take longer to read than a one-line warning: the
* actionable archived notice (two buttons to react to) and a refused Session
* creation, which quotes the Host's reason.
*/
const LONG_TOAST_HOLD_MS = 6000
/**
* 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
* and show-archived actions on a 6 s hold, a refused Session creation with
* the Host's reason on the same hold, or a plain warning for a failed
* 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.
@@ -25,7 +30,7 @@ export function RowActionToast({ useToast, dismissToast, undoArchive, showArchiv
key={`toast-${String(toast.seq)}`}
text={t('toast.archived')}
tone="success"
holdMs={ARCHIVED_TOAST_HOLD_MS}
holdMs={LONG_TOAST_HOLD_MS}
actions={[
{ label: t('toast.archivedUndo'), onClick: () => { dismissToast(); undoArchive(sessionId) } },
{ prefix: t('toast.archivedOr'), label: t('toast.archivedFilter'), onClick: () => { dismissToast(); showArchived() } },
@@ -34,6 +39,17 @@ export function RowActionToast({ useToast, dismissToast, undoArchive, showArchiv
/>
)
}
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}
/>
)
}
const text = toast.kind === 'pinFailed'
? t('toast.pinFailed')
: toast.kind === 'unpinFailed' ? t('toast.unpinFailed')
@@ -404,6 +404,24 @@ describe('RowActionToast', () => {
}
})
it('shows a refused creation with the Host reason and holds it as long as the archived notice', () => {
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')
expect(alert.querySelector('button')).toBeNull()
act(() => { vi.advanceTimersByTime(4000) })
expect(dismissToast).not.toHaveBeenCalled()
act(() => { vi.advanceTimersByTime(3000) })
expect(dismissToast).toHaveBeenCalledOnce()
expect(screen.queryByRole('alert')).toBeNull()
} finally {
vi.useRealTimers()
}
})
it('the archived notice holds longer than a plain notice, and a repeat restarts its hold', () => {
vi.useFakeTimers()
try {
@@ -16,6 +16,7 @@ import type { RemoteResult } from '@deepseek-ai/dsh-api-remotes/client'
import { SessionId } from '@deepseek-ai/dsh-session/types'
import { LayoutController } from '@deepseek-ai/dsh-client-ui-layout/client'
import type { MainPanelId } from '@deepseek-ai/dsh-client-ui-layout/client'
import type { RowToast } from '../src/client/contract/slots.ts'
import { DirectoryBrowseError, UiWorkspaceService } from '../src/client/navigation.ts'
import { createWorkspaceViewStore, FLAT_SESSION_ORDER_KEY } from '../src/client/stores.ts'
import { UNGROUPED_KEY } from '../src/client/tree.ts'
@@ -294,16 +295,16 @@ function bench(options: BenchOptions = {}) {
options.configureWorkspaces?.(workspaces)
options.configureSessions?.(sessions)
const view = createWorkspaceViewStore().create()
const notifyDefaultFailure = vi.fn()
const notify = vi.fn<(toast: RowToast) => void>()
const uiWorkspace = new UiWorkspaceService(
ctx,
directoryPicker.remote,
workspaces,
sessions,
view.actions,
notifyDefaultFailure,
notify,
)
return { ctx, directoryPicker, sessions, uiWorkspace, workspaces, layout, selectPanel, view, notifyDefaultFailure }
return { ctx, directoryPicker, sessions, uiWorkspace, workspaces, layout, selectPanel, view, notify }
}
describe('UiWorkspaceService', () => {
@@ -328,7 +329,7 @@ describe('UiWorkspaceService', () => {
})
expect(b.workspaces.initializeDefault).toHaveBeenCalledExactlyOnceWith({ directoryName, title }, expect.any(AbortSignal))
expect(b.sessions.create).toHaveBeenCalledWith({ workspaceId: wid('default') })
expect(b.notifyDefaultFailure).not.toHaveBeenCalled()
expect(b.notify).not.toHaveBeenCalled()
})
it('leaves an ineligible empty installation without a Session or failure notice', async () => {
@@ -339,7 +340,7 @@ describe('UiWorkspaceService', () => {
await setImmediate()
expect(b.workspaces.initializeDefault).toHaveBeenCalledOnce()
expect(b.sessions.create).not.toHaveBeenCalled()
expect(b.notifyDefaultFailure).not.toHaveBeenCalled()
expect(b.notify).not.toHaveBeenCalled()
})
it('requires explicit selection when the startup Session list contains history', async () => {
@@ -353,12 +354,12 @@ describe('UiWorkspaceService', () => {
const b = bench({ workspaces: workspaceState(), sessions: sessionState(), configureWorkspaces: (workspaces) => {
workspaces.initializeDefault.mockRejectedValueOnce(new Error('denied'))
} })
await vi.waitFor(() => { expect(b.notifyDefaultFailure).toHaveBeenCalledOnce() })
await vi.waitFor(() => { expect(b.notify).toHaveBeenCalledExactlyOnceWith({ kind: 'defaultWorkspaceFailed' }) })
b.workspaces.list.set(workspaceState())
await setImmediate()
expect(b.workspaces.initializeDefault).toHaveBeenCalledOnce()
expect(b.sessions.create).not.toHaveBeenCalled()
expect(b.notifyDefaultFailure).toHaveBeenCalledOnce()
expect(b.notify).toHaveBeenCalledExactlyOnceWith({ kind: 'defaultWorkspaceFailed' })
})
it.each(['session', 'panel', 'disposal'] as const)('cancels startup directory preparation after %s navigation', async (kind) => {
@@ -374,7 +375,7 @@ 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.notifyDefaultFailure).not.toHaveBeenCalled()
expect(b.notify).not.toHaveBeenCalled()
})
it.each(['session', 'panel', 'disposal'] as const)('suppresses a startup directory failure after %s navigation', async (kind) => {
@@ -388,7 +389,7 @@ describe('UiWorkspaceService', () => {
pending.reject(new Error('late failure'))
await setImmediate()
expect(b.sessions.create).not.toHaveBeenCalled()
expect(b.notifyDefaultFailure).not.toHaveBeenCalled()
expect(b.notify).not.toHaveBeenCalled()
})
it.each([false, true])('reports Session failure without a directory error and retains the Workspace (superseded: %s)', async (superseded) => {
@@ -409,7 +410,7 @@ describe('UiWorkspaceService', () => {
expect(warning).toHaveBeenCalledExactlyOnceWith('initial Session restoration failed:', failure)
})
expect(b.workspaces.list.getSnapshot().items).toEqual([workspace('default')])
expect(b.notifyDefaultFailure).not.toHaveBeenCalled()
expect(b.notify).not.toHaveBeenCalled()
expect(b.sessions.retain).not.toHaveBeenCalled()
})
@@ -641,6 +642,40 @@ describe('UiWorkspaceService', () => {
expect(b.sessions.retain).not.toHaveBeenCalled()
})
it('reports a refused explicit Session creation through the Workspace notice', async () => {
const b = bench({ workspaces: workspaceState([workspace('a')]), sessions: sessionState() })
// Startup restoration creates its own Session first and stays quiet on failure (pinned above).
await vi.waitFor(() => { expect(b.sessions.retain).toHaveBeenCalledOnce() })
b.sessions.retain.mockClear()
expect(b.notify).not.toHaveBeenCalled()
const warning = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
const refused = new SessionCreateError(new RemoteError(
'agent-preset/invalid',
'agent-presets: preset "broken" failed to mount: row "workflow-ptc" names a plugin that cannot be resolved',
{ agentPreset: 'broken', reason: 'row "workflow-ptc" names a plugin that cannot be resolved' },
), undefined)
b.sessions.create.mockRejectedValueOnce(refused)
b.uiWorkspace.startSession(wid('a'))
await vi.waitFor(() => {
expect(b.notify).toHaveBeenCalledExactlyOnceWith({
kind: 'createFailed',
message: 'agent-preset/invalid: agent-presets: preset "broken" failed to mount: row "workflow-ptc" names a plugin that cannot be resolved',
})
})
expect(warning).toHaveBeenCalledExactlyOnceWith('new session failed:', refused)
expect(b.sessions.retain).not.toHaveBeenCalled()
// The hero picker reaches the same creation through openWorkspace; a
// failure that is not a Host refusal keeps its own message.
b.sessions.create.mockRejectedValueOnce(new Error('create failed'))
await expect(b.uiWorkspace.openWorkspace(wid('a'))).rejects.toThrow('create failed')
expect(b.notify).toHaveBeenLastCalledWith({ kind: 'createFailed', message: 'create failed' })
b.sessions.create.mockRejectedValueOnce('rejected without an Error')
await expect(b.uiWorkspace.openWorkspace(wid('a'))).rejects.toBe('rejected without an Error')
expect(b.notify).toHaveBeenLastCalledWith({ kind: 'createFailed', message: 'rejected without an Error' })
expect(b.notify).toHaveBeenCalledTimes(3)
})
it('uses only an explicit Workspace or the recent-Workspace policy for new Sessions', async () => {
const current = summary('current', { cwd: '/w/current-home', updatedAt: 1 })
const recent = summary('recent', { cwd: '/w/recent-home', updatedAt: 2 })
@@ -345,6 +345,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
description: 'Connect a Workspace and open its Session unless a later navigation supersedes it.',
parameters: [{ name: 'workspaceId', description: 'target Workspace.' }, { name: 'beforeOpen', description: 'optional synchronous preparation for the selected Session, skipped after supersession.' }],
returns: 'completion; a superseded request may create a Session but does not open it.',
throws: ['when the Session cannot be created; the failure is also shown through the Workspace notice.'],
},
{
signature: 'forkSession(sessionId: SessionId): Promise<void>',
@@ -360,7 +361,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
},
{
signature: 'startSession(workspaceId?: WorkspaceId): void',
description: 'Start a New Session flow and navigate to its Session.',
description: 'Start a New Session flow and navigate to its Session; a creation the Host refuses is shown through the Workspace notice and leaves the selection as it was.',
parameters: [{ name: 'workspaceId', description: 'explicit target; absent inherits the current or most recent Workspace.' }],
},
{