From 1e16d60d9f876d1ec1663919d9a0aaa8f91252c5 Mon Sep 17 00:00:00 2001 From: Facetomyself <[GIT_EMAIL]> Date: Thu, 26 Nov 2026 20:27:09 +0800 Subject: [PATCH 1/4] =?UTF-8?q?feat(chat):=20=E4=B8=A5=E6=A0=BC=E4=BF=9D?= =?UTF-8?q?=E5=AD=98=E4=BC=9A=E8=AF=9D=E4=B8=8E=E9=A1=B9=E7=9B=AE=E7=9A=84?= =?UTF-8?q?=E7=BB=91=E5=AE=9A=20/=20persist=20confirmed=20conversation=20w?= =?UTF-8?q?orkspace=20bindings?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/chat/session-workspace-domain.mjs | 130 ++++++ .../src/chat/session-workspace-storage.mjs | 73 +++ apps/headless/src/chat/session-workspace.mjs | 88 ++++ apps/headless/src/chat/text-turns.mjs | 128 ++++-- .../test/session-workspace-domain.test.mjs | 425 ++++++++++++++++++ 5 files changed, 809 insertions(+), 35 deletions(-) create mode 100644 apps/headless/src/chat/session-workspace-domain.mjs create mode 100644 apps/headless/src/chat/session-workspace-storage.mjs create mode 100644 apps/headless/src/chat/session-workspace.mjs create mode 100644 apps/headless/test/session-workspace-domain.test.mjs diff --git a/apps/headless/src/chat/session-workspace-domain.mjs b/apps/headless/src/chat/session-workspace-domain.mjs new file mode 100644 index 00000000..2c0acfac --- /dev/null +++ b/apps/headless/src/chat/session-workspace-domain.mjs @@ -0,0 +1,130 @@ +import { HttpError } from '../http/policy.mjs' +import { + WORKSPACE_META, grantAccess, workspaceBinding, workspaceConflict, workspacePatch, + workspaceProjection, workspaceRevision, workspaceUnavailable, workspaceView +} from './session-workspace.mjs' +import { + confirmWorkspaceNative, matchesWorkspaceNative, readWorkspaceNative, workspaceFileStamp, workspaceStorageError +} from './session-workspace-storage.mjs' + +const busy = () => new HttpError(409, 'turn_in_progress') + +export function createSessionWorkspaceDomain({ + dataDir, withWorkspace, validSid, isClosing, isActive, isBlocked, compatibility, checkMedia, + lookupSession, commit, quarantine, publishSessionsChanged +}) { + const withGrant = grantAccess(withWorkspace) + const drift = new Set() + const stamps = new WeakMap() + const knownWeb = new Map() + const isDrifted = sid => drift.has(sid) + const note = s => knownWeb.set(s.id, s) + + // Ordinary list/send never query the operator catalog. A cheap file stamp protects the + // loaded native binding; an unexpected change falls back to strict native comparison. + function stable(s) { + if (isDrifted(s.id)) return false + if (!s[WORKSPACE_META] || !workspaceBinding(s) || isBlocked(s.id)) return true + try { + const stamp = workspaceFileStamp(dataDir, s.id) + if (stamp && stamps.get(s) === stamp) return true + const native = readWorkspaceNative(dataDir, s.id) + if (native?.privateMode && matchesWorkspaceNative(native, s)) { + stamps.set(s, native.stamp) + return true + } + } catch { /* unknown native state; quarantine for this process */ } + drift.add(s.id) + return false + } + + function afterSave(s, readback) { + const stamp = readback ? confirmWorkspaceNative(dataDir, s) : workspaceFileStamp(dataDir, s.id) + if (!stamp) throw workspaceStorageError() + stamps.set(s, stamp) + } + + function nativeSession(sid, writing = false) { + if (isBlocked(sid) || isDrifted(sid)) throw workspaceStorageError() + const cached = knownWeb.get(sid) + let native + try { native = readWorkspaceNative(dataDir, sid) } + catch (err) { + if (cached) drift.add(sid) + throw err + } + if (cached && (!native || !matchesWorkspaceNative(native, cached))) { + drift.add(sid) + throw writing && native ? workspaceConflict() : workspaceStorageError() + } + return native + } + + function workspaceSession(sid, writing = false) { + if (isClosing()) throw new HttpError(503, 'chat_closed') + if (!validSid(sid)) throw new HttpError(400, 'invalid_session_id') + if (writing && isActive(sid)) throw busy() + const native = nativeSession(sid, writing) + if (!native) throw new HttpError(404, 'session_not_found') + const kind = compatibility(native.value) + if (kind !== 'text') throw new HttpError(409, kind === 'legacy_text' ? 'read_only_session' : 'unsupported_history') + if (!native.privateMode || (writing && !native.writable)) throw workspaceStorageError() + checkMedia(native.value, knownWeb.get(sid)) + return native + } + + function getWorkspace(sid) { + const { value } = workspaceSession(sid) + return workspaceView(value, workspaceBinding(value), withGrant) + } + + function setWorkspace(sid, { workspaceId, revision }, verifyOwner) { + function authenticate() { + if (verifyOwner === undefined) return + const verified = verifyOwner(sid) + if (typeof verified?.then === 'function') { + Promise.resolve(verified).catch(() => {}) + throw new HttpError(401, 'unauthorized') + } + if (verified === false) throw new HttpError(401, 'unauthorized') + } + function current() { + const native = workspaceSession(sid, true) + if (workspaceRevision(native.value) !== revision) throw workspaceConflict() + return native + } + authenticate() + const native = current() + const binding = workspaceBinding(native.value) + if ((binding?.id ?? null) === workspaceId) return workspaceView(native.value, binding, withGrant) + let rollback + function persist(before, grant) { + const stored = lookupSession(sid) + if (!stored || isDrifted(sid) || !matchesWorkspaceNative(before, stored)) throw workspaceStorageError() + const patch = workspacePatch(sid, grant, grant ? 'manual' : null, workspaceBinding(stored)?.originalId ?? null) + authenticate() // Disk and catalog work may have outlived the owner session. + if (isClosing()) throw new HttpError(503, 'chat_closed') + if (isActive(sid)) throw busy() + if (isBlocked(sid) || isDrifted(sid)) throw workspaceStorageError() + if (workspaceRevision(stored) !== revision || workspaceFileStamp(dataDir, sid) !== before.stamp) throw workspaceConflict() + rollback = commit(stored, patch, null, () => afterSave(stored, true)) + return workspaceProjection(stored, patch[WORKSPACE_META], grant?.name) + } + let result + try { + // No await from authentication and CAS through native readback. Recheck inside the + // pinned action as well, so a synchronous/reentrant adapter cannot defeat same-SID CAS. + result = workspaceId === null ? persist(native) : withGrant(workspaceId, grant => persist(current(), grant)) + } catch (err) { + if (!rollback) throw err + rollback() + quarantine(sid) + throw workspaceStorageError() + } + if (!result) throw workspaceUnavailable() + publishSessionsChanged() + return result + } + + return { note, stable, afterSave, isDrifted, nativeSession, withGrant, getWorkspace, setWorkspace } +} diff --git a/apps/headless/src/chat/session-workspace-storage.mjs b/apps/headless/src/chat/session-workspace-storage.mjs new file mode 100644 index 00000000..8401c130 --- /dev/null +++ b/apps/headless/src/chat/session-workspace-storage.mjs @@ -0,0 +1,73 @@ +import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from 'node:fs' +import { join } from 'node:path' +import { isDeepStrictEqual } from 'node:util' +import { HttpError } from '../http/policy.mjs' +import { parseNativeJSON } from './delivery-records-storage.mjs' + +export const workspaceStorageError = () => new HttpError(503, 'chat_storage_unconfirmed') +const mainPath = (dataDir, sid) => join(dataDir, 'data', 'chats', `${sid}.json`) +const maxFile = 128n * 1024n * 1024n +const statOptions = { bigint: true } +const signature = stat => [stat.dev, stat.ino, stat.mode, stat.nlink, stat.size, stat.uid, stat.gid, stat.mtimeNs, stat.ctimeNs].join(':') +const fileMode = stat => stat.mode & 0o7777n +const regular = stat => stat.isFile() && stat.nlink === 1n && stat.size > 0n && stat.size <= maxFile && + stat.uid === BigInt(process.geteuid()) && (fileMode(stat) & 0o7022n) === 0n +const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }) + +function statMain(path) { + try { + const stat = lstatSync(path, statOptions) + if (!regular(stat)) throw workspaceStorageError() + return stat + } catch (err) { + if (err?.code === 'ENOENT') return null + throw workspaceStorageError() + } +} + +export function workspaceFileStamp(dataDir, sid) { + const stat = statMain(mainPath(dataDir, sid)) + return stat ? signature(stat) : null +} + +function validSession(value, sid) { + return value && value.id === sid && typeof value.title === 'string' && Number.isFinite(value.createdAt) && + Number.isFinite(value.updatedAt) && Array.isArray(value.messages) && value.messages.every(message => + message && ['user', 'assistant'].includes(message.role) && (typeof message.content === 'string' || + (Array.isArray(message.content) && message.content.every(part => part && typeof part.type === 'string')))) +} + +/** Independently confirm the native session without the store's cache or sidecar cleanup. */ +export function readWorkspaceNative(dataDir, sid) { + const path = mainPath(dataDir, sid) + const named = statMain(path) + if (!named) return null + try { + const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK) + try { + const opened = fstatSync(fd, statOptions) + const stamp = signature(opened) + if (!regular(opened) || signature(named) !== stamp) throw workspaceStorageError() + const bytes = Buffer.allocUnsafe(Number(opened.size)) + for (let offset = 0; offset < bytes.length;) { + const count = readSync(fd, bytes, offset, bytes.length - offset, offset) + if (!count) throw workspaceStorageError() + offset += count + } + if (signature(fstatSync(fd, statOptions)) !== stamp || signature(lstatSync(path, statOptions)) !== stamp) throw workspaceStorageError() + const value = parseNativeJSON(decoder.decode(bytes)) + if (!validSession(value, sid)) throw workspaceStorageError() + const mode = fileMode(opened) + return { value, stamp, writable: mode === 0o600n, privateMode: mode === 0o600n || mode === 0o400n } + } finally { closeSync(fd) } + } catch { throw workspaceStorageError() } +} + +export const matchesWorkspaceNative = (native, s) => isDeepStrictEqual(native.value, + Object.fromEntries(Object.entries(s).filter(([, value]) => value !== undefined))) + +export function confirmWorkspaceNative(dataDir, s) { + const native = readWorkspaceNative(dataDir, s.id) + if (!native?.writable || !matchesWorkspaceNative(native, s)) throw workspaceStorageError() + return native.stamp +} diff --git a/apps/headless/src/chat/session-workspace.mjs b/apps/headless/src/chat/session-workspace.mjs new file mode 100644 index 00000000..ad80e70f --- /dev/null +++ b/apps/headless/src/chat/session-workspace.mjs @@ -0,0 +1,88 @@ +import { createHash, randomBytes } from 'node:crypto' +import { basename, isAbsolute, resolve } from 'node:path' +import { validWorkspaceName } from '../files/workspace-files-fd.mjs' +import { HttpError } from '../http/policy.mjs' + +export const WORKSPACE_META = '_devaHeadlessSessionWorkspace' +const hex = (value, size) => typeof value === 'string' && value.length === size && !/[^a-f0-9]/.test(value) +export const validWorkspaceId = value => typeof value === 'string' && value.startsWith('w_') && hex(value.slice(2), 32) +export const workspaceConflict = () => new HttpError(409, 'workspace_conflict') +export const workspaceUnavailable = () => new HttpError(404, 'workspace_unavailable') +const serviceError = () => new HttpError(503, 'chat_workspace_unavailable') +const digest = fields => createHash('sha256').update(JSON.stringify(fields)).digest('hex') +const validRoot = value => typeof value === 'string' && value.length <= 4095 && Buffer.byteLength(value) <= 4095 && + value.isWellFormed() && !value.includes('\0') && isAbsolute(value) && value !== '/' && resolve(value) === value + +export function readWorkspaceInput({ workspaceId, revision }) { + if (workspaceId !== null && !validWorkspaceId(workspaceId)) throw new HttpError(400, 'invalid_workspace_id') + if (!hex(revision, 64)) throw new HttpError(400, 'invalid_workspace_revision') + return { workspaceId, revision } +} + +// This ties Web provenance to the native root and SID, rather than authorizing a filesystem +// operation. Current authority always comes from the operator catalog with its pin held. +const integrity = (sid, root, { id, source, originalId, generation }) => + digest(['deva:native-session-workspace:v1', sid, root, id, source, originalId, generation]) + +/** undefined = a never-bound native Web session; false = invalid/foreign record. */ +export function workspaceBinding(s) { + if (!Object.hasOwn(s, WORKSPACE_META)) return s.focusRoot == null ? undefined : false + const value = s[WORKSPACE_META] + if (!value || Object.getPrototypeOf(value) !== Object.prototype || Object.keys(value).length !== 6 || value.version !== 1 || + !hex(value.generation, 32) || !hex(value.integrity, 64) || + (value.originalId !== null && !validWorkspaceId(value.originalId))) return false + if (value.id === null ? value.source !== null || s.focusRoot !== null + : !validWorkspaceId(value.id) || !['manual', 'role'].includes(value.source) || !validRoot(s.focusRoot)) return false + return integrity(s.id, s.focusRoot, value) === value.integrity ? value : false +} + +export function workspaceRevision(s, binding = workspaceBinding(s)) { + // No native path enters the public revision; the random generation separates detach/rebind ABA. + return digest(['deva:session-workspace-revision:v1', s.id, binding?.generation ?? null]) +} + +export function workspacePatch(sid, grant, source, originalId) { + const root = grant?.root ?? null + const meta = { version: 1, id: grant?.id ?? null, source, originalId, generation: randomBytes(16).toString('hex') } + return { focusRoot: root, [WORKSPACE_META]: { ...meta, integrity: integrity(sid, root, meta) } } +} + +/** Use the grant synchronously and exclusively in the caller's pinned catalog action. */ +export function grantAccess(withWorkspace) { + if (withWorkspace !== undefined && typeof withWorkspace !== 'function') throw new TypeError('withWorkspace must be a function') + return (id, use) => { + if (!withWorkspace) return undefined + let open = true, called = false, outcome, actionError, returned + try { + returned = withWorkspace(id, grant => { + if (!open || called) throw serviceError() + called = true + try { + if (!grant || !Object.isFrozen(grant) || grant.id !== id || !validRoot(grant.root) || + !validWorkspaceName(grant.name) || basename(grant.root) !== grant.name) throw serviceError() + outcome = use(grant) + if (outcome === undefined) throw serviceError() + return outcome + } catch (err) { actionError = err; throw err } + }) + } catch (err) { + if (err === actionError) throw err + throw serviceError() + } finally { open = false } + if (actionError) throw actionError + if (called ? returned !== outcome : returned !== undefined) throw serviceError() + return returned + } +} + +export function workspaceProjection(s, binding, name = null) { + const revision = workspaceRevision(s, binding) + const workspace = binding?.id ? { id: binding.id, name, state: name === null ? 'unavailable' : 'available', source: binding.source } : null + return { workspace, revision } +} + +export function workspaceView(s, binding, withGrant) { + if (!binding?.id) return workspaceProjection(s, binding) + const name = withGrant(binding.id, grant => ({ name: grant.root === s.focusRoot ? grant.name : null }))?.name ?? null + return workspaceProjection(s, binding, name) +} diff --git a/apps/headless/src/chat/text-turns.mjs b/apps/headless/src/chat/text-turns.mjs index a760c8b3..c728bf78 100644 --- a/apps/headless/src/chat/text-turns.mjs +++ b/apps/headless/src/chat/text-turns.mjs @@ -11,6 +11,10 @@ import { preferenceView, readPreferencePatch, resolveTurnModel, splitModel, unsupportedEffort, validPreferenceFields, validatePreferenceModel } from './session-preferences.mjs' import { ATTACHMENT_META, attachmentIds, createTurnAttachments } from './turn-attachments.mjs' +import { createSessionWorkspaceDomain } from './session-workspace-domain.mjs' +import { + WORKSPACE_META, readWorkspaceInput, validWorkspaceId, workspaceBinding, workspacePatch, workspaceRevision, workspaceUnavailable +} from './session-workspace.mjs' const META = '_devaHeadlessTextTurns' const MAX_REQUESTS = 256 // Never evict an accepted ID and later interpret its retry as a fresh request. @@ -33,7 +37,7 @@ const terminalReasons = new Map([ ]) const nativeTextFields = new Set([ 'id', 'title', 'createdAt', 'updatedAt', 'focusRoot', 'personaId', 'model', 'messages', 'notices', - 'archived', 'effort', META, PREFERENCES_META + 'archived', 'effort', META, PREFERENCES_META, WORKSPACE_META ]) const complexFields = [ 'compacted', 'members', 'parentId', 'proposals', 'asks', 'summaries', 'delivered', 'background', @@ -96,14 +100,15 @@ function inputRecord(input, keys, code) { } function createInput(input) { - if (input === undefined) return randomUUID() + if (input === undefined) return { id: randomUUID(), workspaceId: undefined } if (!input || ![Object.prototype, null].includes(Object.getPrototypeOf(input))) throw new HttpError(400, 'invalid_create') - if (Reflect.ownKeys(input).length === 0) return randomUUID() - const { sessionId } = inputRecord(input, ['sessionId'], 'invalid_create') - if (!validSid(sessionId) || !(desktopSid.test(sessionId) || uuidSid.test(sessionId))) { + const keys = ['sessionId', 'workspaceId'].filter(key => Object.hasOwn(input, key)) + const { sessionId, workspaceId } = inputRecord(input, keys, 'invalid_create') + if (keys.includes('sessionId') && (!validSid(sessionId) || !(desktopSid.test(sessionId) || uuidSid.test(sessionId)))) { throw new HttpError(400, 'invalid_session_id') } - return sessionId + if (keys.includes('workspaceId') && workspaceId !== null && !validWorkspaceId(workspaceId)) throw new HttpError(400, 'invalid_workspace_id') + return { id: sessionId ?? randomUUID(), workspaceId } } function sendInput(input, supportsAttachments) { @@ -185,8 +190,8 @@ function appendNotice(notices, after, status, reason, text) { } /** One instance per data directory and journal. The owner closes the journal after awaiting close(). - * resolveRole only reads trusted library state and returns the current enabled role projection. */ -export function createTextTurns({ dataDir, settings, journal, version, allowedOrigins, resolveRole, uploads, deliveries }) { + * resolveRole reads trusted library state. withWorkspace only supplies live pinned catalog grants. */ +export function createTextTurns({ dataDir, settings, journal, version, allowedOrigins, resolveRole, uploads, deliveries, withWorkspace }) { if (typeof settings?.getProvider !== 'function' || !['snapshot', 'snapshotAndSubscribe', 'publishChat', 'publishSessionsChanged'] .every(fn => typeof journal?.[fn] === 'function')) throw new TypeError('Text turns require settings and an event journal') if (resolveRole !== undefined && typeof resolveRole !== 'function') throw new TypeError('resolveRole must be a function') @@ -205,12 +210,25 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr const hidden = new Set() // A failed create may leave a session only in the core's cache. const deliverySessions = deliveries === true ? new Map() : undefined let closing + const workspace = createSessionWorkspaceDomain({ + dataDir, withWorkspace, validSid, isClosing: () => Boolean(closing), isActive: sid => active.has(sid), + isBlocked: sid => hidden.has(sid) || unconfirmed.has(sid), compatibility, lookupSession, commit, publishSessionsChanged, + quarantine: sid => unconfirmed.set(sid, null), + checkMedia(s, cached) { + const index = attachedIndex(s) + if (index && (mediaUnconfirmed.has(cached) || !attachments.available(index))) throw new HttpError(409, 'unsupported_history') + } + }) function lookupSession(sid) { warned = false const s = hidden.has(sid) ? undefined : store.getSession(sid) if (s && warned) incomplete.add(s) - if (s && Object.hasOwn(s, META)) deliverySessions?.set(sid, s) + if (s && Object.hasOwn(s, META)) { + workspace.note(s) + deliverySessions?.set(sid, s) + workspace.stable(s) + } return s } @@ -226,22 +244,24 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr } function compatibility(s) { + const owns = Object.hasOwn(s, META) + const binding = workspaceBinding(s) + if (workspace.isDrifted(s.id) || binding === false || (!owns && binding)) return 'unsupported' if (s[ATTACHMENT_META] !== undefined) { - return attachments && !incomplete.has(s) && s.focusRoot == null && + return attachments && !incomplete.has(s) && (s.personaId === undefined || isChatRoleId(s.personaId)) && validLedger(s[META], s.messages.length) && validNotices(s) && validPreferenceFields(s) && Object.keys(s).every(key => s[key] === undefined || key === ATTACHMENT_META || nativeTextFields.has(key)) && attachedIndex(s) ? 'text' : 'unsupported' } if (classifications.has(s)) return classifications.get(s) - const owns = Object.hasOwn(s, META) const complex = incomplete.has(s) || complexFields.some(key => { const value = s[key] return value && (typeof value !== 'object' || Object.keys(value).length) }) || s.messages.some(m => plainText(m.content) === null) const legacyNotices = !owns && s.notices !== undefined && (!Array.isArray(s.notices) || s.notices.length > 0) const kind = complex || legacyNotices || (owns && ( - !validLedger(s[META], s.messages.length) || !validNotices(s) || !validPreferenceFields(s) || s.focusRoot != null || + !validLedger(s[META], s.messages.length) || !validNotices(s) || !validPreferenceFields(s) || (s.personaId !== undefined && !isChatRoleId(s.personaId)) || Object.keys(s).some(key => s[key] !== undefined && !nativeTextFields.has(key)) )) ? 'unsupported' : owns ? 'text' : 'legacy_text' @@ -258,11 +278,13 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr else if (closing) writeBlockReason = 'chat_closed' else if (unconfirmed.has(s.id)) writeBlockReason = 'chat_storage_unconfirmed' else if (s[META].requests.length >= MAX_REQUESTS) writeBlockReason = 'session_turn_limit' + const binding = kind === 'text' && workspaceBinding(s) return { id: s.id, title: s.title, createdAt: s.createdAt, updatedAt: s.updatedAt, ...(isChatRoleId(s.personaId) ? { personaId: s.personaId } : {}), model: kind === 'text' && typeof s.model === 'string' && s.model ? s.model : null, ...listPreferenceFields(s), + ...(binding && !unconfirmed.has(s.id) ? { workspaceRevision: workspaceRevision(s, binding) } : {}), compatibility: kind, writable: writeBlockReason === null, writeBlockReason, turnLimit: kind === 'text' ? MAX_REQUESTS : null } @@ -270,29 +292,51 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr function create(input, trustedRole) { if (closing) throw closedError() - const id = createInput(input) + const { id, workspaceId } = createInput(input) const role = trustedRole === undefined ? undefined : checkedRole(trustedRole) if (role && !resolveRole) throw roleServiceError() - if (hidden.has(id)) throw storageError() - const existing = lookupSession(id) - if (existing) { - if (compatibility(existing) !== 'text' || (role && existing.personaId !== role.id)) { + function replay() { + const native = workspace.nativeSession(id) + if (!native) return undefined + const s = native.value + if (compatibility(s) !== 'text' || (role && s.personaId !== role.id) || + (workspaceId !== undefined && workspaceId !== (workspaceBinding(s)?.originalId ?? null))) { throw new HttpError(409, 'session_id_conflict') } - return summary(existing) + if (!native.privateMode) throw storageError() + return summary(s) } - let s + const existing = replay() + if (existing) return existing + let started = false + function persist(grant) { + started = true + try { + const s = store.ensureSession(id, role ? { personaId: role.id, model: role.model || undefined } : undefined) + s[META] = { version: 1, messageCount: 0, requests: [] } + if (grant) Object.assign(s, workspacePatch(id, grant, workspaceId === undefined ? 'role' : 'manual', grant.id)) + store.saveStrict(id) + workspace.afterSave(s, true) + workspace.note(s) + deliverySessions?.set(id, s) + return summary(s) + } catch { throw storageError() } + } + let created try { - s = store.ensureSession(id, role ? { personaId: role.id, model: role.model || undefined } : undefined) - s[META] = { version: 1, messageCount: 0, requests: [] } - store.saveStrict(id) - deliverySessions?.set(id, s) - } catch { - hidden.add(id) - throw storageError() + const wanted = workspaceId === undefined ? trustedRole?.workspaceId : workspaceId + if (workspaceId === undefined && wanted != null && wanted !== '' && !validWorkspaceId(wanted)) throw roleServiceError() + if (validWorkspaceId(wanted)) { + created = workspace.withGrant(wanted, grant => replay() ?? persist(grant)) + if (!created && workspaceId !== undefined) throw workspaceUnavailable() + } + created ??= replay() ?? persist() + } catch (err) { + if (started) { hidden.add(id); throw storageError() } + throw err } - publishSessionsChanged() - return summary(s) + if (started) publishSessionsChanged() + return created } function list() { @@ -326,6 +370,12 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr return preferenceView(s, s[META].requests.length) } + function setWorkspace(sid, input, verifyOwner) { + if (!validSid(sid)) throw new HttpError(400, 'invalid_session_id') + const patch = readWorkspaceInput(inputRecord(input, ['workspaceId', 'revision'], 'invalid_workspace')) + return workspace.setWorkspace(sid, patch, verifyOwner) + } + function firstUser(s) { const at = s.messages.findIndex(m => m.role === 'user') if (at < 0) return null @@ -434,20 +484,28 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr // On a strict-save failure the main JSON might already be published, with only its index repair failing. // Restore the last confirmed in-memory view, block further mutation here, and let the next process read disk. function commit(s, patch, terminal = null, verify) { + if (!workspace.stable(s)) throw storageError() const before = new Map(Object.keys(patch).map(key => [key, Object.getOwnPropertyDescriptor(s, key)])) - for (const [key, value] of Object.entries(patch)) { - if (value === undefined) delete s[key] - else s[key] = value - } - try { store.saveStrict(s.id); verify?.() } - catch { + function restore() { for (const [key, descriptor] of before) { if (descriptor) Object.defineProperty(s, key, descriptor) else delete s[key] } + } + for (const [key, value] of Object.entries(patch)) { + if (value === undefined) delete s[key] + else s[key] = value + } + try { + store.saveStrict(s.id) + verify?.() + if (s[WORKSPACE_META] && !Object.hasOwn(patch, WORKSPACE_META)) workspace.afterSave(s, false) + } catch { + restore() unconfirmed.set(s.id, terminal) throw storageError() } + return restore } async function roleForTurn(id) { @@ -672,7 +730,7 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr } }) return Object.freeze({ - create, list, attach, snapshot, send, stop, close, getPreferences, patchPreferences, + create, list, attach, snapshot, send, stop, close, getPreferences, patchPreferences, getWorkspace: workspace.getWorkspace, setWorkspace, attachmentScope, describeCommittedAttachment, readCommittedAttachment, hasBrowserSession, ...records }) } diff --git a/apps/headless/test/session-workspace-domain.test.mjs b/apps/headless/test/session-workspace-domain.test.mjs new file mode 100644 index 00000000..6a4e3ffe --- /dev/null +++ b/apps/headless/test/session-workspace-domain.test.mjs @@ -0,0 +1,425 @@ +import assert from 'node:assert/strict' +import { randomUUID } from 'node:crypto' +import { once } from 'node:events' +import { promises as fs } from 'node:fs' +import { createServer } from 'node:http' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { Readable } from 'node:stream' +import { test } from 'node:test' +import { createChatStore } from '../dist/chat-core.mjs' +import { openUploadStore } from '../src/attachments/upload-store.mjs' +import { openWorkspaceCatalog } from '../src/business/workspace-catalog.mjs' +import { WORKSPACE_META } from '../src/chat/session-workspace.mjs' +import { createTextTurns } from '../src/chat/text-turns.mjs' +import { createEventJournal, SESSIONS_SCOPE } from '../src/events/index.mjs' +import { acquireWriterLock } from '../src/runtime/writer-lock.mjs' + +const model = 'fixture:chat' +const pattern = /^[0-9a-f]{64}$/ +const error = (status, code) => ({ status, code, message: code }) +const storageError = error(503, 'chat_storage_unconfirmed') +const conflict = error(409, 'workspace_conflict') +const unavailable = error(404, 'workspace_unavailable') +const options = { timeout: 10_000 } +const sentinel = 'workspace file contents that must never reach the model' +const request = (sid, clientRequestId, extra) => ({ sid, clientRequestId, text: 'A plain question', model, ...extra }) +const expected = (id, name, source) => ({ id, name, state: name === null ? 'unavailable' : 'available', source }) +const withoutBinding = ({ focusRoot, [WORKSPACE_META]: _, ...rest }) => rest + +function respond(res) { + res.writeHead(200, { 'content-type': 'text/event-stream' }) + res.end(`data: ${JSON.stringify({ choices: [{ index: 0, delta: { content: 'Fixture answer' }, finish_reason: 'stop' }] })}\n\ndata: [DONE]\n\n`) +} + +async function fixture(t) { + const root = await fs.mkdtemp(join(await fs.realpath(tmpdir()), 'deva-session-workspace-')) + const dataDir = join(root, 'home') + const mount = join(root, 'projects') + const aRoot = join(mount, 'alpha') + const bRoot = join(mount, 'beta') + const chats = join(dataDir, 'data', 'chats') + await fs.mkdir(aRoot, { recursive: true }) + await fs.mkdir(bRoot) + await fs.writeFile(join(aRoot, 'scope-note.txt'), sentinel) + const catalog = openWorkspaceCatalog({ root: mount, privateRoots: [dataDir] }) + const ids = () => Object.fromEntries(catalog.list().map(({ id, name }) => [name, id])) + const { alpha: a, beta: b } = ids() + const release = acquireWriterLock(dataDir) + const failures = [], calls = [], reads = [], lookups = [] + const server = createServer((req, res) => { void (async () => { + const chunks = [] + for await (const chunk of req) chunks.push(chunk) + calls.push(JSON.parse(Buffer.concat(chunks))) + respond(res) + })().catch(err => { failures.push(err); res.destroy() }) }) + server.listen(0, '127.0.0.1') + await once(server, 'listening') + const origin = `http://127.0.0.1:${server.address().port}` + const role = { id: 'analyst', enabled: true, name: 'Analyst', prompt: 'Evidence-based presentation.', workspaceId: a } + let beforeProvider, afterGrant + const settings = { async getProvider(id) { + reads.push(id) + await beforeProvider?.() + return { id, adapter: 'openai', apiHost: `${origin}/v1`, purpose: 'llm', enabled: true, + models: [{ id: 'chat', enabled: true }] } + } } + function withWorkspace(id, action) { + lookups.push(id) + const row = catalog.list().find(item => item.id === id) + if (!row) return undefined + const pin = catalog.pinProject(row.id) + try { + const grant = Object.freeze({ id: row.id, name: row.name, root: join(mount, row.name) }) + const result = action(grant) + pin.assertCurrent() + afterGrant?.(grant) + return result + } finally { pin.close() } + } + const uploads = await openUploadStore({ dataDir }) + let journal, turns + function open(withCatalog = true) { + journal = createEventJournal() + turns = createTextTurns({ dataDir, settings, journal, allowedOrigins: [origin], version: 'fixture', uploads, deliveries: true, + resolveRole: id => id === role.id ? role : null, ...(withCatalog ? { withWorkspace } : {}) }) + } + async function close() { + await turns.close() + journal.close() + } + t.after(async () => { + await close() + await uploads.close() + release() + catalog.close() + server.closeAllConnections() + await new Promise(resolve => server.close(resolve)) + assert.equal(await fs.realpath(root), root) + assert.ok(root.startsWith(`${await fs.realpath(tmpdir())}/deva-session-workspace-`)) + await fs.rm(root, { recursive: true, force: true }) + assert.deepEqual(failures, []) + }) + open() + const native = sid => join(chats, `${sid}.json`) + return { + get turns() { return turns }, get seq() { return journal.snapshot(SESSIONS_SCOPE).cursor.seq }, + async restart(catalogEnabled) { await close(); open(catalogEnabled) }, + dataDir, chats, aRoot, bRoot, a, b, ids, mount, role, calls, reads, lookups, native, uploads, + beforeProvider: action => { beforeProvider = action }, afterGrant: action => { afterGrant = action }, + disk: async sid => JSON.parse(await fs.readFile(native(sid), 'utf8')) + } +} + +function watch(turns, sid) { + const done = Promise.withResolvers() + const events = [] + const { subscription } = turns.attach(sid, { onEvent(item) { events.push(item); if (item.event.type === 'done') done.resolve(item) } }) + assert.equal(subscription.status, 'subscribed') + return { done: done.promise, close: subscription.close, events } +} + +async function turn(fx, request) { + const w = watch(fx.turns, request.sid) + try { + const receipt = await fx.turns.send(request) + assert.equal((await w.done).turnId, receipt.turnId) + assert.equal(fx.turns.snapshot(request.sid).state.lastTurn.status, 'completed') + return { receipt, events: w.events } + } finally { w.close() } +} + +function privateFree(value, fx) { + const json = JSON.stringify(value) + for (const field of ['focusRoot', WORKSPACE_META, fx.aRoot, fx.bRoot, sentinel]) assert.equal(json.includes(field), false, field) +} + +test('binding is native, durable, path-free, quiet on no-op and preserves history, prefs, attachments and deliveries', options, async t => { + const fx = await fixture(t) + const { turns, a, b } = fx + const created = turns.create() + const sid = created.id + assert.equal(Object.hasOwn(created, 'workspaceRevision'), false) + const unattached = turns.getWorkspace(sid) + assert.deepEqual(unattached, { workspace: null, revision: unattached.revision }) + assert.match(unattached.revision, pattern) + const bytes = Buffer.from('An explicitly attached note') + const file = await fx.uploads.stage(sid, { name: 'note.txt', mime: 'text/plain', size: bytes.length }, Readable.from([bytes])) + const sent = request(sid, 'first', { attachments: [file.id] }) + const { receipt, events } = await turn(fx, sent) + const prefs = await turns.patchPreferences(sid, { revision: turns.getPreferences(sid).revision, set: { customTitle: 'Mine', archived: true } }) + const delivery = turns.exportReplyDelivery(sid, { turnId: receipt.turnId, format: 'txt' }) + const before = await fx.disk(sid) + const beforeDeliveries = turns.deliverySnapshot(sid) + const seq = fx.seq + const calls = fx.calls.length, reads = fx.reads.length + const current = turns.setWorkspace(sid, { workspaceId: a, revision: unattached.revision }, seen => assert.equal(seen, sid)) + assert.deepEqual(current.workspace, expected(a, 'alpha', 'manual')) + assert.notEqual(current.revision, unattached.revision) + assert.match(current.revision, pattern) + const disk = await fx.disk(sid) + assert.deepEqual(withoutBinding(disk), withoutBinding(before)) + assert.equal(disk.focusRoot, fx.aRoot) + const desktop = createChatStore({ dataDir: fx.dataDir }) + assert.equal(desktop.getSession(sid).focusRoot, fx.aRoot) + assert.equal(desktop.listSessions().find(row => row.id === sid).focusRoot, fx.aRoot) + assert.equal(fx.seq, seq + 1) + assert.deepEqual(turns.setWorkspace(sid, { workspaceId: a, revision: current.revision }), current) + assert.equal(fx.seq, seq + 1) + assert.deepEqual(await fx.disk(sid), disk) + assert.equal(turns.list()[0].workspaceRevision, current.revision) + assert.deepEqual(turns.getPreferences(sid), prefs) + assert.deepEqual(turns.deliverySnapshot(sid), beforeDeliveries) + assert.equal(turns.readReplyDelivery(sid, delivery.record.id, 0).bytes.toString(), 'Fixture answer') + assert.deepEqual(turns.readCommittedAttachment(sid, file.id).bytes, bytes) + assert.equal(turns.hasBrowserSession(sid), true) + assert.deepEqual(await turns.send(sent), { turnId: receipt.turnId, startedAt: receipt.startedAt, status: 'completed', reason: null, duplicate: true }) + assert.equal(fx.calls.length, calls) + assert.equal(fx.reads.length, reads) + privateFree([current, created, turns.list(), turns.snapshot(sid), events], fx) + await fx.restart() + assert.deepEqual(fx.turns.getWorkspace(sid), current) + assert.equal(fx.turns.snapshot(sid).state.workspaceRevision, current.revision) + assert.deepEqual(fx.turns.deliverySnapshot(sid), beforeDeliveries) + const detached = fx.turns.setWorkspace(sid, { workspaceId: null, revision: current.revision }) + assert.equal(detached.workspace, null) + assert.notEqual(detached.revision, unattached.revision) + assert.equal(fx.turns.list()[0].workspaceRevision, detached.revision) + assert.equal((await fx.disk(sid)).focusRoot, null) + await fx.restart() + assert.deepEqual(fx.turns.getWorkspace(sid), detached) + const again = fx.turns.setWorkspace(sid, { workspaceId: b, revision: detached.revision }) + assert.deepEqual(again.workspace, expected(b, 'beta', 'manual')) + assert.equal((await fx.disk(sid)).focusRoot, fx.bRoot) + assert.deepEqual(withoutBinding(await fx.disk(sid)), withoutBinding(before)) +}) + +test('create distinguishes role inheritance, explicit null, original override intent and current binding', options, async t => { + const fx = await fixture(t) + const { turns, role, a, b } = fx + const inherited = turns.create({ sessionId: randomUUID() }, role) + assert.deepEqual(turns.getWorkspace(inherited.id).workspace, expected(a, 'alpha', 'role')) + const suppressed = turns.create({ workspaceId: null }, role) + assert.equal(Object.hasOwn(suppressed, 'workspaceRevision'), false) + assert.equal(turns.getWorkspace(suppressed.id).workspace, null) + const explicit = turns.create({ workspaceId: b }, role) + assert.deepEqual(turns.getWorkspace(explicit.id).workspace, expected(b, 'beta', 'manual')) + assert.deepEqual(turns.getWorkspace(turns.create({ workspaceId: a }).id).workspace, expected(a, 'alpha', 'manual')) + const previous = fx.seq + role.workspaceId = b + assert.deepEqual(turns.create({ sessionId: inherited.id }, role), inherited) + assert.deepEqual(turns.create({ sessionId: inherited.id, workspaceId: a }, role), inherited) + assert.throws(() => turns.create({ sessionId: inherited.id, workspaceId: b }, role), error(409, 'session_id_conflict')) + assert.deepEqual(turns.create({ sessionId: suppressed.id }, role), suppressed) + assert.deepEqual(turns.create({ sessionId: suppressed.id, workspaceId: null }, role), suppressed) + assert.equal(fx.seq, previous) + const rebound = turns.setWorkspace(inherited.id, { workspaceId: b, revision: inherited.workspaceRevision }) + assert.deepEqual(rebound.workspace, expected(b, 'beta', 'manual')) + assert.equal(turns.create({ sessionId: inherited.id, workspaceId: a }, role).workspaceRevision, rebound.revision) + assert.throws(() => turns.create({ sessionId: inherited.id, workspaceId: b }, role), error(409, 'session_id_conflict')) + const cleared = turns.setWorkspace(explicit.id, { workspaceId: null, revision: explicit.workspaceRevision }) + await fx.restart() + assert.equal(fx.turns.create({ sessionId: explicit.id }, role).workspaceRevision, cleared.revision) + assert.equal(fx.turns.create({ sessionId: explicit.id, workspaceId: b }, role).workspaceRevision, cleared.revision) + assert.throws(() => fx.turns.create({ sessionId: explicit.id, workspaceId: null }, role), error(409, 'session_id_conflict')) + assert.deepEqual(fx.turns.getWorkspace(explicit.id), cleared) + assert.equal(fx.calls.length, 0) + assert.equal(fx.reads.length, 0) +}) + +test('authorization, strict ID syntax, stale/cross-session revisions and same-SID races fail without side effects', options, async t => { + const fx = await fixture(t) + const { turns, a, b } = fx + const sid = turns.create().id + const other = turns.create().id + const unseen = randomUUID() + const revision = turns.getWorkspace(sid).revision + const foreign = turns.getWorkspace(other).revision + assert.notEqual(revision, foreign) + const original = await fx.disk(sid) + const seq = fx.seq + for (const invalid of [fx.aRoot, 'alpha', `${a}\n`, a.toUpperCase(), [`${a}`], undefined]) { + assert.throws(() => turns.setWorkspace(sid, { workspaceId: invalid, revision }), error(400, 'invalid_workspace_id')) + assert.throws(() => turns.create({ workspaceId: invalid }), error(400, 'invalid_workspace_id')) + } + assert.throws(() => turns.setWorkspace(sid, { workspaceId: a, revision, focusRoot: fx.aRoot }), error(400, 'invalid_workspace')) + assert.throws(() => turns.setWorkspace(sid, { workspaceId: a, revision: 'a'.repeat(65) }), error(400, 'invalid_workspace_revision')) + assert.throws(() => turns.setWorkspace(sid, { workspaceId: a, revision: foreign }), conflict) + assert.throws(() => turns.setWorkspace(sid, { workspaceId: a, revision }, () => false), error(401, 'unauthorized')) + assert.throws(() => turns.setWorkspace(sid, { workspaceId: b, revision }, async () => true), error(401, 'unauthorized')) + assert.equal(fx.lookups.length, 0) + let authChecks = 0 + assert.throws(() => turns.setWorkspace(sid, { workspaceId: a, revision }, () => ++authChecks === 1), error(401, 'unauthorized')) + assert.equal(authChecks, 2) + assert.equal(fx.seq, seq) + assert.deepEqual(await fx.disk(sid), original) + const missing = 'w_' + '0'.repeat(32) + assert.throws(() => turns.setWorkspace(sid, { workspaceId: missing, revision }), unavailable) + assert.throws(() => turns.create({ sessionId: unseen, workspaceId: missing }), unavailable) + await assert.rejects(fs.lstat(fx.native(unseen)), { code: 'ENOENT' }) + assert.deepEqual(await fx.disk(sid), original) + assert.equal(fx.seq, seq) + const raced = await Promise.allSettled([a, b].map(async workspaceId => turns.setWorkspace(sid, { workspaceId, revision }))) + assert.equal(raced.filter(x => x.status === 'fulfilled').length, 1) + assert.deepEqual(raced[0].value, turns.getWorkspace(sid)) + assert.equal(raced[1].reason.code, conflict.code) + assert.equal(fx.seq, seq + 1) + const bound = raced[0].value + const detached = turns.setWorkspace(sid, { workspaceId: null, revision: bound.revision }) + const rebound = turns.setWorkspace(sid, { workspaceId: a, revision: detached.revision }) + assert.equal(new Set([revision, bound.revision, detached.revision, rebound.revision]).size, 4) + assert.throws(() => turns.setWorkspace(sid, { workspaceId: a, revision: bound.revision }), conflict) + // The owner callback may reenter; the outer operation checks CAS only when it returns. + assert.throws(() => turns.setWorkspace(sid, { workspaceId: null, revision: rebound.revision }, () => { + turns.setWorkspace(sid, { workspaceId: b, revision: rebound.revision }) + }), conflict) + const changed = turns.getWorkspace(sid) + assert.deepEqual(changed.workspace, expected(b, 'beta', 'manual')) + authChecks = 0 + const afterFirstReentry = fx.seq + assert.throws(() => turns.setWorkspace(sid, { workspaceId: null, revision: changed.revision }, () => { + if (++authChecks === 2) turns.setWorkspace(sid, { workspaceId: a, revision: changed.revision }) + }), conflict) + assert.equal(authChecks, 2) + assert.equal(fx.seq, afterFirstReentry + 1) + assert.deepEqual(turns.getWorkspace(sid).workspace, expected(a, 'alpha', 'manual')) + assert.deepEqual([fx.calls.length, fx.reads.length], [0, 0]) +}) + +test('revoked and same-name replacement grant never retarget; turns stay plain and busy changes stay quiet', options, async t => { + const fx = await fixture(t) + const { turns, role, a, b } = fx + const sid = turns.create({}, role).id + const binding = turns.getWorkspace(sid) + const initial = await fx.disk(sid) + const parked = join(fx.mount, 'retired-alpha') + assert.equal(await fs.realpath(fx.aRoot), fx.aRoot) + await fs.rename(fx.aRoot, parked) + await fs.mkdir(fx.aRoot) + await fs.writeFile(join(fx.aRoot, 'new-scope-note.txt'), sentinel) + const replacement = fx.ids().alpha + assert.notEqual(replacement, a) + const revoked = turns.getWorkspace(sid) + assert.deepEqual(revoked, { workspace: expected(a, null, 'role'), revision: binding.revision }) + assert.deepEqual(turns.setWorkspace(sid, { workspaceId: a, revision: binding.revision }), revoked) + assert.equal(turns.getWorkspace(turns.create({}, role).id).workspace, null) + assert.throws(() => turns.create({ workspaceId: a }), unavailable) + assert.deepEqual(await fx.disk(sid), initial) + let readsBefore = fx.reads.length + const scans = fx.lookups.length + const gate = Promise.withResolvers() + fx.beforeProvider(() => gate.promise) + const w = watch(turns, sid) + try { + const pending = turns.send(request(sid, 'role-turn')) + const seq = fx.seq + assert.throws(() => turns.setWorkspace(sid, { workspaceId: b, revision: binding.revision }), error(409, 'turn_in_progress')) + assert.throws(() => turns.setWorkspace(sid, { workspaceId: null, revision: binding.revision }), error(409, 'turn_in_progress')) + assert.equal(fx.seq, seq) + assert.equal(fx.calls.length, 0) + assert.equal(turns.list().find(row => row.id === sid).workspaceRevision, binding.revision) + assert.equal(fx.lookups.length, scans) + gate.resolve() + await pending + await w.done + } finally { gate.resolve(); w.close() } + assert.equal(fx.calls.length, 1) + assert.equal(fx.reads.length, readsBefore + 1) + assert.equal(fx.lookups.length, scans) + const body = fx.calls[0] + assert.deepEqual(body.tools, []) + assert.equal(body.messages.length, 2) + assert.deepEqual(body.messages.map(({ role }) => role), ['system', 'user']) + assert.match(body.messages[1].content, /A plain question/) + privateFree(body, fx) + assert.ok(!JSON.stringify(body).includes(a) && !JSON.stringify(body).includes(replacement)) + readsBefore = fx.reads.length + const detached = turns.setWorkspace(sid, { workspaceId: null, revision: revoked.revision }) + assert.deepEqual(detached, turns.getWorkspace(sid)) + assert.equal(detached.workspace, null) + assert.equal((await fx.disk(sid)).focusRoot, null) + assert.equal(fx.calls.length, 1) + assert.equal(fx.reads.length, readsBefore) + await fx.restart(false) + assert.deepEqual(fx.turns.getWorkspace(sid), detached) + assert.equal(fx.turns.getWorkspace(fx.turns.create().id).workspace, null) + assert.throws(() => fx.turns.create({ workspaceId: b }), unavailable) +}) + +test('old plain, complex, incomplete, unsigned and ambiguous native files are never promoted', options, async t => { + const fx = await fixture(t) + const { turns, a, aRoot, dataDir } = fx + const native = createChatStore({ dataDir }) + const legacy = native.ensureSession('legacy') + legacy.messages.push({ role: 'user', content: 'Desktop history' }) + native.saveStrict(legacy.id) + const focused = native.ensureSession('legacy-focused', { focusRoot: aRoot }) + native.saveStrict(focused.id) + const complex = native.ensureSession('legacy-complex') + complex.members = [{ sessionId: 'member' }] + native.saveStrict(complex.id) + const partial = native.ensureSession('legacy-incomplete') + native.saveStrict(partial.id) + const partialDisk = { ...await fx.disk(partial.id), compacted: { file: `${partial.id}.compacted-missing.jsonl`, count: 1 } } + await fs.writeFile(fx.native(partial.id), JSON.stringify(partialDisk)) + const signed = turns.create({ workspaceId: a }).id + const signedDisk = await fx.disk(signed) + const unsigned = randomUUID() + await fs.writeFile(fx.native(unsigned), JSON.stringify({ ...withoutBinding(signedDisk), id: unsigned, focusRoot: aRoot }), { mode: 0o600 }) + const copied = randomUUID() + await fs.writeFile(fx.native(copied), JSON.stringify({ ...signedDisk, id: copied }), { mode: 0o600 }) + const ambiguous = randomUUID() + await fs.writeFile(fx.native(ambiguous), `{\"id\":\"${ambiguous}\",\"focusRoot\":\"/wrong\",${JSON.stringify({ ...withoutBinding(signedDisk), id: ambiguous, focusRoot: null }).slice(1)}`, { mode: 0o600 }) + const seq = fx.seq + for (const [sid, problem] of [[legacy.id, error(409, 'read_only_session')], ...[focused.id, complex.id, partial.id, unsigned, copied].map(id => [id, error(409, 'unsupported_history')]), [ambiguous, storageError]]) { + const original = await fs.readFile(fx.native(sid), 'utf8') + assert.throws(() => turns.getWorkspace(sid), problem) + assert.throws(() => turns.setWorkspace(sid, { workspaceId: a, revision: 'a'.repeat(64) }), problem) + assert.equal(await fs.readFile(fx.native(sid), 'utf8'), original) + } + assert.equal(fx.seq, seq) + // A warm compatibility WeakMap entry must not allow a stale or changed native path. + const stamp = turns.getWorkspace(signed).revision + assert.equal(turns.list().find(row => row.id === signed).writable, true) + await fs.writeFile(fx.native(signed), JSON.stringify({ ...signedDisk, focusRoot: fx.bRoot })) + assert.throws(() => turns.setWorkspace(signed, { workspaceId: null, revision: stamp }), conflict) + assert.equal(turns.snapshot(signed).state.writable, false) + await assert.rejects(turns.send(request(signed, 'not-admitted')), error(409, 'unsupported_history')) + assert.throws(() => turns.getWorkspace(signed), storageError) + assert.equal(fx.seq, seq) + assert.deepEqual([fx.calls.length, fx.reads.length], [0, 0]) + await fx.restart() + assert.equal(fx.turns.snapshot(signed).state.compatibility, 'unsupported') + assert.throws(() => fx.turns.getWorkspace(signed), error(409, 'unsupported_history')) +}) + +test('strict writer and pin confirmation failures quarantine without announcing a binding', options, async t => { + const fx = await fixture(t) + const { turns, a, b } = fx + const sid = turns.create().id + const before = turns.getWorkspace(sid) + const seq = fx.seq + const pending = join(fx.chats, '_index.pending') + await fs.mkdir(pending) + assert.throws(() => turns.setWorkspace(sid, { workspaceId: a, revision: before.revision }), storageError) + assert.throws(() => turns.getWorkspace(sid), storageError) + assert.throws(() => turns.setWorkspace(sid, { workspaceId: b, revision: before.revision }), storageError) + assert.equal(turns.hasBrowserSession(sid), false) + const failed = randomUUID() + assert.throws(() => turns.create({ sessionId: failed, workspaceId: a }), storageError) + await assert.rejects(fs.stat(fx.native(failed)), { code: 'ENOENT' }) + assert.equal(turns.list().some(row => row.id === failed), false) + assert.equal(fx.seq, seq) + assert.equal((await fx.disk(sid)).focusRoot, null) + assert.equal(await fs.realpath(pending), pending) + await fs.rmdir(pending) + await fx.restart() + const halfway = fx.seq + fx.afterGrant(() => { throw new Error('fixture projects pin invalidated after callback') }) + assert.throws(() => fx.turns.setWorkspace(sid, { workspaceId: a, revision: before.revision }), storageError) + assert.throws(() => fx.turns.getWorkspace(sid), storageError) + assert.equal(fx.turns.hasBrowserSession(sid), false) + assert.equal(fx.turns.snapshot(sid).state.workspaceRevision, undefined) + assert.equal(fx.seq, halfway) + assert.deepEqual([fx.calls.length, fx.reads.length], [0, 0]) +}) \ No newline at end of file From bc9f742985cc94b93f326fc531f5fd578e97ab0f Mon Sep 17 00:00:00 2001 From: Facetomyself <[GIT_EMAIL]> Date: Thu, 26 Nov 2026 20:27:09 +0800 Subject: [PATCH 2/4] =?UTF-8?q?feat(headless):=20=E6=8C=89=E6=89=80?= =?UTF-8?q?=E6=9C=89=E8=80=85=E4=BC=9A=E8=AF=9D=E5=85=B3=E8=81=94=E6=8E=88?= =?UTF-8?q?=E6=9D=83=E9=A1=B9=E7=9B=AE=20/=20bind=20approved=20projects=20?= =?UTF-8?q?to=20owner=20conversations?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/headless/src/business/handlers.mjs | 4 +- apps/headless/src/business/library-routes.mjs | 12 +- apps/headless/src/business/personas.mjs | 33 ++++-- .../src/business/workspace-binding.mjs | 25 +++++ .../src/business/workspace-catalog.mjs | 4 +- apps/headless/src/chat/routes.mjs | 13 ++- apps/headless/src/http/chat-workspace.mjs | 52 +++++++++ apps/headless/src/http/session-routes.mjs | 3 +- apps/headless/test/personas.test.mjs | 20 ++++ .../test/session-workspace-http.test.mjs | 106 ++++++++++++++++++ 10 files changed, 250 insertions(+), 22 deletions(-) create mode 100644 apps/headless/src/business/workspace-binding.mjs create mode 100644 apps/headless/src/http/chat-workspace.mjs create mode 100644 apps/headless/test/session-workspace-http.test.mjs diff --git a/apps/headless/src/business/handlers.mjs b/apps/headless/src/business/handlers.mjs index f9360121..9e243e75 100644 --- a/apps/headless/src/business/handlers.mjs +++ b/apps/headless/src/business/handlers.mjs @@ -55,7 +55,8 @@ export async function openBusiness({ dataDir, vault, auth, version, allowedOrigi library = await openLibrary({ dataDir, workspaceRoot, workspaceWritable, privateRoots, gitProjects }) if (library.gitGrants.enabled) git = openGitService({ grants: library.gitGrants, auth }) uploads = await openUploadStore({ dataDir }) - turns = createTextTurns({ dataDir, settings, journal, ...opts, resolveRole: library.resolveRole, uploads, deliveries: true }) + turns = createTextTurns({ dataDir, settings, journal, ...opts, resolveRole: library.resolveRole, + withWorkspace: library.withWorkspace, uploads, deliveries: true }) // The Unix client is loaded only when the operator mounted a private worker socket. if (browserRunDir) { const { createManualBrowser } = await import('../browser/manual-browser.mjs') @@ -76,6 +77,7 @@ export async function openBusiness({ dataDir, vault, auth, version, allowedOrigi beginShutdown, capabilities: Object.freeze({ textChat: true, library: true, workspaceFiles: library.workspaceFilesEnabled, attachments: true, browserPanel: !!browser, gitInspect: !!git, deliveries: typeof turns.deliverySnapshot === 'function', + sessionWorkspaces: typeof turns.getWorkspace === 'function' && typeof turns.setWorkspace === 'function', sessionPreferences: typeof turns.patchPreferences === 'function' && typeof journal.watchSessions === 'function' }), createRealtime: ({ auth, policy }) => createChatWebSocket({ turns, journal, auth, policy }), getConfig: () => settings.getPublicConfig(), diff --git a/apps/headless/src/business/library-routes.mjs b/apps/headless/src/business/library-routes.mjs index f305c43c..8633df15 100644 --- a/apps/headless/src/business/library-routes.mjs +++ b/apps/headless/src/business/library-routes.mjs @@ -5,6 +5,7 @@ import { openProfile } from './profile.mjs' import { openPersonas } from './personas.mjs' import { checkRoleBindings } from './role-bindings.mjs' import { openWorkspaceCatalog } from './workspace-catalog.mjs' +import { workspaceBindingResolver } from './workspace-binding.mjs' import { gitGrants, gitProjectNames } from '../git/access.mjs' import { openWorkspaceFiles } from '../files/workspace-files.mjs' import { workspaceFileRoutes } from '../files/workspace-routes.mjs' @@ -90,19 +91,18 @@ export async function openLibrary({ dataDir, workspaceRoot, workspaceWritable = } return { ok: true, ...snapshotOf(memory, scope) } } - async function enabledRole(id) { - const role = await personas.get(id) + async function enabledRole(id, inheritWorkspace = false) { + const role = await personas.getForChat(id, inheritWorkspace) if (!role?.enabled) throw new HttpError(409, 'role_unavailable') - // Only these data fields are part of a conversation binding. A role's folder selection - // or an instruction in its Markdown never authorizes execution or external file reads. - return { id: role.id, name: role.name, prompt: role.prompt, model: role.model, enabled: true } + return role } return { workspaceFilesEnabled: Boolean(fileCommands), gitGrants: approvedGit, deliveryFiles: workspaceRoot ? openDeliveryFiles({ catalog }) : undefined, resolveRole: id => serial(() => enabledRole(id)), - withRoleForChat: (id, action) => serial(async () => action(await enabledRole(id))), + withWorkspace: workspaceBindingResolver(catalog), + withRoleForChat: (id, action) => serial(async () => action(await enabledRole(id, true))), async handle(req, res, { auth, policy }) { const path = (req.url ?? '').split('?', 1)[0] if (path.startsWith('/api/v1/workspaces/') && fileCommands) return fileCommands(req, res, { auth, policy }) diff --git a/apps/headless/src/business/personas.mjs b/apps/headless/src/business/personas.mjs index 03309790..c35b9398 100644 --- a/apps/headless/src/business/personas.mjs +++ b/apps/headless/src/business/personas.mjs @@ -385,6 +385,18 @@ export async function openPersonas(options) { await index.verifyUnchanged() await verifyFile(index.directory, nameFor(binding.id), binding.info, MAX_PERSONA_FILE_BYTES) } + async function projectOne(id, project) { + requireId(id) + return access(async index => { + if (!index.ids.includes(id)) return null + const binding = await readRole(index.directory, id) + if (!binding) fail('CONFLICT') + const result = await project(binding, index.config) + await index.verifyUnchanged() + await verifyFile(index.directory, nameFor(id), binding.info, MAX_PERSONA_FILE_BYTES) + return result + }) + } return Object.freeze({ list: () => access(index => publicRoster(workspaceCatalog, index)), async getAvatarImage(id) { @@ -405,16 +417,17 @@ export async function openPersonas(options) { return { ...result, revision: roleRevision(binding, index.config) } })) }, - async get(id) { - requireId(id) - return access(async index => { - if (!index.ids.includes(id)) return null - const binding = await readRole(index.directory, id) - if (!binding) fail('CONFLICT') - const result = await publicRole(workspaceCatalog, binding, index.config) - await index.verifyUnchanged() - await verifyFile(index.directory, nameFor(id), binding.info, MAX_PERSONA_FILE_BYTES) - return result + get: id => projectOne(id, (binding, config) => publicRole(workspaceCatalog, binding, config)), + // Runtime model requests only need identity and presentation. Never resolve a directory + // (or its contents) when reading a role for a turn. Only creation may project a saved, + // ID-backed default; a legacy free-form path alone must not become a durable new grant. + getForChat(id, inheritWorkspace = false) { + return projectOne(id, async (binding, config) => { + const { name, model, prompt, workspaceId } = binding.parsed + const enabled = config.enabled[id] === true + const approved = enabled && inheritWorkspace && matches(catalogId, workspaceId) + ? await workspaceForProjection(workspaceCatalog, binding.parsed, scopedCatalog(workspaceCatalog)) : null + return { id, name, model, prompt, enabled, ...(approved ? {workspaceId: approved.id} : {}) } }) }, async upsert(input) { diff --git a/apps/headless/src/business/workspace-binding.mjs b/apps/headless/src/business/workspace-binding.mjs new file mode 100644 index 00000000..e5532160 --- /dev/null +++ b/apps/headless/src/business/workspace-binding.mjs @@ -0,0 +1,25 @@ +import { HttpError } from '../http/policy.mjs' + +const project = /^w_[a-f0-9]{32}$/u + +/** Resolve an ID against the currently mounted catalog. The callback is synchronous and + * server-internal: it receives the native root only for the desktop file format. Nothing + * here grants a conversation or its model directory, Git, shell or note access. */ +export function workspaceBindingResolver(catalog) { + return function withWorkspace(id, action) { + if (typeof id !== 'string' || id.length !== 34 || !project.test(id) || typeof action !== 'function') return undefined + let lease + try { lease = catalog.pinProject(id) } + catch (error) { if (error?.code === 'ERR_WORKSPACE_UNAVAILABLE') return undefined; throw new HttpError(503, 'workspace_catalog_unavailable') } + try { + lease.assertCurrent() + const result = action(Object.freeze({ id: lease.id, name: lease.name, root: lease.root })) + if (result && typeof result.then === 'function') throw new TypeError('Workspace grant operation must be synchronous') + lease.assertCurrent() + return result + } catch (error) { + if (error?.code === 'ERR_WORKSPACE_UNAVAILABLE') throw new HttpError(409,'workspace_changed') + throw error + } finally { lease.close() } + } +} diff --git a/apps/headless/src/business/workspace-catalog.mjs b/apps/headless/src/business/workspace-catalog.mjs index ddc49213..91c44a6a 100644 --- a/apps/headless/src/business/workspace-catalog.mjs +++ b/apps/headless/src/business/workspace-catalog.mjs @@ -138,7 +138,9 @@ export function openWorkspaceCatalog({ root, privateRoots = [] }) { pinned = openChild(record.name) if (!sameInode(record.info, pinned.info)) throw unavailable() assertCurrent() - return Object.freeze({ fd: pinned.sub, mount: rootMount, assertCurrent, close() { if (!released) { released = true; close(pinned.sub) } } }) + // root/name are private operator facts, not part of the enumerable project list or an HTTP DTO. + return Object.freeze({ fd: pinned.sub, mount: rootMount, id: record.id, name: record.name, root: record.path, + assertCurrent, close() { if (!released) { released = true; close(pinned.sub) } } }) } catch { close(pinned?.sub) throw unavailable() diff --git a/apps/headless/src/chat/routes.mjs b/apps/headless/src/chat/routes.mjs index 908a59f6..a8a61561 100644 --- a/apps/headless/src/chat/routes.mjs +++ b/apps/headless/src/chat/routes.mjs @@ -1,18 +1,20 @@ import { HttpError, json, readJson } from '../http/policy.mjs' import { sessionPreferenceRoute } from './session-routes.mjs' +import { makeChatWorkspaceRoute } from '../http/chat-workspace.mjs' import { isChatRoleId } from './text-turns.mjs' const collection = '/api/v1/chats' -const resource = /^\/api\/v1\/chats\/([A-Za-z0-9_-]{1,128})(?:\/(turns|stop|preferences))?$/ +const resource = /^\/api\/v1\/chats\/([A-Za-z0-9_-]{1,128})(?:\/(turns|stop|preferences|workspace))?$/ const roleServiceError = () => new HttpError(503, 'chat_role_unavailable') const roleUnavailable = () => new HttpError(409, 'role_unavailable') async function createBoundSession(turns, withRoleForChat, body, authenticate) { - if (Object.keys(body).some(key => key !== 'sessionId' && key !== 'personaId')) throw new HttpError(400, 'invalid_create') + if (Object.keys(body).some(key => !['sessionId', 'personaId', 'workspaceId'].includes(key))) throw new HttpError(400, 'invalid_create') const { personaId } = body if (!isChatRoleId(personaId)) throw new HttpError(400, 'invalid_persona_id') if (!withRoleForChat) throw roleServiceError() - const options = Object.hasOwn(body, 'sessionId') ? { sessionId: body.sessionId } : {} + const options = { ...(Object.hasOwn(body, 'sessionId') ? { sessionId: body.sessionId } : {}), + ...(Object.hasOwn(body, 'workspaceId') ? { workspaceId: body.workspaceId } : {}) } let session, finished = false try { const result = await withRoleForChat(personaId, role => { @@ -37,10 +39,14 @@ async function createBoundSession(turns, withRoleForChat, body, authenticate) { * this entry nor a caller-supplied payload can select a model URL, send a system prompt, or run tools. */ export function chatRoutes(turns, { withRoleForChat } = {}) { if (withRoleForChat !== undefined && typeof withRoleForChat !== 'function') throw new TypeError('withRoleForChat must be a function') + const focus = makeChatWorkspaceRoute(turns) return async (req, res, { auth, policy }) => { const path = (req.url ?? '').split('?', 1)[0] const match = resource.exec(path) if (path !== collection && !match) return false + if (match?.[2] === 'workspace') { + await focus(req, res, { auth, policy }, path, match[1]); return true + } if (match?.[2] === 'preferences') { await sessionPreferenceRoute(req, res, { auth, policy }, turns, path, match[1]) return true @@ -57,6 +63,7 @@ export function chatRoutes(turns, { withRoleForChat } = {}) { if (!match) { if (write) { const body = await readJson(req, 512) + authenticateWrite() // Reading a slow request body must not extend the login. const session = Object.hasOwn(body, 'personaId') ? await createBoundSession(turns, withRoleForChat, body, authenticateWrite) : turns.create(body) diff --git a/apps/headless/src/http/chat-workspace.mjs b/apps/headless/src/http/chat-workspace.mjs new file mode 100644 index 00000000..65f81763 --- /dev/null +++ b/apps/headless/src/http/chat-workspace.mjs @@ -0,0 +1,52 @@ +import { HttpError, json, readJson } from './policy.mjs' + +const tag = /^[a-f0-9]{64}$/u +const id = /^w_[a-f0-9]{32}$/u +const matches = (value, pattern) => typeof value === 'string' && pattern.exec(value)?.[0] === value + +function verifiedResponse(reply) { + const unavailable = () => { throw new HttpError(503, 'chat_storage_unconfirmed') } + if (!reply || !matches(reply.revision, tag)) unavailable() + if (reply.workspace === null) return { workspace: null, revision: reply.revision } + const { id: workspaceId, name, source, state } = reply.workspace ?? {} + if (!matches(workspaceId, id) || !['manual', 'role'].includes(source) || !['available', 'unavailable'].includes(state) || + (state === 'unavailable' ? name !== null : typeof name !== 'string' || !name || /[\x00-\x1f\x7f/\\]/u.test(name))) unavailable() + // Whitelist is intentional: native focusRoot and historical paths never leave the volume. + return { workspace: { id: workspaceId, name, state, source }, revision: reply.revision } +} + +/** A conversation preference, not a remote filesystem operation. GET never auto-binds. + * Choosing a human workspace does not read files, notes or Git and does not start a turn. */ +export function makeChatWorkspaceRoute(turns) { + let pending = 0 + return async (req, res, { auth, policy }, path, sid) => { + const write = req.method === 'PATCH' + let admitted = false + try { + policy.check(req, write) + if (req.url !== path) throw new HttpError(400, 'unexpected_query') + if (!write && req.method !== 'GET') { json(res,405,{error:'method'},{allow:'GET, PATCH'}); return } + const cookie = policy.cookie(req) + const authorize = () => write ? auth.authenticate(cookie, req.headers['x-deva-csrf']) : auth.authenticate(cookie) + authorize() + if (typeof turns.getWorkspace !== 'function' || typeof turns.setWorkspace !== 'function') throw new HttpError(503, 'workspace_binding_unavailable') + if (pending >= 8) throw new HttpError(429, 'workspace_busy') + pending++; admitted = true + let result + if (write) { + const body = await readJson(req, 1024) + if (Object.keys(body).length !== 2 || !Object.hasOwn(body, 'workspaceId') || !Object.hasOwn(body, 'revision')) throw new HttpError(400, 'invalid_workspace') + if (body.workspaceId !== null && !matches(body.workspaceId, id)) throw new HttpError(400, 'invalid_workspace_id') + if (!matches(body.revision, tag)) throw new HttpError(400, 'invalid_workspace_revision') + authorize() + result = turns.setWorkspace(sid, body, authorize) + } else result = turns.getWorkspace(sid) + const value = verifiedResponse(await result) + authorize() + if (!res.destroyed) json(res, 200, value) + } catch (error) { + const status = error instanceof HttpError ? error.status : error?.code === 'AUTH_FAILED' ? 401 : 500 + if (!res.headersSent && !res.destroyed) json(res, status, { error: error instanceof HttpError ? error.code : status === 401 ? 'auth' : 'internal' }, write ? { connection: 'close' } : {}) + } finally { if (admitted) pending-- } + } +} diff --git a/apps/headless/src/http/session-routes.mjs b/apps/headless/src/http/session-routes.mjs index 121438d3..be385a1d 100644 --- a/apps/headless/src/http/session-routes.mjs +++ b/apps/headless/src/http/session-routes.mjs @@ -50,7 +50,8 @@ export function sessionRoutes({ auth, policy, version, getConfig, capabilities } capabilities: { textChat: capabilities?.textChat === true, library: capabilities?.library === true, workspaceFiles: capabilities?.workspaceFiles === true, attachments: capabilities?.attachments === true, browserPanel: capabilities?.browserPanel === true, sessionPreferences: capabilities?.sessionPreferences === true, - deliveries: capabilities?.deliveries === true, gitInspect: capabilities?.gitInspect === true } }) + deliveries: capabilities?.deliveries === true, gitInspect: capabilities?.gitInspect === true, + sessionWorkspaces: capabilities?.sessionWorkspaces === true } }) return true } if (path === '/api/v1/auth/logout') { diff --git a/apps/headless/test/personas.test.mjs b/apps/headless/test/personas.test.mjs index eb6c80e4..991fabea 100644 --- a/apps/headless/test/personas.test.mjs +++ b/apps/headless/test/personas.test.mjs @@ -112,6 +112,26 @@ await test('workspace projection is catalog-only, stores desktop path, and track assert.doesNotMatch(await readFile(rolePath(dataDir, role.id), 'utf8'), /^workspace(?:Id)?:/mu) }) +await test('role lookup for a model turn never enumerates or resolves workspace grants', async t => { + const base = await sandbox(t), dataDir = join(base, 'data'), root = join(base,'registered') + const project = join(root, 'Review'); await mkdir(project, { recursive: true }) + const real = openWorkspaceCatalog({ root, privateRoots: [dataDir] }); t.after(() => real.close()) + const calls = [] + const workspaceCatalog = { list() { calls.push('list'); return real.list() }, resolveRoot(id) { calls.push('root'); return real.resolveRoot(id) } } + const api = await openPersonas({ dataDir, workspaceCatalog }) + const [{id: workspaceId}] = real.list() + const role = await api.upsert({ name:'Copy editor', workspaceId, prompt:'Tighten prose.', model:'fixture:editor', enabled:true }) + calls.length = 0 + const turn = await api.getForChat(role.id) + assert.deepEqual(turn, {id:role.id, name:role.name, prompt:role.prompt, model:'fixture:editor', enabled:true}) + assert.deepEqual(calls, []) + assert.deepEqual(await api.getForChat(role.id, true), {...turn,workspaceId}); assert.ok(calls.length > 0) + // A legacy path by itself is not a durable role grant, even when its spelling matches a currently mounted project. + const old = await api.upsert({name:'Legacy copy',enabled:true}) + await writeFile(rolePath(dataDir, old.id), serializePersonaMarkdown({name:old.name,workspace:project,prompt:'Legacy text.'})) + calls.length=0; assert.equal(Object.hasOwn(await api.getForChat(old.id, true),'workspaceId'),false); assert.deepEqual(calls,[]) +}) + await test('two personas instances and settings share an inode queue and reject stale edits', async t => { const dataDir = await sandbox(t) await writeJson(configPath(dataDir), { personas: { seeded: { general: true }, seededPrompt: { general: 'baseline' }, diff --git a/apps/headless/test/session-workspace-http.test.mjs b/apps/headless/test/session-workspace-http.test.mjs new file mode 100644 index 00000000..a1ea5964 --- /dev/null +++ b/apps/headless/test/session-workspace-http.test.mjs @@ -0,0 +1,106 @@ +import assert from 'node:assert/strict' +import { randomBytes, randomUUID } from 'node:crypto' +import { lstat, mkdir, mkdtemp, readFile, realpath, rename, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import test from 'node:test' +import { requestControl } from '../src/control/socket.mjs' +import { startWorkbench } from '../src/server.mjs' +import { initializeMasterKey } from '../src/storage/vault.mjs' + +const options = { timeout: 45_000 } +const crc = /^[a-f0-9]{64}$/u +const rel = sid => `chats/${sid}/workspace` + +async function fixture(t) { + const parent = await realpath(tmpdir()), root = await mkdtemp(join(parent, 'deva-scope-http-')) + const identity = await lstat(root), h = join(root,'data'), mount = join(root,'projects'), runDir = join(root,'run') + assert.equal(dirname(root),parent) + const keyFile = join(root,'key-file'), opts = {dataDir:h, keyFile, runDir, webDir:join(root,'no-assets'),port:0} + let app + t.after(async () => { + try { await app?.close() } finally { + const st=await lstat(root);assert.equal(st.dev,identity.dev);assert.equal(st.ino,identity.ino);assert.equal(await realpath(root),root) + await rm(root,{recursive:true,force:true}) + } + }) + await mkdir(join(mount,'Alpha'),{recursive:true});await mkdir(join(mount,'Beta')) + await writeFile(join(mount,'Alpha','notes.txt'),'private Alpha fixture text\n',{mode:0o600});await initializeMasterKey(keyFile) + async function boot(mounted=true) { app=await startWorkbench({...opts,businessOptions:mounted?{workspaceRoot:mount}:{}}) } + await boot() + const password=randomBytes(24).toString('base64url') + function call(path,who,method='GET',body,headers={}) { + return fetch(`${app.origin}/api/v1/${path}`,{method,headers:{...(who?{cookie:who.cookie}:{}), + ...(body===undefined?{}:{origin:app.origin,'content-type':'application/json',...(who?{'x-deva-csrf':who.csrf}:{})}),...headers}, + ...(body===undefined?{}:{body:JSON.stringify(body)}),signal:AbortSignal.timeout(6500)}) + } + async function accept(req) { const r=await req;assert.equal(r.status,200);return {cookie:r.headers.get('set-cookie').split(';')[0],csrf:(await r.json()).csrf} } + const {credential}=await requestControl({runDir,op:'claim'}), owner=await accept(call('auth/claim',null,'POST',{credential,password})) + const login=()=>accept(call('auth/login',null,'POST',{password})), other=await login() + async function get(path,who=owner,method='GET',body,status=200,extra) { + const r=await call(path,who,method,body,extra),json=await r.json();assert.equal(r.status,status,`${method} ${path}: ${json.error??'unexpected reply'}`);return json + } + const projects=(await get('workspaces')).workspaces + return {root,h,mount,owner,other,get,call,login,alpha:projects.find(x=>x.name==='Alpha').id,beta:projects.find(x=>x.name==='Beta').id, + open:async(body,who=owner)=>(await get('chats',who,'POST',body)).session.id, + disk:async sid=>JSON.parse(await readFile(join(h,'data','chats',`${sid}.json`),'utf8')), + restart:async(mounted=true)=>{await app.close();await boot(mounted)} } +} + +test('owner APIs keep project browsing distinct from a conditional, native session binding',options,async t=>{ + const f=await fixture(t), a=f.owner, b=f.other + assert.equal((await f.get('bootstrap')).capabilities.sessionWorkspaces,true) + const sid=await f.open({}), second=await f.open({}) + const initial=await f.get(rel(sid));assert.equal(initial.workspace,null);assert.match(initial.revision,crc) + const unrelated=await f.get(rel(second));assert.notEqual(unrelated.revision,initial.revision) + // Reading a human-authorized project never binds it to the current conversation. + const listing=await f.get(`workspaces/${f.alpha}/list`,a,'POST',{path:''});assert.equal(listing.entries[0].name,'notes.txt') + assert.deepEqual(await f.get(rel(sid)),initial) + const set={workspaceId:f.alpha,revision:initial.revision} + assert.equal((await f.call(rel(sid),null)).status,401) + assert.equal((await f.call(rel(sid),a,'PATCH',set,{'x-deva-csrf':'wrong'})).status,401) + assert.equal((await f.call(rel(sid),a,'PATCH',set,{origin:'https://elsewhere.invalid'})).status,403) + assert.equal((await f.call(rel(sid)+'?path=foo',a)).status,400) + assert.equal((await f.call(rel(sid),a,'PATCH',{...set,root:f.mount})).status,400) + assert.equal((await f.call(rel(sid),a,'PATCH',{...set,workspaceId:f.mount})).status,400) + assert.equal((await f.call(rel(sid),a,'PATCH',{...set,workspaceId:'w_'+'0'.repeat(32)})).status,404) + assert.deepEqual(await f.get(rel(sid)),initial) + const bound=await f.get(rel(sid),a,'PATCH',set) + assert.deepEqual(bound.workspace,{id:f.alpha,name:'Alpha',state:'available',source:'manual'}) + assert.notEqual(bound.revision,initial.revision);assert.deepEqual(await f.get(rel(sid),b),bound) + assert.equal((await f.disk(sid)).focusRoot,join(f.mount,'Alpha')) + const state=(await f.get('chats/'+sid)).state + assert.equal(state.workspaceRevision,bound.revision) + const publicState=JSON.stringify([state,await f.get('chats'),bound]);assert.equal(publicState.includes(f.mount),false) + assert.equal(publicState.includes('private Alpha fixture text'),false);assert.deepEqual(state.messages,[]) + assert.deepEqual(await f.get(rel(sid),b,'PATCH',{workspaceId:f.beta,revision:initial.revision},409),{error:'workspace_conflict'}) + assert.deepEqual(await f.get(rel(sid),b,'PATCH',{workspaceId:f.alpha,revision:bound.revision}),bound) + assert.deepEqual(await f.get(rel(second)),unrelated) + await f.restart(false);assert.equal((await f.call(rel(sid),a)).status,401);const recovered=await f.login() + const unmounted=await f.get(rel(sid),recovered);assert.equal(unmounted.revision,bound.revision) + assert.deepEqual(unmounted.workspace,{id:f.alpha,name:null,state:'unavailable',source:'manual'}) + const cleared=await f.get(rel(sid),recovered,'PATCH',{workspaceId:null,revision:unmounted.revision});assert.equal(cleared.workspace,null) + await f.restart();const again=await f.login();assert.deepEqual(await f.get(rel(sid),again),cleared) +}) + +test('role defaults apply once while manual overrides, replay and replaced projects keep their identity',options,async t=>{ + const f=await fixture(t), owner=f.owner + const {role}=await f.get('personas',owner,'POST',{name:'Editorial role',prompt:'Use a clear tone.',enabled:true,workspaceId:f.alpha}) + const first=randomUUID(), create={sessionId:first,personaId:role.id} + assert.equal(await f.open(create),first) + const bound=await f.get(rel(first));assert.deepEqual(bound.workspace,{id:f.alpha,name:'Alpha',state:'available',source:'role'}) + await f.get(`personas/${role.id}`,owner,'PATCH',{revision:role.revision,name:role.name,prompt:role.prompt,enabled:true,workspaceId:f.beta}) + assert.equal(await f.open(create),first);assert.deepEqual(await f.get(rel(first)),bound) + const inherited=await f.open({personaId:role.id}), empty=await f.open({personaId:role.id,workspaceId:null}), explicit=await f.open({personaId:role.id,workspaceId:f.alpha}) + assert.deepEqual((await f.get(rel(inherited))).workspace,{id:f.beta,name:'Beta',state:'available',source:'role'}) + assert.equal((await f.get(rel(empty))).workspace,null);assert.equal((await f.get(rel(explicit))).workspace.source,'manual') + assert.equal((await f.call('chats',owner,'POST',{...create,workspaceId:f.beta})).status,409) + const before=await f.disk(first) + await rename(join(f.mount,'Alpha'),join(f.root,'retired'));await mkdir(join(f.mount,'Alpha')) + const nextId=(await f.get('workspaces')).workspaces.find(x=>x.name==='Alpha').id;assert.notEqual(nextId,f.alpha) + const lost=await f.get(rel(first));assert.equal(lost.revision,bound.revision);assert.deepEqual(lost.workspace,{id:f.alpha,name:null,state:'unavailable',source:'role'}) + assert.deepEqual(await f.disk(first),before) + const changed=await f.get(rel(first),owner,'PATCH',{revision:lost.revision,workspaceId:nextId});assert.equal(changed.workspace.id,nextId);assert.equal(changed.workspace.source,'manual') + assert.equal((await f.get(rel(inherited))).workspace.id,f.beta) + assert.equal(await f.open(create),first);assert.deepEqual(await f.get(rel(first)),changed) +}) From 695aa1a4aeb16f390390223cc272cfb60e4285e9 Mon Sep 17 00:00:00 2001 From: Facetomyself <[GIT_EMAIL]> Date: Thu, 26 Nov 2026 20:27:09 +0800 Subject: [PATCH 3/4] =?UTF-8?q?feat(workbench):=20=E5=9C=A8=E5=AF=B9?= =?UTF-8?q?=E8=AF=9D=E9=87=8C=E5=85=B3=E8=81=94=E9=A1=B9=E7=9B=AE=E5=92=8C?= =?UTF-8?q?=E6=89=93=E5=BC=80=E9=A1=B9=E7=9B=AE=E8=AE=B0=E5=BF=86=20/=20at?= =?UTF-8?q?tach=20projects=20and=20open=20scoped=20notes=20from=20conversa?= =?UTF-8?q?tions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/desktop/src/workbench/chat-transport.ts | 4 + apps/desktop/src/workbench/library-memory.tsx | 13 +- .../src/workbench/library-transport.ts | 21 +- .../workbench/session-workspace-transport.ts | 70 ++++ .../src/workbench/session-workspace-ui.tsx | 109 ++++++ .../src/workbench/session-workspace.css | 17 + .../src/workbench/session-workspace.ts | 206 +++++++++++ apps/desktop/src/workbench/text-workbench.tsx | 41 ++- apps/desktop/src/workbench/transport.ts | 10 +- .../src/workbench/use-text-workbench.ts | 9 +- apps/desktop/src/workbench/workspace-files.ts | 57 ++- .../src/workbench/workspace-transport.ts | 8 +- .../workbench/session-workspace-ui.test.mjs | 338 ++++++++++++++++++ 13 files changed, 869 insertions(+), 34 deletions(-) create mode 100644 apps/desktop/src/workbench/session-workspace-transport.ts create mode 100644 apps/desktop/src/workbench/session-workspace-ui.tsx create mode 100644 apps/desktop/src/workbench/session-workspace.css create mode 100644 apps/desktop/src/workbench/session-workspace.ts create mode 100644 scripts/workbench/session-workspace-ui.test.mjs 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 ?