diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bb4f4826..b12fdcf0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3,6 +3,7 @@ name: CI on: pull_request: + workflow_dispatch: push: branches: [main] @@ -162,6 +163,23 @@ jobs: if-no-files-found: error retention-days: 14 + - name: Verify folder reveal and exclusive project document creation in two real Chrome logins + id: project_documents_ui + if: ${{ !cancelled() && steps.host_tests.outcome == 'success' }} + timeout-minutes: 6 + env: + DEVA_QA_DOCUMENT_CAPTURE: '1' + run: node scripts/workbench/e2e-project-documents.mjs + + - name: Publish the verified synthetic workspace document + if: ${{ !cancelled() && steps.project_documents_ui.outcome == 'success' }} + uses: actions/upload-artifact@v4 + with: + name: workbench-project-documents + path: test-results/project-documents/created-document.png + if-no-files-found: error + retention-days: 14 + - name: Select the same installed Chrome for UI and worker if: ${{ !cancelled() && steps.host_tests.outcome == 'success' }} id: handoff_chrome @@ -361,6 +379,28 @@ jobs: timeout-minutes: 3 run: node scripts/workbench/container-skill-library.mjs + packaged-project-documents: + name: Exclusive project documents across native amd64 Compose modes + if: ${{ (github.event_name == 'pull_request' && github.head_ref == 'feat/web-workbench-project-documents') || (github.event_name == 'workflow_dispatch' && github.ref_name == 'feat/web-workbench-project-documents') }} + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-node@v5 + with: + node-version: 22 + package-manager-cache: false + - name: Build the production Linux amd64 workbench + timeout-minutes: 9 + run: | + set -eu + test "$(uname -m)" = x86_64 + docker build --platform linux/amd64 --target runtime -t deva-workbench:project-documents-verify . + docker image inspect -f '{{.Os}}/{{.Architecture}} {{.Id}} {{.Size}} bytes' deva-workbench:project-documents-verify + - name: Verify default, edit-only and create grants, then recreate the real workbench + timeout-minutes: 8 + run: node scripts/workbench/container-project-documents.mjs + packaged-browser-handoff: name: Human handoff with packaged Workbench, Chromium and broker if: ${{ github.event_name == 'pull_request' && github.head_ref == 'feat/web-workbench-sandbox-handoff' }} diff --git a/README.en.md b/README.en.md index add2c2af..2cacc152 100644 --- a/README.en.md +++ b/README.en.md @@ -344,7 +344,7 @@ When memory is full, the next write by the model first consolidates the existing The [amd64 Docker Compose workbench](apps/headless/README.md) runs independently of Electron, a remote desktop or the mobile relay, using the same React components as the desktop application. - **Conversations:** claim the instance, configure models, stream, stop and reconnect. Use the desktop message menu to copy a selection or quote it in an unsent draft. Clipboard, sidebar shortcuts and page fullscreen belong to the client browser. -- **Library and projects:** manage profiles, roles, avatars and scoped notes. A conversation can inherit or explicitly attach an approved project; manually opening its files or notes does not send them to a model. +- **Library and projects:** manage profiles, roles, avatars and scoped notes. A conversation can inherit or explicitly attach an approved project; reveal a file’s parent folder in the workspace tree. A separate opt-in allows owners to review and create new Markdown or plain-text documents without replacing an existing file. Browsing or creating a document does not send it to a model. - **Skill settings:** inspect existing skills under Settings → Extensions and save their enabled preferences and role scopes. Opening a custom skill displays its document; web chat does not load or execute skills. - **Read-only terminal:** an optional [network-isolated PTY worker](apps/terminal-worker/README.md) displays a confirmed, saved workspace text file in the original file panel. Navigation, resize and exit come from a real native process; this is not a host command shell. - **Attachments and deliveries:** explicitly send supported text, static images or PDFs on compatible adapters. Export confirmed replies or use the desktop delivery card to download and reveal an authorized project file. diff --git a/README.md b/README.md index d2f2e9fb..784819d1 100644 --- a/README.md +++ b/README.md @@ -335,7 +335,7 @@ IM 机器人支持 `/new [角色名]`、`/list`、`/stop`、`/status`、`/help` [amd64 Docker Compose 部署与使用](apps/headless/README.md)。这是独立的服务器工作台,复用桌面 React 界面;运行时无需 Electron、远程桌面或手机版中转。 - **对话**:在浏览器认领实例、配置模型,使用原会话列表和编辑器聊天、停止、刷新续接。选中文字可复制或加入当前草稿的引用条;剪贴板、侧栏快捷键和页面全屏都属于操作电脑。 -- **资料与项目**:管理个人资料、角色、头像和分域记忆。会话可继承或显式关联管理员登记的项目;手动打开文件或笔记不会将内容发送给模型。 +- **资料与项目**:管理个人资料、角色、头像和分域记忆。会话可继承或显式关联管理员登记的项目;文件页可定位当前文件夹。另行启用创建权限后,所有者可核对目标并新建 Markdown 或纯文本文档,同名文件保持原样。手动打开或创建文档不会将内容发送给模型。 - **技能设置**:在桌面同源的「设置 → 扩展」查看现有技能,保存启用偏好和角色范围。只有打开自定义条目才显示正文;Web 对话不会加载或运行这些技能。 - **只读终端**:可选的[无网络 PTY 工作器](apps/terminal-worker/README.md)在原文件面板中显示已保存的文本。翻页、调整行列、退出都由真实子进程响应;它不会提供宿主命令行。 - **附件与交付**:显式发送文本、静态图片或兼容协议的 PDF;导出已完成的回复,或在桌面同源交付卡下载、定位授权文件。 diff --git a/apps/desktop/src/workbench/project-document-controller.ts b/apps/desktop/src/workbench/project-document-controller.ts new file mode 100644 index 00000000..f8babf19 --- /dev/null +++ b/apps/desktop/src/workbench/project-document-controller.ts @@ -0,0 +1,289 @@ +import { HttpFailure } from './transport' +import { parentOf, writableDocumentFolders, type WorkspaceFiles } from './workspace-files' +import { documentDirectory, documentPath, documentValidation, InvalidDocumentReceipt, projectDocumentWorkspaceId, type DocumentIssue, + type PreparedDocument, type ProjectDocumentTransport } from './project-document-transport' + +type Issue = DocumentIssue | 'notCreated' +type Phase = 'draft' | 'preparing' | 'prepared' | 'creating' | 'verifying' | 'unconfirmed' | 'saved' +type Draft = Readonly<{ wid: string; directory: string; name: string; content: string; issue?: Issue; uncertainPath?: string }> +type Intent = PreparedDocument & { wid: string; expires: number } +type FocusTarget = 'name' | 'status' | 'return' +export type ProjectDocumentView = { + draft?: Draft; phase?: Phase; issue?: Issue; preview?: string; savedPath?: string; + folders: string[]; canNew: boolean; retained: boolean; canReview: boolean; canCreate: boolean; canVerify: boolean; editable: boolean; + focus?: { target: FocusTarget; serial: number } +} +const emptyView: ProjectDocumentView = { folders: [], canNew: false, retained: false, canReview: false, canCreate: false, canVerify: false, editable: false } + +function issueFor(error: unknown, writing = false): Issue { + if (!(error instanceof HttpFailure)) return writing ? 'unconfirmed' : 'unavailable' + if (error.status === 401 || error.code === 'csrf_failed') return 'expired' + switch (error.status) { + case 400: return 'invalid' + case 403: return error.code === 'document_unsafe' ? 'restricted' : 'readonly' + case 404: return 'missing' + case 409: return error.code === 'document_exists' ? 'exists' : error.code === 'document_changed' ? 'changed' : 'conflict' + case 413: return 'limit' + case 422: return 'restricted' + case 429: return 'busy' + case 503: return writing ? 'unconfirmed' : 'unavailable' + default: return writing ? 'unconfirmed' : 'unavailable' + } +} + +/** Page-memory draft per authorized project. An intent, by contrast, lives only within its current review. */ +export function createProjectDocuments(files: WorkspaceFiles, api: ProjectDocumentTransport, now = Date.now) { + const listeners = new Set<() => void>() + const kept = new Map() + let open = false + let unsubscribe: (() => void) | undefined + let phase: Phase | undefined + let draft: Draft | undefined + let intent: Intent | undefined + let saved: { wid: string; path: string } | undefined + let timer: ReturnType | undefined + let focus: ProjectDocumentView['focus'] + let folderCheck: AbortController | undefined + let serial = 0 + let view = emptyView + + function folders(): string[] { + const workspace = files.snapshot() + return projectDocumentWorkspaceId(workspace.projectId) ? writableDocumentFolders(workspace).filter(documentDirectory) : [] + } + function validTarget(value: Draft): boolean { + return files.snapshot().projectId === value.wid && folders().includes(value.directory) + } + function defaultFolder(): string { + const { file, folder } = files.snapshot() + return folder ?? (file ? parentOf(file.path) : '') + } + function emit(): void { + const workspace = files.snapshot() + const choices = folders() + const current = open && !!draft && workspace.projectId === draft.wid + const scoped = current && choices.includes(draft!.directory) + const path = current && documentDirectory(draft!.directory) && !documentValidation(draft!.name, '') ? + documentPath(draft!.directory, draft!.name) : undefined + const validation = current && draft!.name ? documentValidation(draft!.name, draft!.content) : undefined + const blocked = phase === 'draft' && !!path && workspace.blockedDocumentPaths.has(path) + const status = saved?.wid === workspace.projectId ? saved : undefined + view = { + draft: current ? draft : undefined, phase: current ? phase : status ? 'saved' : undefined, + issue: current ? workspace.issue === 'expired' ? 'expired' : draft!.issue ?? (!scoped ? 'directory' : blocked ? 'unconfirmed' : validation) : undefined, + preview: path || undefined, savedPath: status?.path, folders: choices, + canNew: open && !current && choices.includes(defaultFolder()), retained: kept.has(workspace.projectId), + editable: current && !workspace.issue && (phase === 'draft' || phase === 'preparing' || phase === 'prepared'), + canReview: scoped && phase === 'draft' && !!path && !blocked && draft!.uncertainPath !== path && !validation, + canCreate: scoped && phase === 'prepared' && !!intent && intent.path === path && intent.expires > now(), + canVerify: current && !workspace.issue && !!intent && phase === 'unconfirmed', focus + } + listeners.forEach((notify) => notify()) + } + function requestFocus(target: FocusTarget): void { focus = { target, serial: ++serial } } + function keep(next: Draft): void { kept.set(next.wid, next); draft = next } + function release(wid: string, id: string): void { void api.cancel(wid, id).catch(() => {}) } + function detachIntent(): Intent | undefined { + clearTimeout(timer) + timer = undefined + const previous = intent + intent = undefined + return previous + } + function backToDraft(issue?: Issue, unconfirmed = false): void { + const previous = detachIntent() + if (!draft) return + keep({ ...draft, issue, ...(unconfirmed && previous ? { uncertainPath: previous.path } : {}) }) + phase = unconfirmed ? 'unconfirmed' : 'draft' + if (previous) { + if (!unconfirmed) files.blockDocumentPath(previous.wid, previous.path, false) + release(previous.wid, previous.id) + } + emit() + } + function dismiss(returnFocus = false): void { + folderCheck?.abort() + folderCheck = undefined + if (!returnFocus) focus = undefined + const old = draft + const previous = detachIntent() + const uncertain = previous && (phase === 'creating' || phase === 'verifying' || phase === 'unconfirmed') ? previous.path : undefined + if (old) { + if (old.name || old.content || old.uncertainPath) kept.set(old.wid, { + ...old, issue: uncertain ? 'unconfirmed' : old.issue, uncertainPath: uncertain ?? old.uncertainPath + }) + else kept.delete(old.wid) + draft = undefined + phase = undefined + } + saved = undefined + if (returnFocus) { + requestFocus('return') + // An explicit Cancel leaves ordinary browsing available while the kept draft still fences that create target. + if (old?.uncertainPath) files.blockDocumentPath(old.wid, old.uncertainPath, false) + if (previous && uncertain) files.blockDocumentPath(previous.wid, uncertain, false) + } + if (previous) release(previous.wid, previous.id) + emit() + } + function workspaceChanged(): void { + const workspace = files.snapshot() + if (saved && (saved.wid !== workspace.projectId || saved.path !== workspace.file?.path || !workspace.file.saved)) saved = undefined + if (draft && draft.wid !== workspace.projectId) { dismiss(); return } + if (draft && workspace.issue && (intent || phase === 'preparing')) { + backToDraft(workspace.issue === 'expired' ? 'expired' : 'missing', + phase === 'creating' || phase === 'verifying' || phase === 'unconfirmed') + return + } + if (draft && (phase === 'preparing' || phase === 'prepared') && !validTarget(draft)) { + backToDraft('directory') + return + } + emit() + } + function setOpen(enabled: boolean): void { + if (open === enabled) return + open = enabled + if (enabled) { unsubscribe = files.subscribe(workspaceChanged); emit() } + else { unsubscribe?.(); unsubscribe = undefined; dismiss() } + } + function begin(): void { + if (!view.canNew) return + const wid = files.snapshot().projectId + draft = kept.get(wid) ?? { wid, directory: defaultFolder(), name: '', content: '' } + saved = undefined + phase = 'draft' + requestFocus('name') + emit() + } + function update(patch: Partial>): void { + if (!draft || !view.editable || (patch.directory !== undefined && !folders().includes(patch.directory))) return + const candidate = { ...draft, ...patch } + if (candidate.directory === draft.directory && candidate.name === draft.name && candidate.content === draft.content) return + const target = documentPath(candidate.directory, candidate.name) + const previous = detachIntent() + keep({ ...candidate, issue: target === candidate.uncertainPath ? 'unconfirmed' : undefined }) + phase = 'draft' + if (candidate.uncertainPath && target !== candidate.uncertainPath) + files.blockDocumentPath(candidate.wid, candidate.uncertainPath, false) + if (previous) release(previous.wid, previous.id) + emit() + } + function expire(review: Intent): void { + if (phase === 'prepared' && intent === review) backToDraft('missing') + } + async function prepare(): Promise { + if (!draft || !view.canReview || !validTarget(draft)) return + const original = draft + const started = now() + phase = 'preparing' + emit() + try { + const result = await api.prepare(original.wid, original.directory, original.name) + if (draft !== original || phase !== 'preparing' || !open || !validTarget(original)) { release(original.wid, result.id); return } + const next = { ...result, wid: original.wid, expires: started + result.ttlMs } + if (next.expires <= now()) { release(original.wid, next.id); backToDraft('missing'); return } + intent = next + phase = 'prepared' + keep({ ...original, issue: undefined }) + timer = setTimeout(() => expire(next), next.expires - now()) + requestFocus('status') + emit() + } catch (error) { + if (error instanceof InvalidDocumentReceipt && error.id) release(original.wid, error.id) + if (draft !== original || phase !== 'preparing') return + requestFocus('status') + backToDraft(issueFor(error)) + files.reportDocumentFailure(error, original.wid) + } + } + const same = (target: Intent): boolean => open && intent === target && draft?.wid === target.wid && + files.snapshot().projectId === target.wid && !files.snapshot().issue + + async function readback(target: Intent, content: string, revision: string): Promise { + phase = 'verifying' + emit() + const confirmed = await files.verifyCreatedDocument(target.wid, target.path, content, revision, () => same(target)) + if (!same(target)) return + if (!confirmed) { phase = 'unconfirmed'; keep({ ...draft!, issue: 'unconfirmed' }); emit(); return } + detachIntent() + release(target.wid, target.id) + kept.delete(target.wid) + saved = { wid: target.wid, path: target.path } + phase = 'saved' + draft = undefined + emit() + } + function uncertain(issue: Issue): void { + if (!draft) return + phase = 'unconfirmed' + keep({ ...draft, issue }) + requestFocus('status') + emit() + } + async function create(): Promise { + if (!intent || !draft || phase !== 'prepared') return + const target = intent + if (target.expires <= now()) { expire(target); return } + if (!view.canCreate || !validTarget(draft)) return + const { content } = draft + clearTimeout(timer) + phase = 'creating' + files.blockDocumentPath(target.wid, target.path, true) + emit() + let result: Awaited> + try { + result = await api.create(target.wid, target.id, target.path, content) + } catch (error) { + if (!same(target)) return + const issue = issueFor(error, true) + if (issue === 'unconfirmed') uncertain(issue) + else { + requestFocus('status') + // Authorization or the intent TTL can lapse after publication but before the receipt. + backToDraft(issue, issue === 'expired' || issue === 'missing') + } + files.reportDocumentFailure(error, target.wid) + return + } + if (same(target)) await verifyReadback(target, content, result.revision) + } + async function verifyReadback(target: Intent, content: string, revision: string): Promise { + try { await readback(target, content, revision) } + catch (error) { + if (!same(target)) return + uncertain(issueFor(error, true)) + files.reportDocumentFailure(error, target.wid) + } + } + async function verify(): Promise { + if (!view.canVerify || !intent || !draft) return + const target = intent + const { content } = draft + phase = 'verifying' + emit() + try { + const status = await api.status(target.wid, target.id, target.path) + if (!same(target)) return + if (status.state === 'created') await verifyReadback(target, content, status.revision) + else if (status.state === 'prepared') { backToDraft('notCreated'); requestFocus('status'); emit() } + else uncertain('unconfirmed') + } catch (error) { + if (!same(target)) return + const issue = issueFor(error, true) + if (['expired', 'missing', 'readonly', 'restricted', 'changed', 'exists', 'conflict'].includes(issue)) backToDraft(issue, true) + else uncertain(issue) + files.reportDocumentFailure(error, target.wid) + } + } + function checkFolder(): Promise | undefined { + if (!draft || !open || draft.wid !== files.snapshot().projectId) return undefined + folderCheck?.abort() + folderCheck = new AbortController() + return files.revealFolder(draft.wid, draft.directory, folderCheck.signal) + } + return { snapshot: () => view, subscribe: (report: () => void) => { listeners.add(report); return () => { listeners.delete(report) } }, + setOpen, begin, update, prepare, create, verify, checkFolder, dismiss, anyDirty: () => kept.size > 0 } +} + +export type ProjectDocuments = ReturnType diff --git a/apps/desktop/src/workbench/project-document-transport.ts b/apps/desktop/src/workbench/project-document-transport.ts new file mode 100644 index 00000000..b014b259 --- /dev/null +++ b/apps/desktop/src/workbench/project-document-transport.ts @@ -0,0 +1,114 @@ +import type { Transport } from './transport' + +export const DOCUMENT_NAME_BYTES = 200 +export const DOCUMENT_BODY_BYTES = 2 * 1024 * 1024 +export const DOCUMENT_TTL = 120_000 + +const bytes = new TextEncoder() +const invisible = /[\p{C}\p{Zl}\p{Zp}\p{Default_Ignorable_Code_Point}]/u +const nonText = /[\u0000-\u0008\u000e-\u001f\u007f-\u0084\u0086-\u009f\p{Cs}]/u +const workspaceId = /^w_[a-f0-9]{32}$/u +const intentId = /^di_[a-f0-9]{32}$/u +const revision = /^r_[a-f0-9]{64}$/u +const matches = (pattern: RegExp, value: unknown): value is string => typeof value === 'string' && pattern.exec(value)?.[0] === value +export const projectDocumentWorkspaceId = (value: unknown): value is string => matches(workspaceId, value) + +export type DocumentIssue = 'directory' | 'name' | 'limit' | 'invalid' | 'readonly' | 'restricted' | 'expired' | 'missing' | + 'exists' | 'changed' | 'conflict' | 'busy' | 'unavailable' | 'unconfirmed' +export type PreparedDocument = { id: string; path: string; ttlMs: number } +export type DocumentStatus = { state: 'prepared' | 'unconfirmed'; path: string; revision: null } | + { state: 'created'; path: string; revision: string } + +export function documentDirectory(path: unknown): path is string { + if (typeof path !== 'string' || path.length > 4095 || bytes.encode(path).length > 4095) return false + if (path === '') return true + const segments = path.split('/') + return segments.length <= 16 && segments.every((segment) => !!segment && !segment.startsWith('.') && + !/\\|^[A-Za-z]:/u.test(segment) && !invisible.test(segment) && bytes.encode(segment).length <= 255) +} + +export function documentValidation(name: unknown, content: unknown): 'name' | 'limit' | 'invalid' | undefined { + if (typeof name !== 'string' || name.length > DOCUMENT_NAME_BYTES || !matches(/^.+\.(md|txt)$/iu, name) || + invisible.test(name) || bytes.encode(name).length > DOCUMENT_NAME_BYTES) return 'name' + const folded = name.normalize('NFKC') + const stem = folded.replace(/\.(md|txt)$/iu, '') + if (!stem || /^[.\s]|[.\s]$/u.test(stem) || /[/\\<>:"|?*]/u.test(folded)) return 'name' + if (typeof content !== 'string') return 'invalid' + if (content.length > DOCUMENT_BODY_BYTES || bytes.encode(content).length > DOCUMENT_BODY_BYTES) return 'limit' + return nonText.test(content) ? 'invalid' : undefined +} + +export const documentPath = (directory: string, name: string): string => directory === '' ? name : `${directory}/${name}` + +function object(value: unknown): Record { + return value && typeof value === 'object' && !Array.isArray(value) ? value as Record : {} +} + +function exact(value: Record, ...keys: string[]): boolean { + return Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key)) +} + +function validPath(path: string): boolean { + if (typeof path !== 'string') return false + const slash = path.lastIndexOf('/') + const directory = slash === -1 ? '' : path.slice(0, slash) + return slash !== 0 && documentDirectory(directory) && !documentValidation(path.slice(slash + 1), '') +} + +export class InvalidDocumentReceipt extends Error { + constructor(readonly id?: string) { super('Invalid document intent receipt') } +} + +/** Owner-session JSON only; the intent ID is never used as authority for a different workspace or target. */ +export function createProjectDocumentTransport(transport: Transport, csrf: string) { + const base = (wid: string): string => { + if (!csrf || !projectDocumentWorkspaceId(wid)) throw new Error('Invalid project document request') + return `/workspaces/${wid}/document-intents` + } + const resource = (wid: string, id: string, action: 'create' | 'status' | 'cancel'): string => { + if (!matches(intentId, id)) throw new Error('Invalid project document intent') + return `${base(wid)}/${id}/${action}` + } + const post = (path: string, body: object, expectedStatus: NonNullable[4]>['expectedStatus'], keepalive = false) => + transport.request(path, 'POST', body, csrf, { referrerPolicy: 'same-origin', expectedStatus, ...(keepalive ? { keepalive: true } : {}) }) + return { + async prepare(wid: string, directory: string, name: string): Promise { + if (!documentDirectory(directory) || documentValidation(name, '')) throw new Error('Invalid project document target') + const path = documentPath(directory, name) + const result = object(await post(base(wid), { directory, name }, (status, body) => { + const prepared = object(body) + const id = matches(intentId, prepared.id) ? prepared.id : undefined + // Preserve a well-formed ID from a rejected receipt solely to release its original pin. + if (status !== 201 || !id || !exact(prepared, 'id', 'path', 'ttlMs') || prepared.path !== path || prepared.ttlMs !== DOCUMENT_TTL) + throw new InvalidDocumentReceipt(id) + return true + })) + return { id: result.id as string, path, ttlMs: DOCUMENT_TTL } + }, + async create(wid: string, id: string, path: string, content: string): Promise<{ path: string; revision: string; replayed: boolean }> { + if (!validPath(path) || documentValidation(path.slice(path.lastIndexOf('/') + 1), content)) throw new Error('Invalid project document input') + const result = object(await post(resource(wid, id, 'create'), { content }, (status, value) => + (status === 201 && object(value).replayed === false) || (status === 200 && object(value).replayed === true))) + if (!exact(result, 'created', 'path', 'revision', 'replayed') || result.created !== true || result.path !== path || + !matches(revision, result.revision) || typeof result.replayed !== 'boolean') + throw new InvalidDocumentReceipt() + return { path, revision: result.revision, replayed: result.replayed } + }, + async status(wid: string, id: string, path: string): Promise { + if (!validPath(path)) throw new Error('Invalid project document target') + const result = object(await post(resource(wid, id, 'status'), {}, 200)) + if (exact(result, 'state', 'path', 'revision') && result.path === path) { + if (result.state === 'created' && matches(revision, result.revision)) return { state: 'created', path, revision: result.revision } + if ((result.state === 'prepared' || result.state === 'unconfirmed') && result.revision === null) + return { state: result.state, path, revision: null } + } + throw new InvalidDocumentReceipt() + }, + async cancel(wid: string, id: string): Promise { + const result = object(await post(resource(wid, id, 'cancel'), {}, 200, true)) + if (!exact(result, 'closed') || result.closed !== true) throw new InvalidDocumentReceipt() + } + } +} + +export type ProjectDocumentTransport = ReturnType diff --git a/apps/desktop/src/workbench/project-document-ui.tsx b/apps/desktop/src/workbench/project-document-ui.tsx new file mode 100644 index 00000000..e6abbf16 --- /dev/null +++ b/apps/desktop/src/workbench/project-document-ui.tsx @@ -0,0 +1,95 @@ +import type { ProjectDocuments, ProjectDocumentView } from './project-document-controller' +import './project-document.css' + +const copy = { + en: { + new: 'New document', resume: 'Resume document draft', draftTitle: 'New document draft', parent: 'Folder', root: 'Project root (/)', + name: 'File name (.md or .txt)', content: 'Document text', empty: 'An empty document is allowed.', target: 'Target path', + review: 'Review', create: 'Create document', cancel: 'Cancel', verify: 'Verify create result', checkFolder: 'Reveal target folder', + draft: 'Draft only. Review checks the path without creating a file.', preparing: 'Checking target…', + prepared: 'Target checked. The file has not been created.', creating: 'Creating file…', verifying: 'Checking file and contents…', + unconfirmed: 'Create result unconfirmed. The draft has been kept.', saved: 'Document saved', + directory: 'Select a confirmed writable folder from this project.', nameIssue: 'Use an ordinary .md or .txt name, up to 200 UTF-8 bytes.', + limit: 'The name, path, or document text exceeds its size limit (text: 2 MiB).', invalid: 'The document name or text is invalid.', readonly: 'This location is read-only.', + restricted: 'This location or file name is restricted.', expired: 'Your session expired. Copy the draft before signing in again.', + missing: 'The target or review is missing or expired. The draft has been kept.', exists: 'That file already exists. Enter a different name.', + changed: 'The target folder or file changed. Review the target again.', conflict: 'The target conflicts with the reviewed location. The draft has been kept.', + busy: 'The document service is busy. Your draft is still here.', unavailable: 'The document check is unavailable. Your draft is still here.', + notCreated: 'The review reports no creation. Review again before creating.', + }, + 'zh-CN': { + new: '新建文档', resume: '继续编辑文档草稿', draftTitle: '新建文档草稿', parent: '文件夹', root: '项目根目录 (/)', + name: '文件名(.md 或 .txt)', content: '文档正文', empty: '正文可为空。', target: '目标路径', + review: '核对目标', create: '创建文档', cancel: '取消', verify: '核实创建结果', checkFolder: '定位目标文件夹', + draft: '当前仅为草稿。核对目标时仅检查路径。', preparing: '正在检查目标…', + prepared: '目标已核对,文件尚未创建。', creating: '正在创建文件…', verifying: '正在核实文件与正文…', + unconfirmed: '创建结果尚未确认,草稿已保留。', saved: '文档已保存', + directory: '请选择本项目中已确认可写的文件夹。', nameIssue: '请输入普通的 .md 或 .txt 文件名,最多 200 个 UTF-8 字节。', + limit: '文件名、路径或正文超过大小上限(正文限 2 MiB)。', invalid: '文件名或正文无效。', readonly: '此位置为只读。', + restricted: '此位置或文件名受限。', expired: '会话已过期,请在重新登录前复制草稿。', + missing: '目标或核对记录已失效或不存在,草稿已保留。', exists: '同名文件已存在,请更换文件名。', + changed: '目标文件夹或文件已变更,请重新核对。', conflict: '目标与核对时的位置冲突,草稿已保留。', + busy: '文档服务正忙,草稿已保留。', unavailable: '文档核对服务暂不可用,草稿已保留。', + notCreated: '核实结果显示文件尚未创建。创建前请重新核对目标。', + } +} as const + +type Locale = keyof typeof copy +const pending = (phase: ProjectDocumentView['phase']): boolean => phase === 'preparing' || phase === 'creating' || phase === 'verifying' + +export function ProjectDocumentNew({ view, api, locale }: { view: ProjectDocumentView; api: ProjectDocuments; locale: Locale }): React.JSX.Element | null { + const labels = copy[locale] + return view.canNew ? : null +} + +export function ProjectDocumentStatus({ view, locale }: { view: ProjectDocumentView; locale: Locale }): React.JSX.Element | null { + if (!view.phase) return null + const labels = copy[locale] + const issue = view.issue === 'name' ? 'nameIssue' : view.issue + return

+ {pending(view.phase) &&

+} + +export function ProjectDocumentDraft({ view, api, locale }: { view: ProjectDocumentView; api: ProjectDocuments; locale: Locale }): React.JSX.Element | null { + const draft = view.draft + if (!draft) return null + const labels = copy[locale] + const prepared = view.phase === 'prepared' || view.phase === 'creating' + const uncertain = view.phase === 'unconfirmed' || view.issue === 'unconfirmed' || draft.uncertainPath === view.preview && !!draft.uncertainPath + return
+ {labels.draftTitle} + + + {view.preview &&

{labels.target}: /{view.preview}

} +