diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 16d72d5f..1448b0ba 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -76,6 +76,11 @@ jobs: timeout-minutes: 5 run: node scripts/workbench/e2e-git-view.mjs + - name: Verify session project binding across two owner browsers + if: ${{ !cancelled() && steps.host_tests.outcome == 'success' }} + timeout-minutes: 5 + run: node scripts/workbench/e2e-session-workspaces.mjs + - name: Select the same installed Chrome for UI and worker run: bash scripts/workbench/ci-select-chromium.sh @@ -83,6 +88,28 @@ jobs: timeout-minutes: 5 run: node scripts/workbench/e2e-manual-browser.mjs + packaged-session-workspaces: + name: Packaged session workspace on native amd64 Docker + if: ${{ github.event_name == 'pull_request' && github.head_ref == 'feat/web-workbench-session-workspaces' }} + runs-on: ubuntu-latest + timeout-minutes: 12 + steps: + - uses: actions/checkout@v5 + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v5 + with: + node-version: 22 + package-manager-cache: false + - name: Build the actual amd64 workbench runtime + timeout-minutes: 8 + run: | + set -eu + test "$(uname -m)" = x86_64 + docker build --platform linux/amd64 --target runtime -t deva-workbench:focus-verify . + - name: Verify owner bindings across new containers and a removed grant + timeout-minutes: 3 + run: node scripts/workbench/container-focus-ci.mjs + sandbox: name: Private human browser worker runs-on: ubuntu-latest diff --git a/README.en.md b/README.en.md index 4092eac9..77e8c112 100644 --- a/README.en.md +++ b/README.en.md @@ -341,7 +341,7 @@ When memory is full, the next write by the model first consolidates the existing ## Headless server workbench (fork development) -The [amd64 Docker Compose workbench](apps/headless/README.md) supports browser enrollment, the original desktop model settings, and general text conversations with shared desktop UI, streaming, cancellation and reconnect. It also includes profile and role editing, avatar management, and notes scoped to the owner, a role, or a registered project. Manual workspaces and explicit chat attachments are separate: browsing a project does not send its files to a model. Separately approved projects also have a manually activated Git view for tracked changes, branches, first-parent history and staged versus working-tree comparisons. The workbench accepts supported UTF-8 text, static images and PDFs for compatible adapters. Confirmed replies can be exported as Markdown or plain text. Desktop delivery cards are reused for scoped downloads and project file reveal. An [optional human-operated browser](apps/browser-worker/README.md) uses a separate sandboxed worker and an explicit list of sites. The base app requires neither that worker nor a running desktop. This is separate from the mobile relay; see the [parity inventory](docs/development/web-workbench/README.md) for the remaining desktop workflows. +The [amd64 Docker Compose workbench](apps/headless/README.md) supports browser enrollment, the original desktop model settings, and general text conversations with shared desktop UI, streaming, cancellation and reconnect. It also includes profile and role editing, avatar management, and notes scoped to the owner, a role, or a registered project. A conversation may keep an explicitly attached project or inherit its role’s registered project at creation. Browsing another folder is separate from changing this binding; neither operation sends files or notes to a model. Separately approved projects also have a manually activated Git view for tracked changes, branches, first-parent history and staged versus working-tree comparisons. The workbench accepts supported UTF-8 text, static images and PDFs for compatible adapters. Confirmed replies can be exported as Markdown or plain text. Desktop delivery cards are reused for scoped downloads and project file reveal. An [optional human-operated browser](apps/browser-worker/README.md) uses a separate sandboxed worker and an explicit list of sites. The base app requires neither that worker nor a running desktop. This is separate from the mobile relay; see the [parity inventory](docs/development/web-workbench/README.md) for the remaining desktop workflows. ## Build from Source diff --git a/README.md b/README.md index 9d6973ce..4af03c16 100644 --- a/README.md +++ b/README.md @@ -332,7 +332,7 @@ IM 机器人支持 `/new [角色名]`、`/list`、`/stop`、`/status`、`/help` ## 无 GUI 服务器工作台(本分支开发中) -[amd64 Docker Compose 与 Web 工作台说明](apps/headless/README.md):当前可在浏览器认领服务器、配置模型,并使用桌面同源的会话列表、编辑器及消息区进行通用文本对话;支持停止与刷新续接。网页还可以编辑个人资料、普通角色及其头像,并分别管理全局、角色和已授权项目的记忆。可手动浏览获准项目的文件,也可显式把所选文本、静态图片或兼容协议的 PDF 作为会话附件发送;浏览项目不会自动上传。管理员另外批准的仓库可手动查看已跟踪文件的改动、分支、首父提交历史,以及暂存和工作树的差异。已确认的回复可导出为 Markdown 或纯文本;桌面交付卡复用于 Web,支持按授权项目下载文件和定位。还可配置[独立人工浏览器面板](apps/browser-worker/README.md),由当前登录者接管已登记站点;实际工作器须通过 Chromium 沙箱就绪检查。它和手机版中转是两个不同部署目标;完整业务进度见[对等清单](docs/development/web-workbench/README.md)。 +[amd64 Docker Compose 与 Web 工作台说明](apps/headless/README.md):当前可在浏览器认领服务器、配置模型,并使用桌面同源的会话列表、编辑器及消息区进行通用文本对话;支持停止与刷新续接。网页还可以编辑个人资料、普通角色及其头像,并分别管理全局、角色和已授权项目的记忆。可手动浏览获准项目的文件,也可显式把所选文本、静态图片或兼容协议的 PDF 作为会话附件发送;浏览项目不会自动上传。每段对话可独立关联或解除项目;从已关联标签打开文件和项目记忆,角色的新对话可继承已登记的默认项目。管理员另外批准的仓库可手动查看已跟踪文件的改动、分支、首父提交历史,以及暂存和工作树的差异。已确认的回复可导出为 Markdown 或纯文本;桌面交付卡复用于 Web,支持按授权项目下载文件和定位。还可配置[独立人工浏览器面板](apps/browser-worker/README.md),由当前登录者接管已登记站点;实际工作器须通过 Chromium 沙箱就绪检查。它和手机版中转是两个不同部署目标;完整业务进度见[对等清单](docs/development/web-workbench/README.md)。 ## 从源码构建 diff --git a/apps/desktop/src/workbench/chat-transport.ts b/apps/desktop/src/workbench/chat-transport.ts index 6113371f..6b58614b 100644 --- a/apps/desktop/src/workbench/chat-transport.ts +++ b/apps/desktop/src/workbench/chat-transport.ts @@ -1,5 +1,7 @@ import type { Transport } from './transport' +export const isWorkspaceRevision = (value: unknown): value is string => typeof value === 'string' && value.length === 64 && /^[a-f0-9]+$/u.test(value) + type Dictionary = Record const record = (x: unknown): x is Dictionary => typeof x === 'object' && x !== null && !Array.isArray(x) const nullableString = (x: unknown): x is string | null => x === null || typeof x === 'string' @@ -29,6 +31,7 @@ export interface ChatSummary { personaId?: string archived?: boolean customTitle?: string + workspaceRevision?: string compatibility: 'text' | 'legacy_text' | 'unsupported' writable: boolean } @@ -83,6 +86,7 @@ function summary(value: unknown): value is Omit { (value.personaId === undefined || isRoleId(value.personaId)) && (value.archived === undefined || typeof value.archived === 'boolean') && (value.customTitle === undefined || typeof value.customTitle === 'string') && + (value.workspaceRevision === undefined || isWorkspaceRevision(value.workspaceRevision)) && (value.compatibility === 'text' || value.compatibility === 'legacy_text' || value.compatibility === 'unsupported') && typeof value.writable === 'boolean' } diff --git a/apps/desktop/src/workbench/library-memory.tsx b/apps/desktop/src/workbench/library-memory.tsx index 7df9fc25..46466b7c 100644 --- a/apps/desktop/src/workbench/library-memory.tsx +++ b/apps/desktop/src/workbench/library-memory.tsx @@ -84,8 +84,9 @@ export function LibraryMemoryPane({ api, scope, locked }: { api: Library; scope: } -export function ProjectMemoryDialog({ api, locked, notice, onClose }: { +export function ProjectMemoryDialog({ api, locked, notice, onClose, lockedProject }: { api: Library; locked: boolean; notice: React.ReactNode; onClose: () => void + lockedProject?: { id: string; name: string | null; signal: AbortSignal } }): React.JSX.Element { const { locale } = useI18n() const c = libraryCopy(locale) @@ -96,7 +97,15 @@ export function ProjectMemoryDialog({ api, locked, notice, onClose }: { setWorkspaces(next) setId((prev) => next.some((item) => item.id === prev) ? prev : '') })) - useEffect(() => { load() }, []) + useEffect(() => { if (!lockedProject) load() }, []) + if (lockedProject) return + {notice} +
+ {lockedProject.name &&

{lockedProject.name}

} + {!lockedProject.signal.aborted && } +
+
return {notice}
diff --git a/apps/desktop/src/workbench/library-transport.ts b/apps/desktop/src/workbench/library-transport.ts index 0f936ba3..36e99c05 100644 --- a/apps/desktop/src/workbench/library-transport.ts +++ b/apps/desktop/src/workbench/library-transport.ts @@ -4,7 +4,7 @@ import { HttpFailure, type LibraryQueue, type Revision, type Transport } from '. export const MEMORY_TYPES = ['user', 'feedback', 'project', 'reference'] as const export type MemoryInput = Pick -export type Scope = { kind: 'global' } | { kind: 'role' | 'project'; id: string } +export type Scope = { kind: 'global' } | { kind: 'role'; id: string } | { kind: 'project'; id: string; signal?: AbortSignal } export type ProfileSnapshot = { profile: UserProfile; revision: Revision; imageRevision: Revision } export type RoleImage = { image: string; revision: Revision; imageRevision: Revision } export type MemoryState = { snapshot: MemorySnapshot; revision: Revision } @@ -113,9 +113,24 @@ export function createLibrary(transport: Transport, queue: LibraryQueue) { } const getRoleImage = (id: string) => transport.request(`${rolePath(id)}/avatar-image`).then(parseRoleImage) + // A conversation-scoped editor may close while waiting in the owner library queue. + async function memoryRequest(scope: Scope, method: string, body?: unknown, token?: string): Promise { + const signal = scope.kind === 'project' ? scope.signal : undefined + const ensureOpen = (): void => { if (signal?.aborted) throw new Error('Project view closed') } + ensureOpen() + try { + const value = await transport.request(memoryPath(scope), method, body, token, signal ? { signal, referrerPolicy: 'same-origin' } : undefined) + ensureOpen() + return value + } catch (error) { + ensureOpen() + throw error + } + } + function changeMemory(scope: Scope, method: 'POST' | 'DELETE', body: Record & { revision: Revision }): Promise { return queue('write', async (token) => { - const result = object(await transport.request(memoryPath(scope), method, body, token)) + const result = object(await memoryRequest(scope, method, body, token)) const current = revision(result.revision) if (result.ok === true) return { value: { ok: true, snapshot: parseMemory(result.snapshot), revision: current } } const code = string(result.code) as MemoryErrorCode @@ -174,7 +189,7 @@ export function createLibrary(transport: Transport, queue: LibraryQueue) { workspaces: () => queue('read', async () => ({ value: array(object(await transport.request('/workspaces')).workspaces) .map((item): WorkspaceOption => { const w = object(item); return { id: opaqueId(w.id), name: string(w.name) } }) })), memory: (scope: Scope) => queue('read', async () => { - const result = object(await transport.request(memoryPath(scope))) + const result = object(await memoryRequest(scope, 'GET')) return { value: { snapshot: parseMemory(result.snapshot), revision: revision(result.revision) } } }), writeMemory: (scope: Scope, input: MemoryInput, revision: Revision, id?: string) => diff --git a/apps/desktop/src/workbench/session-workspace-transport.ts b/apps/desktop/src/workbench/session-workspace-transport.ts new file mode 100644 index 00000000..ca406d02 --- /dev/null +++ b/apps/desktop/src/workbench/session-workspace-transport.ts @@ -0,0 +1,70 @@ +import { isWorkspaceRevision } from './chat-transport' +import { HttpFailure, type Transport } from './transport' +import type { WorkspaceOption } from './workspace-transport' + +export type AttachedWorkspace = { + id: string + name: string | null + state: 'available' | 'unavailable' + source: 'manual' | 'role' +} +export type WorkspaceBinding = { workspace: AttachedWorkspace | null; revision: string } + +const record = (value: unknown): value is Record => typeof value === 'object' && value !== null && !Array.isArray(value) +const isWorkspaceId = (value: unknown): value is string => typeof value === 'string' && value.length === 34 && + value.startsWith('w_') && !/[^a-f0-9]/u.test(value.slice(2)) +const projectLabel = (value: unknown): value is string => typeof value === 'string' && value.length > 0 && + value.length <= 255 && !/[\\/\x00-\x1f\x7f-\x9f]/u.test(value) && value !== '.' && value !== '..' + +function parseBinding(value: unknown): WorkspaceBinding { + if (!record(value) || !isWorkspaceRevision(value.revision)) throw new Error('Invalid conversation workspace revision') + const { workspace, revision } = value + if (workspace === null) return { workspace, revision } + if (!record(workspace)) throw new Error('Invalid conversation workspace') + const { id, name, state, source } = workspace + if (!isWorkspaceId(id) || (state !== 'available' && state !== 'unavailable') || + (source !== 'manual' && source !== 'role')) throw new Error('Invalid conversation workspace') + if (state === 'unavailable' && name === null) return { workspace: { id, name: null, state, source }, revision } + if (state !== 'available' || !projectLabel(name)) throw new Error('Invalid conversation workspace') + return { workspace: { id, name, state, source }, revision } +} + +export function createSessionWorkspaceTransport(transport: Transport, csrf: string) { + function path(sid: string): string { + if (!sid || /^[A-Za-z0-9_-]{1,128}$/u.exec(sid)?.[0] !== sid) throw new Error('Invalid chat id') + return `/chats/${sid}/workspace` + } + const options = (signal: AbortSignal) => ({ signal, referrerPolicy: 'same-origin' as const }) + return { + async read(sid: string, signal: AbortSignal): Promise { + return parseBinding(await transport.request(path(sid), 'GET', undefined, undefined, options(signal))) + }, + async patch(sid: string, revision: string, workspaceId: string | null, signal: AbortSignal): Promise { + if (!csrf || !isWorkspaceRevision(revision) || (workspaceId !== null && !isWorkspaceId(workspaceId))) + throw new Error('Invalid conversation workspace selection') + const result = parseBinding(await transport.request(path(sid), 'PATCH', { revision, workspaceId }, csrf, options(signal))) + if (workspaceId === null ? result.workspace !== null : result.workspace?.id !== workspaceId || result.workspace.source !== 'manual') + throw new Error('Conversation workspace change not confirmed') + return result + }, + async projects(signal: AbortSignal): Promise { + let value: unknown + try { value = await transport.request('/workspaces', 'GET', undefined, undefined, options(signal)) } + catch (error) { + // Older or unmounted catalogues may omit this route; the conversation resource is independent. + if (error instanceof HttpFailure && ([404, 405, 501].includes(error.status) || error.code === 'workspace_unavailable')) return [] + throw error + } + if (!record(value) || !Array.isArray(value.workspaces)) throw new Error('Invalid workspace catalogue') + const seen = new Set() + return value.workspaces.map((item) => { + if (!record(item) || !isWorkspaceId(item.id) || !projectLabel(item.name) || seen.has(item.id)) + throw new Error('Invalid workspace catalogue entry') + seen.add(item.id) + return { id: item.id, name: item.name } + }) + } + } +} + +export type SessionWorkspaceTransport = ReturnType diff --git a/apps/desktop/src/workbench/session-workspace-ui.tsx b/apps/desktop/src/workbench/session-workspace-ui.tsx new file mode 100644 index 00000000..1eb98134 --- /dev/null +++ b/apps/desktop/src/workbench/session-workspace-ui.tsx @@ -0,0 +1,109 @@ +import { useLayoutEffect, useMemo, useSyncExternalStore } from 'react' +import { Folder, FolderOpen } from 'lucide-react' +import { createSessionWorkspace, emptySessionWorkspace, type SessionWorkspaceController, type SessionWorkspaceView } from './session-workspace' +import type { SessionWorkspaceTransport } from './session-workspace-transport' +import './session-workspace.css' + +const copy = { + en: { + title: 'Conversation project', chooser: 'Project to attach', choose: 'Choose an authorized project', attach: 'Attach to this conversation', + detach: 'Detach', notes: 'Open project notes', open: 'Open attached project files', reload: 'Reload and review', project: 'Attached project', + conflict: 'The conversation’s project changed. Your choice was kept. Reload and review it before trying again.', + busy: 'This conversation is busy. Wait for the turn to finish, then reload and review.', + permission: 'Project access was denied. Reload and review the current permissions.', + missing: 'This conversation is no longer available.', readOnly: 'This conversation’s project is read-only.', + unavailable: 'The attached or selected project is unavailable. Reload to check its current status.', + choiceUnavailable: 'Your project choice is no longer available. Choose another project to attach.', + storage: 'Saving the conversation’s project was not confirmed. Reload and review.', + invalid: 'The project change was rejected. Reload and review your choice.', + readFailure: 'The conversation’s project could not be checked. Reload to try again.', + writeFailure: 'The project change was not confirmed. Your choice was kept. Reload and review.', + catalogueFailure: 'The authorized projects could not be loaded.', + read: 'Checking the conversation’s project…', write: 'Saving the conversation’s project…', + files: 'Checking access to the attached project…', + }, + 'zh-CN': { + title: '对话项目', chooser: '要关联的项目', choose: '选择已授权的项目', attach: '关联到此对话', + detach: '解除关联', notes: '打开项目记忆', open: '打开已关联项目的文件', reload: '重新加载并核对', project: '已关联项目', + conflict: '此对话的项目已更改。所选项目仍保留,请重新加载并核对后再试。', + busy: '此对话正在运行。等待本轮结束后,重新加载并核对。', + permission: '项目访问遭拒。请重新加载并核对当前权限。', + missing: '此对话已失效。', readOnly: '此对话的项目为只读。', + unavailable: '关联或所选的项目已失效。重新加载可检查当前状态。', + choiceUnavailable: '所选项目已失效。请选择其他项目来关联。', + storage: '对话项目的保存尚未确认,请重新加载并核对。', + invalid: '项目更改遭拒,请重新加载并核对所选项目。', + readFailure: '读取对话项目失败,请重新加载。', + writeFailure: '项目更改尚未确认。所选项目仍保留,请重新加载并核对。', + catalogueFailure: '读取已授权项目失败。', + read: '正在检查对话项目…', write: '正在保存对话项目…', + files: '正在检查关联项目的访问权限…', + } +} +const labels = (locale: string) => locale === 'zh-CN' ? copy['zh-CN'] : copy.en +const noSubscribe = () => () => undefined + +export function useSessionWorkspace(api: SessionWorkspaceTransport | undefined, sid: string | undefined, listRevision: string | undefined, + detailRevision: string | undefined, writable: boolean, beforeWrite: () => Promise, expired: () => void, committed: () => void) { + const controller = useMemo(() => api ? createSessionWorkspace(api, { beforeWrite, expired, committed }) : undefined, + [api, beforeWrite, expired, committed]) + const snapshot = useSyncExternalStore(controller?.subscribe ?? noSubscribe, controller?.snapshot ?? emptySessionWorkspace) + useLayoutEffect(() => () => controller?.pause(), [controller]) + useLayoutEffect(() => { controller?.watch(sid, listRevision, detailRevision, writable) }, [controller, sid, listRevision, detailRevision, writable]) + return { controller, view: sid && snapshot.sid === sid ? snapshot : emptySessionWorkspace() } +} + +export function AttachedWorkspaceLabel({ view, locale, open }: { + view: SessionWorkspaceView; locale: string; open?: () => void +}): React.JSX.Element | null { + const workspace = view.confirmed?.workspace + if (!workspace) return null + const c = labels(locale) + const name = workspace.name ?? c.project + const available = workspace.state === 'available' + const contents = <>{available ?