From 01d8fb1f8badd8771bdf0405714c00d768a0a96a Mon Sep 17 00:00:00 2001 From: codesstar <825323057@qq.com> Date: Mon, 9 Nov 2026 14:50:57 +0800 Subject: [PATCH 1/3] feat(desktop): rename cloud chats and show their running state Cloud Chat rows only offered move and delete. They now rename like Work rows: a Rename menu item and a title double-click open a dialog that posts to BiSheng's existing POST /api/v1/chat/conversation/rename under the same history grant deletion uses. The main process validates the name against message_session.name (1-255 characters, no control characters) and tells the open enterprise document so it can reread the conversation name. The native Chat view yields while the dialog is open, as for deletion. The enterprise document can now report which conversations are still generating (reportRunning). The host validates the report from the current main frame, keeps it per document and identity, and the sidebar shows the same ongoing StateDot as Work rows with a screen-reader label. Older documents that never report leave the list unchanged. Tests: rename and activity contracts in enterprise-chat-view, real-primitive dialog/row coverage in cloud-chat-rename-running, native view yielding in desktop-modes-ui; fixtures updated for the new overlay and navigation fields. --- packages/dsh-desktop-client-ui/client.js | 132 ++++++++++-- src/main/enterprise/chat-view.ts | 45 +++- src/main/index.ts | 7 +- src/preload/enterprise-chat.ts | 13 ++ src/preload/index.ts | 1 + src/shared/enterprise-chat-view.ts | 16 ++ test/cloud-chat-rename-running.test.mjs | 231 +++++++++++++++++++++ test/desktop-account-presentation.test.mjs | 3 +- test/desktop-client-ui.test.ts | 2 + test/desktop-modes-ui.test.mjs | 13 +- test/enterprise-chat-view.test.ts | 149 +++++++++++++ test/helpers/session-search-fixture.mjs | 2 +- test/helpers/sidebar-primitives.mjs | 39 ++++ 13 files changed, 628 insertions(+), 25 deletions(-) create mode 100644 test/cloud-chat-rename-running.test.mjs create mode 100644 test/helpers/sidebar-primitives.mjs diff --git a/packages/dsh-desktop-client-ui/client.js b/packages/dsh-desktop-client-ui/client.js index 7b527f97..de6ea28b 100644 --- a/packages/dsh-desktop-client-ui/client.js +++ b/packages/dsh-desktop-client-ui/client.js @@ -7,7 +7,7 @@ window.__ModuleLoader__.load({ const React = require('react') const { - Menu, MenuItemButton, Modal, Button, HoverCard, relativeTime, ReferenceIconRegular, + Menu, MenuItemButton, Modal, Button, HoverCard, StateDot, relativeTime, ReferenceIconRegular, IconChevronRightOutlineRegular, IconEditOutlineRegular, IconEllipsisOutlineRegular, IconFolderCloseRegular, IconFolderOpenRegular, IconNewChatOutlineRegular, IconPlusOutlineRegular, IconTrashOutlineRegular, IconTriangleRightFillRegular } = require('@deepseek-ai/dsh-client-ui-primitives') @@ -214,7 +214,8 @@ window.__ModuleLoader__.load({ const DELETE_SESSION_NS = 'dsh-desktop-delete-session' // The shell owns the request: closing a row menu unmounts its occupants. - function createSessionDeletion(deleteSession) { + // Deletion confirms without input; rename passes the submitted name through. + function createSessionRequest(run) { let state = null let active = true const listeners = new Set() @@ -229,12 +230,12 @@ window.__ModuleLoader__.load({ if (active && state === null) publish({ sessionId, displayTitle, context, busy: false, error: null }) }, close: () => { if (state && state.busy === false) publish(null) }, - confirm: async () => { + confirm: async (input) => { if (state === null || state.busy || active === false) return const pending = { ...state, busy: true, error: null } publish(pending) try { - await deleteSession(pending.sessionId, pending.context) + await run(pending.sessionId, pending.context, input) if (active && state === pending) publish(null) } catch (reason) { if (active && state === pending) { @@ -273,7 +274,7 @@ window.__ModuleLoader__.load({ 'data-modal-autofocus': true }, t('cancel')), React.createElement(Button, { - variant: 'primary', disabled: request.busy, onClick: deletion.confirm + variant: 'primary', disabled: request.busy, onClick: () => { void deletion.confirm() } }, t(request.busy ? 'pending' : 'confirm'))) }, request?.busy && React.createElement('p', { role: 'status' }, t('pending')), request && request.error !== null && React.createElement('div', { role: 'alert' }, @@ -281,6 +282,45 @@ window.__ModuleLoader__.load({ React.createElement('p', null, request.error))) } + // Mirrors Work's session rename: one form per request, so each opens with a fresh draft. + function RenameChatDialog({ renaming, t }) { + const request = React.useSyncExternalStore(renaming.subscribe, renaming.getSnapshot) + if (request === null) return null + return React.createElement(RenameChatForm, { key: `${request.context}:${request.sessionId}`, request, renaming, t }) + } + + function RenameChatForm({ request, renaming, t }) { + const [draft, setDraft] = React.useState(request.displayTitle) + const composing = React.useRef(false) + const trimmed = draft.trim() + const blocked = request.busy || trimmed === '' + const confirm = () => { if (!blocked) void renaming.confirm(trimmed) } + return React.createElement(Modal, { + open: true, + onClose: renaming.close, + title: t('title'), + closeLabel: t('close'), + footer: React.createElement(React.Fragment, null, + React.createElement(Button, { variant: 'outline', disabled: request.busy, onClick: renaming.close }, t('cancel')), + React.createElement(Button, { variant: 'primary', disabled: blocked, onClick: confirm }, t(request.busy ? 'pending' : 'confirm'))) + }, + React.createElement('input', { + className: 'dshChatRenameInput', value: draft, maxLength: CHAT_NAME_MAX_LENGTH, 'aria-label': t('name'), + 'data-modal-autofocus': true, disabled: request.busy, + onFocus: event => event.target.select(), + onChange: event => setDraft(event.target.value), + onCompositionStart: () => { composing.current = true }, + onCompositionEnd: () => { composing.current = false }, + onKeyDown: event => { + if (event.key === 'Enter' && !composing.current) { event.preventDefault(); confirm() } + } + }), + request.busy && React.createElement('p', { role: 'status', className: 'dshChatRenameStatus' }, t('pending')), + request.error !== null && React.createElement('div', { role: 'alert', className: 'dshChatRenameError' }, + React.createElement('p', null, t('failed')), + React.createElement('p', null, request.error))) + } + function OpenSessionFolderMenuItem({ sessionId, useMenuOpenState, openInFinder }) { const [, setMenuOpen] = useMenuOpenState() if (typeof window.dshDesktop?.openInFinder !== 'function') return null @@ -312,6 +352,13 @@ window.__ModuleLoader__.load({ zh: { menu: '删除', actions: '会话操作', title: '删除会话', close: '关闭', cancel: '取消', confirm: '删除会话', description: '确定删除“{name}”?会话及其聊天记录将被永久删除。', pending: '正在删除会话…', failed: '删除失败,请重试。' }, en: { menu: 'Delete', actions: 'Conversation actions', title: 'Delete conversation', close: 'Close', cancel: 'Cancel', confirm: 'Delete conversation', description: 'Permanently delete “{name}” and its chat history?', pending: 'Deleting conversation…', failed: 'Deletion failed. Please try again.' } } + const CLOUD_RENAME_NS = 'desktop.cloudChatRename' + const CLOUD_RENAME_COPY = { + zh: { title: '重命名会话', name: '会话名称', close: '关闭', cancel: '取消', confirm: '重命名', pending: '正在重命名…', failed: '重命名失败,请重试。' }, + en: { title: 'Rename conversation', name: 'Conversation name', close: 'Close', cancel: 'Cancel', confirm: 'Rename', pending: 'Renaming…', failed: 'Rename failed. Please try again.' } + } + // Matches the server's message_session.name column; the host validates it again. + const CHAT_NAME_MAX_LENGTH = 255 const PROJECTS_NS = 'desktop.chatProjects' const PROJECTS_COPY = { zh: { title: '对话项目', create: '新建项目', rename: '重命名项目', remove: '删除项目', actions: '项目操作', startChat: '在此项目新建对话', empty: '暂无对话', name: '项目名称', nameHelp: '请输入 1–30 个字符', cancel: '取消', save: '保存', close: '关闭', move: '移入项目', moveOut: '移出项目', deleteHelp: '删除“{name}”后,其中的对话将移回对话列表,聊天记录会保留。', failed: '项目保存失败,请重试。', unavailable: '项目数据无法读取,点击重试。', retry: '重试' }, @@ -635,6 +682,9 @@ window.__ModuleLoader__.load({ } Object.assign(MODES_COPY.zh, { 'time.now': '刚刚', 'time.minutes': '{n}分钟', 'time.hours': '{n}小时', 'time.days': '{n}天', 'time.months': '{n}个月', 'time.years': '{n}年', 'time.ago': '{t}前' }) Object.assign(MODES_COPY.en, { 'time.now': 'now', 'time.minutes': '{n}min', 'time.hours': '{n}h', 'time.days': '{n}d', 'time.months': '{n}mo', 'time.years': '{n}y', 'time.ago': '{t} ago' }) + // Same words as Work's session row menu and status. + Object.assign(MODES_COPY.zh, { rename: '重命名', running: '进行中' }) + Object.assign(MODES_COPY.en, { rename: 'Rename', running: 'Running' }) /** * Host tokens the embedded enterprise document reuses. It cannot read the host's CSS, so the * presenter resolves them here and sends plain channels with the presentation. @@ -700,7 +750,7 @@ window.__ModuleLoader__.load({ /** One renderer-owned mode/history controller shared by the content and sidebar slots. */ function createChatNavigation(ctx) { - let value = { mode: 'work', connected: false, phase: 'idle', epoch: undefined, items: [], page: 0, hasMore: false, historyPhase: 'idle', settingsOpen: false, signInPromptOpen: false, approvalsOpen: false, accountDialogOpen: false, settingsSurface: undefined, pageId: undefined, navigation: undefined, workLanding: false, nativeWork: true, panelOpen: false, activePanelId: null } + let value = { mode: 'work', connected: false, phase: 'idle', epoch: undefined, items: [], running: [], page: 0, hasMore: false, historyPhase: 'idle', settingsOpen: false, signInPromptOpen: false, approvalsOpen: false, accountDialogOpen: false, settingsSurface: undefined, pageId: undefined, navigation: undefined, workLanding: false, nativeWork: true, panelOpen: false, activePanelId: null } const listeners = new Set() const projects = createChatProjects() let openRequest = 0 @@ -757,7 +807,7 @@ publish({ items: [...new Map(items.map(item => [item.id, item])).values()], page if (active && request === historyRequest && historyDirty) { historyDirty = false; void refreshHistory() } } } - const deletion = createSessionDeletion(async (id, epoch) => { + const deletion = createSessionRequest(async (id, epoch) => { if (epoch !== value.epoch || !value.connected) throw new Error('Chat identity changed.') const response = await window.dshEnterpriseChat.remove(id, epoch) if (!active || epoch !== value.epoch || response.epoch !== epoch) return @@ -765,6 +815,16 @@ publish({ items: [...new Map(items.map(item => [item.id, item])).values()], page publish({ items: value.items.filter(item => item.id !== id), historyPhase: 'idle' }) void refreshHistory() }) + const renaming = createSessionRequest(async (id, epoch, name) => { + if (epoch !== value.epoch || !value.connected) throw new Error('Chat identity changed.') + const response = await window.dshEnterpriseChat.rename(id, name, epoch) + if (!active || epoch !== value.epoch || response.epoch !== epoch) return + // The server also moves the conversation's update time. A newer local row + // outranks cached project pages until the reread brings the server's own. + historyRequest++ + publish({ items: value.items.map(item => item.id === id ? { ...item, title: name, updatedAt: new Date().toISOString() } : item), historyPhase: 'idle' }) + void refreshHistory() + }) const open = async (id, projectId) => { if (!select('chat')) return const epoch = value.epoch @@ -784,11 +844,13 @@ publish({ items: [...new Map(items.map(item => [item.id, item])).values()], page const conversationChanged = next.conversationId !== value.conversationId const becameReady = next.phase === 'ready' && value.phase !== 'ready' const clearHistory = identityChanged || !next.connected -if (clearHistory) { historyRequest++; openRequest++; historyDirty = false; deletion.reset() } +if (clearHistory) { historyRequest++; openRequest++; historyDirty = false; deletion.reset(); renaming.reset() } projects.setScope(next.connected ? next.projectScope : undefined, next.epoch) publish({ ...next, ...(clearHistory ? { items: [], page: 0, hasMore: false, historyPhase: 'idle' } : {}), + // The host omits an empty activity list, so absence must clear the previous one. + running: next.connected && Array.isArray(next.running) ? next.running : [], signInPromptOpen: next.connected ? false : value.signInPromptOpen, pageId: next.navigation?.entries.find(entry => entry.active)?.id, mode: next.connected ? signedIn ? 'chat' : value.mode : 'work' @@ -830,7 +892,7 @@ if (clearHistory) { historyRequest++; openRequest++; historyDirty = false; delet return { snapshot: () => value, subscribe: (fn) => { listeners.add(fn); return () => listeners.delete(fn) }, - select, open, refreshHistory, deletion, projects, + select, open, refreshHistory, deletion, renaming, projects, startProjectChat(id) { if (!value.connected || !projects.snapshot().projects.some(project => project.id === id)) return projects.reveal(id) @@ -844,6 +906,9 @@ if (clearHistory) { historyRequest++; openRequest++; historyDirty = false; delet if (projectId === undefined) projects.edit('create', id) else if (await projects.assign(id, projectId) && projectId && value.epoch === epoch) projects.reveal(projectId) }, + requestRename(id, title, epoch) { + if (value.connected && epoch === value.epoch && (value.items.some(item => item.id === id) || Object.hasOwn(projects.snapshot().assignments, id))) renaming.request(id, title, epoch) + }, requestDelete(id, title, epoch) { if (value.connected && epoch === value.epoch && (value.items.some(item => item.id === id) || Object.hasOwn(projects.snapshot().assignments, id))) deletion.request(id, title, epoch) }, @@ -959,7 +1024,7 @@ if (revealWorkSession) ctx.uiWorkspace.openSession = revealWorkSession active = false startupStateRetryCount = startupStateRetryDelays.length cancelStartupStateRetry() -deletion.reset(); projects.setScope(undefined); revision++; historyRequest++; unsubscribe(); unsubscribeSessions(); unsubscribeWork(); unsubscribeChat?.(); unsubscribeProjects?.() +deletion.reset(); renaming.reset(); projects.setScope(undefined); revision++; historyRequest++; unsubscribe(); unsubscribeSessions(); unsubscribeWork(); unsubscribeChat?.(); unsubscribeProjects?.() window.removeEventListener('dsh-desktop:enterprise-account-changed', account) disposeNavigation() if (revealWorkSession && ctx.uiWorkspace.openSession === revealWorkSession) ctx.uiWorkspace.openSession = originalOpenSession @@ -1024,6 +1089,9 @@ deletion.reset(); projects.setScope(undefined); revision++; historyRequest++; un const title = item.title || t('newChat') const marquee = useHistoryTitleMarquee(title) const timeId = React.useId() + const statusId = React.useId() + // Parents subscribe to navigation; the row reads the same snapshot as its project state. + const running = navigation.snapshot().running.includes(item.id) const date = Date.parse(item.updatedAt) const time = Number.isFinite(date) ? relativeTime(date, now) : null const dateTime = time && new Date(date).toISOString() @@ -1033,6 +1101,7 @@ deletion.reset(); projects.setScope(undefined); revision++; historyRequest++; un const currentProject = Object.hasOwn(projects.assignments, item.id) ? projects.assignments[item.id] : undefined const actions = [] if (menu.open) { + actions.push({ id: 'rename', label: t('rename'), icon: React.createElement(IconEditOutlineRegular) }) if (projectText) { actions.push({ id: 'move', disabled: !canMove, @@ -1050,11 +1119,16 @@ deletion.reset(); projects.setScope(undefined); revision++; historyRequest++; un } actions.push({ id: 'delete', label: deleteText('menu'), icon: React.createElement(IconTrashOutlineRegular), danger: true }) } + const requestRename = () => { + const epoch = navigation.snapshot().epoch + setTimeout(() => navigation.requestRename(item.id, item.title || '', epoch), 0) + } const select = action => { const epoch = navigation.snapshot().epoch menu.close() - // Only deletion and creation need a dialog. Let Menu restore focus before it opens. - if (action === 'delete') setTimeout(() => navigation.requestDelete(item.id, title, epoch), 0) + // Only rename, deletion and creation need a dialog. Let Menu restore focus before it opens. + if (action === 'rename') requestRename() + else if (action === 'delete') setTimeout(() => navigation.requestDelete(item.id, title, epoch), 0) else if (action === 'new-project') setTimeout(() => { void navigation.moveProjectChat(item.id, epoch) }, 0) else if (action === 'move-out') void navigation.moveProjectChat(item.id, epoch, null) else if (action.startsWith('project:')) void navigation.moveProjectChat(item.id, epoch, action.slice('project:'.length)) @@ -1067,9 +1141,13 @@ deletion.reset(); projects.setScope(undefined); revision++; historyRequest++; un }, React.createElement('button', { type: 'button', 'data-history-kind': 'chat', className: 'dshHistoryRow', 'aria-current': selected ? 'page' : undefined, - 'aria-label': title, 'aria-describedby': time ? timeId : undefined, onClick: () => navigation.open(item.id) + 'aria-label': title, 'aria-describedby': [running && statusId, time && timeId].filter(Boolean).join(' ') || undefined, onClick: () => navigation.open(item.id) }, - React.createElement('span', { className: 'dshHistoryTitle', ref: marquee.ref }, title), + running && React.createElement('span', { className: 'dshHistoryStatus' }, + React.createElement(StateDot, { state: 'ongoing' }), + React.createElement('span', { id: statusId, className: 'dshVisuallyHidden' }, t('running'))), + // Work rows rename on a title double-click too. + React.createElement('span', { className: 'dshHistoryTitle', ref: marquee.ref, onDoubleClick: event => { event.stopPropagation(); requestRename() } }, title), time && React.createElement('time', { id: timeId, dateTime }, age)), React.createElement('div', { className: 'dshSidebarItemTools' }, React.createElement(Menu, { @@ -1080,7 +1158,8 @@ deletion.reset(); projects.setScope(undefined); revision++; historyRequest++; un }))), content: React.createElement('div', { className: 'dshCloudHistoryPreview', 'data-dsh-chat-history-preview': '' }, React.createElement('div', null, title), - time && React.createElement('time', { dateTime }, time.unit === 'now' ? age : t('time.ago', { t: age }))), + time && React.createElement('time', { dateTime }, time.unit === 'now' ? age : t('time.ago', { t: age })), + running && React.createElement('span', { className: 'dshCloudHistoryStatus' }, React.createElement(StateDot, { state: 'ongoing', size: 12 }), t('running'))), openDelayMs: 800, grouped: true, disabled: menu.open }) } @@ -1528,6 +1607,8 @@ deletion.reset(); projects.setScope(undefined); revision++; historyRequest++; un const projectDialogOpen = projectState.editor !== null const deletionRequest = React.useSyncExternalStore(navigation.deletion.subscribe, navigation.deletion.getSnapshot) const cloudDeleteOpen = deletionRequest !== null + const renameRequest = React.useSyncExternalStore(navigation.renaming.subscribe, navigation.renaming.getSnapshot) + const cloudRenameOpen = renameRequest !== null const { mode, settingsOpen, settingsSurface } = state const candidate = state.landingMorph const morph = candidate?.to === mode && candidate.epoch === state.epoch && hasSharedLanding(state) && @@ -1645,7 +1726,7 @@ deletion.reset(); projects.setScope(undefined); revision++; historyRequest++; un const safeModePageOpen = document.documentElement.hasAttribute('data-dsh-safe-mode-page') const surface = remote ? document.querySelector(`[data-dsh-native-surface="${remote.section}"]`) : panel.current // Project dialogs have an explicit lifecycle; yield the native sibling as they open. -const hostModalOpen = projectDialogOpen || cloudDeleteOpen || overlays.isModal(surface) || appRoot?.inert || document.documentElement.hasAttribute('data-dsh-about-open') +const hostModalOpen = projectDialogOpen || cloudDeleteOpen || cloudRenameOpen || overlays.isModal(surface) || appRoot?.inert || document.documentElement.hasAttribute('data-dsh-about-open') const bounds = remote ? remote.bounds : { x, y, width: Math.max(0, rect.right - x), height: Math.max(0, rect.y + rect.height - y) } return presenter.present({ visible: hostModalOpen ? false : (remote ? state.connected && remote.bounds.width > 0 && remote.bounds.height > 0 : mode === 'chat' && (!morph || revealMorph.current === morph) && !surfaceOpen && !safeModePageOpen), ...(remote ? { settings: remote.section } : {}), ...(palette ? { palette } : {}), bounds, theme: document.body.hasAttribute('data-ds-dark-theme') ? 'dark' : 'light', locale: locale.getSnapshot().active === 'zh' ? 'zh' : 'en' }, overlays.intersects(bounds, surface), () => overlays.defer(bounds, surface)) } @@ -1678,7 +1759,7 @@ interaction.observe(document.documentElement, { attributes: true, attributeFilte if (presentSurface.current === present) presentSurface.current = null stopWarmup(); overlays.dispose(); interaction.disconnect(); resize.disconnect(); chromeLayout.disconnect(); theme.disconnect(); unsubscribeLocale(); window.removeEventListener('resize', present) } - }, [mode, morph, usesModuleFrame, squarePage, settingsOpen, state.approvalsOpen, state.accountDialogOpen, settingsSurface, state.connected, state.epoch, state.settingsProtocolVersion, projectDialogOpen, cloudDeleteOpen, locale]) + }, [mode, morph, usesModuleFrame, squarePage, settingsOpen, state.approvalsOpen, state.accountDialogOpen, settingsSurface, state.connected, state.epoch, state.settingsProtocolVersion, projectDialogOpen, cloudDeleteOpen, cloudRenameOpen, locale]) React.useEffect(() => { surfacePresenter.current?.invalidate() }, [state.path, state.pageId, state.phase]) React.useEffect(() => () => { void window.dshEnterpriseChat?.present({ visible: false, bounds: { x: 0, y: 48, width: 0, height: 0 }, theme: 'light' }).catch(() => {}) @@ -1796,14 +1877,19 @@ interaction.observe(document.documentElement, { attributes: true, attributeFilte // their fixed-position containing block attached to the viewport. function installDesktopModes(ctx) { const navigation = createChatNavigation(ctx) - ctx.effect(() => () => navigation.deletion.dispose()) + ctx.effect(() => () => { navigation.deletion.dispose(); navigation.renaming.dispose() }) ctx.effect(() => ctx.locale.register(MODES_NS, MODES_COPY), 'desktop: Chat and Work locale') ctx.effect(() => ctx.locale.register(CLOUD_DELETE_NS, CLOUD_DELETE_COPY)) + ctx.effect(() => ctx.locale.register(CLOUD_RENAME_NS, CLOUD_RENAME_COPY)) ctx.effect(() => ctx.locale.register(PROJECTS_NS, PROJECTS_COPY)) ctx.slots.inject('shell.overlay', () => ctx.slots.register({ name: 'shell.overlay', id: 'desktop-cloud-chat-delete-dialog', locale: CLOUD_DELETE_NS, inject: () => ({ deletion: navigation.deletion, t: ctx.locale.bind(CLOUD_DELETE_NS) }) }, DeleteSessionDialog)) + ctx.slots.inject('shell.overlay', () => ctx.slots.register({ + name: 'shell.overlay', id: 'desktop-cloud-chat-rename-dialog', locale: CLOUD_RENAME_NS, + inject: () => ({ renaming: navigation.renaming, t: ctx.locale.bind(CLOUD_RENAME_NS) }) + }, RenameChatDialog)) ctx.effect(() => { const style = document.createElement('style') style.dataset.plugin = 'dsh-desktop-client-ui' @@ -1916,6 +2002,14 @@ interaction.observe(document.documentElement, { attributes: true, attributeFilte .dshHistoryTitle[data-scrolled][data-clipped]{mask-image:linear-gradient(90deg,transparent,black 12px calc(100% - 12px),transparent)} .dshCloudHistoryPreview{display:grid;gap:4px;overflow-wrap:anywhere;color:var(--dsw-alias-label-primary)} .dshCloudHistoryPreview time{font-size:12px;color:var(--dsw-alias-label-tertiary)} + .dshCloudHistoryStatus{display:flex;align-items:center;gap:6px;font-size:12px;color:var(--dsw-alias-label-secondary)} + .dshHistoryStatus{position:absolute;inset-block:0;inset-inline-start:8px;width:16px;display:inline-flex;align-items:center;justify-content:center;color:var(--dsw-alias-label-tertiary);pointer-events:none} + .dshChatProject .dshHistoryStatus{inset-inline-start:12px} + .dshVisuallyHidden{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap} + .dshChatRenameInput{box-sizing:border-box;width:100%;height:44px;padding:7px 14px;border:.5px solid var(--dsw-alias-border-l4);border-radius:var(--dsw-radius-lg);background:transparent;color:var(--dsw-alias-label-primary);font:inherit;font-size:14px;line-height:22px;outline:none} + .dshChatRenameInput:disabled{color:var(--dsw-alias-label-dimmed)} + .dshChatRenameStatus{margin:8px 0 0;font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary)} + .dshChatRenameError{margin-top:8px;font-size:12px;line-height:18px;color:var(--dsw-alias-state-error-primary)}.dshChatRenameError p{margin:0} @media(hover:none){ .dshSidebarItem .dshSidebarItemTools :is(.dshChatProjectAction,.dshCloudHistoryActions){opacity:1;pointer-events:auto} .dshChatProjectHeading .dshChatProjectToggle{padding-inline-end:64px} @@ -2388,7 +2482,7 @@ interaction.observe(document.documentElement, { attributes: true, attributeFilte pending: 'Deleting session…', failed: 'Deletion failed. Please try again.' } })) - const deletion = createSessionDeletion((sessionId) => { + const deletion = createSessionRequest((sessionId) => { const workspace = ctx.get('uiWorkspace') if (!workspace) throw new Error('Workspace navigation is unavailable') return workspace.deleteSession(sessionId) diff --git a/src/main/enterprise/chat-view.ts b/src/main/enterprise/chat-view.ts index a6ea4cb5..a6e7e9aa 100644 --- a/src/main/enterprise/chat-view.ts +++ b/src/main/enterprise/chat-view.ts @@ -1,7 +1,7 @@ import { join } from 'node:path' import { randomUUID } from 'node:crypto' import { app, session, shell, WebContentsView, type BrowserWindow, type Session } from 'electron' -import { parseEnterpriseNavigation, parseEnterpriseSettingsSection, parseChatPage, parseChatId, parseChatPresentation, type EnterpriseSettingsSection, type EnterpriseChatFrame, type EnterpriseChatHistory, type EnterpriseChatLandingGeometry, type EnterpriseChatPresentation, type EnterpriseChatViewState } from '../../shared/enterprise-chat-view' +import { parseEnterpriseNavigation, parseEnterpriseSettingsSection, parseChatPage, parseChatId, parseChatName, parseChatPresentation, parseRunningConversations, type EnterpriseSettingsSection, type EnterpriseChatFrame, type EnterpriseChatHistory, type EnterpriseChatLandingGeometry, type EnterpriseChatPresentation, type EnterpriseChatViewState } from '../../shared/enterprise-chat-view' import type { EnterpriseDesktopRuntime } from './enterprise-desktop' import { MODULE_ROUTE_PATTERN, MODULE_THEME_CSS, moduleThemeScript } from './chat-module-theme' import { chatDialogViewportScript, guardChatDialogViewportScript } from './chat-dialog-viewport' @@ -95,6 +95,8 @@ export class EnterpriseChatView { private origin?: string private routes = new Map() private deletedConversations = new Set() + /** Reported by the current enterprise document; a new document starts empty and reports again. */ + private running: string[] = [] private view?: WebContentsView private isolated?: Session private owner?: BrowserWindow @@ -151,7 +153,8 @@ export class EnterpriseChatView { conversationId: url?.pathname.match(/\/workspace\/(?:c|chat|linsight)\/([a-zA-Z0-9_-]+)/u)?.[1], connected: account.connected, projectScope: account.connected ? account.connectionKey : undefined, - draftProjectId: projectId && /^[a-zA-Z0-9_-]{1,128}$/u.test(projectId) ? projectId : undefined + draftProjectId: projectId && /^[a-zA-Z0-9_-]{1,128}$/u.test(projectId) ? projectId : undefined, + ...(this.running.length ? { running: this.running } : {}) } } @@ -439,6 +442,32 @@ export class EnterpriseChatView { return { epoch } } + /** Same history grant as deletion. The server also stamps the conversation's update time. */ + async rename(input: unknown, nameInput: unknown, expectedEpoch: unknown): Promise<{ epoch: number }> { + const id = parseChatId(input) + const name = parseChatName(nameInput) + const epoch = this.generation + if (expectedEpoch !== epoch || !this.enterprise.snapshot().connected || !this.routes.has(id)) { + throw new Error('Select a conversation from current Chat history.') + } + if (this.state.phase !== 'ready') await this.connect() + if (epoch !== this.generation || !this.isolated || !this.origin) throw new Error('Chat identity changed.') + const response = await this.isolated.fetch(new URL('/api/v1/chat/conversation/rename', this.origin).href, { + method: 'POST', redirect: 'error', headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ conversationId: id, name }), signal: AbortSignal.timeout(15_000) + }) + if (!response.ok) throw new Error(`Chat rename failed (${response.status}).`) + const result: unknown = await response.json() + if (epoch !== this.generation) throw new Error('Chat identity changed.') + if (!result || typeof result !== 'object' || !('status_code' in result) || result.status_code !== 200) { + throw new Error('Chat rename failed.') + } + this.note('[enterprise-chat] conversation renamed') + // The open document loads a conversation's name once; tell it to read the new one. + if (this.view && !this.view.webContents.isDestroyed()) this.view.webContents.send('enterprise-chat:conversation-renamed', { conversationId: id }) + return { epoch } + } + async open(input: unknown, projectInput?: unknown): Promise { const id = parseChatId(input) const projectId = projectInput === undefined ? undefined : projectUuid(projectInput) @@ -754,6 +783,15 @@ export class EnterpriseChatView { catch { this.note('[enterprise-chat] invalid_navigation_report') } return } + if (channel === 'enterprise-chat:running') { + try { + const running = parseRunningConversations(report.ids) + if (running.join() === this.running.join()) return + this.running = running + this.notify() + } catch { this.note('[enterprise-chat] invalid_running_report') } + return + } if (channel !== 'enterprise-chat:landing' || !/^\/workspace\/c\/[a-zA-Z0-9_-]+$/u.test(url.pathname) || typeof report.landing !== 'boolean') return this.landing = url.pathname === '/workspace/c/new' && report.landing this.landingPath = url.pathname @@ -768,6 +806,8 @@ export class EnterpriseChatView { this.landingPath = undefined this.welcomeCases = undefined this.layout() + // Streams belong to the outgoing document; the next one reports its own. + if (this.running.length) { this.running = []; this.notify() } } if (isMainFrame && !isInPlace && generation === this.generation && this.view === view && this.settingsSection) { this.settingsReady = false @@ -1052,6 +1092,7 @@ export class EnterpriseChatView { this.origin = undefined this.routes.clear() this.deletedConversations.clear() + this.running = [] const view = this.view const isolated = this.isolated this.view = undefined diff --git a/src/main/index.ts b/src/main/index.ts index ef39c3b1..6d50461a 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -1738,7 +1738,7 @@ function registerHarnessHandlers(): void { } }) - for (const channel of ['enterprise-chat:present', 'enterprise-chat:capture', 'enterprise-chat:landing-geometry', 'enterprise-chat:landing-text-motion', 'enterprise-chat:state', 'enterprise-chat:retry', 'enterprise-chat:usage', 'enterprise-chat:history', 'enterprise-chat:open', 'enterprise-chat:remove', 'enterprise-chat:open-page', 'enterprise-chat:focus-settings', 'enterprise-chat:projects-state', 'enterprise-chat:project-action', 'enterprise-chat:project-conversations']) ipcMain.removeHandler(channel) + for (const channel of ['enterprise-chat:present', 'enterprise-chat:capture', 'enterprise-chat:landing-geometry', 'enterprise-chat:landing-text-motion', 'enterprise-chat:state', 'enterprise-chat:retry', 'enterprise-chat:usage', 'enterprise-chat:history', 'enterprise-chat:open', 'enterprise-chat:remove', 'enterprise-chat:rename', 'enterprise-chat:open-page', 'enterprise-chat:focus-settings', 'enterprise-chat:projects-state', 'enterprise-chat:project-action', 'enterprise-chat:project-conversations']) ipcMain.removeHandler(channel) ipcMain.handle('enterprise-chat:projects-state', (event) => { assertTrustedMainWindowEvent(event) return enterpriseChat?.projectsState() @@ -1803,6 +1803,11 @@ function registerHarnessHandlers(): void { if (!enterpriseChat) throw new Error('Enterprise Chat unavailable.') return enterpriseChat.remove(id, epoch) }) + ipcMain.handle('enterprise-chat:rename', (event, id: unknown, name: unknown, epoch: unknown) => { + assertTrustedMainWindowEvent(event) + if (!enterpriseChat) throw new Error('Enterprise Chat unavailable.') + return enterpriseChat.rename(id, name, epoch) + }) ipcMain.removeHandler('harness:restart') ipcMain.handle('harness:restart', async (event) => { if (!mainWindow || mainWindow.isDestroyed() || event.sender !== mainWindow.webContents) { diff --git a/src/preload/enterprise-chat.ts b/src/preload/enterprise-chat.ts index c74ecf18..758560fe 100644 --- a/src/preload/enterprise-chat.ts +++ b/src/preload/enterprise-chat.ts @@ -20,6 +20,19 @@ contextBridge.exposeInMainWorld('dshChatPresentation', Object.freeze({ ipcRenderer.on('enterprise-chat:projects-changed', receive) return () => ipcRenderer.removeListener('enterprise-chat:projects-changed', receive) }, + onConversationRenamed(listener: unknown): () => void { + if (typeof listener !== 'function') throw new TypeError('Rename listener must be a function.') + const receive = (_event: Electron.IpcRendererEvent, detail: unknown): void => { + const id = detail && typeof detail === 'object' ? (detail as { conversationId?: unknown }).conversationId : undefined + if (typeof id === 'string') listener(id) + } + ipcRenderer.on('enterprise-chat:conversation-renamed', receive) + return () => ipcRenderer.removeListener('enterprise-chat:conversation-renamed', receive) + }, + /** Conversations whose replies or tasks are still running in this document. */ + reportRunning(ids: unknown): void { + ipcRenderer.send('enterprise-chat:running', { ids, path: window.location.pathname }) + }, reportNavigation(navigation: unknown): void { ipcRenderer.send('enterprise-chat:navigation', { navigation, path: window.location.pathname }) }, diff --git a/src/preload/index.ts b/src/preload/index.ts index e8aa3e1c..bb5ac3f2 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -649,6 +649,7 @@ contextBridge.exposeInMainWorld('dshEnterpriseChat', Object.freeze({ openPage: (id: string): Promise => ipcRenderer.invoke('enterprise-chat:open-page', id), open: (id: string, projectId?: string): Promise => ipcRenderer.invoke('enterprise-chat:open', id, projectId), remove: (id: string, epoch: number): Promise<{ epoch: number }> => ipcRenderer.invoke('enterprise-chat:remove', id, epoch), + rename: (id: string, name: string, epoch: number): Promise<{ epoch: number }> => ipcRenderer.invoke('enterprise-chat:rename', id, name, epoch), subscribe: (listener: (state: EnterpriseChatViewState) => void): (() => void) => { const receive = (_event: Electron.IpcRendererEvent, state: EnterpriseChatViewState): void => listener(state) ipcRenderer.on('enterprise-chat:changed', receive) diff --git a/src/shared/enterprise-chat-view.ts b/src/shared/enterprise-chat-view.ts index 8236599a..d869c26b 100644 --- a/src/shared/enterprise-chat-view.ts +++ b/src/shared/enterprise-chat-view.ts @@ -93,6 +93,8 @@ export interface EnterpriseChatViewState { settingsSection?: EnterpriseSettingsSection settingsReady?: boolean settingsFailure?: 'load' | 'unsupported' + /** Cloud conversations the enterprise document reports as generating; absent until it reports any. */ + running?: string[] } export function parseChatPresentation(value: unknown): EnterpriseChatPresentation { @@ -138,6 +140,20 @@ export function parseChatId(value: unknown): string { if (typeof value !== 'string' || !/^[a-zA-Z0-9_-]{1,128}$/u.test(value)) throw new Error('Invalid Chat identity.') return value } +/** BiSheng stores conversation names in message_session.name, a VARCHAR(255) column. */ +export const CHAT_NAME_MAX_LENGTH = 255 +export function parseChatName(value: unknown): string { + if (typeof value !== 'string') throw new Error('Invalid Chat name.') + const name = value.trim() + if (!name || [...name].length > CHAT_NAME_MAX_LENGTH || /\p{Cc}/u.test(name)) throw new Error('Invalid Chat name.') + return name +} +const MAX_RUNNING_CONVERSATIONS = 100 +/** Activity is presentation data from the enterprise document, never an authorization signal. */ +export function parseRunningConversations(value: unknown): string[] { + if (!Array.isArray(value) || value.length > MAX_RUNNING_CONVERSATIONS) throw new Error('Invalid Chat activity.') + return [...new Set(value.map(parseChatId))].sort() +} export interface EnterpriseNavigationEntry { id: string diff --git a/test/cloud-chat-rename-running.test.mjs b/test/cloud-chat-rename-running.test.mjs new file mode 100644 index 00000000..73306de5 --- /dev/null +++ b/test/cloud-chat-rename-running.test.mjs @@ -0,0 +1,231 @@ +// @vitest-environment jsdom +import { readFileSync } from 'node:fs' +import React, { act } from 'react' +import { createRoot } from 'react-dom/client' +import { afterEach, beforeAll, expect, it, vi } from 'vitest' +import { loadSidebarPrimitives } from './helpers/sidebar-primitives.mjs' + +globalThis.IS_REACT_ACT_ENVIRONMENT = true +const source = readFileSync('packages/dsh-desktop-client-ui/client.js', 'utf8') +let primitives, cleanup +beforeAll(() => { + primitives = loadSidebarPrimitives(['Modal', 'Menu', 'MenuItemButton', 'Button', 'HoverCard', 'StateDot', 'relativeTime', + ...['ChevronRightOutline', 'EditOutline', 'EllipsisOutline', 'FolderClose', 'FolderOpen', 'NewChatOutline', 'PlusOutline', 'TrashOutline', 'TriangleRightFill'].map(icon => `Icon${icon}Regular`)]) +}) +afterEach(async () => { await cleanup?.(); cleanup = undefined; vi.restoreAllMocks() }) + +async function fixture({ language = 'zh', rename = async () => {} } = {}) { + let plugin + const entries = new Map(), dictionaries = new Map(), disposers = [] + let state = { connected: true, phase: 'ready', epoch: 1, conversationId: 'cloud-a' }, listener + let items = [{ id: 'cloud-a', title: '季度复盘', updatedAt: '2026-11-03' }, { id: 'cloud-b', title: '', updatedAt: '2026-11-02' }] + const bridge = { + state: async () => state, + subscribe: fn => { listener = fn; return () => { listener = undefined } }, + history: vi.fn(async () => ({ epoch: state.epoch, items: items.map(item => ({ ...item })), hasMore: false })), + rename: vi.fn(async (id, name, epoch) => { + await rename(id, name) + if (epoch === state.epoch) items = items.map(item => item.id === id ? { ...item, title: name, updatedAt: '2026-11-09' } : item) + return { epoch } + }), + remove: vi.fn(async (_id, epoch) => ({ epoch })), + open: vi.fn(async () => {}) + } + window.dshEnterpriseChat = bridge + window.__ModuleLoader__ = { load({ factory }) { + plugin = factory(name => { + if (name === 'react') return React + if (name === '@deepseek-ai/dsh-client-ui-primitives') return primitives + throw new Error(name) + }) + } } + new Function(source)() + plugin.apply({ + uiWorkspace: { registerNavigationHandler: () => () => {} }, + sessions: { list: { getSnapshot: () => ({ phase: 'ready', byId: {} }), subscribe: () => () => {} } }, + layout: { panelInfo: { getSnapshot: () => ({ activePanelId: null }), subscribe: () => () => {} } }, + get: () => ({ deleteSession: vi.fn() }), + effect(fn) { const dispose = fn(); if (typeof dispose === 'function') disposers.push(dispose) }, + locale: { + register(ns, dictionary) { dictionaries.set(ns, dictionary); return () => dictionaries.delete(ns) }, + bind: ns => (key, args = {}) => dictionaries.get(ns)[language][key].replace(/\{(\w+)\}/g, (_, name) => args[name]) + }, + slots: { + inject(name, fn) { if (['shell.overlay', 'sidebar.workspaces.collection'].includes(name)) fn() }, + register(meta, Component) { entries.set(meta.id, { meta, Component }); return () => {} } + } + }) + const collection = entries.get('desktop-shared-collection'), overlay = entries.get('desktop-cloud-chat-rename-dialog') + expect(overlay.meta.locale).toBe('desktop.cloudChatRename') + const collectionProps = collection.meta.inject(), overlayProps = overlay.meta.inject() + disposers.push(collectionProps.navigation.start()) + const container = document.createElement('div') + document.body.append(container) + const root = createRoot(container) + await act(async () => root.render(React.createElement(React.Fragment, null, + React.createElement(collection.Component, { ...collectionProps, mode: 'projects', query: '', archivedOnly: false, items: [], projects: () => null }), + React.createElement(overlay.Component, overlayProps)))) + const settle = () => act(async () => new Promise(resolve => setTimeout(resolve, 0))) + await settle() + const click = async label => { + const button = [...document.querySelectorAll('button')].find(node => node.textContent === label) + expect(button, label).toBeDefined() + act(() => button.click()) + await settle() + } + cleanup = async () => { + await act(async () => root.unmount()) + disposers.reverse().forEach(dispose => dispose()) + container.remove() + delete window.dshEnterpriseChat + delete window.__ModuleLoader__ + } + const row = title => document.querySelector(`[data-history-kind=chat][aria-label="${title}"]`)?.closest('.dshCloudHistoryRow') + return { + bridge, click, settle, row, + navigation: collectionProps.navigation, + renaming: overlayProps.renaming, + dialog: () => document.querySelector('[role=dialog]'), + input: () => document.querySelector('[role=dialog] input'), + async menu(title) { + const trigger = row(title).querySelector('.dshCloudHistoryActions') + trigger.focus() + await act(async () => trigger.click()) + return [...document.querySelectorAll('[role=menuitem]')].map(node => node.textContent) + }, + async type(value) { + const input = document.querySelector('[role=dialog] input') + const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set + await act(async () => { setter.call(input, value); input.dispatchEvent(new Event('input', { bubbles: true })) }) + }, + async key(key, init = {}) { + await act(async () => document.querySelector('[role=dialog] input').dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true, ...init }))) + await settle() + }, + async push(patch) { state = { ...state, ...patch }; await act(async () => listener(state)); await settle() } + } +} + +it.each([ + ['zh', ['重命名', '移入项目', '删除'], '重命名会话', '取消'], + ['en', ['Rename', 'Move to project', 'Delete'], 'Rename conversation', 'Cancel'] +])('renames a cloud conversation from its row menu in %s', async (language, menu, title, cancel) => { + const ui = await fixture({ language }) + expect(await ui.menu('季度复盘')).toEqual(menu) + await ui.click(menu[0]) + expect(document.querySelector('[role=menu]')).toBeNull() + expect(ui.dialog().textContent).toContain(title) + expect(ui.input().value).toBe('季度复盘') + expect(document.activeElement).toBe(ui.input()) + expect([...ui.dialog().querySelectorAll('button')].map(node => node.textContent)).toContain(cancel) + const reads = ui.bridge.history.mock.calls.length + await ui.type(' 年度复盘 ') + await ui.key('Enter') + expect(ui.bridge.rename).toHaveBeenCalledWith('cloud-a', '年度复盘', 1) + expect(ui.dialog()).toBeNull() + expect(ui.row('年度复盘')).toBeTruthy() + expect(ui.row('季度复盘')).toBeFalsy() + expect(ui.bridge.history.mock.calls.length).toBeGreaterThan(reads) +}) + +it('starts an unnamed conversation with an empty draft and keeps blank names blocked', async () => { + const ui = await fixture() + await ui.menu('新聊天') + await ui.click('重命名') + const confirm = () => [...ui.dialog().querySelectorAll('button')].find(node => node.textContent === '重命名') + expect(ui.input().value).toBe('') + expect(confirm().disabled).toBe(true) + await ui.type(' ') + await ui.key('Enter') + expect(confirm().disabled).toBe(true) + expect(ui.bridge.rename).not.toHaveBeenCalled() + await ui.click('取消') + expect(ui.dialog()).toBeNull() + expect(ui.bridge.rename).not.toHaveBeenCalled() +}) + +it('does not submit while an input method is composing', async () => { + const ui = await fixture() + await ui.menu('季度复盘') + await ui.click('重命名') + await ui.type('jidu') + await act(async () => ui.input().dispatchEvent(new CompositionEvent('compositionstart', { bubbles: true }))) + await ui.key('Enter') + expect(ui.bridge.rename).not.toHaveBeenCalled() + await ui.type('季度') + await act(async () => ui.input().dispatchEvent(new CompositionEvent('compositionend', { bubbles: true }))) + await ui.key('Enter') + expect(ui.bridge.rename).toHaveBeenCalledWith('cloud-a', '季度', 1) +}) + +it('opens rename from a title double-click like Work rows', async () => { + const ui = await fixture() + const title = ui.row('季度复盘').querySelector('.dshHistoryTitle') + await act(async () => title.dispatchEvent(new MouseEvent('dblclick', { bubbles: true }))) + await ui.settle() + expect(ui.input().value).toBe('季度复盘') +}) + +it('locks the dialog while saving and keeps a failed rename retryable', async () => { + let fail + const rename = vi.fn() + .mockImplementationOnce(() => new Promise((_resolve, reject) => { fail = reject })) + .mockResolvedValue(undefined) + const ui = await fixture({ rename }) + await ui.menu('季度复盘') + await ui.click('重命名') + await ui.type('年度复盘') + await ui.key('Enter') + expect(ui.dialog().querySelector('[role=status]').textContent).toBe('正在重命名…') + expect(ui.input().disabled).toBe(true) + await act(async () => { ui.renaming.close(); void ui.renaming.confirm('again') }) + expect(ui.dialog()).toBeTruthy() + expect(ui.bridge.rename).toHaveBeenCalledTimes(1) + await act(async () => fail(new Error('offline'))) + await ui.settle() + const alert = ui.dialog().querySelector('[role=alert]') + expect(alert.textContent).toContain('重命名失败,请重试。') + expect(alert.textContent).toContain('offline') + expect(ui.input().value).toBe('年度复盘') + expect(ui.row('季度复盘')).toBeTruthy() + await ui.key('Enter') + expect(ui.dialog()).toBeNull() + expect(ui.bridge.rename).toHaveBeenCalledTimes(2) + expect(ui.row('年度复盘')).toBeTruthy() +}) + +it('drops a pending rename when the account changes', async () => { + const ui = await fixture() + await ui.menu('季度复盘') + await ui.click('重命名') + await ui.push({ epoch: 2 }) + expect(ui.dialog()).toBeNull() + await act(async () => ui.renaming.confirm('年度复盘')) + expect(ui.bridge.rename).not.toHaveBeenCalled() +}) + +it.each([['zh', '进行中'], ['en', 'Running']])('shows host-reported activity on cloud rows in %s', async (language, label) => { + const ui = await fixture({ language }) + const unnamed = language === 'zh' ? '新聊天' : 'New chat' + const status = title => ui.row(title).querySelector('.dshHistoryStatus') + expect(status('季度复盘')).toBeNull() + await ui.push({ running: ['cloud-a', 'cloud-gone'] }) + const indicator = status('季度复盘') + expect(indicator.querySelector('svg[data-state=ongoing]')).toBeTruthy() + const description = ui.row('季度复盘').querySelector('[data-history-kind=chat]').getAttribute('aria-describedby').split(' ') + expect(description.map(id => document.getElementById(id)?.textContent)).toContain(label) + expect(status(unnamed)).toBeNull() + // The host omits an empty list; absence clears the previous activity. + const { running, ...rest } = ui.navigation.snapshot() + expect(running).toEqual(['cloud-a', 'cloud-gone']) + await ui.push({ ...rest, running: undefined }) + expect(status('季度复盘')).toBeNull() + expect(ui.navigation.snapshot().running).toEqual([]) +}) + +it('clears activity when the account signs out', async () => { + const ui = await fixture() + await ui.push({ running: ['cloud-a'] }) + await ui.push({ connected: false, running: ['cloud-a'] }) + expect(ui.navigation.snapshot().running).toEqual([]) +}) diff --git a/test/desktop-account-presentation.test.mjs b/test/desktop-account-presentation.test.mjs index ae8b7144..f25d8e17 100644 --- a/test/desktop-account-presentation.test.mjs +++ b/test/desktop-account-presentation.test.mjs @@ -13,7 +13,8 @@ const noDialog = () => null const projectSnapshot = { editor: null } const modalControllers = () => ({ projects: { subscribe: () => () => {}, snapshot: () => projectSnapshot }, - deletion: { subscribe: () => () => {}, getSnapshot: noDialog } + deletion: { subscribe: () => () => {}, getSnapshot: noDialog }, + renaming: { subscribe: () => () => {}, getSnapshot: noDialog } }) const HOST_COLORS = { diff --git a/test/desktop-client-ui.test.ts b/test/desktop-client-ui.test.ts index 33f08ed4..dd821ab6 100644 --- a/test/desktop-client-ui.test.ts +++ b/test/desktop-client-ui.test.ts @@ -104,7 +104,9 @@ describe('BISHENG client slot occupants', () => { }) expect(plugin.inject).toEqual(['slots', 'locale', 'remote', 'remote.session', 'sessions', 'uiWorkspace', 'layout']) + // Overlays: Work session deletion, cloud Chat deletion and cloud Chat rename. expect(registrations.map(({ config }) => config.name)).toEqual([ + 'shell.overlay', 'shell.overlay', 'shell.overlay', 'sidebar.primaryNavigation', diff --git a/test/desktop-modes-ui.test.mjs b/test/desktop-modes-ui.test.mjs index 68ba648e..f76f6c92 100644 --- a/test/desktop-modes-ui.test.mjs +++ b/test/desktop-modes-ui.test.mjs @@ -293,6 +293,16 @@ it('delivers the active Harness language while settings hides Chat and cleans up expect(window.dshEnterpriseChat.present).toHaveBeenCalledTimes(calls) }) +it('hides Chat while a cloud rename dialog is open and restores it afterwards', async () => { + const ui = await mount(true) + expect(window.dshEnterpriseChat.present).toHaveBeenLastCalledWith(expect.objectContaining({ visible: true })) + // The dialog renders in the host document, beneath the native Chat view. + await act(async () => ui.controller.requestRename('cloud-a', 'Cloud chat', 1)) + expect(window.dshEnterpriseChat.present).toHaveBeenLastCalledWith(expect.objectContaining({ visible: false })) + await act(async () => ui.controller.renaming.close()) + expect(window.dshEnterpriseChat.present).toHaveBeenLastCalledWith(expect.objectContaining({ visible: true })) +}) + it('hides Chat while a sidebar account dialog is open and restores it afterwards', async () => { await mount(true) expect(window.dshEnterpriseChat.present).toHaveBeenLastCalledWith(expect.objectContaining({ visible: true })) @@ -392,7 +402,8 @@ it('places cloud projects between workspaces and conversations and files each ch await act(async () => filed.dispatchEvent(shortcut)) expect(shortcut.defaultPrevented).toBe(true) expect(container.querySelector('[data-chat-project] .dshCloudHistoryActions').getAttribute('aria-expanded')).toBe('true') - expect([...container.querySelectorAll('[role=menuitem]')].map(node => node.textContent)).toEqual(['Move to project', 'menu']) + // Cloud rows lead with Rename, as Work rows do; this harness echoes non-project keys. + expect([...container.querySelectorAll('[role=menuitem]')].map(node => node.textContent)).toEqual(['rename', 'Move to project', 'menu']) await act(async () => move().click()) expect(destination()).toBeUndefined() expect(choices().map(node => node.textContent)).toEqual(['New project', 'Another project', 'Move out of project']) diff --git a/test/enterprise-chat-view.test.ts b/test/enterprise-chat-view.test.ts index 13983fef..22390147 100644 --- a/test/enterprise-chat-view.test.ts +++ b/test/enterprise-chat-view.test.ts @@ -1577,3 +1577,152 @@ describe('cloud conversation deletion', () => { } finally { f.host.dispose() } }) }) + +// Rename uses BiSheng's own conversation rename endpoint under the history grant deletion uses. +describe('cloud conversation rename', () => { + it('posts the trimmed name for a listed conversation and tells the open document', async () => { + const f = fixture() + try { + f.host.present(f.owner, presentation) + await flush() + await f.host.history(1) + await f.host.open('cloud-a') + const epoch = f.host.snapshot().epoch + const fetch = fake.sessions[0].fetch + fetch.mockResolvedValueOnce(new Response(JSON.stringify({ status_code: 200 }))) + await expect(f.host.rename('cloud-a', ' 季度复盘 ', epoch)).resolves.toEqual({ epoch }) + const [url, init] = fetch.mock.lastCall + expect(url).toBe('https://enterprise.example/api/v1/chat/conversation/rename') + expect(init).toMatchObject({ method: 'POST', redirect: 'error', headers: { 'content-type': 'application/json' }, signal: expect.any(AbortSignal) }) + expect(JSON.parse(init.body)).toEqual({ conversationId: 'cloud-a', name: '季度复盘' }) + expect(fake.views[0].webContents.send).toHaveBeenCalledWith('enterprise-chat:conversation-renamed', { conversationId: 'cloud-a' }) + // Unlike deletion, rename keeps the open document and the conversation's navigation grant. + expect(fake.views[0].webContents.loadURL).not.toHaveBeenLastCalledWith(expect.stringContaining('/workspace/c/new')) + await expect(f.host.open('cloud-a')).resolves.toBeUndefined() + } finally { f.host.dispose() } + }) + + it.each([ + ['a stale identity', 'cloud-a', 'Name', -1], + ['an unlisted conversation', 'unknown', 'Name', undefined], + ['a forged identity', '../cloud-a', 'Name', undefined], + ['an empty name', 'cloud-a', ' ', undefined], + ['a non-string name', 'cloud-a', 42, undefined], + ['a control character', 'cloud-a', 'line\nbreak', undefined], + ['a name beyond the column', 'cloud-a', '名'.repeat(256), undefined] + ])('rejects %s before calling the server', async (_label, id, name, staleEpoch) => { + const f = fixture() + try { + f.host.present(f.owner, presentation) + await flush() + await f.host.history(1) + const fetch = fake.sessions[0].fetch + fetch.mockClear() + await expect(f.host.rename(id, name, staleEpoch ?? f.host.snapshot().epoch)).rejects.toThrow() + expect(fetch).toHaveBeenCalledTimes(0) + expect(fake.views[0].webContents.send).not.toHaveBeenCalledWith('enterprise-chat:conversation-renamed', expect.anything()) + } finally { f.host.dispose() } + }) + + it('accepts a name at the column limit counted in characters', async () => { + const f = fixture() + try { + f.host.present(f.owner, presentation) + await flush() + await f.host.history(1) + fake.sessions[0].fetch.mockResolvedValueOnce(new Response(JSON.stringify({ status_code: 200 }))) + const name = '😀'.repeat(255) + await f.host.rename('cloud-a', name, f.host.snapshot().epoch) + expect(JSON.parse(fake.sessions[0].fetch.mock.lastCall[1].body).name).toBe(name) + } finally { f.host.dispose() } + }) + + it.each([new Response('', { status: 403 }), new Response(JSON.stringify({ status_code: 500 })), new Response('invalid')])('reports a failed rename without notifying the document', async response => { + const f = fixture() + try { + f.host.present(f.owner, presentation) + await flush() + await f.host.history(1) + const epoch = f.host.snapshot().epoch + fake.sessions[0].fetch.mockResolvedValueOnce(response) + await expect(f.host.rename('cloud-a', 'Name', epoch)).rejects.toThrow() + expect(fake.views[0].webContents.send).not.toHaveBeenCalledWith('enterprise-chat:conversation-renamed', expect.anything()) + fake.sessions[0].fetch.mockResolvedValueOnce(new Response(JSON.stringify({ status_code: 200 }))) + await expect(f.host.rename('cloud-a', 'Name', epoch)).resolves.toEqual({ epoch }) + } finally { f.host.dispose() } + }) + + it('discards a rename response after logout', async () => { + const f = fixture() + try { + f.host.present(f.owner, presentation) + await flush() + await f.host.history(1) + let finish: (response: Response) => void = () => {} + fake.sessions[0].fetch.mockImplementationOnce(() => new Promise(resolve => { finish = resolve })) + const pending = f.host.rename('cloud-a', 'Name', f.host.snapshot().epoch) + const rejected = expect(pending).rejects.toThrow('identity changed') + f.change({ connected: false, connectionKey: 'tenant-a' }) + finish(new Response(JSON.stringify({ status_code: 200 }))) + await rejected + } finally { f.host.dispose() } + }) +}) + +// The enterprise document reports which conversations it is still generating. +describe('cloud conversation activity', () => { + async function ready() { + const f = fixture() + f.host.present(f.owner, presentation) + await flush() + const wc = fake.views[0].webContents + await wc.loadURL('https://enterprise.example/workspace/c/cloud-a') + const report = (input: unknown, frame: unknown = wc.mainFrame) => wc.emit('ipc-message', { senderFrame: frame }, 'enterprise-chat:running', input) + return { f, wc, report } + } + + it('publishes a sorted, unique list from the current main frame', async () => { + const { f, report } = await ready() + try { + expect(f.host.snapshot().running).toBeUndefined() + report({ ids: ['cloud-b', 'cloud-a', 'cloud-b'], path: '/workspace/c/cloud-a' }) + expect(f.host.snapshot().running).toEqual(['cloud-a', 'cloud-b']) + expect(f.owner.webContents.send).toHaveBeenLastCalledWith('enterprise-chat:changed', expect.objectContaining({ running: ['cloud-a', 'cloud-b'] })) + const sends = f.owner.webContents.send.mock.calls.length + report({ ids: ['cloud-a', 'cloud-b'], path: '/workspace/c/cloud-a' }) + expect(f.owner.webContents.send.mock.calls.length).toBe(sends) + report({ ids: [], path: '/workspace/c/cloud-a' }) + expect(f.host.snapshot().running).toBeUndefined() + } finally { f.host.dispose() } + }) + + it.each([ + ['a subframe', { ids: ['cloud-x'], path: '/workspace/c/cloud-a' }, {}], + ['another path', { ids: ['cloud-x'], path: '/workspace/c/other' }, undefined], + ['a forged identity', { ids: ['../cloud-x'], path: '/workspace/c/cloud-a' }, undefined], + ['a non-array', { ids: 'cloud-x', path: '/workspace/c/cloud-a' }, undefined], + ['an oversized list', { ids: Array.from({ length: 101 }, (_, i) => `cloud-${i}`), path: '/workspace/c/cloud-a' }, undefined] + ])('ignores a report from %s and keeps the previous list', async (_label, input, frame) => { + const { f, report } = await ready() + try { + report({ ids: ['cloud-a'], path: '/workspace/c/cloud-a' }) + report(input, frame) + expect(f.host.snapshot().running).toEqual(['cloud-a']) + } finally { f.host.dispose() } + }) + + it('clears activity when the document is replaced or the account signs out', async () => { + const { f, wc, report } = await ready() + try { + report({ ids: ['cloud-a'], path: '/workspace/c/cloud-a' }) + wc.emit('did-start-navigation', {}, wc.getURL(), true, true) + expect(f.host.snapshot().running).toEqual(['cloud-a']) + wc.emit('did-start-navigation', {}, wc.getURL(), false, true) + expect(f.host.snapshot().running).toBeUndefined() + expect(f.owner.webContents.send).toHaveBeenLastCalledWith('enterprise-chat:changed', expect.not.objectContaining({ running: expect.anything() })) + report({ ids: ['cloud-a'], path: '/workspace/c/cloud-a' }) + f.change({ connected: false, connectionKey: 'tenant-a' }) + expect(f.host.snapshot().running).toBeUndefined() + } finally { f.host.dispose() } + }) +}) diff --git a/test/helpers/session-search-fixture.mjs b/test/helpers/session-search-fixture.mjs index 277cb9da..d630f7a7 100644 --- a/test/helpers/session-search-fixture.mjs +++ b/test/helpers/session-search-fixture.mjs @@ -36,7 +36,7 @@ export function createSessionSearchFixture(workspaceSource, desktopSource, { gro const catalog = { phase: 'ready', projectionsBySession: {}, ids: ['one', 'two'], byId: Object.fromEntries(['one', 'two'].map(id => [id, { id, title: `会话 ${id}`, updatedAt: 1, blank: false, retainedBy: {} }])) } const workspaces = { phase: 'ready', state: 'ready', items: [], archivedSessionIds: [], pinnedSessionIds: [] } const view = { groupBy, orderBy: 'updated', archivedFilter: archivedOnly ? 'only' : 'default', groupExpansion: { '': true }, sessionOrderByAccount: {}, unreadSessionIds: [] } - let cloud = { mode: 'work', page: 1, historyPhase: 'ready', items: [{ id: 'cloud', title: '云端会话', updatedAt: '2026-01-01T00:00:00Z' }] } + let cloud = { mode: 'work', page: 1, historyPhase: 'ready', running: [], items: [{ id: 'cloud', title: '云端会话', updatedAt: '2026-01-01T00:00:00Z' }] } const cloudListeners = new Set() const opened = [] const navigation = { projects: createChatProjects(), snapshot: () => cloud, subscribe: fn => { cloudListeners.add(fn); return () => cloudListeners.delete(fn) }, open: id => opened.push(`chat:${id}`) } diff --git a/test/helpers/sidebar-primitives.mjs b/test/helpers/sidebar-primitives.mjs new file mode 100644 index 00000000..68d5095e --- /dev/null +++ b/test/helpers/sidebar-primitives.mjs @@ -0,0 +1,39 @@ +import { execFileSync } from 'node:child_process' +import React from 'react' +import * as ReactDOM from 'react-dom' +import * as jsxRuntime from 'react/jsx-runtime' + +/** + * Load the installed sidebar primitives for jsdom tests. The distributed ESM also + * initializes unrelated markdown highlighters, so only the UI prefix through Modal + * and the relative-time helper are bundled, with their real focus and menu behavior. + * @param {string[]} names - primitive exports the test needs. + */ +export function loadSidebarPrimitives(names) { + const bundle = execFileSync(process.execPath, ['--input-type=module', '-e', + `import { build } from 'esbuild'; import { readFileSync } from 'node:fs'; import { createRequire } from 'node:module'; + const require = createRequire(import.meta.url); + const source = readFileSync(require.resolve('@deepseek-ai/dsh-client-ui-primitives'), 'utf8'); + const boundary = source.indexOf('//#region lib/types/RiskConfirmation.js'); + const timeStart = source.indexOf('//#region lib/types/relative-time.js'); + const timeEnd = source.indexOf('//#region lib/types/rank-by-name.js', timeStart); + if (boundary < 0 || timeStart < boundary || timeEnd < timeStart) throw new Error('Recheck the installed primitive layout'); + const result = await build({ stdin: { contents: source.slice(0, boundary) + source.slice(timeStart, timeEnd) + '\\nexport { ${names.join(', ')} };', resolveDir: process.cwd() }, + bundle: true, write: false, format: 'cjs', platform: 'browser', + plugins: [{ name: 'ui-only', setup(build) { + build.onResolve({ filter: /\\.css$/ }, args => ({ path: args.path, namespace: 'css' })); + build.onLoad({ filter: /.*/, namespace: 'css' }, () => ({ contents: 'export default {}', loader: 'js' })); + build.onResolve({ filter: /^[^./]/ }, args => ({ path: args.path, external: true, sideEffects: false })); + } }] + }); process.stdout.write(result.outputFiles[0].text)` + ], { encoding: 'utf8', maxBuffer: 4_000_000 }) + const module = { exports: {} } + new Function('module', 'exports', 'require', bundle)(module, module.exports, name => { + if (name === 'react') return React + if (name === 'react-dom') return ReactDOM + if (name === 'react/jsx-runtime') return jsxRuntime + if (name === 'clsx') return (...values) => values.filter(Boolean).join(' ') + throw new Error(name) + }) + return module.exports +} From cde9ef9c84fee2d730f0fd20a43a353b7f42b133 Mon Sep 17 00:00:00 2001 From: codesstar <825323057@qq.com> Date: Wed, 11 Nov 2026 16:27:15 +0800 Subject: [PATCH 2/3] test(desktop): send rejected activity reports from the main frame explicitly --- test/enterprise-chat-view.test.ts | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/test/enterprise-chat-view.test.ts b/test/enterprise-chat-view.test.ts index 22390147..051a8254 100644 --- a/test/enterprise-chat-view.test.ts +++ b/test/enterprise-chat-view.test.ts @@ -1696,17 +1696,18 @@ describe('cloud conversation activity', () => { } finally { f.host.dispose() } }) + // Only the subframe case leaves the main frame, so every other case reaches the path and list checks. it.each([ - ['a subframe', { ids: ['cloud-x'], path: '/workspace/c/cloud-a' }, {}], - ['another path', { ids: ['cloud-x'], path: '/workspace/c/other' }, undefined], - ['a forged identity', { ids: ['../cloud-x'], path: '/workspace/c/cloud-a' }, undefined], - ['a non-array', { ids: 'cloud-x', path: '/workspace/c/cloud-a' }, undefined], - ['an oversized list', { ids: Array.from({ length: 101 }, (_, i) => `cloud-${i}`), path: '/workspace/c/cloud-a' }, undefined] - ])('ignores a report from %s and keeps the previous list', async (_label, input, frame) => { - const { f, report } = await ready() + ['a subframe', { ids: ['cloud-x'], path: '/workspace/c/cloud-a' }, 'subframe'], + ['another path', { ids: ['cloud-x'], path: '/workspace/c/other' }, 'main'], + ['a forged identity', { ids: ['../cloud-x'], path: '/workspace/c/cloud-a' }, 'main'], + ['a non-array', { ids: 'cloud-x', path: '/workspace/c/cloud-a' }, 'main'], + ['an oversized list', { ids: Array.from({ length: 101 }, (_, i) => `cloud-${i}`), path: '/workspace/c/cloud-a' }, 'main'] + ])('ignores a report from %s and keeps the previous list', async (_label, input, sender) => { + const { f, wc, report } = await ready() try { report({ ids: ['cloud-a'], path: '/workspace/c/cloud-a' }) - report(input, frame) + report(input, sender === 'main' ? wc.mainFrame : {}) expect(f.host.snapshot().running).toEqual(['cloud-a']) } finally { f.host.dispose() } }) From 3d6657453fb969ab78e81817a1f9eb19347e2b92 Mon Sep 17 00:00:00 2001 From: codesstar <825323057@qq.com> Date: Wed, 11 Nov 2026 17:33:38 +0800 Subject: [PATCH 3/3] fix(desktop): rename conversations shown in project pages and search results Project pages and the current search keep their own copies of a conversation, so a rename now updates them in place (they are ordered by creation time and are not reread). A page requested before the rename finished keeps the new name. Every row the sidebar shows can open the rename dialog; the host still checks its own routes. --- packages/dsh-desktop-client-ui/client.js | 42 ++++++++-- test/cloud-chat-rename-running.test.mjs | 100 ++++++++++++++++++++++- test/enterprise-chat-view.test.ts | 26 ++++++ 3 files changed, 155 insertions(+), 13 deletions(-) diff --git a/packages/dsh-desktop-client-ui/client.js b/packages/dsh-desktop-client-ui/client.js index de6ea28b..d9ada137 100644 --- a/packages/dsh-desktop-client-ui/client.js +++ b/packages/dsh-desktop-client-ui/client.js @@ -377,6 +377,13 @@ window.__ModuleLoader__.load({ let generation = 0, searchRequest = 0 let migrationRun, migrationTimer, migrationAttempt = 0 const rowRequests = new Map() + // Conversation renames this session; a page requested before one finished still carries the old title. + const renames = new Map() + let renameMark = 0 + const renamedSince = (mark, items) => items.map(item => { + const rename = renames.get(item.id) + return rename && rename.mark > mark ? { ...item, title: rename.title, updatedAt: rename.updatedAt } : item + }) const validId = value => typeof value === 'string' && /^[a-zA-Z0-9_-]{1,255}$/u.test(value) const publish = patch => { state = { ...state, ...patch }; listeners.forEach(fn => fn()) } const legacyKey = () => 'desktop.chatProjects.v1:' + state.scope @@ -414,14 +421,14 @@ window.__ModuleLoader__.load({ const scope = state.scope, epoch = state.epoch const previous = state.rows[id] || { items: [], nextCursor: null, phase: 'idle' } if (more && !previous.nextCursor) return - const request = (rowRequests.get(id) || 0) + 1 + const request = (rowRequests.get(id) || 0) + 1, mark = renameMark rowRequests.set(id, request) publish({ rows: { ...state.rows, [id]: { ...previous, phase: 'loading' } } }) try { const page = await window.dshEnterpriseChat.projectConversations({ project_id: id, ...(more ? { cursor: previous.nextCursor } : {}) }, epoch) if (!same(scope, epoch) || rowRequests.get(id) !== request) return if (page.epoch !== epoch || BigInt(page.revision) < BigInt(state.revision)) { void load(id); return } - const items = [...new Map([...(more ? previous.items : []), ...page.items].map(item => [item.id, item])).values()] + const items = renamedSince(mark, [...new Map([...(more ? previous.items : []), ...page.items].map(item => [item.id, item])).values()]) publish({ rows: { ...state.rows, [id]: { items, nextCursor: page.nextCursor, phase: 'ready', revision: page.revision } } }) } catch { if (same(scope, epoch) && rowRequests.get(id) === request) publish({ rows: { ...state.rows, [id]: { ...previous, phase: 'error' } } }) @@ -429,7 +436,7 @@ window.__ModuleLoader__.load({ } const search = async (query, more = false) => { query = String(query || '').trim() - const request = ++searchRequest, scope = state.scope, epoch = state.epoch + const request = ++searchRequest, scope = state.scope, epoch = state.epoch, mark = renameMark const previous = state.search if (!query || !scope) { publish({ search: { query, items: [], phase: 'idle', nextCursor: null } }); return } if (more && !previous.nextCursor) return @@ -437,7 +444,7 @@ window.__ModuleLoader__.load({ try { const page = await window.dshEnterpriseChat.projectConversations({ query, ...(more ? { cursor: previous.nextCursor } : {}) }, epoch) if (!same(scope, epoch) || request !== searchRequest || page.epoch !== epoch) return - const items = [...new Map([...(more ? previous.items : []), ...page.items].map(item => [item.id, item])).values()] + const items = renamedSince(mark, [...new Map([...(more ? previous.items : []), ...page.items].map(item => [item.id, item])).values()]) publish({ search: { query, items, phase: 'ready', nextCursor: page.nextCursor } }) } catch { if (same(scope, epoch) && request === searchRequest) publish({ search: { ...previous, query, phase: 'error' } }) } } @@ -501,7 +508,7 @@ window.__ModuleLoader__.load({ setScope(scope, epoch) { scope = validId(scope) ? scope : undefined if (scope === state.scope && epoch === state.epoch) { if (scope && state.phase === 'idle') void read(); return } - generation++; searchRequest++; rowRequests.clear(); reading = false; readPending = undefined + generation++; searchRequest++; rowRequests.clear(); renames.clear(); reading = false; readPending = undefined clearTimeout(migrationTimer); migrationTimer = undefined; migrationRun = undefined; migrationAttempt = 0 let migrationAvailable = false try { migrationAvailable = !!scope && window.localStorage.getItem('desktop.chatProjects.v1:' + scope) !== null && !window.localStorage.getItem('desktop.chatProjects.importDone.v1:' + scope) } @@ -528,6 +535,20 @@ window.__ModuleLoader__.load({ } } }, + /** Conversations a project page or the current search shows; the host still checks its own routes. */ + lists(id) { + return Object.hasOwn(state.assignments, id) || state.search.items.some(item => item.id === id) || + Object.values(state.rows).some(page => page.items.some(item => item.id === id)) + }, + /** Project pages keep creation order and are not reread on rename, so patch them and the search in place. */ + renamed(id, title, updatedAt) { + renames.set(id, { title, updatedAt, mark: ++renameMark }) + const patch = items => items.map(item => item.id === id ? { ...item, title, updatedAt } : item) + publish({ + rows: Object.fromEntries(Object.entries(state.rows).map(([project, page]) => [project, { ...page, items: patch(page.items) }])), + search: { ...state.search, items: patch(state.search.items) } + }) + }, toggle(id) { const expanded = { ...state.expanded, [id]: !state.expanded[id] } publish({ expanded }) @@ -819,10 +840,12 @@ publish({ items: [...new Map(items.map(item => [item.id, item])).values()], page if (epoch !== value.epoch || !value.connected) throw new Error('Chat identity changed.') const response = await window.dshEnterpriseChat.rename(id, name, epoch) if (!active || epoch !== value.epoch || response.epoch !== epoch) return - // The server also moves the conversation's update time. A newer local row - // outranks cached project pages until the reread brings the server's own. + // The server also moves the conversation's update time. History is reread; + // project pages and the current search are not, so they take the same change. historyRequest++ - publish({ items: value.items.map(item => item.id === id ? { ...item, title: name, updatedAt: new Date().toISOString() } : item), historyPhase: 'idle' }) + const updatedAt = new Date().toISOString() + publish({ items: value.items.map(item => item.id === id ? { ...item, title: name, updatedAt } : item), historyPhase: 'idle' }) + projects.renamed(id, name, updatedAt) void refreshHistory() }) const open = async (id, projectId) => { @@ -906,8 +929,9 @@ if (clearHistory) { historyRequest++; openRequest++; historyDirty = false; delet if (projectId === undefined) projects.edit('create', id) else if (await projects.assign(id, projectId) && projectId && value.epoch === epoch) projects.reveal(projectId) }, + // Every row the sidebar shows can be renamed: history, project pages and search results. requestRename(id, title, epoch) { - if (value.connected && epoch === value.epoch && (value.items.some(item => item.id === id) || Object.hasOwn(projects.snapshot().assignments, id))) renaming.request(id, title, epoch) + if (value.connected && epoch === value.epoch && (value.items.some(item => item.id === id) || projects.lists(id))) renaming.request(id, title, epoch) }, requestDelete(id, title, epoch) { if (value.connected && epoch === value.epoch && (value.items.some(item => item.id === id) || Object.hasOwn(projects.snapshot().assignments, id))) deletion.request(id, title, epoch) diff --git a/test/cloud-chat-rename-running.test.mjs b/test/cloud-chat-rename-running.test.mjs index 73306de5..df1fe984 100644 --- a/test/cloud-chat-rename-running.test.mjs +++ b/test/cloud-chat-rename-running.test.mjs @@ -14,10 +14,11 @@ beforeAll(() => { }) afterEach(async () => { await cleanup?.(); cleanup = undefined; vi.restoreAllMocks() }) -async function fixture({ language = 'zh', rename = async () => {} } = {}) { +// `project` turns on one cloud project: its memberships and what its pages and searches return. +async function fixture({ language = 'zh', rename = async () => {}, mode = 'projects', query = '', project } = {}) { let plugin const entries = new Map(), dictionaries = new Map(), disposers = [] - let state = { connected: true, phase: 'ready', epoch: 1, conversationId: 'cloud-a' }, listener + let state = { connected: true, phase: 'ready', epoch: 1, conversationId: 'cloud-a', ...(project ? { projectScope: 'scope-a' } : {}) }, listener let items = [{ id: 'cloud-a', title: '季度复盘', updatedAt: '2026-11-03' }, { id: 'cloud-b', title: '', updatedAt: '2026-11-02' }] const bridge = { state: async () => state, @@ -29,7 +30,9 @@ async function fixture({ language = 'zh', rename = async () => {} } = {}) { return { epoch } }), remove: vi.fn(async (_id, epoch) => ({ epoch })), - open: vi.fn(async () => {}) + open: vi.fn(async () => {}), + projectsState: vi.fn(async () => ({ epoch: state.epoch, phase: 'ready', connection: 'live', revision: '1', projects: [{ id: 'project-a', name: '研究' }], assignments: project.assignments })), + projectConversations: vi.fn(async input => ({ epoch: state.epoch, revision: '1', items: await project.list(input), nextCursor: null })) } window.dshEnterpriseChat = bridge window.__ModuleLoader__ = { load({ factory }) { @@ -63,7 +66,7 @@ async function fixture({ language = 'zh', rename = async () => {} } = {}) { document.body.append(container) const root = createRoot(container) await act(async () => root.render(React.createElement(React.Fragment, null, - React.createElement(collection.Component, { ...collectionProps, mode: 'projects', query: '', archivedOnly: false, items: [], projects: () => null }), + React.createElement(collection.Component, { ...collectionProps, mode, query, archivedOnly: false, items: [], projects: () => null }), React.createElement(overlay.Component, overlayProps)))) const settle = () => act(async () => new Promise(resolve => setTimeout(resolve, 0))) await settle() @@ -204,6 +207,84 @@ it('drops a pending rename when the account changes', async () => { expect(ui.bridge.rename).not.toHaveBeenCalled() }) +// Project pages and search results keep their own copies; history pages are not the only source of rows. +const olderProjectChat = { assignments: { 'cloud-old': 'project-a' }, list: async () => [{ id: 'cloud-old', title: '旧项目会话', updatedAt: '2026-10-01' }] } +async function expandProject(ui) { + await act(async () => document.querySelector('.dshChatProjectToggle').click()) + await ui.settle() +} +// The sidebar debounces the server search. +const searchSettled = () => act(async () => new Promise(resolve => setTimeout(resolve, 250))) + +it('renames an older project conversation that no loaded history page contains', async () => { + const ui = await fixture({ project: olderProjectChat }) + await expandProject(ui) + await ui.menu('旧项目会话') + await ui.click('重命名') + await ui.type('项目会话新名') + await ui.key('Enter') + expect(ui.bridge.rename).toHaveBeenCalledWith('cloud-old', '项目会话新名', 1) + expect(ui.row('项目会话新名')).toBeTruthy() + expect(ui.row('旧项目会话')).toBeFalsy() +}) + +it('keeps the new name when a project page requested before the rename arrives after it', async () => { + const list = vi.fn(olderProjectChat.list) + const ui = await fixture({ project: { ...olderProjectChat, list } }) + await expandProject(ui) + let arrive + list.mockImplementationOnce(() => new Promise(resolve => { arrive = resolve })) + void ui.navigation.projects.load('project-a') + await ui.menu('旧项目会话') + await ui.click('重命名') + await ui.type('项目会话新名') + await ui.key('Enter') + await act(async () => arrive([{ id: 'cloud-old', title: '旧项目会话', updatedAt: '2026-10-01' }])) + await ui.settle() + expect(ui.row('项目会话新名')).toBeTruthy() + expect(ui.row('旧项目会话')).toBeFalsy() + // A page requested afterwards is the server's own answer, even if it was renamed elsewhere. + list.mockResolvedValueOnce([{ id: 'cloud-old', title: '网页端改的名', updatedAt: '2026-11-10' }]) + await act(async () => ui.navigation.projects.load('project-a')) + await ui.settle() + expect(ui.row('网页端改的名')).toBeTruthy() +}) + +it('keeps the new name when a search requested before the rename arrives after it', async () => { + const list = vi.fn(async () => [{ id: 'cloud-found', title: '搜索会话', updatedAt: '2026-10-01' }]) + const ui = await fixture({ mode: 'search', query: '搜索', project: { assignments: {}, list } }) + await searchSettled() + let arrive + list.mockImplementationOnce(() => new Promise(resolve => { arrive = resolve })) + void ui.navigation.projects.search('搜索') + await ui.menu('搜索会话') + await ui.click('重命名') + await ui.type('搜索会话新名') + await ui.key('Enter') + await act(async () => arrive([{ id: 'cloud-found', title: '搜索会话', updatedAt: '2026-10-01' }])) + await ui.settle() + expect(ui.row('搜索会话新名')).toBeTruthy() + expect(ui.row('搜索会话')).toBeFalsy() +}) + +it.each([ + ['outside history and projects', {}, 'cloud-found', '搜索会话'], + ['in a project but outside history', { 'cloud-found': 'project-a' }, 'cloud-found', '搜索会话'], + ['also in history', {}, 'cloud-a', '季度复盘'] +])('renames a search result %s and updates that row', async (_label, assignments, id, title) => { + const query = title.slice(0, 2) + const ui = await fixture({ mode: 'search', query, project: { assignments, list: async input => input.query === query ? [{ id, title, updatedAt: '2026-10-01' }] : [] } }) + await searchSettled() + await ui.menu(title) + await ui.click('重命名') + expect(ui.input().value).toBe(title) + await ui.type(`${title}(改)`) + await ui.key('Enter') + expect(ui.bridge.rename).toHaveBeenCalledWith(id, `${title}(改)`, 1) + expect(ui.row(`${title}(改)`)).toBeTruthy() + expect(ui.row(title)).toBeFalsy() +}) + it.each([['zh', '进行中'], ['en', 'Running']])('shows host-reported activity on cloud rows in %s', async (language, label) => { const ui = await fixture({ language }) const unnamed = language === 'zh' ? '新聊天' : 'New chat' @@ -229,3 +310,14 @@ it('clears activity when the account signs out', async () => { await ui.push({ connected: false, running: ['cloud-a'] }) expect(ui.navigation.snapshot().running).toEqual([]) }) + +it.each([ + ['a project page', { project: olderProjectChat }, expandProject], + ['a search result', { mode: 'search', query: '旧项', project: olderProjectChat }, searchSettled] +])('shows host-reported activity on %s too', async (_label, options, reveal) => { + const ui = await fixture(options) + await reveal(ui) + expect(ui.row('旧项目会话').querySelector('.dshHistoryStatus')).toBeNull() + await ui.push({ running: ['cloud-old'] }) + expect(ui.row('旧项目会话').querySelector('.dshHistoryStatus svg[data-state=ongoing]')).toBeTruthy() +}) diff --git a/test/enterprise-chat-view.test.ts b/test/enterprise-chat-view.test.ts index 051a8254..85700e7f 100644 --- a/test/enterprise-chat-view.test.ts +++ b/test/enterprise-chat-view.test.ts @@ -1602,6 +1602,32 @@ describe('cloud conversation rename', () => { } finally { f.host.dispose() } }) + // The sidebar also offers rename on project pages and search results, which come from this read. + it.each([ + ['a project page', { project_id: '11111111-1111-4111-8111-111111111111' }], + ['a search result', { query: 'Older' }] + ])('renames a conversation listed only by %s', async (_label, page) => { + const f = fixture() + try { + f.host.present(f.owner, presentation) + await flush() + const json = (data: unknown) => new Response(JSON.stringify({ status_code: 200, data }), { headers: { 'content-type': 'application/json' } }) + const fetch = fake.sessions[0].fetch + fetch.mockImplementation(async (url: string) => url.includes('/api/v1/chat/projects/snapshot') + ? json({ identity: { user_id: 7, tenant_id: 2 }, projects: [{ id: '11111111-1111-4111-8111-111111111111', name: 'Research' }], memberships: [{ chat_id: 'cloud-p', project_id: '11111111-1111-4111-8111-111111111111' }] }) + : url.includes('/api/v1/chat/projects/conversations') + ? json({ data: [{ chat_id: 'cloud-p', name: 'Older', flow_type: 15, update_time: '2026-10-01T00:00:00' }], total: 1, next_cursor: null }) + : new Response(JSON.stringify({ status_code: 200 }))) + const epoch = f.host.snapshot().epoch + await expect(f.host.rename('cloud-p', 'Renamed', epoch)).rejects.toThrow('current Chat history') + expect((await f.host.projectConversations(page, epoch)).items.map(item => item.id)).toEqual(['cloud-p']) + await expect(f.host.rename('cloud-p', 'Renamed', epoch)).resolves.toEqual({ epoch }) + const [url, init] = fetch.mock.lastCall + expect(url).toBe('https://enterprise.example/api/v1/chat/conversation/rename') + expect(JSON.parse(init.body)).toEqual({ conversationId: 'cloud-p', name: 'Renamed' }) + } finally { f.host.dispose() } + }) + it.each([ ['a stale identity', 'cloud-a', 'Name', -1], ['an unlisted conversation', 'unknown', 'Name', undefined],