From 568ea3f358ef3405617975706df40d98ff2d00e3 Mon Sep 17 00:00:00 2001 From: Facetomyself <[GIT_EMAIL]> Date: Thu, 26 Nov 2026 15:55:10 +0800 Subject: [PATCH 1/6] =?UTF-8?q?feat(events):=20=E5=90=8C=E6=AD=A5=E5=B7=B2?= =?UTF-8?q?=E7=A1=AE=E8=AE=A4=E7=9A=84=E4=BC=9A=E8=AF=9D=E5=88=97=E8=A1=A8?= =?UTF-8?q?=E5=8F=98=E6=9B=B4=20/=20broadcast=20committed=20session=20list?= =?UTF-8?q?=20changes=20without=20transcript=20data?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/headless/src/events/index.mjs | 12 +- apps/headless/src/events/journal.mjs | 39 +- .../src/events/session-list-stream.mjs | 23 ++ apps/headless/src/events/websocket.mjs | 86 +++-- .../test/session-list-stream.test.mjs | 358 ++++++++++++++++++ 5 files changed, 473 insertions(+), 45 deletions(-) create mode 100644 apps/headless/src/events/session-list-stream.mjs create mode 100644 apps/headless/test/session-list-stream.test.mjs diff --git a/apps/headless/src/events/index.mjs b/apps/headless/src/events/index.mjs index 24671305..29c2cce4 100644 --- a/apps/headless/src/events/index.mjs +++ b/apps/headless/src/events/index.mjs @@ -1,5 +1,8 @@ +import { projectChatEvent } from './chat-event.mjs' import { createEventJournal } from './journal.mjs' +const desktopListEvents = new Set(['turn_start', 'done', 'member_report']) + export { chatScope, createEventJournal, SESSIONS_SCOPE } from './journal.mjs' /** @@ -32,7 +35,14 @@ export function installDesktopEventBridge(source, limits) { try { register(source.onChatEvent, (payload) => { if (!installed) return - try { journal.publishChat(payload) } catch { /* protect the producer without logging payloads */ } + try { + const event = projectChatEvent(payload) + if (!event) return + journal.publishChat(event) + // Preserve the desktop adapter's legacy list hints. The headless journal + // itself advances the list only when a business producer publishes it. + if (desktopListEvents.has(event.event.type)) journal.publishSessionsChanged() + } catch { /* protect the producer without logging payloads */ } }) register(source.onSessionsChanged, () => { if (!installed) return diff --git a/apps/headless/src/events/journal.mjs b/apps/headless/src/events/journal.mjs index e5eb1a98..758a26a8 100644 --- a/apps/headless/src/events/journal.mjs +++ b/apps/headless/src/events/journal.mjs @@ -52,10 +52,10 @@ function closeHandle(control) { return () => { control.close?.() } } -function startSubscription({ bus, stream, after, onEvent, onClose, release, deliveryTimeoutMs }) { +function startSubscription({ bus, stream, after, onEvent, onClose, release, deliveryTimeoutMs, latestEvent }) { let delivered = after; let scheduled; let pending; let closed = false const control = { close: () => finish() } - const terminal = () => stream.retired ?? (delivered < stream.floor ? 'history_lost' : null) + const terminal = () => stream.retired ?? (!latestEvent && delivered < stream.floor ? 'history_lost' : null) function finish(reason) { if (closed) return @@ -99,11 +99,11 @@ function startSubscription({ bus, stream, after, onEvent, onClose, release, deli const reason = terminal() if (reason) return finish(reason) if (pending || delivered === stream.seq) return - const next = stream.entries.get(delivered + 1) - if (!next) return finish('history_lost') - delivered = next.seq + const next = latestEvent ? null : stream.entries.get(delivered + 1) + if (!latestEvent && !next) return finish('history_lost') + delivered = latestEvent ? stream.seq : next.seq try { - const result = onEvent(JSON.parse(next.json)) + const result = onEvent(latestEvent ? latestEvent() : JSON.parse(next.json)) if (result === false) return finish('backpressure') if (typeof result?.then === 'function') { if (closed) void Promise.resolve(result).catch(ignore) @@ -243,32 +243,45 @@ export function createEventJournal({ if (reason) return { status: 'fresh_snapshot', reason } if (subscribers === maxSubscribers) return { status: 'busy' } useStream(scope) + return openSubscription(stream, cursor.seq, { onEvent, onClose }) + } + + function openSubscription(stream, after, { onEvent, onClose }, latestEvent) { subscribers++ return { status: 'subscribed', close: startSubscription({ - bus, stream, after: cursor.seq, onEvent, onClose, deliveryTimeoutMs, + bus, stream, after, onEvent, onClose, deliveryTimeoutMs, latestEvent, release: () => { subscribers-- } }) } } + // A list reader needs the latest invalidation, not replay. Capture the initial + // watermark and attach within one synchronous turn, independent of retained history. + function watchSessions({ onEvent, onClose } = {}) { + const cursor = cursorAt(sessions) + if (closed) return { cursor, subscription: { status: 'closed' } } + if (subscribers === maxSubscribers) return { cursor, subscription: { status: 'busy' } } + if (typeof onEvent !== 'function' || (onClose !== undefined && typeof onClose !== 'function')) { + throw new TypeError('Expected event delivery callbacks') + } + const latestEvent = () => ({ cursor: cursorAt(sessions), type: 'sessions_changed' }) + return { cursor, subscription: openSubscription(sessions, cursor.seq, { onEvent, onClose }, latestEvent) } + } + return Object.freeze({ epoch, publishChat(payload) { if (closed) return { status: 'closed' } const event = projectChatEvent(payload) if (!event) return { status: 'ignored' } - const result = publish(chatScope(event.sessionId), event) - // These desktop events also update the list (for example, a first turn creates a session). - if (event.event.type === 'turn_start' || event.event.type === 'done' || event.event.type === 'member_report') { - publish(SESSIONS_SCOPE, { type: 'sessions_changed' }) - } - return result + return publish(chatScope(event.sessionId), event) }, publishSessionsChanged() { return closed ? { status: 'closed' } : publish(SESSIONS_SCOPE, { type: 'sessions_changed' }) }, + watchSessions, snapshot, subscribe, snapshotAndSubscribe(scope, readState, callbacks) { diff --git a/apps/headless/src/events/session-list-stream.mjs b/apps/headless/src/events/session-list-stream.mjs new file mode 100644 index 00000000..3c93fe2d --- /dev/null +++ b/apps/headless/src/events/session-list-stream.mjs @@ -0,0 +1,23 @@ +import { HttpError } from '../http/policy.mjs' +import { SESSIONS_SCOPE } from './journal.mjs' + +const journalId = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/ + +export const SESSION_LIST_PATH = '/api/v1/chats/stream' +export const MAX_SESSION_LIST_EVENT_BYTES = 512 + +export function attachSessionListStream(journal, cursor, callbacks) { + if (cursor && (cursor.scope !== SESSIONS_SCOPE || !journalId.test(cursor.epoch) || !journalId.test(cursor.generation))) { + throw new HttpError(400, 'invalid_cursor') + } + // The cursor is a reconnect hint only. Never replay obsolete invalidations or + // trust a client-supplied sequence as the watermark (even after restart). + const { cursor: latest, subscription } = journal.watchSessions(callbacks) + return { subscription, initial: JSON.stringify({ t: 'sessions-snapshot', cursor: latest }) } +} + +export function projectSessionListEvent(frame) { + if (frame.type !== 'sessions_changed' || frame.cursor?.scope !== SESSIONS_SCOPE) return null + const { epoch, generation, seq } = frame.cursor + return { t: 'sessions-changed', cursor: { epoch, generation, scope: SESSIONS_SCOPE, seq } } +} diff --git a/apps/headless/src/events/websocket.mjs b/apps/headless/src/events/websocket.mjs index 6b2ddc9a..569eb1b6 100644 --- a/apps/headless/src/events/websocket.mjs +++ b/apps/headless/src/events/websocket.mjs @@ -4,10 +4,12 @@ import { WebSocketServer } from 'ws' import { isSessionId, projectChatEvent } from './chat-event.mjs' import { chatScope } from './journal.mjs' import { HttpError } from '../http/policy.mjs' +import { attachSessionListStream, MAX_SESSION_LIST_EVENT_BYTES, projectSessionListEvent, SESSION_LIST_PATH } from './session-list-stream.mjs' const PREFIX = '/api/v1/chats/' const SUFFIX = '/stream' const MAX_PEERS = 16 +const MAX_LIST_PEERS = 8 // List-only tabs cannot monopolize the existing shared WS budget. const MAX_CURSOR_CHARS = 512 const MAX_INBOUND_BYTES = 1024 const MAX_EVENT_BYTES = 128 * 1024 @@ -120,7 +122,13 @@ function guardControlOnly(socket, onData) { return () => socket.off('data', scan) } -function createPeer(ws, { socket, sid, scope, auth, cookie, subscription, remove }) { +function projectChatFrame(frame, sid, scope) { + if (frame.type !== 'chat' || frame.sessionId !== sid || frame.cursor?.scope !== scope) return null + const event = projectChatEvent(frame) + return event && { t: 'event', cursor: frame.cursor, ...event } +} + +function createPeer(ws, { socket, auth, identity, subscription, project, maxEventBytes, remove }) { let active = true let outstandingWrite, closeTimer, expectedPong let controlPending = false @@ -128,7 +136,7 @@ function createPeer(ws, { socket, sid, scope, auth, cookie, subscription, remove function release() { if (!active) return active = false - cookie = undefined + identity = undefined stopIngressGuard() subscription.close() outstandingWrite?.settle(false) @@ -146,8 +154,10 @@ function createPeer(ws, { socket, sid, scope, auth, cookie, subscription, remove function authorized() { if (!active) return false if (ws.readyState !== ws.OPEN) { disconnect(); return false } - try { auth.authenticate(cookie) } - catch { disconnect(1008, 'auth'); return false } + if (!auth.isLoginActive(identity)) { + if (active) disconnect(1008, 'auth') // isLoginActive can revoke synchronously on expiration. + return false + } return true } @@ -183,14 +193,10 @@ function createPeer(ws, { socket, sid, scope, auth, cookie, subscription, remove } function writeEvent(frame) { - if (frame.type !== 'chat' || frame.sessionId !== sid || frame.cursor?.scope !== scope) { - disconnect(1012, 'snapshot_required') - return false - } - const event = projectChatEvent(frame) + const event = project(frame) if (!event) { disconnect(1012, 'snapshot_required'); return false } - if (event.event.text?.length > MAX_EVENT_BYTES) { disconnect(1009, 'frame_too_large'); return false } - return writeData(JSON.stringify({ t: 'event', cursor: frame.cursor, ...event }), MAX_EVENT_BYTES) + if (event.event?.text?.length > maxEventBytes) { disconnect(1009, 'frame_too_large'); return false } + return writeData(JSON.stringify(event), maxEventBytes) } const dataReceived = () => { if (active) disconnect(1008, 'read_only') } @@ -230,11 +236,14 @@ function createPeer(ws, { socket, sid, scope, auth, cookie, subscription, remove expectedPong = randomBytes(8) writeControl('ping', expectedPong) }, + revoke(loginSessionId) { + if (identity?.loginSessionId === loginSessionId) disconnect(1008, 'auth') + }, shutdown() { disconnect(1001, 'shutdown') } } } -/** Bind only the owner workbench's chat stream; the caller owns the HTTP upgrade listener. */ +/** Bind the owner workbench's read-only chat streams using one upgrade transport and peer budget. */ export function createChatWebSocket({ turns, journal, auth, policy }) { const wss = new WebSocketServer({ noServer: true, perMessageDeflate: false, maxPayload: MAX_INBOUND_BYTES, @@ -242,27 +251,32 @@ export function createChatWebSocket({ turns, journal, auth, policy }) { }) wss.on('wsClientError', (_error, socket) => endUpgrade(socket, 400)) const peers = new Set() + const stopRevocation = auth.onSessionRevoked(loginSessionId => { for (const peer of peers) peer.revoke(loginSessionId) }) const heartbeat = setInterval(() => { for (const peer of peers) peer.heartbeat() }, HEARTBEAT_MS).unref() + let listPeers = 0 let closing function upgrade(req, socket, head) { const target = req.url ?? '' const split = target.indexOf('?') const path = split < 0 ? target : target.slice(0, split) - if (!path.startsWith(PREFIX) || !path.endsWith(SUFFIX)) return false + const list = path === SESSION_LIST_PATH + if (!list && (!path.startsWith(PREFIX) || !path.endsWith(SUFFIX))) return false if (closing) { endUpgrade(socket, 503); return true } try { policy.check(req, true) if (req.headersDistinct.host?.length !== 1 || req.headersDistinct.origin?.length !== 1) throw new Error('origin') } catch { endUpgrade(socket, 403); return true } - const cookie = policy.cookie(req) - try { auth.authenticate(cookie) } catch { endUpgrade(socket, 401); return true } + let identity + try { identity = auth.identify(policy.cookie(req)) } catch { endUpgrade(socket, 401); return true } if (req.method !== 'GET') { endUpgrade(socket, 405); return true } - const sid = path.slice(PREFIX.length, -SUFFIX.length) - if (!isSessionId(sid) || head.length > 4096) { endUpgrade(socket, 400); return true } - if (wss.clients.size >= MAX_PEERS) { endUpgrade(socket, 503); return true } + const sid = list ? null : path.slice(PREFIX.length, -SUFFIX.length) + if ((!list && !isSessionId(sid)) || head.length > 4096) { endUpgrade(socket, 400); return true } + if (wss.clients.size >= MAX_PEERS || (list && listPeers >= MAX_LIST_PEERS)) { + endUpgrade(socket, 503); return true + } - const scope = chatScope(sid) + const scope = list ? null : chatScope(sid) let subscription, peer, initial const callbacks = { onEvent: frame => peer?.event(frame) ?? false, @@ -270,15 +284,19 @@ export function createChatWebSocket({ turns, journal, auth, policy }) { } try { const cursor = readCursor(split < 0 ? undefined : target.slice(split + 1)) - if (cursor) { - checkSnapshot(turns.snapshot(sid), sid) - subscription = journal.subscribe(scope, cursor, callbacks) - } - if (!subscription || subscription.status === 'fresh_snapshot') { - const attached = turns.attach(sid, callbacks) - subscription = attached.subscription - checkSnapshot(attached.snapshot, sid) - if (subscription.status === 'subscribed') initial = encodeSnapshot(attached.snapshot) + if (list) { + ({ subscription, initial } = attachSessionListStream(journal, cursor, callbacks)) + } else { + if (cursor) { + checkSnapshot(turns.snapshot(sid), sid) + subscription = journal.subscribe(scope, cursor, callbacks) + } + if (!subscription || subscription.status === 'fresh_snapshot') { + const attached = turns.attach(sid, callbacks) + subscription = attached.subscription + checkSnapshot(attached.snapshot, sid) + if (subscription.status === 'subscribed') initial = encodeSnapshot(attached.snapshot) + } } if (subscription.status !== 'subscribed') throw new HttpError(503, 'stream_unavailable') } catch (error) { @@ -289,15 +307,20 @@ export function createChatWebSocket({ turns, journal, auth, policy }) { } // Snapshot construction can consume time near the authentication deadline. - try { auth.authenticate(cookie) } - catch { subscription.close(); endUpgrade(socket, 401); return true } + if (!auth.isLoginActive(identity)) { subscription.close(); endUpgrade(socket, 401); return true } try { // handleUpgrade is synchronous with no verifyClient callback. The journal defers delivery // until the next Node turn, so the snapshot is queued before any event can be delivered. wss.handleUpgrade(req, socket, head, ws => { - peer = createPeer(ws, { socket, sid, scope, auth, cookie, subscription, remove: () => peers.delete(peer) }) + const project = list ? projectSessionListEvent : frame => projectChatFrame(frame, sid, scope) + peer = createPeer(ws, { + socket, auth, identity, subscription, project, + maxEventBytes: list ? MAX_SESSION_LIST_EVENT_BYTES : MAX_EVENT_BYTES, + remove() { peers.delete(peer); if (list) listPeers-- } + }) peers.add(peer) + if (list) listPeers++ peer.start(initial) initial = undefined }) @@ -309,6 +332,7 @@ export function createChatWebSocket({ turns, journal, auth, policy }) { function close() { if (closing) return closing clearInterval(heartbeat) + stopRevocation() closing = new Promise((resolve, reject) => wss.close(error => error ? reject(error) : resolve())) for (const peer of peers) peer.shutdown() return closing diff --git a/apps/headless/test/session-list-stream.test.mjs b/apps/headless/test/session-list-stream.test.mjs new file mode 100644 index 00000000..bf2e60b3 --- /dev/null +++ b/apps/headless/test/session-list-stream.test.mjs @@ -0,0 +1,358 @@ +import assert from 'node:assert/strict' +import crypto from 'node:crypto' +import { once } from 'node:events' +import { mkdir, mkdtemp, readFile, rename, rm } from 'node:fs/promises' +import { createServer } from 'node:http' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { performance } from 'node:perf_hooks' +import test from 'node:test' +import { setImmediate } from 'node:timers/promises' +import WebSocket from 'ws' +import { createAuthService } from '../src/auth/index.mjs' +import { chatScope, createEventJournal, SESSIONS_SCOPE } from '../src/events/journal.mjs' +import { createChatWebSocket } from '../src/events/websocket.mjs' +import { httpPolicy } from '../src/http/policy.mjs' +import { sessionRoutes } from '../src/http/session-routes.mjs' + +const LIST = '/api/v1/chats/stream' +const CHAT = '/api/v1/chats/fixture-chat/stream' +const password = 'temporary loopback fixture password' +const options = { timeout: 10_000 } +const timeout = () => ({ signal: AbortSignal.timeout(2000) }) +const resume = cursor => `${LIST}?cursor=${Buffer.from(JSON.stringify(cursor)).toString('base64url')}` +const snapshot = cursor => ({ t: 'sessions-snapshot', cursor }) +const changed = cursor => ({ t: 'sessions-changed', cursor }) + +async function fixture(t, journalOptions, withChatRoutes = false) { + const scrypt = crypto.scrypt + t.mock.method(crypto, 'scrypt', (value, salt, length, config, done) => { + scrypt(value, salt, length, { ...config, N: 1024 }, done) + }) + const dataDir = await mkdtemp(join(tmpdir(), 'deva-session-list-stream-')) + const sockets = new Set() + const clients = new Set() + const server = createServer() + let journal = createEventJournal(journalOptions) + let transport, upgradedSocket, businessTurns + t.after(async () => { + for (const ws of clients) ws.terminate() + await transport?.close() + await businessTurns?.close() + journal.close() + for (const socket of sockets) socket.destroy() + if (server.listening) await new Promise(resolve => server.close(resolve)) + await rm(dataDir, { recursive: true, force: true }) + }) + const auth = await createAuthService({ dataDir }) + const { credential } = await auth.issueClaim() + const owner = await auth.claim(credential, password) + const chatReads = [] + const chatState = sid => ({ id: sid, compatibility: 'text', messages: [{ content: 'private chat body' }] }) + const turns = { + snapshot(sid) { + chatReads.push(sid) + return journal.snapshot(chatScope(sid), () => chatState(sid)) + }, + attach(sid, callbacks) { + chatReads.push(sid) + return journal.snapshotAndSubscribe(chatScope(sid), () => chatState(sid), callbacks) + } + } + server.on('connection', socket => { sockets.add(socket); socket.once('close', () => sockets.delete(socket)) }) + server.on('upgrade', (req, socket, head) => { + upgradedSocket = socket + if (!transport.upgrade(req, socket, head)) socket.destroy() + }) + server.listen(0, '127.0.0.1') + await once(server, 'listening') + const authority = `127.0.0.1:${server.address().port}` + const origin = `http://${authority}` + const policy = httpPolicy(origin) + const authCookie = session => policy.issueCookie(session.session, session.expiresAt).split(';', 1)[0] + const cookie = authCookie(owner) + const session = sessionRoutes({ auth, policy, version: 'fixture', getConfig: () => ({}) }) + let chats + if (withChatRoutes) { + const [{ createTextTurns }, { chatRoutes }] = await Promise.all([ + import('../src/chat/text-turns.mjs'), import('../src/chat/routes.mjs') + ]) + businessTurns = createTextTurns({ dataDir, journal, settings: { getProvider() { assert.fail('unexpected model access') } } }) + chats = chatRoutes(businessTurns) + } + server.on('request', async (req, res) => { + if (await session(req, res) || await chats?.(req, res, { auth, policy })) return + res.writeHead(404).end() + }) + const bind = () => createChatWebSocket({ turns: businessTurns ?? turns, journal, auth, policy }) + transport = bind() + + function connect(path = LIST, headers = {}, wsOptions = {}) { + const requestHeaders = { origin, cookie, ...headers } + for (const name of ['origin', 'cookie']) if (requestHeaders[name] === null) delete requestHeaders[name] + const ws = new WebSocket(`ws://${authority}${path}`, { headers: requestHeaders, ...wsOptions }) + clients.add(ws) + const frames = [] + let index = 0 + ws.on('error', () => {}) // Assertions read handshake responses or terminal close codes. + ws.on('message', data => frames.push(JSON.parse(data.toString()))) + ws.once('close', () => clients.delete(ws)) + const closed = new Promise(resolve => ws.once('close', (code, reason) => resolve([code, reason.toString()]))) + return { ws, frames, closed, async next() { + if (index === frames.length) await once(ws, 'message', timeout()) + return frames[index++] + }, async flush() { + // Give the journal a delivery turn and use a control round trip as the wire barrier. + await setImmediate() + const pong = once(ws, 'pong', timeout()) + ws.ping('list-stream-barrier') + assert.equal((await pong)[0].toString(), 'list-stream-barrier') + } } + } + + return { + connect, auth, chatReads, origin, cookie, authCookie, dataDir, + http(path, { body, method = body === undefined ? 'GET' : 'POST', headers } = {}) { + return fetch(`${origin}${path}`, { + method, headers: { origin, cookie, 'x-deva-csrf': owner.csrf, 'content-type': 'application/json', ...headers }, + body: body === undefined ? undefined : JSON.stringify(body), ...timeout() + }) + }, + get journal() { return journal }, + get socket() { return upgradedSocket }, + async status(path = LIST, headers) { + const { ws } = connect(path, headers) + const [, res] = await once(ws, 'unexpected-response', timeout()) + res.resume() + await once(res, 'end', timeout()) + ws.terminate() + return res.statusCode + }, + async replaceJournal() { + await transport.close() + journal.close() + journal = createEventJournal(journalOptions) + transport = bind() + } + } +} + +test('list-only tabs get just the latest explicitly published invalidation', options, async t => { + const f = await fixture(t, { maxEventsPerScope: 1 }) + const first = f.connect() + const second = f.connect() + const initial = f.journal.snapshot(SESSIONS_SCOPE).cursor + assert.equal(initial.seq, 0) + assert.deepEqual(await Promise.all([first.next(), second.next()]), [snapshot(initial), snapshot(initial)]) + assert.deepEqual(f.chatReads, []) + assert.equal(f.journal.stats().chatStreams, 0) + + const chat = f.connect(CHAT) + assert.equal((await chat.next()).state.messages[0].content, 'private chat body') + for (const event of [ + { type: 'text_delta', text: 'unrelated private delta' }, { type: 'turn_start' }, + { type: 'done', stopReason: 'error' }, { type: 'member_report' } + ]) f.journal.publishChat({ sessionId: 'other-chat', turnId: 'other-turn', event }) + const mine = f.journal.publishChat({ sessionId: 'fixture-chat', turnId: 'chat-turn', event: { type: 'text_delta', text: 'selected-only' } }) + assert.deepEqual(await chat.next(), { + t: 'event', cursor: mine.cursor, type: 'chat', sessionId: 'fixture-chat', turnId: 'chat-turn', + event: { type: 'text_delta', text: 'selected-only' } + }) + await first.flush() + await second.flush() + assert.deepEqual(first.frames, [snapshot(initial)]) + assert.deepEqual(second.frames, first.frames) + assert.deepEqual(f.journal.snapshot(SESSIONS_SCOPE).cursor, initial) + + f.journal.publishSessionsChanged() + f.journal.publishSessionsChanged() + const { cursor: latest } = f.journal.publishSessionsChanged() + assert.equal(latest.seq, 3) + assert.deepEqual(await Promise.all([first.next(), second.next()]), [changed(latest), changed(latest)]) + const { cursor: next } = f.journal.publishSessionsChanged() + assert.equal(next.seq, 4) + assert.deepEqual(await Promise.all([first.next(), second.next()]), [changed(next), changed(next)]) + await first.flush() + await second.flush() + await chat.flush() + assert.deepEqual(first.frames, [snapshot(initial), changed(latest), changed(next)]) + assert.deepEqual(second.frames, first.frames) + assert.equal(chat.frames.length, 2) +}) + +test('actual chat HTTP create invalidates both tabs only after strict storage succeeds', options, async t => { + const f = await fixture(t, undefined, true) + const first = f.connect() + const second = f.connect() + const [initial, otherInitial] = await Promise.all([first.next(), second.next()]) + assert.deepEqual(initial, otherInitial) + assert.deepEqual(await (await f.http('/api/v1/chats')).json(), { sessions: [] }) + const sid = 'sess_durable_create' + const chatsDir = join(f.dataDir, 'data', 'chats') + const created = await f.http('/api/v1/chats', { body: { sessionId: sid } }) + assert.equal(created.status, 200) + const { session } = await created.json() + const next = changed({ ...initial.cursor, seq: initial.cursor.seq + 1 }) + assert.deepEqual(await Promise.all([first.next(), second.next()]), [next, next]) + assert.equal(JSON.parse(await readFile(join(chatsDir, `${sid}.json`), 'utf8')).id, sid) + assert.equal(session.id, sid) + const duplicate = await f.http('/api/v1/chats', { body: { sessionId: sid } }) + assert.equal(duplicate.status, 200) + assert.deepEqual(await duplicate.json(), { session }) + const denied = await f.http('/api/v1/chats', { body: { sessionId: 'unauthed' }, headers: { 'x-deva-csrf': 'wrong' } }) + assert.equal(denied.status, 401) + await denied.json() + + // The session JSON alone does not confirm the strict write: make replacing the + // list index fail even though the main session file is visible on disk. + const index = join(chatsDir, '_index.json') + await rename(index, `${index}.fixture-backup`) + await mkdir(index) + const failedSid = 'sess_failed_create' + const failed = await f.http('/api/v1/chats', { body: { sessionId: failedSid } }) + assert.equal(failed.status, 503) + await failed.json() + assert.equal(JSON.parse(await readFile(join(chatsDir, `${failedSid}.json`), 'utf8')).id, failedSid) + const reread = await f.http('/api/v1/chats') + assert.equal(reread.status, 200) + assert.deepEqual((await reread.json()).sessions.map(chat => chat.id), [sid]) + await first.flush() + await second.flush() + assert.deepEqual(first.frames, [initial, next]) + assert.deepEqual(second.frames, first.frames) + assert.deepEqual(f.journal.snapshot(SESSIONS_SCOPE).cursor, next.cursor) +}) + +test('reconnect always starts at the server watermark, also after an epoch replacement', options, async t => { + const f = await fixture(t, { maxEventsPerScope: 1 }) + const first = f.connect() + const { cursor: old } = await first.next() + first.ws.close() + await first.closed + f.journal.publishSessionsChanged() + const { cursor: current } = f.journal.publishSessionsChanged() + const returned = f.connect(resume(old)) + assert.deepEqual(await returned.next(), snapshot(current)) + await returned.flush() + assert.deepEqual(returned.frames, [snapshot(current)]) + const future = f.connect(resume({ ...current, seq: Number.MAX_SAFE_INTEGER })) + assert.deepEqual(await future.next(), snapshot(current)) + const { cursor: live } = f.journal.publishSessionsChanged() + assert.deepEqual(await Promise.all([returned.next(), future.next()]), [changed(live), changed(live)]) + + await f.replaceJournal() + assert.deepEqual(await returned.closed, [1001, 'shutdown']) + const recovered = f.connect(resume(live)) + const fresh = f.journal.snapshot(SESSIONS_SCOPE).cursor + assert.notEqual(fresh.epoch, live.epoch) + assert.notEqual(fresh.generation, live.generation) + assert.equal(fresh.seq, 0) + assert.deepEqual(await recovered.next(), snapshot(fresh)) + await recovered.flush() + assert.equal(recovered.frames.length, 1) +}) + +test('requires fixed Host, Origin and cookie, validates the cursor, and closes on application frames', options, async t => { + const f = await fixture(t) + const invalidOrigins = [ + { origin: 'https://unrelated.invalid' }, { origin: null }, { origin: '' }, { origin: [f.origin, f.origin] }, + { host: 'unrelated.invalid', 'x-forwarded-host': new URL(f.origin).host }, { 'sec-fetch-site': 'cross-site' } + ] + for (const headers of invalidOrigins) assert.equal(await f.status(LIST, headers), 403) + for (const cookie of [null, '', `${f.cookie}; ${f.cookie}`]) assert.equal(await f.status(LIST, { cookie }), 401) + const initial = f.journal.snapshot(SESSIONS_SCOPE).cursor + for (const path of [ + `${LIST}?cursor=`, `${LIST}?cursor=${'A'.repeat(513)}`, `${resume(initial)}&rpc=1`, + `${resume(initial)}=`, resume({ ...initial, seq: -1 }), resume({ ...initial, epoch: '' }), + resume({ ...initial, scope: 'chat:another' }), resume({ ...initial, sid: 'other' }) + ]) assert.equal(await f.status(path), 400) + assert.equal(f.journal.stats().subscribers, 0) + + for (const [data, opts] of [ + [JSON.stringify({ t: 'create', sid: 'untrusted' }), {}], [Buffer.from('binary'), {}], ['', { fin: false }] + ]) { + const peer = f.connect() + assert.deepEqual(await peer.next(), snapshot(initial)) + peer.ws.send(data, opts) + assert.deepEqual(await peer.closed, [1008, 'read_only']) + assert.deepEqual(peer.frames, [snapshot(initial)]) + } + assert.deepEqual(f.chatReads, []) + assert.equal(f.journal.stats().subscribers, 0) + assert.deepEqual(f.journal.snapshot(SESSIONS_SCOPE).cursor, initial) +}) + +test('idle logout closes only that login’s tabs and the heartbeat removes expired logins', options, async t => { + t.mock.timers.enable({ apis: ['setInterval'] }) + const f = await fixture(t) + const otherLogin = await f.auth.login(password) + const otherHeaders = { cookie: f.authCookie(otherLogin) } + const first = f.connect() + const second = f.connect() + const other = f.connect(LIST, otherHeaders) + await Promise.all([first.next(), second.next(), other.next()]) + const logout = await f.http('/api/v1/auth/logout', { method: 'POST' }) + assert.equal(logout.status, 200) + assert.deepEqual(await logout.json(), { ok: true }) + assert.deepEqual(await Promise.all([first.closed, second.closed]), [[1008, 'auth'], [1008, 'auth']]) + assert.equal(first.frames.length, 1) + assert.equal(second.frames.length, 1) + assert.equal(await f.status(), 401) + const { cursor } = f.journal.publishSessionsChanged() + assert.deepEqual(await other.next(), changed(cursor)) + const expired = performance.now() + 12 * 60 * 60_000 + t.mock.method(performance, 'now', () => expired) + t.mock.timers.tick(5000) + assert.deepEqual(await other.closed, [1008, 'auth']) + assert.equal(f.journal.stats().subscribers, 0) + assert.equal(await f.status(LIST, otherHeaders), 401) +}) + +test('list peers reserve chat capacity and share the global WebSocket limit', options, async t => { + const f = await fixture(t) + const lists = Array.from({ length: 8 }, () => f.connect()) + await Promise.all(lists.map(peer => peer.next())) + assert.equal(await f.status(), 503) + const chats = Array.from({ length: 8 }, () => f.connect(CHAT)) + await Promise.all(chats.map(peer => peer.next())) + assert.equal(f.journal.stats().subscribers, 16) + assert.equal(await f.status(CHAT), 503) + lists[0].ws.close() + await lists[0].closed + const ninthChat = f.connect(CHAT) + assert.equal((await ninthChat.next()).t, 'snapshot') + assert.equal(await f.status(), 503) + ninthChat.ws.close() + await ninthChat.closed + assert.equal((await f.connect().next()).t, 'sessions-snapshot') + assert.equal(f.journal.stats().subscribers, 16) +}) + +test('stalled list writes stay bounded and missed pongs time out', options, async t => { + t.mock.timers.enable({ apis: ['setInterval', 'setTimeout'] }) + const f = await fixture(t) + const client = f.connect() + const first = await client.next() + const socket = f.socket + socket.cork() + f.journal.publishSessionsChanged() + await setImmediate() + const buffered = socket.writableLength + assert.ok(buffered > 0 && buffered < 512, `one pending list frame: ${buffered} bytes`) + for (let i = 0; i < 20; i++) f.journal.publishSessionsChanged() + await setImmediate() + assert.equal(socket.writableLength, buffered) + t.mock.timers.tick(5000) + assert.deepEqual(await client.closed, [1006, '']) + assert.deepEqual(client.frames, [first]) + assert.equal(f.journal.stats().subscribers, 0) + + const idle = f.connect(LIST, {}, { autoPong: false }) + assert.equal((await idle.next()).cursor.seq, 21) + const ping = once(idle.ws, 'ping', timeout()) + t.mock.timers.tick(5000) + assert.equal((await ping)[0].length, 8) + t.mock.timers.tick(5000) + assert.deepEqual(await idle.closed, [1006, '']) + assert.equal(f.journal.stats().subscribers, 0) +}) From dbe8ec5579b111c17d7cea893679a9a62c0d4a53 Mon Sep 17 00:00:00 2001 From: Facetomyself <[GIT_EMAIL]> Date: Thu, 26 Nov 2026 15:55:10 +0800 Subject: [PATCH 2/6] =?UTF-8?q?feat(chat):=20=E4=BF=9D=E5=AD=98=E4=BC=9A?= =?UTF-8?q?=E8=AF=9D=E5=BD=92=E6=A1=A3=E5=92=8C=E4=B8=8B=E6=AC=A1=E6=A8=A1?= =?UTF-8?q?=E5=9E=8B=E5=81=8F=E5=A5=BD=20/=20persist=20conversation=20orga?= =?UTF-8?q?nization=20and=20next-turn=20model=20preferences?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/headless/src/business/handlers.mjs | 3 +- apps/headless/src/chat/routes.mjs | 7 +- .../src/chat/session-preferences-storage.mjs | 62 ++++ .../headless/src/chat/session-preferences.mjs | 155 +++++++++ apps/headless/src/chat/session-routes.mjs | 32 ++ apps/headless/src/chat/text-turns.mjs | 141 ++++++-- apps/headless/src/http/session-routes.mjs | 2 +- .../session-preferences-concurrency.test.mjs | 34 ++ .../test/session-preferences.test.mjs | 308 ++++++++++++++++++ 9 files changed, 711 insertions(+), 33 deletions(-) create mode 100644 apps/headless/src/chat/session-preferences-storage.mjs create mode 100644 apps/headless/src/chat/session-preferences.mjs create mode 100644 apps/headless/src/chat/session-routes.mjs create mode 100644 apps/headless/test/session-preferences-concurrency.test.mjs create mode 100644 apps/headless/test/session-preferences.test.mjs diff --git a/apps/headless/src/business/handlers.mjs b/apps/headless/src/business/handlers.mjs index 48ba9043..253a33a4 100644 --- a/apps/headless/src/business/handlers.mjs +++ b/apps/headless/src/business/handlers.mjs @@ -67,7 +67,8 @@ export async function openBusiness({ dataDir, vault, auth, version, allowedOrigi } return { beginShutdown, - capabilities: Object.freeze({ textChat: true, library: true, workspaceFiles: library.workspaceFilesEnabled, attachments: true, browserPanel: !!browser }), + capabilities: Object.freeze({ textChat: true, library: true, workspaceFiles: library.workspaceFilesEnabled, attachments: true, + browserPanel: !!browser, sessionPreferences: typeof turns.patchPreferences === 'function' && typeof journal.watchSessions === 'function' }), createRealtime: ({ auth, policy }) => createChatWebSocket({ turns, journal, auth, policy }), getConfig: () => settings.getPublicConfig(), async handle(req, res, { auth, policy }) { diff --git a/apps/headless/src/chat/routes.mjs b/apps/headless/src/chat/routes.mjs index 82c416f1..908a59f6 100644 --- a/apps/headless/src/chat/routes.mjs +++ b/apps/headless/src/chat/routes.mjs @@ -1,8 +1,9 @@ import { HttpError, json, readJson } from '../http/policy.mjs' +import { sessionPreferenceRoute } from './session-routes.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))?$/ +const resource = /^\/api\/v1\/chats\/([A-Za-z0-9_-]{1,128})(?:\/(turns|stop|preferences))?$/ const roleServiceError = () => new HttpError(503, 'chat_role_unavailable') const roleUnavailable = () => new HttpError(409, 'role_unavailable') @@ -40,6 +41,10 @@ export function chatRoutes(turns, { withRoleForChat } = {}) { const path = (req.url ?? '').split('?', 1)[0] const match = resource.exec(path) if (path !== collection && !match) return false + if (match?.[2] === 'preferences') { + await sessionPreferenceRoute(req, res, { auth, policy }, turns, path, match[1]) + return true + } const write = req.method === 'POST' const methods = match ? [match[2] ? 'POST' : 'GET'] : ['GET', 'POST'] try { diff --git a/apps/headless/src/chat/session-preferences-storage.mjs b/apps/headless/src/chat/session-preferences-storage.mjs new file mode 100644 index 00000000..e4227ccb --- /dev/null +++ b/apps/headless/src/chat/session-preferences-storage.mjs @@ -0,0 +1,62 @@ +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' + +const mainPath = (dataDir, sid) => join(dataDir, 'data', 'chats', `${sid}.json`) +const unconfirmed = () => new HttpError(503, 'chat_storage_unconfirmed') +// 256 turns × (64 Ki UTF-16 assistant + 12 KiB user) × six JSON bytes per escaped unit, +// plus receipts and media references. Native blobs themselves are never read here. +const maxFile = 128n * 1024n * 1024n +const signature = ['dev', 'ino', 'size', 'mode', 'nlink', 'uid', 'gid', 'mtimeNs', 'ctimeNs'] +const same = (a, b) => signature.every(key => a[key] === b[key]) +const readStat = { bigint: true } +const validPrivateFile = (stat, writable) => stat.isFile() && stat.nlink === 1n && stat.uid === BigInt(process.geteuid()) && + ((stat.mode & 0o7777n) === 0o600n || (!writable && (stat.mode & 0o7777n) === 0o400n)) && + stat.size > 0n && stat.size <= maxFile + +function loadPrivateFile(path, writable) { + const named = lstatSync(path, readStat) + if (!validPrivateFile(named, writable)) throw unconfirmed() + const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0)) + try { + const opened = fstatSync(fd, readStat) + if (!validPrivateFile(opened, writable) || !same(named, opened)) throw unconfirmed() + 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 unconfirmed() + offset += count + } + if (!same(fstatSync(fd, readStat), opened) || !same(lstatSync(path, readStat), opened)) throw unconfirmed() + return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)) + } finally { closeSync(fd) } +} + +/** Check a cold target's size before the core loads its cache. Non-Web native files still + * reach the existing history classification; private mode is required for Web mutation. */ +export function preflightPreferenceStorage(dataDir, sid) { + let stat + try { stat = lstatSync(mainPath(dataDir, sid), readStat) } + catch (err) { + if (err?.code === 'ENOENT') return false + throw unconfirmed() + } + if (!stat.isFile() || stat.nlink !== 1n || stat.size <= 0n || stat.size > maxFile) throw unconfirmed() + return true +} + +/** The workbench already holds the volume's writer lock. Compare the native file with the + * core's cached session before writing, and verify the native readback after saveStrict. + * This also detects out-of-band drift already visible on disk without silently merging it. + * Call only after SID and native history compatibility checks; no paths are returned. */ +export function confirmPreferenceStorage(dataDir, s, conflictOnDrift = false) { + let disk + try { disk = loadPrivateFile(mainPath(dataDir, s.id), conflictOnDrift) } + catch { throw unconfirmed() } + // The core's new-session defaults may contain undefined top-level properties; the on-disk + // object omits those. Known native nested fields have already been JSON-loaded or persisted. + const expected = Object.fromEntries(Object.entries(s).filter(([, value]) => value !== undefined)) + if (!isDeepStrictEqual(disk, expected)) throw conflictOnDrift + ? new HttpError(409, 'preferences_conflict') : unconfirmed() +} diff --git a/apps/headless/src/chat/session-preferences.mjs b/apps/headless/src/chat/session-preferences.mjs new file mode 100644 index 00000000..c78447fe --- /dev/null +++ b/apps/headless/src/chat/session-preferences.mjs @@ -0,0 +1,155 @@ +import { createHash } from 'node:crypto' +import { deriveTitle } from '../../dist/chat-core.mjs' +import { providerId as checkedProviderId } from '../business/settings-schema.mjs' +import { HttpError } from '../http/policy.mjs' + +export const PREFERENCES_META = '_devaHeadlessSessionPreferences' +const titleMax = 100 // Match the desktop rename action's UTF-16 limit and whitespace folding. +const nativeEfforts = new Set(['default', 'low', 'medium', 'high', 'xhigh', 'max']) +const adapters = new Set(['openai', 'anthropic', 'responses']) +const preferenceKeys = ['customTitle', 'archived', 'model', 'effort'] +const conflict = () => new HttpError(409, 'preferences_conflict') +const invalidPatch = () => new HttpError(400, 'invalid_preferences') +export const unsupportedEffort = () => new HttpError(422, 'effort_unsupported') + +function record(value, allowed) { + if (!value || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) throw invalidPatch() + const fields = Object.create(null) + for (const key of Reflect.ownKeys(value)) { + const d = Object.getOwnPropertyDescriptor(value, key) + if (!allowed.includes(key) || !d.enumerable || !Object.hasOwn(d, 'value')) throw invalidPatch() + fields[key] = d.value + } + return fields +} + +export function splitModel(ref) { + if (typeof ref !== 'string' || ref.length > 609) throw new HttpError(400, 'invalid_model_ref') + const colon = ref.indexOf(':') + if (colon < 1) throw new HttpError(400, 'invalid_model_ref') + const providerId = ref.slice(0, colon) + const modelId = ref.slice(colon + 1) + try { checkedProviderId(providerId) } catch { throw new HttpError(400, 'invalid_model_ref') } + if (!modelId || modelId.length > 512 || modelId !== modelId.trim() || /[\x00-\x1f\x7f]/.test(modelId)) { + throw new HttpError(400, 'invalid_model_ref') + } + return { providerId, modelId } +} + +export function readPreferencePatch(input) { + const fields = record(input, ['revision', 'set']) + if (!Object.hasOwn(fields, 'revision')) throw new HttpError(409, 'revision_required') + const { revision } = fields + if (typeof revision !== 'string' || revision.length !== 64 || /[^a-f0-9]/.test(revision)) throw new HttpError(400, 'invalid_revision') + const set = record(fields.set, preferenceKeys) + if (!Object.keys(set).length) throw invalidPatch() + if (Object.hasOwn(set, 'customTitle') && set.customTitle !== null) { + if (typeof set.customTitle !== 'string' || !set.customTitle.isWellFormed()) throw invalidPatch() + set.customTitle = set.customTitle.replace(/\s+/g, ' ').trim().slice(0, titleMax).toWellFormed() || null + } + if (Object.hasOwn(set, 'archived') && typeof set.archived !== 'boolean') throw invalidPatch() + let model + if (Object.hasOwn(set, 'model') && set.model !== null) { + if (typeof set.model !== 'string' || !set.model.isWellFormed()) throw new HttpError(400, 'invalid_model_ref') + model = splitModel(set.model) + } + if (Object.hasOwn(set, 'effort') && set.effort !== null && !nativeEfforts.has(set.effort)) throw new HttpError(400, 'invalid_effort') + return { revision, set, model } +} + +export function validPreferenceFields(s) { + const meta = s[PREFERENCES_META] + if (s.archived !== undefined && typeof s.archived !== 'boolean') return false + if (s.effort !== undefined && !nativeEfforts.has(s.effort)) return false + if (s.model !== undefined && typeof s.model !== 'string') return false + if (meta === undefined) return true + try { + const fields = record(meta, ['version', 'generation', 'customTitle', 'managedModel']) + return Object.keys(fields).length === 4 && fields.version === 1 && Number.isSafeInteger(fields.generation) && fields.generation > 0 && + (fields.customTitle === null || (typeof fields.customTitle === 'string' && fields.customTitle.length > 0 && + fields.customTitle.length <= titleMax && fields.customTitle.isWellFormed())) && typeof fields.managedModel === 'boolean' + } catch { return false } +} + +export const managedModel = s => s[PREFERENCES_META]?.managedModel === true +const storedModel = s => typeof s.model === 'string' && s.model ? s.model : null + +export function preferenceView(s, turnCount) { + const meta = s[PREFERENCES_META] + // A desktop rename can change the native title without understanding the headless sidecar. + const title = s.title + const customTitle = meta?.customTitle === title ? title : null + const preferences = { title, customTitle, archived: s.archived === true, model: storedModel(s), effort: s.effort ?? null } + // Include the legacy turn count to avoid ABA if successive legacy sends change the native model and change it back. + // Once managed, the ledger has no bearing on a metadata revision. + const revision = createHash('sha256').update(JSON.stringify([ + 'headless-session-preferences-v1', s.id, s.createdAt, meta?.generation ?? 0, + managedModel(s) ? null : turnCount, preferences + ])).digest('hex') + return { preferences, revision } +} + +export const checkPreferenceRevision = (expected, current) => { + if (expected !== current) throw conflict() +} + +export function firstTitle(text, names = []) { + return (deriveTitle(text) || deriveTitle(names.join(' '))).toWellFormed() +} + +export function preferenceChanges(s, set, firstUser) { + const prior = s[PREFERENCES_META] + const generation = (prior?.generation ?? 0) + 1 + if (!Number.isSafeInteger(generation)) throw new HttpError(409, 'preferences_revision_exhausted') + const patch = {} + let customTitle = prior?.customTitle === s.title ? s.title : null + if (Object.hasOwn(set, 'customTitle')) { + customTitle = set.customTitle + const first = customTitle === null ? firstUser() : null + patch.title = customTitle ?? (first ? firstTitle(first.content, first.attachments?.map(a => a.name)) : '') + } + if (Object.hasOwn(set, 'archived')) patch.archived = set.archived ? true : undefined + const pinChanged = Object.hasOwn(set, 'model') + if (pinChanged) patch.model = set.model ?? '' // Desktop represents following its default as an empty native model. + if (Object.hasOwn(set, 'effort')) patch.effort = set.effort ?? undefined + patch[PREFERENCES_META] = { version: 1, generation, customTitle, managedModel: pinChanged || managedModel(s) } + return patch +} + +export function listPreferenceFields(s) { + return { + ...(s.archived === true || s.archived === false ? { archived: s.archived } : {}), + ...(s[PREFERENCES_META]?.customTitle === s.title && s.title ? { customTitle: s.title } : {}) + } +} + +export async function validatePreferenceModel(settings, ref) { + let p + try { p = await settings.getProvider(ref.providerId) } + catch { throw new HttpError(503, 'chat_model_unavailable') } + if (!p) throw new HttpError(404, 'provider_not_found') + if (p.purpose === 'decision' || !adapters.has(p.adapter) || typeof p.apiHost !== 'string' || !p.apiHost.trim()) { + throw new HttpError(422, 'not_chat_provider') + } + if (!p.enabled || !p.models?.some(m => m.id === ref.modelId && m.enabled)) throw new HttpError(422, 'model_not_enabled') +} + +/** Setters make no provider requests. A later fresh send must agree with the effective model; + * accepting a different request model would silently replace the setting or break ledger identity. */ +export async function resolveTurnModel(settings, s, role, requested) { + const isManaged = managedModel(s) + if (!isManaged && requested !== null) return requested + const pin = storedModel(s) + if (pin) { + if (requested !== pin) throw new HttpError(409, 'session_model_changed') + return pin + } + let effective = role?.model + if (!effective) { + try { effective = (await settings.getPublicConfig()).models.activeModelId } + catch { throw new HttpError(503, 'chat_model_unavailable') } + } + if (!effective) throw new HttpError(422, 'model_not_enabled') + if (requested !== null && requested !== effective) throw new HttpError(409, 'session_model_changed') + return effective +} diff --git a/apps/headless/src/chat/session-routes.mjs b/apps/headless/src/chat/session-routes.mjs new file mode 100644 index 00000000..af56777c --- /dev/null +++ b/apps/headless/src/chat/session-routes.mjs @@ -0,0 +1,32 @@ +import { HttpError, json, readJson } from '../http/policy.mjs' + +/** Owner-only session metadata. The resource path supplies the only session scope. */ +export async function sessionPreferenceRoute(req, res, { auth, policy }, turns, path, sid) { + const write = req.method === 'PATCH' + 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 authenticateWrite = () => { + policy.check(req, true) + auth.authenticate(cookie, req.headers['x-deva-csrf']) + } + if (!write) { + auth.authenticate(cookie) + json(res, 200, turns.getPreferences(sid)) + return + } + authenticateWrite() + const body = await readJson(req, 8 * 1024) + authenticateWrite() + json(res, 200, await turns.patchPreferences(sid, body, authenticateWrite)) + } catch (error) { + const known = error instanceof HttpError + const status = known ? error.status : error?.code === 'AUTH_FAILED' ? 401 : 500 + if (!res.headersSent && !res.destroyed) json(res, status, { error: known ? error.code : status === 401 ? 'auth' : 'internal' }, write ? { connection: 'close' } : {}) + } +} diff --git a/apps/headless/src/chat/text-turns.mjs b/apps/headless/src/chat/text-turns.mjs index 682a46ea..b20c8ef4 100644 --- a/apps/headless/src/chat/text-turns.mjs +++ b/apps/headless/src/chat/text-turns.mjs @@ -1,10 +1,14 @@ import { createHash, randomUUID } from 'node:crypto' import { setImmediate as nextTick } from 'node:timers/promises' -import { consumeModelStep, createChatStore, deriveTitle, isValidSessionId, modelMessages } from '../../dist/chat-core.mjs' +import { consumeModelStep, createChatStore, isValidSessionId, modelMessages } from '../../dist/chat-core.mjs' import { connectProvider } from '../business/model-connection.mjs' -import { providerId as checkedProviderId } from '../business/settings-schema.mjs' import { chatScope } from '../events/index.mjs' import { HttpError } from '../http/policy.mjs' +import { confirmPreferenceStorage, preflightPreferenceStorage } from './session-preferences-storage.mjs' +import { + PREFERENCES_META, checkPreferenceRevision, firstTitle, listPreferenceFields, managedModel, preferenceChanges, + preferenceView, readPreferencePatch, resolveTurnModel, splitModel, unsupportedEffort, validPreferenceFields, validatePreferenceModel +} from './session-preferences.mjs' import { ATTACHMENT_META, attachmentIds, createTurnAttachments } from './turn-attachments.mjs' const META = '_devaHeadlessTextTurns' @@ -26,7 +30,10 @@ const terminalReasons = new Map([ ['failed', new Set(['model_failed', 'unexpected_tool', 'timeout'])], ['interrupted', new Set(['interrupted'])] ]) -const nativeTextFields = new Set(['id', 'title', 'createdAt', 'updatedAt', 'focusRoot', 'personaId', 'model', 'messages', 'notices', META]) +const nativeTextFields = new Set([ + 'id', 'title', 'createdAt', 'updatedAt', 'focusRoot', 'personaId', 'model', 'messages', 'notices', + 'archived', 'effort', META, PREFERENCES_META +]) const complexFields = [ 'compacted', 'members', 'parentId', 'proposals', 'asks', 'summaries', 'delivered', 'background', 'durations', 'plans', 'autotasks', 'todos', 'todoCancelled', 'todoCancelNote', 'checkpoints', 'lastKnown', @@ -98,19 +105,6 @@ function createInput(input) { return sessionId } -function splitModel(ref) { - if (typeof ref !== 'string' || ref.length > 609) throw new HttpError(400, 'invalid_model_ref') - const colon = ref.indexOf(':') - if (colon < 1) throw new HttpError(400, 'invalid_model_ref') - const providerId = ref.slice(0, colon) - const modelId = ref.slice(colon + 1) - try { checkedProviderId(providerId) } catch { throw new HttpError(400, 'invalid_model_ref') } - if (!modelId || modelId.length > 512 || modelId !== modelId.trim() || /[\x00-\x1f\x7f]/.test(modelId)) { - throw new HttpError(400, 'invalid_model_ref') - } - return { providerId, modelId } -} - function sendInput(input, supportsAttachments) { const keys = ['sid', 'clientRequestId', 'text', 'model'] if (supportsAttachments && input && Object.hasOwn(input, 'attachments')) keys.push('attachments') @@ -122,9 +116,10 @@ function sendInput(input, supportsAttachments) { if (typeof text !== 'string' || text.length > MAX_TEXT_BYTES || (!attachments?.length && !text.trim()) || Buffer.byteLength(text) > MAX_TEXT_BYTES) { throw new HttpError(400, 'invalid_text') } - const ref = splitModel(model) + if (model !== null) splitModel(model) + // Preserve existing receipts byte-for-byte. A null model records the intention to follow current defaults. const fingerprint = createHash('sha256').update(JSON.stringify(attachments?.length ? [model, text, attachments] : [model, text])).digest('hex') - return { sid, clientRequestId, text, model, ...ref, fingerprint, attachments } + return { sid, clientRequestId, text, model, fingerprint, attachments } } function plainText(content) { @@ -231,6 +226,7 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr if (s[ATTACHMENT_META] !== undefined) { return attachments && !incomplete.has(s) && s.focusRoot == null && (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' } @@ -242,7 +238,7 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr }) || 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) || s.focusRoot != null || + !validLedger(s[META], s.messages.length) || !validNotices(s) || !validPreferenceFields(s) || s.focusRoot != null || (s.personaId !== undefined && !isChatRoleId(s.personaId)) || Object.keys(s).some(key => s[key] !== undefined && !nativeTextFields.has(key)) )) ? 'unsupported' : owns ? 'text' : 'legacy_text' @@ -262,7 +258,8 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr 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 : null, + model: kind === 'text' && typeof s.model === 'string' && s.model ? s.model : null, + ...listPreferenceFields(s), compatibility: kind, writable: writeBlockReason === null, writeBlockReason, turnLimit: kind === 'text' ? MAX_REQUESTS : null } @@ -290,7 +287,7 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr hidden.add(id) throw storageError() } - try { journal.publishSessionsChanged() } catch { /* invalidate on the next client snapshot */ } + publishSessionsChanged() return summary(s) } @@ -303,6 +300,63 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr }) } + function preferencesSession(sid) { + if (closing) throw closedError() + if (!validSid(sid)) throw new HttpError(400, 'invalid_session_id') + if (unconfirmed.has(sid) || hidden.has(sid)) throw storageError() + const exists = preflightPreferenceStorage(dataDir, sid) + const s = lookupSession(sid) + if (!exists && !s) throw new HttpError(404, 'session_not_found') + if (!exists || !s) throw storageError() + const kind = compatibility(s) + if (kind === 'legacy_text') throw new HttpError(409, 'read_only_session') + if (kind !== 'text') throw new HttpError(409, 'unsupported_history') + const index = attachedIndex(s) + if (index && (mediaUnconfirmed.has(s) || !attachments.available(index))) throw new HttpError(409, 'unsupported_history') + return s + } + + function getPreferences(sid) { + const s = preferencesSession(sid) + confirmPreferenceStorage(dataDir, s) + return preferenceView(s, s[META].requests.length) + } + + function firstUser(s) { + const at = s.messages.findIndex(m => m.role === 'user') + if (at < 0) return null + const message = s.messages[at] + const row = attachedIndex(s)?.byMessage.get(at) + return row ? attachments.snapshot(message, row) : { content: plainText(message.content) } + } + + async function patchPreferences(sid, input, verifyOwner) { + const { revision, set, model } = readPreferencePatch(input) + function checkedCurrent() { + if (active.has(sid)) throw new HttpError(409, 'turn_in_progress') + const s = preferencesSession(sid) + checkPreferenceRevision(revision, preferenceView(s, s[META].requests.length).revision) + return s + } + checkedCurrent() + if (set.effort != null && set.effort !== 'default') throw unsupportedEffort() + // The settings lookup can outlive the login. Recheck even when validation itself fails. + try { if (model) await validatePreferenceModel(settings, model) } + finally { verifyOwner?.() } + // A competing editor or turn can also have committed while the lookup awaited. Nothing awaits from here. + const s = checkedCurrent() + confirmPreferenceStorage(dataDir, s, true) + const previous = preferenceView(s, s[META].requests.length).preferences + const wasManaged = managedModel(s) + const patch = preferenceChanges(s, set, () => firstUser(s)) + commit(s, patch, null, () => confirmPreferenceStorage(dataDir, s)) + const after = preferenceView(s, s[META].requests.length) + if (wasManaged !== managedModel(s) || Object.keys(previous).some(key => previous[key] !== after.preferences[key])) { + publishSessionsChanged() + } + return after + } + function readState(s) { const base = summary(s) const slot = active.get(s.id) @@ -359,6 +413,10 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr return committed } + function publishSessionsChanged() { + try { journal.publishSessionsChanged() } catch { /* invalidate on the next client snapshot */ } + } + function publish(slot, event) { try { journal.publishChat({ sessionId: slot.session.id, turnId: slot.record.turnId, event }) } catch { /* a journal fault does not change the outcome of the confirmed store write */ } @@ -371,12 +429,18 @@ 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) { - const before = Object.fromEntries(Object.keys(patch).map(key => [key, s[key]])) - Object.assign(s, patch) - try { store.saveStrict(s.id) } + function commit(s, patch, terminal = null, verify) { + 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 { - Object.assign(s, before) + for (const [key, descriptor] of before) { + if (descriptor) Object.defineProperty(s, key, descriptor) + else delete s[key] + } unconfirmed.set(s.id, terminal) throw storageError() } @@ -404,6 +468,9 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr throw new HttpError(409, 'unsupported_history') } const role = s.personaId === undefined ? undefined : await roleForTurn(s.personaId) + if (s.effort !== undefined && s.effort !== 'default') throw unsupportedEffort() + const model = await resolveTurnModel(settings, s, role, input.model) + const { providerId, modelId } = splitModel(model) let client, adapter // Capture the adapter from the same trusted provider snapshot that binds credentials, model and URL. const binding = withMedia ? { async getProvider(id) { @@ -413,7 +480,7 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr return { ...provider, adapter } } } : settings try { - client = await connectProvider(binding, input.providerId, { version, allowedOrigins, signal: controller.signal, modelId: input.modelId }) + client = await connectProvider(binding, providerId, { version, allowedOrigins, signal: controller.signal, modelId }) } catch (err) { if (closing) throw closedError() const knownStatus = err instanceof HttpError ? publicModelErrors.get(err.code) : undefined @@ -422,6 +489,7 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr if (closing) throw closedError() const record = { clientRequestId: input.clientRequestId, fingerprint: input.fingerprint, + ...(input.model === null || managedModel(s) ? { model } : {}), turnId: randomUUID(), startedAt: Date.now(), status: 'running', reason: null } const requests = [...s[META].requests] @@ -443,12 +511,19 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr prepared?.persist?.() // Publish immutable media before the confirmed JSON and before streamChat. // Native text part avoids interpreting a literal desktop compaction/auto marker as metadata. const messages = prepared?.messages ?? [...s.messages, { role: 'user', content: [{ type: 'text', text: input.text }] }] + const itemNames = prepared?.patch[ATTACHMENT_META]?.rows.at(-1)?.items.map(item => item.name) + const title = s.title || firstTitle(input.text, itemNames) + const modelPatch = managedModel(s) ? {} : input.model === null + ? preferenceChanges(s, { model: null }, () => null) : { model } + const modelChanged = Object.hasOwn(modelPatch, 'model') && (modelPatch.model || null) !== (s.model || null) + const listChanged = title !== s.title || modelChanged || record.startedAt !== s.updatedAt || requests.length === MAX_REQUESTS commit(s, { - messages, notices, model: input.model, title: s.title || deriveTitle(prepared?.question ?? input.text), updatedAt: record.startedAt, + ...modelPatch, messages, notices, title, updatedAt: record.startedAt, [META]: { version: 1, messageCount: messages.length, requests }, ...prepared?.patch }) slot.record = record publish(slot, { type: 'turn_start' }) + if (listChanged) publishSessionsChanged() // The session now owns durable bytes. Retire spent draft reservations after commit, // never before: a failed save must keep the user's files available for a retry. if (input.attachments?.length && typeof uploads?.remove === 'function') { @@ -510,10 +585,13 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr try { const index = attachedIndex(s) if (index && (mediaUnconfirmed.has(s) || !attachments.available(index))) throw storageError() + const updatedAt = Date.now() + const listChanged = updatedAt !== s.updatedAt commit(s, { - messages, notices, updatedAt: Date.now(), + messages, notices, updatedAt, [META]: { version: 1, messageCount: messages.length, requests: [...s[META].requests.slice(0, -1), ended] } }, { ...record, status: 'failed', reason: 'storage_unconfirmed' }) + if (listChanged) publishSessionsChanged() } catch { status = 'failed' stopReason = 'error' @@ -579,5 +657,8 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr const s = lookupSession(sid) return !!s && compatibility(s) === 'text' } - return Object.freeze({ create, list, attach, snapshot, send, stop, close, attachmentScope, describeCommittedAttachment, readCommittedAttachment, hasBrowserSession }) + return Object.freeze({ + create, list, attach, snapshot, send, stop, close, getPreferences, patchPreferences, + attachmentScope, describeCommittedAttachment, readCommittedAttachment, hasBrowserSession + }) } diff --git a/apps/headless/src/http/session-routes.mjs b/apps/headless/src/http/session-routes.mjs index 12945a47..c4950c6c 100644 --- a/apps/headless/src/http/session-routes.mjs +++ b/apps/headless/src/http/session-routes.mjs @@ -49,7 +49,7 @@ export function sessionRoutes({ auth, policy, version, getConfig, capabilities } json(res, 200, { protocol: 1, version, platform: process.platform, config, csrf, expiresAt, capabilities: { textChat: capabilities?.textChat === true, library: capabilities?.library === true, workspaceFiles: capabilities?.workspaceFiles === true, attachments: capabilities?.attachments === true, - browserPanel: capabilities?.browserPanel === true } }) + browserPanel: capabilities?.browserPanel === true, sessionPreferences: capabilities?.sessionPreferences === true } }) return true } if (path === '/api/v1/auth/logout') { diff --git a/apps/headless/test/session-preferences-concurrency.test.mjs b/apps/headless/test/session-preferences-concurrency.test.mjs new file mode 100644 index 00000000..39d9c818 --- /dev/null +++ b/apps/headless/test/session-preferences-concurrency.test.mjs @@ -0,0 +1,34 @@ +import assert from 'node:assert/strict' +import { promises as fs } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import test from 'node:test' +import { createTextTurns } from '../src/chat/text-turns.mjs' +import { createEventJournal } from '../src/events/index.mjs' + +const target = 'prefs-race:model' +const provider = { adapter: 'openai', purpose: 'llm', apiHost: 'https://fixture.invalid/v1', enabled: true, models: [{ id: 'model', enabled: true }] } + +test('model settings lookup rechecks CAS and owner immediately before committing', { timeout: 5000 }, async t => { + const dataDir = await fs.mkdtemp(join(await fs.realpath(tmpdir()), 'deva-preferences-race-')) + const journal = createEventJournal() + let lookup = Promise.withResolvers() + const turns = createTextTurns({ dataDir, journal, settings: { getProvider: () => lookup.promise } }) + t.after(async () => { await turns.close(); journal.close(); await fs.rm(dataDir, { recursive: true, force: true }) }) + const { id } = turns.create() + const initial = turns.getPreferences(id) + const slow = turns.patchPreferences(id, { revision: initial.revision, set: { model: target } }) + const rename = await turns.patchPreferences(id, { revision: initial.revision, set: { customTitle: 'fast editor' } }) + lookup.resolve(provider) + await assert.rejects(slow, { status: 409, code: 'preferences_conflict' }) + assert.deepEqual(turns.getPreferences(id), rename) + lookup = Promise.withResolvers() + let activeLogin = true + const afterRevocation = turns.patchPreferences(id, { revision: rename.revision, set: { model: target } }, () => { + if (!activeLogin) throw Object.assign(Error('expired login'), { code: 'AUTH_FAILED' }) + }) + activeLogin = false + lookup.resolve(provider) + await assert.rejects(afterRevocation, { code: 'AUTH_FAILED' }) + assert.deepEqual(turns.getPreferences(id), rename) +}) diff --git a/apps/headless/test/session-preferences.test.mjs b/apps/headless/test/session-preferences.test.mjs new file mode 100644 index 00000000..3afc0407 --- /dev/null +++ b/apps/headless/test/session-preferences.test.mjs @@ -0,0 +1,308 @@ +import assert from 'node:assert/strict' +import { randomBytes, 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 { setTimeout as delay } from 'node:timers/promises' +import test from 'node:test' +import WebSocket from 'ws' +import { createChatStore } from '../dist/chat-core.mjs' +import { requestControl } from '../src/control/socket.mjs' +import { startWorkbench } from '../src/server.mjs' +import { initializeMasterKey } from '../src/storage/vault.mjs' + +const options = { timeout: 15_000 } +const providerId = 'preferences-fixture' +const model = id => `${providerId}:${id}` +const ledger = '_devaHeadlessTextTurns' +const attachments = '_devaHeadlessTurnAttachments' +const prefs = sid => `chats/${sid}/preferences` +const send = (clientRequestId, text, model) => ({ clientRequestId, text, model }) +const reply = `data: ${JSON.stringify({ choices: [{ index: 0, delta: { content: 'confirmed response' }, finish_reason: 'stop' }] })}\n\ndata: [DONE]\n\n` + +async function fixture(t) { + const tmp = await fs.mkdtemp(join(await fs.realpath(tmpdir()), 'deva-preferences-')) + const keyFile = join(tmp, 'master.key') + const password = randomBytes(24).toString('base64url') + const key = randomBytes(24).toString('hex') + const opts = { dataDir: join(tmp, 'deva-home'), keyFile, runDir: join(tmp, 'run'), webDir: join(tmp, 'web'), port: 0 } + const chats = join(opts.dataDir, 'data', 'chats') + const calls = [], failures = [] + const upstream = createServer((req, res) => { + void (async () => { + const chunks = [] + for await (const chunk of req) chunks.push(chunk) + const body = JSON.parse(Buffer.concat(chunks)) + assert.equal(req.url, '/v1/chat/completions') + assert.equal(req.headers.authorization, `Bearer ${key}`) + assert.equal(body.tools?.length ?? 0, 0) + assert.equal(Object.hasOwn(body, 'reasoning_effort'), false) + calls.push(body) + res.writeHead(200, { 'content-type': 'text/event-stream' }) + if (body.messages.at(-1).content === 'hold response') res.flushHeaders() + else res.end(reply) + })().catch(error => { failures.push(error); res.destroy() }) + }) + upstream.listen(0, '127.0.0.1') + await once(upstream, 'listening') + const origin = `http://127.0.0.1:${upstream.address().port}` + opts.businessOptions = { allowedOrigins: [origin] } + let app + t.after(async () => { + await app?.close() + upstream.closeAllConnections() + await new Promise(resolve => upstream.close(resolve)) + await fs.rm(tmp, { recursive: true, force: true }) + assert.deepEqual(failures, []) + }) + await initializeMasterKey(keyFile) + app = await startWorkbench(opts) + const endpoint = (path, method, body, headers = {}) => fetch(`${app.origin}/api/v1/${path}`, { + method, headers: { ...(method === 'GET' ? {} : { origin: app.origin, 'content-type': 'application/json' }), ...headers }, + ...(body === undefined ? {} : { body: Buffer.isBuffer(body) ? body : JSON.stringify(body) }) + }) + function scope(cookie, csrf) { + const raw = (path, method, body, overrides) => endpoint(path, method, body, { cookie, 'x-deva-csrf': csrf, ...overrides }) + return { + cookie, raw, + request: async (path, method = 'GET', body, status = 200, overrides) => { + const r = await raw(path, method, body, overrides) + const json = await r.json() + assert.equal(r.status, status, `${method} ${path}: ${JSON.stringify(json)}`) + return json + } + } + } + async function login(path = 'auth/login', body = { password }) { + const r = await endpoint(path, 'POST', body) + assert.equal(r.status, 200) + return scope(r.headers.get('set-cookie').split(';')[0], (await r.json()).csrf) + } + const { credential } = await requestControl({ runDir: opts.runDir, op: 'claim' }) + let owner = await login('auth/claim', { credential, password }) + const request = (...args) => owner.request(...args) + const { revision } = await request('settings') + const config = await request('settings', 'PATCH', { revision, set: { models: { activeModelId: model('first'), activeEffort: 'default', providers: [{ + id: providerId, name: 'Preferences fixture', kind: 'custom', purpose: 'llm', adapter: 'openai', accent: '#234567', + apiHost: `${origin}/v1`, enabled: true, models: ['first', 'gpt-5.2', 'role', 'disabled'].map(id => ({ id, name: id, enabled: id !== 'disabled' })) + }] } } }) + await request(`provider-keys/${providerId}`, 'PUT', { value: key, revision: config.revision }) + async function complete(sid, body, status = 202) { + const ack = await request(`chats/${sid}/turns`, 'POST', body, status) + for (let n = 0; n < 150; n++) { + const { state } = await request(`chats/${sid}`) + if (!state.active && state.lastTurn?.turnId === ack.turnId) return state + await delay(10) + } + assert.fail('model stream did not end') + } + return { + opts, chats, calls, origin, key, request, login, complete, endpoint, + get owner() { return owner }, get originWeb() { return app.origin }, + async restart() { await app.close(); app = await startWorkbench(opts); owner = await login() }, + async disk(sid) { return JSON.parse(await fs.readFile(join(chats, `${sid}.json`), 'utf8')) } + } +} + +test('owner HTTP preferences enforce same scope, two-tab CAS, quiet no-op and native desktop ordering', options, async t => { + const fx = await fixture(t) + const { request } = fx + const [sid, other, legacy, complex] = Array.from({ length: 4 }, randomUUID) + await fs.mkdir(fx.chats, { recursive: true }) + const privateRoot = '/private/never-serialize-this-folder' + const nativeSeed = { title: 'Desktop', createdAt: 1, updatedAt: 11, messages: [] } + await fs.writeFile(join(fx.chats, `${legacy}.json`), JSON.stringify({ id: legacy, ...nativeSeed })) + await fs.writeFile(join(fx.chats, `${complex}.json`), JSON.stringify({ id: complex, ...nativeSeed, focusRoot: privateRoot, members: [{ sessionId: legacy }] })) + assert.equal((await fx.endpoint(prefs(sid), 'GET')).status, 401) + assert.equal((await fx.endpoint(prefs(sid), 'PATCH', { set: { archived: true } })).status, 401) + assert.deepEqual(await request(prefs(randomUUID()), 'GET', undefined, 404), { error: 'session_not_found' }) + assert.deepEqual(await request(prefs(legacy), 'GET', undefined, 409), { error: 'read_only_session' }) + assert.deepEqual(await request(prefs(complex), 'GET', undefined, 409), { error: 'unsupported_history' }) + assert.deepEqual(await request(prefs(complex), 'PATCH', { revision: 'a'.repeat(64), set: { archived: true } }, 409), { error: 'unsupported_history' }) + const { session } = await request('chats', 'POST', { sessionId: sid }) + await request('chats', 'POST', { sessionId: other }) + const tab = await fx.login() + const first = await request(prefs(sid)) + assert.deepEqual(first.preferences, { title: '', customTitle: null, archived: false, model: null, effort: null }) + assert.deepEqual(await tab.request(prefs(sid)), first) + assert.deepEqual(await request(prefs(other), 'PATCH', { revision: first.revision, set: { archived: true } }, 409), { error: 'preferences_conflict' }) + assert.deepEqual(await request(prefs(sid), 'PATCH', { revision: first.revision, set: { archived: true } }, 401, { 'x-deva-csrf': 'wrong' }), { error: 'auth' }) + assert.deepEqual(await request(prefs(sid), 'PATCH', { revision: first.revision, set: { archived: true } }, 403, { origin: fx.origin }), { error: 'origin' }) + for (const set of [{}, [], { folder: privateRoot }, { apiHost: fx.origin }, { sid: other }, { archived: 'false' }, { title: 'unknown' }, { customTitle: 1 }]) { + assert.deepEqual(await request(prefs(sid), 'PATCH', { revision: first.revision, set }, 400), { error: 'invalid_preferences' }) + } + const ws = new WebSocket(`${fx.originWeb.replace('http:', 'ws:')}/api/v1/chats/stream`, { headers: { origin: fx.originWeb, cookie: tab.cookie } }) + t.after(() => ws.terminate()) + const [initial] = await once(ws, 'message') + assert.equal(JSON.parse(initial).t, 'sessions-snapshot') + const events = [] + ws.on('message', wire => events.push(JSON.parse(wire))) + const changed = once(ws, 'message') + const second = await request(prefs(sid), 'PATCH', { revision: first.revision, set: { customTitle: ' New\n title ', archived: true } }) + const [wire] = await changed + assert.deepEqual(Object.keys(JSON.parse(wire)), ['t', 'cursor']) + assert.equal(JSON.parse(wire).t, 'sessions-changed') + assert.equal(second.preferences.title, 'New title') + assert.equal(second.preferences.customTitle, 'New title') + assert.equal(second.preferences.archived, true) + assert.deepEqual(await tab.request(prefs(sid), 'PATCH', { revision: first.revision, set: { archived: false } }, 409), { error: 'preferences_conflict' }) + const third = await request(prefs(sid), 'PATCH', { revision: second.revision, set: { archived: true } }) + assert.notEqual(third.revision, second.revision) + assert.deepEqual(third.preferences, second.preferences) + await delay(30) + assert.equal(events.length, 1) + const { sessions } = await request('chats') + const entry = sessions.find(s => s.id === sid) + assert.equal(entry.updatedAt, session.updatedAt) + assert.equal(entry.archived, true) + assert.equal(entry.customTitle, 'New title') + const state = (await request(`chats/${sid}`)).state + for (const secret of [privateRoot, fx.opts.dataDir, fx.origin, fx.key]) assert.ok(!JSON.stringify([state, sessions, third]).includes(secret)) + const desktop = createChatStore({ dataDir: fx.opts.dataDir }) + const { title, archived, updatedAt } = desktop.getSession(sid) + assert.deepEqual({ title, archived, updatedAt }, { title: 'New title', archived: true, updatedAt: session.updatedAt }) + assert.deepEqual(desktop.listSessions().map(s => s.id), sessions.map(s => s.id)) + await fx.restart() + assert.deepEqual(await request(prefs(sid)), third) + const reset = await request(prefs(sid), 'PATCH', { revision: third.revision, set: { archived: false, customTitle: '' } }) + assert.deepEqual(reset.preferences, first.preferences) + assert.notEqual(reset.revision, first.revision) + assert.equal(Object.hasOwn(await fx.disk(sid), 'archived'), false) + assert.deepEqual(await request(prefs(sid), 'PATCH', { revision: first.revision, set: { archived: true } }, 409), { error: 'preferences_conflict' }) + assert.equal(fx.calls.length, 0) +}) + +test('ordinary pins and follow intents affect later real provider wire without changing old charge receipts', options, async t => { + const fx = await fixture(t) + const { request, complete } = fx + const { session: { id: sid } } = await request('chats', 'POST', {}) + const firstBody = send('legacy-accepted', 'first question', model('first')) + await complete(sid, firstBody) + const firstDisk = await fx.disk(sid) + const first = await request(prefs(sid)) + assert.equal(first.preferences.title, firstBody.text) + assert.equal(first.preferences.model, model('first')) + assert.deepEqual(await request(prefs(sid), 'PATCH', { revision: first.revision, set: { model: model('disabled') } }, 422), { error: 'model_not_enabled' }) + assert.deepEqual(await request(prefs(sid), 'PATCH', { revision: first.revision, set: { model: model('gpt-5.2'), effort: 'high' } }, 422), { error: 'effort_unsupported' }) + assert.deepEqual(await request(prefs(sid), 'PATCH', { revision: first.revision, set: { effort: 'turbo' } }, 400), { error: 'invalid_effort' }) + const pin = await request(prefs(sid), 'PATCH', { revision: first.revision, set: { model: model('gpt-5.2'), customTitle: 'Pinned session', effort: 'default' } }) + assert.equal(pin.preferences.effort, 'default') + assert.equal(fx.calls.length, 1) + const afterPin = await fx.disk(sid) + assert.deepEqual(afterPin[ledger], firstDisk[ledger]) + assert.deepEqual(afterPin.messages, firstDisk.messages) + assert.equal(afterPin.updatedAt, firstDisk.updatedAt) + assert.equal((await request(`chats/${sid}/turns`, 'POST', firstBody)).duplicate, true) + assert.equal(fx.calls.length, 1) + for (const wrong of [null, model('first')]) { + assert.deepEqual(await request(`chats/${sid}/turns`, 'POST', send('new', 'stale', wrong), 409), { error: 'session_model_changed' }) + } + const busy = await request(`chats/${sid}/turns`, 'POST', send('busy', 'hold response', model('gpt-5.2')), 202) + assert.deepEqual(await request(prefs(sid), 'PATCH', { revision: pin.revision, set: { archived: true } }, 409), { error: 'turn_in_progress' }) + const stop = await request(`chats/${sid}/stop`, 'POST', { turnId: busy.turnId }) + assert.equal(stop.stopped, true) + await complete(sid, send('busy', 'hold response', model('gpt-5.2')), 200) + const pinned = await complete(sid, send('wire-pin', 'pin reaches wire', model('gpt-5.2'))) + assert.equal(fx.calls.at(-1).model, 'gpt-5.2') + assert.equal(pinned.model, model('gpt-5.2')) + assert.deepEqual(await request(prefs(sid)), pin) + const follow = await request(prefs(sid), 'PATCH', { revision: pin.revision, set: { model: null, customTitle: null, effort: null } }) + assert.deepEqual(follow.preferences, { title: firstBody.text, customTitle: null, archived: false, model: null, effort: null }) + const follows = send('follow', 'first default', null) + const firstFollow = await complete(sid, follows) + assert.equal(firstFollow.model, null) + assert.equal(fx.calls.at(-1).model, 'first') + assert.equal((await fx.disk(sid)).model, '') + const { revision } = await request('settings') + await request('settings', 'PATCH', { revision, set: { models: { activeModelId: model('gpt-5.2') } } }) + const count = fx.calls.length + assert.equal((await request(`chats/${sid}/turns`, 'POST', follows)).duplicate, true) + assert.equal(fx.calls.length, count) + const last = await complete(sid, send('second-follow', 'second default', null)) + assert.equal(last.model, null) + assert.equal(fx.calls.at(-1).model, 'gpt-5.2') + const stored = await fx.disk(sid) + assert.equal(stored.model, '') + assert.equal(stored[ledger].requests.find(r => r.clientRequestId === 'follow').model, model('first')) + assert.equal(stored[ledger].requests.find(r => r.clientRequestId === 'second-follow').model, model('gpt-5.2')) + await fx.restart() + assert.deepEqual(await request(prefs(sid)), follow) + assert.equal((await request(`chats/${sid}/turns`, 'POST', firstBody)).duplicate, true) + assert.equal((await request(`chats/${sid}/turns`, 'POST', follows)).duplicate, true) + assert.equal(fx.calls.length, count + 1) +}) + +test('verified role and attachment history survive metadata edits and strict disk failures are explicit', options, async t => { + const fx = await fixture(t) + const { request, complete } = fx + const persona = { name: 'Preferences tester', prompt: 'Use a clear tone.', model: model('role'), enabled: true } + const { role } = await request('personas', 'POST', persona) + const { session: { id: sid } } = await request('chats', 'POST', { personaId: role.id }) + const initial = await request(prefs(sid)) + const follow = await request(prefs(sid), 'PATCH', { revision: initial.revision, set: { model: null } }) + const fileName = 'research notes.txt' + const { attachment } = await request(`chats/${sid}/attachments`, 'POST', Buffer.from('Fixture attachment bytes\n'), 201, + { 'content-type': 'application/octet-stream', 'x-deva-file-name': Buffer.from(fileName).toString('base64url'), 'x-deva-file-type': 'text/plain' }) + const attached = { ...send('with-attachment', '', null), attachments: [attachment.id] } + const first = await complete(sid, attached) + assert.equal(first.title, fileName) + assert.equal(first.model, null) + assert.deepEqual(first.messages[0].attachments, [attachment]) + assert.equal(fx.calls.at(-1).model, 'role') + const before = await fx.disk(sid) + const rev = await request(prefs(sid)) + assert.notEqual(rev.revision, follow.revision) + const renamed = await request(prefs(sid), 'PATCH', { revision: rev.revision, set: { customTitle: 'Documents', archived: true } }) + const reset = await request(prefs(sid), 'PATCH', { revision: renamed.revision, set: { customTitle: null, archived: false } }) + assert.equal(reset.preferences.title, fileName) + assert.equal(reset.preferences.customTitle, null) + const committed = await fx.disk(sid) + for (const field of [ledger, attachments, 'messages', 'updatedAt']) assert.deepEqual(committed[field], before[field]) + await request(`personas/${role.id}`, 'PATCH', { revision: role.revision, ...persona, model: model('gpt-5.2') }) + await complete(sid, send('after-role-update', 'With current role', null)) + assert.equal(fx.calls.at(-1).model, 'gpt-5.2') + assert.equal(fx.calls.at(-1).messages.some(m => m.role === 'user' && m.content.includes('Fixture attachment bytes')), true) + const candidate = await request(prefs(sid)) + const path = join(fx.chats, `${sid}.json`) + const checked = await fx.disk(sid) + // A writable parent can replace a 0400 inode, but a preference request must still respect read-only mode. + await fs.chmod(path, 0o400) + assert.deepEqual(await request(prefs(sid)), candidate) + assert.deepEqual(await request(prefs(sid), 'PATCH', { revision: candidate.revision, set: { archived: true } }, 503), { error: 'chat_storage_unconfirmed' }) + assert.deepEqual(await fx.disk(sid), checked) + await fs.chmod(path, 0o640) + assert.deepEqual(await request(prefs(sid), 'PATCH', { revision: candidate.revision, set: { archived: true } }, 503), { error: 'chat_storage_unconfirmed' }) + assert.deepEqual(await fx.disk(sid), checked) + await fs.chmod(path, 0o600) + const oversized = randomUUID() + const oversizedPath = join(fx.chats, `${oversized}.json`) + await fs.writeFile(oversizedPath, '{}', { mode: 0o600 }) + await fs.truncate(oversizedPath, 128 * 1024 * 1024 + 1) + assert.deepEqual(await request(prefs(oversized), 'GET', undefined, 503), { error: 'chat_storage_unconfirmed' }) + await fs.unlink(oversizedPath) + const drifted = { ...checked, title: 'External native edit' } + await fs.writeFile(path, JSON.stringify(drifted)) + assert.deepEqual(await request(prefs(sid), 'PATCH', { revision: candidate.revision, set: { archived: true } }, 409), { error: 'preferences_conflict' }) + assert.deepEqual(await request(prefs(sid), 'GET', undefined, 503), { error: 'chat_storage_unconfirmed' }) + assert.deepEqual(await fx.disk(sid), drifted) + await fx.restart() + const fresh = await request(prefs(sid)) + assert.equal(fresh.preferences.title, drifted.title) + const index = join(fx.chats, '_index.json') + await fs.unlink(index) + await fs.mkdir(index) + assert.deepEqual(await request(prefs(sid), 'PATCH', { revision: fresh.revision, set: { archived: true } }, 503), { error: 'chat_storage_unconfirmed' }) + assert.deepEqual(await request(prefs(sid), 'GET', undefined, 503), { error: 'chat_storage_unconfirmed' }) + assert.deepEqual(await request(prefs(sid), 'PATCH', { revision: fresh.revision, set: { archived: false } }, 503), { error: 'chat_storage_unconfirmed' }) + await fs.rmdir(index) + const count = fx.calls.length + await fx.restart() + const recovered = await request(prefs(sid)) + assert.equal(recovered.preferences.archived, true) + assert.notEqual(recovered.revision, fresh.revision) + assert.deepEqual((await request(`chats/${sid}`)).state.messages[0].attachments, [attachment]) + assert.equal((await request(`chats/${sid}/turns`, 'POST', attached)).duplicate, true) + assert.equal(fx.calls.length, count) +}) From bf482797815baf9dc70f884219c6fbbcb66031f4 Mon Sep 17 00:00:00 2001 From: Facetomyself <[GIT_EMAIL]> Date: Thu, 26 Nov 2026 15:55:11 +0800 Subject: [PATCH 3/6] =?UTF-8?q?feat(workbench):=20=E5=AF=B9=E9=BD=90?= =?UTF-8?q?=E5=AF=B9=E8=AF=9D=E6=95=B4=E7=90=86=E5=B9=B6=E6=A0=A1=E9=AA=8C?= =?UTF-8?q?=E8=B7=A8=E9=A1=B5=E9=9D=A2=E8=81=94=E5=8A=A8=20/=20manage=20co?= =?UTF-8?q?nversations=20and=20verify=20cross-window=20updates?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/ci.yml | 4 + apps/desktop/src/workbench/chat-copy.ts | 4 + apps/desktop/src/workbench/chat-transport.ts | 6 +- apps/desktop/src/workbench/session-list.ts | 44 ++ .../src/workbench/session-preference-ui.tsx | 116 ++++++ .../src/workbench/session-preferences.ts | 160 ++++++++ apps/desktop/src/workbench/sessions-stream.ts | 84 ++++ apps/desktop/src/workbench/text-workbench.css | 11 + apps/desktop/src/workbench/text-workbench.tsx | 151 +++++-- apps/desktop/src/workbench/transport.ts | 3 +- .../src/workbench/use-text-workbench.ts | 81 ++-- apps/headless/README.md | 6 + apps/headless/src/chat/README.md | 3 + docs/development/web-workbench/README.md | 2 +- .../web-workbench/parity-manifest.json | 14 +- scripts/workbench/e2e-sessions.mjs | 376 ++++++++++++++++++ .../workbench/session-management-ui.test.mjs | 266 +++++++++++++ 17 files changed, 1252 insertions(+), 79 deletions(-) create mode 100644 apps/desktop/src/workbench/session-list.ts create mode 100644 apps/desktop/src/workbench/session-preference-ui.tsx create mode 100644 apps/desktop/src/workbench/session-preferences.ts create mode 100644 apps/desktop/src/workbench/sessions-stream.ts create mode 100644 scripts/workbench/e2e-sessions.mjs create mode 100644 scripts/workbench/session-management-ui.test.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0c11fada..1c9b81a1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -58,6 +58,10 @@ jobs: timeout-minutes: 5 run: node scripts/workbench/e2e-attachments.mjs + - name: Verify conversation preferences across two independent owner logins + timeout-minutes: 5 + run: node scripts/workbench/e2e-sessions.mjs + - name: Select the same installed Chrome for UI and worker run: bash scripts/workbench/ci-select-chromium.sh diff --git a/apps/desktop/src/workbench/chat-copy.ts b/apps/desktop/src/workbench/chat-copy.ts index 7ef344ff..d3f9f063 100644 --- a/apps/desktop/src/workbench/chat-copy.ts +++ b/apps/desktop/src/workbench/chat-copy.ts @@ -19,6 +19,8 @@ export function chatCopy(locale: Locale) { selectModel: 'Select an enabled model. Configure providers, keys and models in Model settings.', turnFailure: 'Could not confirm the message. The draft was kept; sending the same draft retries the same request.', busy: 'A reply is already in progress in this conversation.', modelFailure: 'Check the selected model and provider in Model settings.', + preferencesChanged: 'This conversation’s model changed. Your draft is still here. Check the refreshed selection before sending again.', + effortUnavailable: 'Workbench does not support the saved thinking level. Your draft is still here.', listFailure: 'Could not load conversations.', createFailure: 'Could not confirm a new conversation. Try New conversation again.', stopFailure: 'Could not confirm the stop request.', reloadList: 'Retry', limits: '{turns} turns per conversation · 12 KiB input · 65,536 UTF-16 code units of output', input: 'Message the assistant…', inputLimit: 'Messages can contain up to 12 KiB of UTF-8 text.', previous: 'Show earlier messages' @@ -39,6 +41,8 @@ export function chatCopy(locale: Locale) { selectModel: '请选择已启用的模型。可在模型设置中配置服务商、密钥和模型。', turnFailure: '消息发送结果尚未确认。已保留草稿,再次提交原草稿会使用同一个请求。', busy: '这段对话已有一条回复正在进行。', modelFailure: '请在模型设置中检查所选模型和服务商。', + preferencesChanged: '对话模型已变更。草稿已保留,请核对同步后的模型再发送。', + effortUnavailable: '已保存的思考档位在工作台中尚未开放。草稿已保留。', listFailure: '加载对话列表失败。', createFailure: '新建对话的结果尚未确认,可再次点击新建对话。', stopFailure: '停止请求的结果尚未确认。', reloadList: '重试', limits: '每段对话 {turns} 轮 · 输入 12 KiB · 输出 65,536 个 UTF-16 码元', input: '跟助手说点什么…', inputLimit: '单条消息最多 12 KiB UTF-8 文本。', previous: '显示更早的消息' diff --git a/apps/desktop/src/workbench/chat-transport.ts b/apps/desktop/src/workbench/chat-transport.ts index 2c99542e..6113371f 100644 --- a/apps/desktop/src/workbench/chat-transport.ts +++ b/apps/desktop/src/workbench/chat-transport.ts @@ -27,6 +27,8 @@ export interface ChatSummary { updatedAt: number model: string | null personaId?: string + archived?: boolean + customTitle?: string compatibility: 'text' | 'legacy_text' | 'unsupported' writable: boolean } @@ -52,7 +54,7 @@ export interface ChatSnapshot { cursor: ChatCursor; state: ChatState } export type ChatFrame = ({ t: 'snapshot' } & ChatSnapshot) | { t: 'event'; cursor: ChatCursor; sessionId: string; turnId: string; type: 'chat'; event: { type: string; text?: string } } -export interface TurnRequest { clientRequestId: string; text: string; model: string; attachments?: string[] } +export interface TurnRequest { clientRequestId: string; text: string; model: string | null; attachments?: string[] } type TurnDraft = Omit export function sameTurnDraft(a: TurnDraft | undefined, b: TurnDraft): boolean { @@ -79,6 +81,8 @@ function message(value: unknown): value is ChatMessage { function summary(value: unknown): value is Omit { return record(value) && id(value.id) && typeof value.title === 'string' && nullableString(value.model) && (value.personaId === undefined || isRoleId(value.personaId)) && + (value.archived === undefined || typeof value.archived === 'boolean') && + (value.customTitle === undefined || typeof value.customTitle === 'string') && (value.compatibility === 'text' || value.compatibility === 'legacy_text' || value.compatibility === 'unsupported') && typeof value.writable === 'boolean' } diff --git a/apps/desktop/src/workbench/session-list.ts b/apps/desktop/src/workbench/session-list.ts new file mode 100644 index 00000000..5fc38494 --- /dev/null +++ b/apps/desktop/src/workbench/session-list.ts @@ -0,0 +1,44 @@ +import type { ChatSummary } from './chat-transport' + +export function sessionAfterRefresh(sessions: ChatSummary[], selected: string | null, saved: string | null, grouped: boolean): string | null { + // A list invalidation is not a navigation action. In the owner workbench an archived (or now missing) + // selected conversation keeps its pane and drafts until the user chooses another conversation. + if (grouped && selected) return selected + const wanted = selected ?? saved + if (wanted && sessions.some((row) => row.id === wanted)) return wanted + return (grouped ? sessions.find((row) => !row.archived) : undefined)?.id ?? sessions[0]?.id ?? null +} + +/** At most one GET in flight, plus one trailing GET for all invalidations received during it. */ +export function createListRefresh(read: () => Promise, updated: (value: T) => void, failed: (error: unknown) => void) { + let active = true + let pending = false + let running = false + let revision = 0 + async function run(): Promise { + while (active && pending) { + pending = false + const expected = revision + try { + const next = await read() + if (active && revision === expected) updated(next) + } catch (error) { + if (active && revision === expected) failed(error) + } + } + running = false + } + function request(): void { + if (!active) return + pending = true + if (running) return + running = true + queueMicrotask(() => void run()) + } + return { + request, + // A locally acknowledged mutation is newer than any outstanding read started before it. + afterWrite() { ++revision; request() }, + close() { active = false } + } +} diff --git a/apps/desktop/src/workbench/session-preference-ui.tsx b/apps/desktop/src/workbench/session-preference-ui.tsx new file mode 100644 index 00000000..51646465 --- /dev/null +++ b/apps/desktop/src/workbench/session-preference-ui.tsx @@ -0,0 +1,116 @@ +import { useEffect, useId, useRef } from 'react' +import { Archive, ArchiveRestore, Check, ChevronDown, Pencil } from 'lucide-react' +import { Modal } from '../renderer/src/components/Modal' +import { useI18n } from '../renderer/src/i18n/i18n' +import { ModelMenu, ModelSelectButton } from '../renderer/src/redesign/ModelMenu' +import { normalizeTitle, type PreferenceEntry, type PreferenceIssue, type SessionPreferenceController } from './session-preferences' + +const labels = { + en: { + conflict: 'These preferences changed elsewhere. Your draft is still here. Reload the saved preferences before applying changes again.', + busy: 'This conversation has a reply in progress. Try again once it ends.', + readOnly: 'Preferences for this desktop history are read-only in Workbench.', + missing: 'This conversation is no longer available.', + storage: 'The save was not confirmed in storage. Reload the saved preferences to check the result.', + invalid: 'The server rejected this preference. Check the title or the model enabled in settings.', + readFailure: 'Could not load saved conversation preferences.', + writeFailure: 'Could not confirm the save. Reload the saved preferences to check the result.', + reload: 'Reload saved preferences', saving: 'Saving preferences…', loading: 'Loading preferences…', + follow: 'Follow default', actions: 'Conversation actions' + }, + 'zh-CN': { + conflict: '其他窗口已更改会话设置。草稿已保留;请重新读取已保存的设置,再提交修改。', + busy: '这段对话有一条回复正在进行,请在回复结束后重试。', + readOnly: '这段桌面历史的会话设置在工作台中为只读。', + missing: '这段对话已失效。', + storage: '保存结果尚未在存储中确认,请重新读取已保存的设置核对结果。', + invalid: '服务端未接受这项设置,请检查标题或模型设置中的启用状态。', + readFailure: '加载已保存的会话设置失败。', + writeFailure: '保存结果尚未确认,请重新读取已保存的设置核对结果。', + reload: '重读已保存的设置', saving: '正在保存会话设置…', loading: '正在读取会话设置…', + follow: '跟随默认', actions: '会话操作' + } +} satisfies Record> + +export function SessionPreferenceStatus({ entry, reload, locked }: { + entry: PreferenceEntry; reload: () => void; locked?: boolean +}): React.JSX.Element | null { + const { locale } = useI18n() + const c = labels[locale] + if (entry.pending) return

{c.saving}

+ if (!entry.issue) return entry.reading && !entry.confirmed ?

{c.loading}

: null + return
+ {c[entry.issue]}{' '} + {entry.needsRead && } +
+} + +export function SessionHeaderActions({ archived, blocked, disabled, rename, archive }: { + archived: boolean; blocked?: string; disabled: boolean; rename: () => void; archive: () => void +}): React.JSX.Element { + const { t, locale } = useI18n() + return
+ {archived && {t('cf.archivedTag')}} + + +
+} + +export function SessionRenameDialog({ sid, entry, store, disabled, close, reload }: { + sid: string; entry: PreferenceEntry; store: SessionPreferenceController; disabled: boolean; close: () => void; reload: () => void +}): React.JSX.Element | null { + const { t } = useI18n() + const field = useRef(null) + const id = useId() + useEffect(() => { field.current?.select() }, []) + const draft = entry.draft + if (!draft) return null + const title = normalizeTitle(draft.text) + const unchanged = title === draft.initial + const ready = !disabled && !entry.reading && !entry.pending && !entry.needsRead && !unchanged + const cancel = (): void => { if (!entry.pending) { store.discardRename(sid); close() } } + const save = (): void => { if (ready) void store.saveRename(sid).then((ok) => { if (ok) close() }) } + return +

{t('cf.renameChatTitle')}

+
+ store.editRename(sid, event.target.value)} + onKeyDown={(event) => { if (event.key === 'Enter' && !event.nativeEvent.isComposing) save() }} /> +
+ +
+ + +
+
+} + +type ModelButton = Parameters[0] +export function SessionModelPicker({ open, active, groups, onToggle, onPick, follow, pinned, disabled }: ModelButton & { + follow: () => void; pinned: string | null | undefined; disabled: boolean +}): React.JSX.Element { + const { t, locale } = useI18n() + const c = labels[locale] + const name = pinned === null ? c.follow : active?.model.name ?? pinned ?? t('chat.selectModel') + const id = useId() + return <> + + {open && !disabled &&
+ + +
} + +} diff --git a/apps/desktop/src/workbench/session-preferences.ts b/apps/desktop/src/workbench/session-preferences.ts new file mode 100644 index 00000000..37c09c73 --- /dev/null +++ b/apps/desktop/src/workbench/session-preferences.ts @@ -0,0 +1,160 @@ +import type { ChatSummary } from './chat-transport' +import { HttpFailure, type Revision, type Transport } from './transport' + +export interface SessionPreferences { + title: string + customTitle: string | null + archived: boolean + model: string | null + effort: string | null +} +export interface PreferenceSnapshot { preferences: SessionPreferences; revision: Revision } +export type PreferenceSet = Partial> + +function record(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} +function nullableString(value: unknown): value is string | null { return value === null || typeof value === 'string' } +function parse(value: unknown): PreferenceSnapshot { + if (!record(value) || !record(value.preferences)) throw new Error('Invalid session preferences') + const { title, customTitle, archived, model, effort } = value.preferences + const { revision } = value + if (typeof title !== 'string' || !nullableString(customTitle) || typeof archived !== 'boolean' || !nullableString(model) || !nullableString(effort) || + !((typeof revision === 'string' && revision.length > 0) || (typeof revision === 'number' && Number.isSafeInteger(revision)))) + throw new Error('Invalid session preferences') + return { preferences: { title, customTitle, archived, model, effort }, revision } +} +export function createPreferenceTransport(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}/preferences` + } + return { + async read(sid: string): Promise { return parse(await transport.request(path(sid))) }, + async patch(sid: string, revision: Revision, set: PreferenceSet): Promise { + return parse(await transport.request(path(sid), 'PATCH', { revision, set }, csrf)) + } + } +} + +type PreferenceTransport = ReturnType +export type PreferenceIssue = 'conflict' | 'busy' | 'readOnly' | 'missing' | 'storage' | 'invalid' | 'readFailure' | 'writeFailure' +export interface RenameDraft { text: string; initial: string; revision: Revision } +export interface PreferenceEntry { + confirmed?: PreferenceSnapshot + reading?: boolean + pending?: PreferenceSet + draft?: RenameDraft + issue?: PreferenceIssue + needsRead?: boolean +} +const empty: PreferenceEntry = {} + +function failure(error: unknown, reading: boolean): PreferenceIssue { + if (error instanceof HttpFailure) { + if (error.code === 'turn_in_progress') return 'busy' + if (error.code === 'preferences_conflict') return 'conflict' + if (error.code === 'chat_storage_unconfirmed') return 'storage' + if (error.code === 'read_only_session' || error.code === 'unsupported_history') return 'readOnly' + if (error.status === 400 || error.status === 422 || error.code === 'provider_not_found') return 'invalid' + if (error.status === 404) return 'missing' + if (error.status === 409) return 'conflict' + } + return reading ? 'readFailure' : 'writeFailure' +} + +export const normalizeTitle = (text: string): string => text.replace(/\s+/g, ' ').trim() +export function matchesPreferences(row: ChatSummary, confirmed: PreferenceSnapshot | undefined): boolean { + const p = confirmed?.preferences + return !!p && p.title === row.title && p.customTitle === (row.customTitle ?? null) && + p.archived === (row.archived === true) && p.model === row.model +} +export function projectSession(row: ChatSummary, change: PreferenceSet | undefined): ChatSummary { + if (!change) return row + return { ...row, title: change.customTitle ?? row.title, archived: change.archived ?? row.archived, + model: change.model === undefined ? row.model : change.model } +} + +/** Revisions and draft baselines belong to the session, never to the currently mounted controls. */ +export function createSessionPreferences(api: PreferenceTransport, options: { + beforeWrite: () => Promise + expired: () => void + committed: (sid: string, preferences: SessionPreferences) => void + blocked: (sid: string, issue: PreferenceIssue) => void +}) { + const entries = new Map() + const subscribers = new Set<() => void>() + let version = 0 + let revoked = false + const get = (sid: string): PreferenceEntry => entries.get(sid) ?? empty + function put(sid: string, patch: Partial): void { + entries.set(sid, { ...get(sid), ...patch }) + ++version + subscribers.forEach((notify) => notify()) + } + function expired(error: unknown): boolean { + if (revoked) return true + if (!(error instanceof HttpFailure) || error.status !== 401) return false + revoked = true + options.expired() + return true + } + async function read(sid: string, explicit = false): Promise { + const current = get(sid) + if (revoked || current.reading || current.pending || (!explicit && current.needsRead)) return + put(sid, { reading: true }) + try { + const confirmed = await api.read(sid) + if (revoked) return + const draft = get(sid).draft + // Only an explicit reread can rebase an edit. A new background snapshot must not make a stale draft writable. + put(sid, { confirmed, issue: explicit ? undefined : current.issue, needsRead: false, ...(explicit && draft ? { + draft: { text: draft.text, initial: confirmed.preferences.title, revision: confirmed.revision } + } : {}) }) + } catch (error) { + if (!expired(error)) put(sid, { issue: failure(error, true), needsRead: true }) + } finally { put(sid, { reading: false }) } + } + async function write(sid: string, set: PreferenceSet, fromDraft = false): Promise { + const current = get(sid) + if (revoked || !current.confirmed || current.reading || current.pending || current.needsRead || (fromDraft && !current.draft)) return false + const revision = fromDraft ? current.draft!.revision : current.confirmed.revision + put(sid, { pending: set, issue: undefined }) + try { + await options.beforeWrite() + if (revoked) return false + const confirmed = await api.patch(sid, revision, set) + if (revoked) return false + options.committed(sid, confirmed.preferences) + put(sid, { confirmed, ...(fromDraft ? { draft: undefined } : {}) }) + return true + } catch (error) { + if (!expired(error)) { + const issue = failure(error, false) + put(sid, { issue, needsRead: issue !== 'busy' && issue !== 'invalid' }) + options.blocked(sid, issue) + } + return false + } finally { put(sid, { pending: undefined }) } + } + return { + get, read, write, version: () => version, + subscribe(notify: () => void) { subscribers.add(notify); return () => { subscribers.delete(notify) } }, + beginRename(sid: string) { + const { confirmed, draft } = get(sid) + if (!confirmed || draft) return + const { title } = confirmed.preferences + put(sid, { draft: { text: title, initial: title, revision: confirmed.revision } }) + }, + editRename(sid: string, text: string) { + const { draft, pending } = get(sid) + if (draft && !pending) put(sid, { draft: { ...draft, text } }) + }, + discardRename(sid: string) { if (!get(sid).pending) put(sid, { draft: undefined }) }, + saveRename(sid: string) { + const { draft } = get(sid) + return draft ? write(sid, { customTitle: normalizeTitle(draft.text) || null }, true) : Promise.resolve(false) + } + } +} +export type SessionPreferenceController = ReturnType diff --git a/apps/desktop/src/workbench/sessions-stream.ts b/apps/desktop/src/workbench/sessions-stream.ts new file mode 100644 index 00000000..304c2c90 --- /dev/null +++ b/apps/desktop/src/workbench/sessions-stream.ts @@ -0,0 +1,84 @@ +type Cursor = { epoch: string; generation: string; scope: 'sessions'; seq: number } +type Frame = { t: 'sessions-snapshot' | 'sessions-changed'; cursor: Cursor } +type Socket = Pick + +function record(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} +export function parseSessionsFrame(data: unknown): Frame | null { + if (typeof data !== 'string') return null + try { + const value: unknown = JSON.parse(data) + if (!record(value) || Object.keys(value).length !== 2 || (value.t !== 'sessions-snapshot' && value.t !== 'sessions-changed')) return null + const c = value.cursor + if (!record(c) || Object.keys(c).length !== 4 || c.scope !== 'sessions' || typeof c.epoch !== 'string' || !c.epoch || + typeof c.generation !== 'string' || !c.generation || typeof c.seq !== 'number' || !Number.isSafeInteger(c.seq) || c.seq < 0) return null + return { t: value.t, cursor: { scope: c.scope, epoch: c.epoch, generation: c.generation, seq: c.seq } } + } catch { return null } +} +function streamUrl(origin: string): string { + const url = new URL('/api/v1/chats/stream', origin) + if (url.protocol === 'https:') url.protocol = 'wss:' + else if (url.protocol === 'http:') url.protocol = 'ws:' + else throw new Error('Invalid workbench origin') + return url.href +} + +/** Only the GET supplies list data. Each connection begins with a fresh authoritative invalidation. */ +export function createSessionsStream({ origin, invalidate, expired, open = (url) => new WebSocket(url), + schedule = (fn, ms) => { const id = setTimeout(fn, ms); return () => clearTimeout(id) } +}: { + origin: string + invalidate: () => void + expired: () => void + open?: (url: string) => Socket + schedule?: (callback: () => void, ms: number) => () => void +}) { + let active = true + let socket: Socket | undefined + let timer: (() => void) | undefined + let failures = 0 + function clearTimer(): void { timer?.(); timer = undefined } + function disconnect(): void { + clearTimer() + const old = socket + socket = undefined + if (old) { old.onmessage = old.onclose = null; old.close() } + } + function retry(recheck: boolean): void { + disconnect() + if (!active) return + if (recheck) invalidate() // Also checks cookie expiry if the browser hides the failed upgrade's HTTP status. + timer = schedule(connect, Math.min(500 * 2 ** failures++, 8000)) + } + function connect(): void { + if (!active) return + disconnect() + let ws: Socket + try { ws = open(streamUrl(origin)) } catch { retry(true); return } + socket = ws + let cursor: Cursor | undefined + ws.onmessage = ({ data }) => { + if (!active || socket !== ws) return + const frame = parseSessionsFrame(data) + if (!frame || (!cursor && frame.t !== 'sessions-snapshot')) { retry(true); return } + const next = frame.cursor + if (cursor && (next.epoch !== cursor.epoch || next.generation !== cursor.generation)) { + if (frame.t !== 'sessions-snapshot') { retry(true); return } + } else if (cursor && next.seq <= cursor.seq) return + // A gap is legal when the server coalesces invalidations; one GET reads through that watermark. + cursor = next + clearTimer() + failures = 0 + invalidate() + } + ws.onclose = ({ code, reason }) => { + if (!active || socket !== ws) return + if (code === 1008 && reason === 'auth') { active = false; disconnect(); expired(); return } + retry(!cursor) + } + timer = schedule(() => retry(true), 5000) + } + connect() + return { close() { active = false; disconnect() } } +} diff --git a/apps/desktop/src/workbench/text-workbench.css b/apps/desktop/src/workbench/text-workbench.css index 546b3892..74722a09 100644 --- a/apps/desktop/src/workbench/text-workbench.css +++ b/apps/desktop/src/workbench/text-workbench.css @@ -19,6 +19,17 @@ .wb-chat .wb-attachment__draft-status { display: flex; gap: 8px; justify-content: space-between; padding: 0 10px; font-size: 12px; overflow-wrap: anywhere; } .wb-chat .wb-attachment__hint { margin: 4px 0 0; padding-inline: 10px; font-size: 12px; color: var(--fg-muted); } .wb-chat .wb-attachment__preview-failed { text-align: center; font-size: 10px; padding: 2px; color: var(--fg-muted); } +.wb-chat .wb-session-prefs__archive-link { display: inline-flex; gap: 4px; width: auto; min-width: 28px; padding-inline: 6px; } +.wb-chat .wb-session-prefs__archive-link .cf-rail__count { margin-right: 0; } +.wb-chat .wb-session-prefs__actions { display: flex; flex-shrink: 0; align-items: center; gap: 4px; } +.wb-chat .wb-session-prefs__actions .cf-conv__tag { margin-left: 0; } +.wb-chat .wb-session-prefs__actions button:disabled, .wb-chat .cf-mp__model:disabled { opacity: .5; cursor: default; } +.wb-session-prefs__notice { margin: 0; padding: 6px 12px; color: var(--fg-muted); font-size: 12px; overflow-wrap: anywhere; } +.modal__card .wb-session-prefs__notice { padding-inline: 0; } +.wb-chat .wb-session-model__menu > .model-pick__item { flex: none; } +.wb-chat .wb-session-model__menu > .cf-mp__menu { + position: static; flex: 1; min-height: 0; width: 100%; min-width: 0; border: none; padding: 0; box-shadow: none; +} @media (max-width: 700px) { .wb-chat .cf-modal__body { overflow: auto; } .wb-chat .cf-box__bar .cf-wschip:disabled { font-size: 0; } diff --git a/apps/desktop/src/workbench/text-workbench.tsx b/apps/desktop/src/workbench/text-workbench.tsx index e2dc1dee..4cdbad97 100644 --- a/apps/desktop/src/workbench/text-workbench.tsx +++ b/apps/desktop/src/workbench/text-workbench.tsx @@ -1,5 +1,5 @@ -import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react' -import { Globe, Plus, Search } from 'lucide-react' +import { useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from 'react' +import { Archive, ArrowLeft, Globe, Plus, Search } from 'lucide-react' import { useI18n } from '../renderer/src/i18n/i18n' import { findActive, useModels } from '../renderer/src/store/models' import { ChatSurface, ConversationHeader, ConversationScroller, ConversationSurface } from '../renderer/src/redesign/ChatSurface' @@ -19,6 +19,8 @@ import { chatCopy, turnLabel, type ChatCopy } from './chat-copy' import { createChatTransport, inputBytes, MAX_TEXT_INPUT, type ChatState } from './chat-transport' import { createLibrary, type Roster } from './library-transport' import { LibraryWorkspace, type LibraryPanel } from './library-workspace' +import { createPreferenceTransport, matchesPreferences, projectSession } from './session-preferences' +import { SessionHeaderActions, SessionModelPicker, SessionPreferenceStatus, SessionRenameDialog } from './session-preference-ui' import type { Bootstrap, LibraryQueue, Transport } from './transport' import { useTextWorkbench } from './use-text-workbench' import { WorkspaceFilesPanel } from './workspace-dialog' @@ -34,12 +36,21 @@ type Workspace = ReturnType const EMPTY: NonNullable = [] const PAGE = 80 const WORKSPACE_OPEN = 'workbench-workspace-open' +const emptyVersion = () => 0 +const emptySubscribe = () => () => {} export default function TextWorkbench({ transport, bootstrap, beforeWrite, onExpired, libraryQueue, locked, notice, renderSettings }: TextWorkbenchProps): React.JSX.Element { const { t, locale } = useI18n() const c = chatCopy(locale) const api = useMemo(() => createChatTransport(transport, bootstrap.csrf), [transport, bootstrap.csrf]) - const wk = useTextWorkbench(api, beforeWrite, onExpired, bootstrap.capabilities?.attachments === true) + const preferenceEnabled = bootstrap.capabilities?.sessionPreferences === true + const preferenceApi = useMemo(() => preferenceEnabled ? createPreferenceTransport(transport, bootstrap.csrf) : undefined, + [preferenceEnabled, transport, bootstrap.csrf]) + const wk = useTextWorkbench(api, beforeWrite, onExpired, bootstrap.capabilities?.attachments === true, preferenceApi) + const preferences = wk.preferences + const preferenceVersion = useSyncExternalStore(preferences?.subscribe ?? emptySubscribe, preferences?.version ?? emptyVersion) + const [archivedView, setArchivedView] = useState(false) + const [renameSid, setRenameSid] = useState() const supported = bootstrap.capabilities?.library === true const library = useMemo(() => supported ? createLibrary(transport, libraryQueue) : undefined, [supported, transport, libraryQueue]) const [panel, setPanel] = useState() @@ -65,9 +76,40 @@ export default function TextWorkbench({ transport, bootstrap, beforeWrite, onExp const [filesOpen, setFilesOpen] = useState(false) const workspaceLabel = locale === 'zh-CN' ? '工作区文件' : 'Workspace files' const openFiles = files ? () => { setFilesOpen(true); void files.loadProjects() } : undefined - const selectedEntry = wk.sessions.find((s) => s.id === wk.selected) - const shown = useMemo(() => [...wk.sessions].sort((a, b) => b.updatedAt - a.updatedAt) - .filter((s) => (s.title || t('chat.untitled')).toLowerCase().includes(query.trim().toLowerCase())), [wk.sessions, query, t]) + const sid = wk.selected + const selectedEntry = wk.sessions.find((s) => s.id === sid) + const preferenceEntry = sid ? preferences?.get(sid) : undefined + const projectedEntry = selectedEntry ? projectSession(selectedEntry, preferenceEntry?.pending) : undefined + useEffect(() => { + if (selectedEntry?.compatibility === 'text' && preferences && !matchesPreferences(selectedEntry, preferences.get(selectedEntry.id).confirmed)) + void preferences.read(selectedEntry.id) + }, [preferences, selectedEntry]) + const shown = useMemo(() => wk.sessions.map((row) => projectSession(row, preferences?.get(row.id).pending)) + .sort((a, b) => b.updatedAt - a.updatedAt), [wk.sessions, preferences, preferenceVersion]) + const archivedCount = preferences ? shown.filter((row) => row.archived).length : 0 + const visibleRows = shown.filter((row) => (!preferences || !!row.archived === archivedView) && + (archivedView || (row.title || t('chat.untitled')).toLowerCase().includes(query.trim().toLowerCase()))) + const compatible = selectedEntry?.compatibility === 'text' && state?.compatibility === 'text' + const busyPreferences = !!(state?.active || wk.pending) + const storageLocked = state && !state.writable && state.writeBlockReason !== 'session_turn_limit' + const preferenceLocked = locked || wk.projection?.status !== 'ready' || !compatible || storageLocked || busyPreferences || + preferenceEntry?.issue === 'readOnly' || preferenceEntry?.issue === 'missing' + const preferenceBlockReason = busyPreferences ? c.busy : selectedEntry?.compatibility === 'unsupported' ? c.unsupported + : selectedEntry?.compatibility === 'legacy_text' ? c.readOnly : storageLocked ? c.locked : wk.projection?.status !== 'ready' ? c.loading : undefined + const preferenceControlsDisabled = preferenceLocked || !preferenceEntry?.confirmed || !!(preferenceEntry.reading || preferenceEntry.pending || preferenceEntry.needsRead) + const confirmedModel = preferenceEntry?.confirmed?.preferences.model + const archiveSession = (): void => { + if (!sid || !preferences || preferenceControlsDisabled || !preferenceEntry?.confirmed) return + void preferences.write(sid, { archived: !projectedEntry?.archived }) + } + const renameSession = (): void => { + if (!sid || !preferences || preferenceControlsDisabled) return + preferences.beginRename(sid) + setRenameSid(sid) + } + const reloadPreferences = (): void => { + if (sid && preferences) void preferences.read(sid, true).then(() => wk.refreshList()) + } const roleMap = useMemo(() => new Map(roster?.roles.map((role) => [role.id, role])), [roster]) const appearance = (id?: string) => { const role = id ? roleMap.get(id) : undefined @@ -75,7 +117,6 @@ export default function TextWorkbench({ transport, bootstrap, beforeWrite, onExp } const personaId = state?.personaId ?? selectedEntry?.personaId const scope = wk.attachments ? (locale === 'zh-CN' ? '文本对话与手动上传附件' : 'Text chat with manual attachment uploads') : library ? c.libraryScope : c.scope - const sid = wk.selected const browserConfigured = bootstrap.capabilities?.browserPanel === true const browser = useMemo(() => browserConfigured ? createBrowserTransport(transport, bootstrap.csrf) : undefined, [browserConfigured, transport, bootstrap.csrf]) @@ -97,7 +138,7 @@ export default function TextWorkbench({ transport, bootstrap, beforeWrite, onExp window.removeEventListener('drop', preventFileDrop) } }, []) - const start = (): void => { setQuery(''); void wk.create() } + const start = (): void => { setQuery(''); setArchivedView(false); void wk.create() } const openSettings = (): void => setSettingsOpen(true) const surface =
@@ -110,24 +151,35 @@ export default function TextWorkbench({ transport, bootstrap, beforeWrite, onExp @@ -138,8 +190,12 @@ export default function TextWorkbench({ transport, bootstrap, beforeWrite, onExp event.dataTransfer.dropEffect = !locked && wk.projection?.status === 'ready' && state?.writable && !state.active && !wk.pending ? 'copy' : 'none' } : undefined}> - {state?.title || selectedEntry?.title || (wk.selected ? t('chat.untitled') : t('cf.tabChats'))} + {(preferences ? projectedEntry?.title ?? state?.title : state?.title || selectedEntry?.title) + || (sid ? t('chat.untitled') : t('cf.tabChats'))} {personaId && {appearance(personaId).name}} + {preferences && selectedEntry && } {openFiles && !(wk.selected && (state?.writable || state?.active)) && } {browser && sid && -
} + {(!managedModel ? !picked : (managedModel.pinned === null ? groups.length === 0 : !!managedModel.pinned && !picked)) && +
{c.selectModel}{' '} + +
} {over &&

{c.inputLimit}

}
{open &&
setOpen(false)} />} -
setOpen((value) => !value)} onPick={(pid, mid) => { onPick(`${pid}:${mid}`); setOpen(false) }} />
+
{managedModel ? setOpen((value) => !value)} + onPick={(pid, mid) => { managedModel.choose(`${pid}:${mid}`); setOpen(false) }} follow={() => { managedModel.choose(null); setOpen(false) }} /> + : setOpen((value) => !value)} onPick={(pid, mid) => { onPick(`${pid}:${mid}`); setOpen(false) }} />}
{active ? void stop(sid, active.turnId)} /> - : } + : }
{add && } diff --git a/apps/desktop/src/workbench/transport.ts b/apps/desktop/src/workbench/transport.ts index b5c526e3..a4c7fd66 100644 --- a/apps/desktop/src/workbench/transport.ts +++ b/apps/desktop/src/workbench/transport.ts @@ -14,7 +14,7 @@ export interface Bootstrap { config: RecordValue csrf: string expiresAt: number - capabilities?: { textChat?: true; library?: true; workspaceFiles?: true; attachments?: true; browserPanel?: true } + capabilities?: { textChat?: true; library?: true; workspaceFiles?: true; attachments?: true; browserPanel?: true; sessionPreferences?: true } } export type SessionScreen = { mode: 'authenticated'; bootstrap: Bootstrap } | { mode: 'claim' | 'login' } @@ -106,6 +106,7 @@ export function createTransport(send: Fetch = fetch) { if (result.capabilities.workspaceFiles === true) capabilities.workspaceFiles = true if (result.capabilities.attachments === true) capabilities.attachments = true if (result.capabilities.browserPanel === true) capabilities.browserPanel = true + if (result.capabilities.sessionPreferences === true) capabilities.sessionPreferences = true } return { protocol, version, platform, config, csrf, expiresAt, ...(Object.keys(capabilities).length ? { capabilities } : {}) } } diff --git a/apps/desktop/src/workbench/use-text-workbench.ts b/apps/desktop/src/workbench/use-text-workbench.ts index 9cfdfdc4..18908bf6 100644 --- a/apps/desktop/src/workbench/use-text-workbench.ts +++ b/apps/desktop/src/workbench/use-text-workbench.ts @@ -2,10 +2,13 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { attachmentTurnIssue, createAttachmentDrafts, readyAttachmentIds, type BrowserFiles } from './attachment-drafts' import { createChatStream, type ChatProjection } from './chat-stream' import { sameTurnDraft, type ChatSummary, type ChatTransport, type TurnRequest } from './chat-transport' +import { createListRefresh, sessionAfterRefresh } from './session-list' +import { createSessionPreferences, type createPreferenceTransport } from './session-preferences' +import { createSessionsStream } from './sessions-stream' import { HttpFailure } from './transport' type ListIssue = 'listFailure' | 'createFailure' -type TurnIssue = 'turnFailure' | 'busy' | 'modelFailure' | 'stopFailure' | 'roleUnavailable' +type TurnIssue = 'turnFailure' | 'busy' | 'modelFailure' | 'stopFailure' | 'roleUnavailable' | 'preferencesChanged' | 'effortUnavailable' const savedSelection = 'deva-workbench.chat' function lastSession(): string | null { try { return window.sessionStorage.getItem(savedSelection) } catch { return null } @@ -17,13 +20,14 @@ function remember(id: string | null): void { } catch { /* storage availability does not affect selection in the current page */ } } -export function useTextWorkbench(api: ChatTransport, beforeWrite: () => Promise, onExpired: () => void, uploadsEnabled: boolean) { +export function useTextWorkbench(api: ChatTransport, beforeWrite: () => Promise, onExpired: () => void, uploadsEnabled: boolean, + preferenceApi?: ReturnType) { const [sessions, setSessions] = useState([]) const [selected, setSelected] = useState(null) const selectedRef = useRef(null) const [listIssue, setListIssue] = useState() const [listLoading, setListLoading] = useState(true) - const listRevision = useRef(0) + const list = useRef>>() const creating = useRef() const [createPending, setCreatePending] = useState(false) const retryCreate = useRef(new Map()).current @@ -43,31 +47,40 @@ export function useTextWorkbench(api: ChatTransport, beforeWrite: () => Promise< remember(id) setSelected(id) }, []) - const refreshList = useCallback(async () => { - const revision = ++listRevision.current - try { - const next = await api.list() - if (listRevision.current !== revision) return + const managed = !!preferenceApi + const refreshList = useCallback(() => list.current?.request(), []) + const preferences = useMemo(() => preferenceApi && createSessionPreferences(preferenceApi, { + beforeWrite, + expired: onExpired, + committed(sid, { title, model, archived, customTitle }) { + setSessions((rows) => rows.map((row) => row.id === sid ? { ...row, title, model, archived, customTitle: customTitle ?? undefined } : row)) + list.current?.afterWrite() + }, + blocked(sid, issue) { + if (issue === 'busy' || issue === 'storage' || issue === 'readOnly' || issue === 'missing') { + if (live.current?.sid === sid) void live.current.stream.refresh() + } + refreshList() + } + }), [preferenceApi, beforeWrite, onExpired, refreshList]) + useEffect(() => { + const refresh = createListRefresh(api.list, (next) => { setSessions(next) setListIssue((current) => current === 'createFailure' ? current : undefined) - const id = selectedRef.current ?? lastSession() - if (!id || !next.some((s) => s.id === id)) select(next[0]?.id ?? null) - else select(id) - } catch (e) { - if (listRevision.current !== revision) return - if (e instanceof HttpFailure && e.status === 401) onExpired() + select(sessionAfterRefresh(next, selectedRef.current, lastSession(), managed)) + setListLoading(false) + }, (error) => { + if (error instanceof HttpFailure && error.status === 401) onExpired() else setListIssue('listFailure') - } finally { - if (listRevision.current === revision) setListLoading(false) - } - }, [api, onExpired, select]) - useEffect(() => { - void refreshList() - const onFocus = (): void => { void refreshList() } - const timer = window.setInterval(() => { if (document.visibilityState === 'visible') onFocus() }, 20000) - window.addEventListener('focus', onFocus) - return () => { ++listRevision.current; window.clearInterval(timer); window.removeEventListener('focus', onFocus) } - }, [refreshList]) + setListLoading(false) + }) + list.current = refresh + const link = managed ? createSessionsStream({ origin: window.location.origin, invalidate: refresh.request, expired: onExpired }) : undefined + if (!link) refresh.request() + const timer = window.setInterval(() => { if (document.visibilityState === 'visible') refresh.request() }, 20000) + window.addEventListener('focus', refresh.request) + return () => { link?.close(); refresh.close(); list.current = undefined; window.clearInterval(timer); window.removeEventListener('focus', refresh.request) } + }, [api, managed, onExpired, select]) useEffect(() => { if (!selected) return const sid = selected @@ -76,7 +89,7 @@ export function useTextWorkbench(api: ChatTransport, beforeWrite: () => Promise< if (projection.status === 'expired') { onExpired(); return } setView({ sid, projection }) const state = projection.snapshot?.state - if (state) setSessions((list) => { + if (!managed && state) setSessions((list) => { const previous = list.find((entry) => entry.id === sid) if (!previous) return list const { title, writable, model, personaId = previous.personaId, updatedAt = previous.updatedAt } = state @@ -86,7 +99,7 @@ export function useTextWorkbench(api: ChatTransport, beforeWrite: () => Promise< } }) live.current = { sid, stream } return () => { stream.close(); if (live.current?.stream === stream) live.current = undefined } - }, [api, onExpired, selected]) + }, [api, managed, onExpired, selected]) const current = (sid: string): ReturnType | undefined => live.current?.sid === sid ? live.current.stream : undefined async function create(personaId?: string): Promise { @@ -101,10 +114,9 @@ export function useTextWorkbench(api: ChatTransport, beforeWrite: () => Promise< await beforeWrite() const session = await api.create(id, personaId) retryCreate.delete(scope) - ++listRevision.current setSessions((list) => [session, ...list.filter((s) => s.id !== id)]) select(id) - void refreshList() + list.current?.afterWrite() return true } catch (e) { if (e instanceof HttpFailure && e.status < 500 && e.status !== 408) retryCreate.delete(scope) @@ -136,9 +148,11 @@ export function useTextWorkbench(api: ChatTransport, beforeWrite: () => Promise< } attachments.add(sid, files) } - async function send(sid: string, text: string, model: string): Promise { + async function send(sid: string, text: string, model: string | null): Promise { const projection = current(sid)?.current() if (projection?.status !== 'ready' || !projection.snapshot?.state.writable || projection.snapshot.state.active) return false + const preference = preferences?.get(sid) + if (preference && (preference.pending || preference.reading || preference.needsRead || preference.confirmed?.preferences.model !== model)) return false const ids = attachments ? readyAttachmentIds(attachments.get(sid)) : [] if (!ids || (!text && !ids.length) || !begin(sid, 'send')) return false const previous = retrySend.get(sid) @@ -159,8 +173,11 @@ export function useTextWorkbench(api: ChatTransport, beforeWrite: () => Promise< if (e instanceof HttpFailure && e.status === 401) onExpired() else { const code = e instanceof HttpFailure ? e.code : undefined - const issue = code === 'role_unavailable' ? 'roleUnavailable' : code === 'turn_in_progress' ? 'busy' : ['provider_not_found', 'not_chat_provider', 'model_not_enabled', 'chat_model_unavailable'].includes(code ?? '') ? 'modelFailure' : 'turnFailure' + const issue = code === 'role_unavailable' ? 'roleUnavailable' : code === 'turn_in_progress' ? 'busy' : code === 'session_model_changed' ? 'preferencesChanged' + : code === 'effort_unsupported' ? 'effortUnavailable' + : ['provider_not_found', 'not_chat_provider', 'model_not_enabled', 'chat_model_unavailable'].includes(code ?? '') ? 'modelFailure' : 'turnFailure' if (e instanceof HttpFailure && e.status < 500 && e.status !== 408) retrySend.delete(sid) + if (issue === 'preferencesChanged') { void preferences?.read(sid); refreshList() } const uploadIssue = ids.length ? attachmentTurnIssue(e) : undefined if (uploadIssue) attachments?.reportTurn(sid, ids, uploadIssue) else setTurnIssues((issues) => ({ ...issues, [sid]: issue })) @@ -184,6 +201,6 @@ export function useTextWorkbench(api: ChatTransport, beforeWrite: () => Promise< } } return { sessions, selected, select, projection: view?.sid === selected ? view?.projection : undefined, listIssue, listLoading, - refreshList, create, createPending, pending: selected ? pending[selected] : undefined, drafts, attachments, addAttachments, send, stop, + refreshList, preferences, create, createPending, pending: selected ? pending[selected] : undefined, drafts, attachments, addAttachments, send, stop, turnIssue: selected ? turnIssues[selected] : undefined } } diff --git a/apps/headless/README.md b/apps/headless/README.md index 8b70ec3d..2d2daaf7 100644 --- a/apps/headless/README.md +++ b/apps/headless/README.md @@ -2,6 +2,12 @@ 在无图形桌面的 Linux 服务器上,从浏览器认领实例、登录,使用**桌面同源的会话布局、编辑器、消息气泡和模型设置**。网页现可用配置好的服务商进行通用文本对话:新建会话、选择模型、看到流式回复、中途停止、刷新续接并读取已保存的历史。模型设置、密钥和自定义头仍由同一已认证实例管理。这不是手机版、中转或完整 Agent 桌面:执行工具、会话级工作区绑定和协作任务仍待移植。人工浏览器接管是一个需要独立沙箱的可选组件,默认关闭;受支持的聊天附件如下。 +## 整理对话和选择下次使用的模型 + +在对话顶部可改名、归档或还原。清空自定义标题会根据首条用户消息重新命名;若首条只有附件,则使用附件名称。归档只改变显示分组,不删除历史,也不把该对话排到最近位置。其他同账号网页会收到一个只提示「列表已改变」的通知,随后重新向服务端读取;标题、内容和附件均不在该通知中广播。 + +已确认的 Web 对话可单独固定一个已启用的模型,也可选择「跟随默认」。更改偏好本身不会向模型发请求。跟随模式在下一次实际发送时按服务端当前角色模型或全局默认解析;同一个已受理请求重试时仍返回原来的回合。两个页面同时修改会返回版本冲突,保留输入供核对;正在进行的回合不被中途切换模型。旧桌面复杂会话维持原来的只读保护,非默认思考档位仍待单独验收。 + ## 个人资料、角色与记忆 - 左侧头像打开桌面同源的个人资料与头像编辑器。生成头像样式与上传的静态图片独立保存;图片上传、清除和角色编辑带修订号。页面检测到另一标签页已写入时,应先重读再编辑。 diff --git a/apps/headless/src/chat/README.md b/apps/headless/src/chat/README.md index a4d8011b..d504a431 100644 --- a/apps/headless/src/chat/README.md +++ b/apps/headless/src/chat/README.md @@ -8,6 +8,9 @@ | `POST /api/v1/chats` | `{}` 创建通用会话;`{sessionId}` 提供规范 UUID 或受限桌面 `sess_…` ID;可另给 `personaId` 绑定已启用的服务器角色并定格首选模型。客户端只传角色 ID,重复创建不会覆盖身份或触发新的模型请求。| | `GET /api/v1/chats/:sid` | 取历史、正在生成的部分文字、回合 ID、起始时间、最近终态和同一水位的游标。| | `POST /api/v1/chats/:sid/turns` | `{clientRequestId,text,model,attachments?}`。可选 `attachments` 最多是本会话的 4 个上传 ID,并非路径;顺序纳入幂等比较。同一请求 ID 再试不会重开上游请求。新请求在用户消息及幂等记录落盘后回 `202`;相同 ID 与同内容重复调用返回原回合,内容不同时为 `409`。| +| `GET /api/v1/chats/:sid/preferences` | 当前会话标题、自定义标题、归档状态、模型选项和该会话版本。版本用于条件写入,不是访问凭证。| +| `PATCH /api/v1/chats/:sid/preferences` | `{revision,set}` 只改指定字段(如 `customTitle:null`、`archived:true` 或 `model:null`)。取得持久化回执后更新 UI,同版本并发写不能静默覆盖。普通 `model` 字符串请求保持兼容;`model:null` 发送表示由服务端选择该时刻的默认模型。| +| `WS /api/v1/chats/stream` | 登录所有者的只读列表失效通知。首帧 `sessions-snapshot` 给出真实水位,之后 `sessions-changed` 触发重新 GET 列表;重连和服务重启都重新取快照。通知不含会话名称、ID、正文或其他标签的操作。| | `POST /api/v1/chats/:sid/stop` | `{turnId}` 只停止目标回合。重建进程不会重发未完成的上游请求。| | `POST /api/v1/chats/:sid/attachments` | 当前所有者把文件字节作为 `application/octet-stream` 上传;`x-deva-file-name` 是 UTF-8 文件名的无填充 base64url,`x-deva-file-type` 是所选内容类型。返回不透明附件 ID 和显示元数据,不触发模型请求。| | `DELETE /api/v1/chats/:sid/attachments/:id` | 幂等撤回未发送的草稿;已经确认的会话历史独立保存。| diff --git a/docs/development/web-workbench/README.md b/docs/development/web-workbench/README.md index c58eb00f..c758d37e 100644 --- a/docs/development/web-workbench/README.md +++ b/docs/development/web-workbench/README.md @@ -1,6 +1,6 @@ # Web Workbench 能力清单与门禁 -[能力清单](./parity-manifest.json)按桌面 [preload 运行时 `const api`](../../../apps/desktop/src/preload/index.ts)逐项登记:**21 组、186 个方法(含 18 个订阅)、1 个值 `platform`**。当前有 **27 个 `implemented`**:模型与设置 9 项、个人资料 3 项、分域记忆 4 项、角色管理 7 项、授权项目的目录与文件读取 2 项、网页文件选择与粘贴上传 2 项;其余 **155 个 `pending`、4 个 `desktop-only`**。上传格式与模型协议限制在部署说明中列出;目录拖放及图片缩略资源仍按部分覆盖登记。手动选项目和受限文本保存另记为部分覆盖:尚不包含会话挂载或新建文件。角色删除可处理未被引用的自定义角色,对受保护的默认角色和已有引用报冲突;未将其列为桌面级联删除已完成。`platform` 的完整工作台投影仍为 `pending`:为启动页面传递服务器平台名称不等于已经处理完整外壳的快捷键和客户端布局。已有手机版 PWA/relay 和桌面 IPC 都是参照,不是 Workbench 覆盖证明。 +[能力清单](./parity-manifest.json)按桌面 [preload 运行时 `const api`](../../../apps/desktop/src/preload/index.ts)逐项登记:**21 组、186 个方法(含 18 个订阅)、1 个值 `platform`**。当前有 **30 个 `implemented`**:模型与设置 9 项、个人资料 3 项、分域记忆 4 项、角色管理 7 项、授权项目文件读取 2 项、网页文件选择与粘贴上传 2 项,以及会话模型、归档和列表变更订阅 3 项;其余 **152 个 `pending`、4 个 `desktop-only`**。空闲会话可以改名;在途改名和非默认思考档位仍属部分覆盖。上传格式与模型协议限制在部署说明中列出;目录拖放及图片缩略资源仍按部分覆盖登记。手动选项目和受限文本保存另记为部分覆盖:尚不包含会话挂载或新建文件。角色删除可处理未被引用的自定义角色,对受保护的默认角色和已有引用报冲突;未将其列为桌面级联删除已完成。`platform` 的完整工作台投影仍为 `pending`:为启动页面传递服务器平台名称不等于已经处理完整外壳的快捷键和客户端布局。已有手机版 PWA/relay 和桌面 IPC 都是参照,不是 Workbench 覆盖证明。 通用文本阶段另外给七个 `chat` 条目登记了 `web.partial`:`createSession`、`send`、`abort`、`listSessions`、`loadSession`、`attachSession`、`onEvent`。每项记录已验证范围、专有测试和仍缺的桌面行为;它们仍计入 `pending`,不等同于附件、工具、成员或审批均已接通。[通用文本协议与阶段限制](../../../apps/headless/src/chat/README.md)。 diff --git a/docs/development/web-workbench/parity-manifest.json b/docs/development/web-workbench/parity-manifest.json index 603b438d..80ea517b 100644 --- a/docs/development/web-workbench/parity-manifest.json +++ b/docs/development/web-workbench/parity-manifest.json @@ -127,15 +127,15 @@ {"name":"insert","kind":"invoke","channel":"chat:insert","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/chat.tsx","use":"聊天状态向正在运行的同一回合插入消息"},"web":{"status":"pending","target":"rpc","semantic":"保留进入待送达队列/本轮已结束的区别;按会话记录插入顺序。"}}, {"name":"withdrawInserts","kind":"invoke","channel":"chat:withdraw-inserts","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/chat.tsx","use":"输入框撤回仍未送达的插入项恢复草稿"},"web":{"status":"pending","target":"rpc","semantic":"仅取回尚在队列的消息和附件;与已送达的历史区分。"}}, {"name":"compact","kind":"invoke","channel":"chat:compact","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/chat.tsx","use":"聊天状态发起手动历史压缩并观察完成"},"web":{"status":"pending","target":"rpc","semantic":"尊重历史锁,返回压缩回合 ID 并发压缩完成事件,不误触发下一轮。"}}, - {"name":"createSession","kind":"invoke","channel":"chat:create-session","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/chat.tsx","use":"聊天外壳在首发消息前建立空会话"},"web":{"status":"pending","target":"rpc","semantic":"按角色/工作区创建并落盘;重试复用会话标识,初始列表立即可见。","partial":{"scope":"通用文本新建、指定 ID 幂等及跨重启重用。","remaining":"按绑定角色、聚焦工作区及成员创建。","handler":"apps/headless/src/chat/routes.mjs","test":"apps/headless/test/chat-http.test.mjs"}}}, - {"name":"setModel","kind":"invoke","channel":"chat:set-model","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/chat.tsx","use":"会话模型选择器立即保存模型引用"},"web":{"status":"pending","target":"rpc","semantic":"按会话持久化模型引用,支持跟随默认,模型变化向其他连接同步。"}}, - {"name":"setEffort","kind":"invoke","channel":"chat:set-effort","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/chat.tsx","use":"会话思考等级选择器立即落盘"},"web":{"status":"pending","target":"rpc","semantic":"保存会话独立思考等级并校验当前生效模型的能力。"}}, + {"name":"createSession","kind":"invoke","channel":"chat:create-session","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/chat.tsx","use":"聊天外壳在首发消息前建立空会话"},"web":{"status":"pending","target":"rpc","semantic":"按角色/工作区创建并落盘;重试复用会话标识,初始列表立即可见。","partial":{"scope":"新建普通或已启用角色的会话,指定ID幂等及跨重启重用。","remaining":"绑定聚焦工作区与成员创建。","handler":"apps/headless/src/chat/routes.mjs","test":"apps/headless/test/chat-http.test.mjs"}}}, + {"name":"setModel","kind":"invoke","channel":"chat:set-model","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/chat.tsx","use":"会话模型选择器立即保存模型引用"},"web":{"status":"implemented","target":"rpc","semantic":"按会话持久化模型引用,支持跟随默认,模型变化向其他连接同步。","implementation":{"handler":"apps/headless/src/chat/session-routes.mjs","test":"apps/headless/test/session-preferences.test.mjs"}}}, + {"name":"setEffort","kind":"invoke","channel":"chat:set-effort","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/chat.tsx","use":"会话思考等级选择器立即落盘"},"web":{"status":"pending","target":"rpc","semantic":"保存会话独立思考等级并校验当前生效模型的能力。","partial":{"scope":"可清除覆盖或明确采用协议默认档位;其他档位会得到明确错误,不会被伪装成成功。","remaining":"逐适配器验证各非默认思考档位可被真实模型接收并应用。","handler":"apps/headless/src/chat/session-routes.mjs","test":"apps/headless/test/session-preferences.test.mjs"}}}, {"name":"setFocus","kind":"invoke","channel":"chat:set-focus","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/chat.tsx","use":"聊天状态为当前会话挂载或卸载聚焦目录"},"web":{"status":"pending","target":"rpc","semantic":"选择授权宿主目录或明确卸载,两种结果都持久化且能重连恢复。"}}, - {"name":"renameSession","kind":"invoke","channel":"chat:rename-session","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/chat.tsx","use":"对话菜单持久化标题并刷新展示"},"web":{"status":"pending","target":"rpc","semantic":"区分自定义标题、清空恢复自动标题、会话不存在。"}}, - {"name":"setArchived","kind":"invoke","channel":"chat:set-archived","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/chat.tsx","use":"聊天外壳执行归档与取消归档"},"web":{"status":"pending","target":"rpc","semantic":"保留列表顺序和归档导航,跨连接同步归档状态。"}}, + {"name":"renameSession","kind":"invoke","channel":"chat:rename-session","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/chat.tsx","use":"对话菜单持久化标题并刷新展示"},"web":{"status":"pending","target":"rpc","semantic":"区分自定义标题、清空恢复自动标题、会话不存在。","partial":{"scope":"已确认且空闲的会话可立即改名、清空恢复自动标题,保留次序和附件;CAS冲突保留编辑内容。","remaining":"桌面还允许在回合进行期间改名;此模式会报告忙碌。","handler":"apps/headless/src/chat/session-routes.mjs","test":"apps/headless/test/session-preferences.test.mjs"}}}, + {"name":"setArchived","kind":"invoke","channel":"chat:set-archived","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/chat.tsx","use":"聊天外壳执行归档与取消归档"},"web":{"status":"implemented","target":"rpc","semantic":"保留列表顺序和归档导航,跨连接同步归档状态。","implementation":{"handler":"apps/headless/src/chat/session-routes.mjs","test":"apps/headless/test/session-preferences.test.mjs"}}}, {"name":"abort","kind":"invoke","channel":"chat:abort","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/chat.tsx","use":"输入框停止当前 turnId 对应的回合"},"web":{"status":"pending","target":"rpc","semantic":"仅停止目标活跃回合;重复停止是安全的,结束事件用于收敛 UI。","partial":{"scope":"按所属会话与真实回合 ID 中止上游文本流;保留可见部分。","remaining":"非文本工具、子进程及协作轮的取消和清理。","handler":"apps/headless/src/chat/routes.mjs","test":"apps/headless/test/chat-http.test.mjs"}}}, {"name":"stopSubagent","kind":"invoke","channel":"chat:stop-subagent","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/chat.tsx","use":"会话里停止由工具卡标识的子智能体任务"},"web":{"status":"pending","target":"rpc","semantic":"按会话和工具使用 ID 精确停止仍在运行的子任务,不停止整个主回合。"}}, - {"name":"listSessions","kind":"invoke","channel":"chat:list-sessions","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/chat.tsx","use":"会话状态刷新聚焦工作区或全局会话表"},"web":{"status":"pending","target":"bootstrap","semantic":"启动时拉取按工作区过滤、排序的可见会话,区分归档和成员会话。","partial":{"scope":"显示当前所有者的文本会话,标明旧历史的只读或不兼容状态。","remaining":"完整还原归档、成员和工作区筛选。","handler":"apps/headless/src/chat/routes.mjs","test":"apps/headless/test/chat-http.test.mjs"}}}, + {"name":"listSessions","kind":"invoke","channel":"chat:list-sessions","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/chat.tsx","use":"会话状态刷新聚焦工作区或全局会话表"},"web":{"status":"pending","target":"bootstrap","semantic":"启动时拉取按工作区过滤、排序的可见会话,区分归档和成员会话。","partial":{"scope":"按当前所有者显示普通或归档会话,保持活动时间次序;收到列表水位变化后从同一已登录实例重读。","remaining":"成员会话和基于工作区的筛选。","handler":"apps/headless/src/chat/routes.mjs","test":"apps/headless/test/chat-http.test.mjs"}}}, {"name":"loadSession","kind":"invoke","channel":"chat:load-session","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/chat.tsx","use":"聊天状态从已落盘记录重建气泡"},"web":{"status":"pending","target":"rpc","semantic":"稳定分页读取历史,返回展示视图;最新历史和活跃流拼接时不能重影。","partial":{"scope":"读取已落盘的通用文本历史。","remaining":"分页和复杂展示块(文件、卡片、成员)。","handler":"apps/headless/src/chat/routes.mjs","test":"apps/headless/test/chat-http.test.mjs"}}}, {"name":"attachmentImage","kind":"invoke","channel":"chat:attachment-image","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/redesign/attachments.tsx","use":"历史聊天气泡按消息引用显示图片"},"web":{"status":"pending","target":"download","semantic":"按会话和附件引用受权读取缩略图或原图,不接收文件路径。","partial":{"scope":"按会话授权显示支持的静态图片,草稿和已发送记录分别校验;原桌面缩略图卡与大图查看器可用。","remaining":"单独的小尺寸缩略资源、没有服务端索引的旧桌面图片引用和更多桌面图片格式。","handler":"apps/headless/src/attachments/routes.mjs","test":"apps/headless/test/attachment-http.test.mjs"}}}, {"name":"attachSession","kind":"invoke","channel":"chat:attach-session","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/chat.tsx","use":"切换会话时原子取历史、turnId 与开始时刻"},"web":{"status":"pending","target":"bootstrap","semantic":"同一快照返回历史与运行锚点;随后能接续事件,避免快照与订阅之间丢消息。","partial":{"scope":"历史文本和已确认附件的展示元数据与活跃回合游标一致,无二进制内容进入快照。","remaining":"复杂历史和未决交互快照。","handler":"apps/headless/src/chat/routes.mjs","test":"apps/headless/test/chat-http.test.mjs"}}}, @@ -155,7 +155,7 @@ {"name":"respondPlan","kind":"invoke","channel":"chat:plan-response","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/chat.tsx","use":"计划审阅批准执行或退回继续完善"},"web":{"status":"pending","target":"rpc","semantic":"同一未决卡片只落一次决议,保留反馈文本;过期与并发提交可辨。"}}, {"name":"respondMount","kind":"invoke","channel":"chat:mount-response","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/chat.tsx","use":"挂载卡确认已选目录或跳过"},"web":{"status":"pending","target":"rpc","semantic":"卡片决议只接收已验证的宿主工作区引用或跳过,不因本地浏览器选择绕过授权。"}}, {"name":"onEvent","kind":"subscription","channel":"chat:event","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/chat.tsx","use":"聊天状态订阅会话回合、流式内容和卡片事件"},"web":{"status":"pending","target":"events","semantic":"按会话和回合路由,验证事件顺序、去重、断线补偿、终止和取消订阅。","partial":{"scope":"受权文本/WebSocket 流:初始快照、重连、去重和终态收敛。","remaining":"工具、卡片、附件、成员和跨设备的全部事件。","handler":"apps/headless/src/events/websocket.mjs","test":"apps/headless/test/chat-http.test.mjs"}}}, - {"name":"onSessionsChanged","kind":"subscription","channel":"chat:sessions-changed","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/chat.tsx","use":"外部新建会话后刷新桌面列表"},"web":{"status":"pending","target":"events","semantic":"列表失效触发重拉;事件丢失时用启动或重连快照补齐。"}}, + {"name":"onSessionsChanged","kind":"subscription","channel":"chat:sessions-changed","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/chat.tsx","use":"外部新建会话后刷新桌面列表"},"web":{"status":"implemented","target":"events","semantic":"列表失效触发重拉;事件丢失时用启动或重连快照补齐。","implementation":{"handler":"apps/headless/src/events/session-list-stream.mjs","test":"apps/headless/test/session-list-stream.test.mjs"}}}, {"name":"markRead","kind":"invoke","channel":"chat:mark-read","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/remote-sync.ts","host":"apps/desktop/src/main/services/read-sync.ts","use":"前台查看时同步手机与桌面未读"},"web":{"status":"pending","target":"rpc","semantic":"仅对当前用户和会话推进已读标记,不覆盖后到的更新。"}}, {"name":"onRemoteChange","kind":"subscription","channel":"chat:remote-change","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/remote-sync.ts","host":"apps/desktop/src/main/services/read-sync.ts","use":"收到手机等设备发来的已读/删除/归档/模型变化"},"web":{"status":"pending","target":"events","semantic":"按字段合并跨客户端会话更新,恢复时用服务器状态防止本地陈旧覆盖。"}} ] diff --git a/scripts/workbench/e2e-sessions.mjs b/scripts/workbench/e2e-sessions.mjs new file mode 100644 index 00000000..279731c1 --- /dev/null +++ b/scripts/workbench/e2e-sessions.mjs @@ -0,0 +1,376 @@ +import { randomBytes } from 'node:crypto' +import { access, lstat, mkdir, mkdtemp, realpath, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { requestControl } from '../../apps/headless/src/control/socket.mjs' +import { DEFAULT_WEB_DIR, startWorkbench } from '../../apps/headless/src/server.mjs' +import { initializeMasterKey } from '../../apps/headless/src/storage/vault.mjs' +import { ChatFixtureError, startChatFixture } from './e2e-chat-fixture.mjs' +import { startLocalWebDriver, waitFor, WebDriverError } from './webdriver-local.mjs' + +const hook = name => `[data-testid="workbench-${name}"]` +const chat = hook('chat') +const list = `${chat} .cf-list` +const row = `${list} .cf-thread` +const title = '.cf-thread__title' +const header = `${chat} .wb-chat__title` +const action = name => `${hook('session-menu')} ${hook(`session-${name}`)}` +const chip = `${chat} .model-pick button.cf-mp__model` +const modelMenu = `${chat} .model-pick [role="menu"]` +const follow = `${chat} .model-pick ${hook('session-model-default')}` +const draft = `${chat} .cf-draft__input[role="textbox"][contenteditable="true"]` +const send = `${chat} .cf-send:not(.is-stop)` +const untitled = 'New chat' +const anchorName = 'Fixture empty anchor' +const firstText = 'Fixture automatic title from one ordinary message' +const autoTitle = 'Fixture automatic title from o…' +const followLabel = 'Follow default' +const customTitle = 'Session fixture renamed' +const reply = 'Deterministic local reply.' +const providerId = 'e2e-sessions-provider' +const providerName = 'Session fixture provider' +const defaultModel = 'session-fixture-default' +const pinnedModel = 'session-fixture-pinned' +const modelRef = model => `${providerId}:${model}` +const selectAll = '\uE009a\uE000' +const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/ + +class CheckFailure extends Error {} +function check(value, diagnostic) { + if (!value) throw new CheckFailure(diagnostic) +} + +function uiFor(browser, signal) { + const until = (probe, diagnostic, timeout) => waitFor(probe, diagnostic, { signal, timeout }) + const element = (selector, diagnostic, text, child) => until(() => browser.execute(` + const [selector, expected, child] = arguments; + return [...document.querySelectorAll(selector)].find(node => node.getClientRects().length && + getComputedStyle(node).visibility === 'visible' && !node.matches(':disabled, [aria-disabled="true"]') && + (expected == null || (child ? node.querySelector(child) : node)?.textContent.trim() === expected)) ?? null; + `, selector, text ?? null, child ?? null), diagnostic) + return { + browser, until, element, + click: async (...args) => browser.click(await element(...args)), + selected: () => browser.execute('return sessionStorage.getItem("deva-workbench.chat");'), + // Require the complete visible list, plus an unchanged observer document and selected anchor + // when given. Checking the positive anchor also prevents an unloaded/hidden list passing. + rows: (expected, diagnostic, stable = null, view = 'active') => until(() => browser.execute(` + const [list, title, expected, stable, view] = arguments; + if (stable && (performance.timeOrigin !== stable.document || + sessionStorage.getItem('deva-workbench.chat') !== stable.anchor)) return false; + const visible = node => node.getClientRects().length && getComputedStyle(node).visibility === 'visible'; + const rail = document.querySelector(list); + if (rail?.dataset.sessionView !== view || !visible(rail)) return false; + const rows = [...rail.querySelectorAll('.cf-thread')].filter(visible); + if (stable && !rows.some(node => node.matches('.is-active') && + node.querySelector(title)?.textContent.trim() === stable.name)) return false; + const labels = rows.map(node => node.querySelector(title)?.textContent.trim()).sort(); + return labels.length === expected.length && expected.every((label, i) => labels[i] === label); + `, list, title, [...expected].sort(), stable, view), diagnostic, stable ? 7_000 : undefined), + gone: (selector, diagnostic) => until(() => browser.execute(` + return ![...document.querySelectorAll(arguments[0])].some(node => node.getClientRects().length && + getComputedStyle(node).visibility === 'visible'); + `, selector), diagnostic) + } +} + +async function submitPassword(ui, mode, value) { + const input = await ui.element(`.wb-auth input[type="password"][autocomplete="${mode}-password"]`, 'real owner authentication form') + await ui.browser.keys(input, value) + await ui.click('.wb-auth button[type="submit"]', 'submit owner authentication') + await ui.element(chat, 'authenticated Workbench conversation view') +} + +// The provider setup is deliberately the only direct write from WebDriver. The existing +// settings E2E covers those controls; all session CRUD and model choices here are real clicks. +async function seedModels(ui, mockOrigin, key) { + const ok = await ui.browser.executeAsync(` + const [provider, activeModelId, key, done] = arguments; + const api = async (path, method = 'GET', body, csrf) => { + const response = await fetch('/api/v1/' + path, { method, credentials: 'same-origin', mode: 'same-origin', + redirect: 'error', cache: 'no-store', ...(body === undefined ? {} : { body: JSON.stringify(body), + headers: { 'content-type': 'application/json', 'x-deva-csrf': csrf } }) }); + return response.ok ? response.json() : null; + }; + (async () => { + const bootstrap = await api('bootstrap'); + const settings = await api('settings'); + if (bootstrap?.capabilities?.sessionPreferences !== true || !bootstrap.csrf || !settings?.revision) return false; + const saved = await api('settings', 'PATCH', { revision: settings.revision, unset: [], + set: { locale: 'en', models: { providers: [provider], activeModelId, activeEffort: 'default' } } }, bootstrap.csrf); + if (!saved?.ok || !saved.revision) return false; + const credential = await api('provider-keys/' + provider.id, 'PUT', { value: key, revision: saved.revision }, bootstrap.csrf); + return credential?.ok === true && credential.available === true; + })().then(done, () => done(false)); + `, { + id: providerId, name: providerName, kind: 'custom', purpose: 'llm', accent: '#345678', adapter: 'openai', + apiHost: `${mockOrigin}/v1`, enabled: true, + models: [defaultModel, pinnedModel].map(id => ({ id, name: id, enabled: true })) + }, modelRef(defaultModel), key) + check(ok, 'Could not seed the two private loopback models') + await ui.browser.refresh() + await ui.element(chat, 'Workbench with saved synthetic model settings') +} + +// Readbacks use B's ordinary owner cookie, and return only an opaque revision when the public +// list, preference document, and actual thread agree. They never refresh the app's React state. +function readBack(ui, id, expect, diagnostic, previous = null) { + return ui.until(() => ui.browser.executeAsync(` + const [id, expected, previous, done] = arguments; + const get = async path => { + const response = await fetch('/api/v1/chats' + path, { credentials: 'same-origin', mode: 'same-origin', + cache: 'no-store', redirect: 'error' }); + return response.ok ? response.json() : null; + }; + (async () => { + const path = '/' + encodeURIComponent(id); + const [list, document, thread] = await Promise.all([get(''), get(path + '/preferences'), get(path)]); + const entry = list?.sessions.find(session => session.id === id); + const { preferences, revision } = document ?? {}; + const state = thread?.state; + if (!entry || entry.compatibility !== 'text' || entry.personaId != null || !preferences || + typeof revision !== 'string' || !/^[0-9a-f]{64}$/.test(revision) || + (previous !== null && revision === previous) || state?.id !== id) return false; + if (![entry, state].every(row => row.title === expected.title && + (row.customTitle ?? null) === expected.customTitle && (row.archived === true) === expected.archived && + row.model === expected.model)) return false; + if (preferences.title !== expected.title || preferences.customTitle !== expected.customTitle || + preferences.archived !== expected.archived || preferences.effort !== null || preferences.model !== expected.model) return false; + if (!Array.isArray(state.messages) || state.active || state.messages.length !== expected.messages.length || + !expected.messages.every(([role, content], i) => state.messages[i]?.role === role && state.messages[i]?.content === content)) return false; + return revision; + })().then(done, () => done(false)); + `, id, expect, previous), diagnostic) +} + +async function createSession(ui, prior) { + await ui.click(`${chat} ${hook('new-chat')}`, 'new ordinary conversation button') + const sid = await ui.until(async () => { + const id = await ui.selected() + return id !== prior && uuid.test(id ?? '') ? id : null + }, 'new conversation selected by the UI') + await ui.element(draft, 'new conversation composer') + return sid +} + +async function openSession(ui, name, id) { + await ui.click(row, 'open the intended conversation row', name, title) + await ui.until(async () => await ui.selected() === id, 'intended conversation selected by the user') + await ui.element(header, 'selected conversation heading', name) +} + +async function rename(ui, value) { + await ui.click(action('rename'), 'rename action for the selected conversation') + const input = await ui.element(hook('rename-input'), 'visible rename input') + await ui.browser.keys(input, `${selectAll}${value || '\uE003'}`) + await ui.until(() => ui.browser.execute('return arguments[0].value === arguments[1];', input, value), 'rename input contains the typed value') + await ui.click(hook('rename-save'), 'explicitly save the title change') + await ui.gone(hook('rename-input'), 'rename form closed after save') +} + +const empty = { title: '', customTitle: null, archived: false, model: null, messages: [] } +const automatic = { ...empty, title: autoTitle, messages: [['user', firstText], ['assistant', reply]] } +const renamed = { ...automatic, title: customTitle, customTitle } + +async function verifyTitlesAndArchive(a, b, mock, signal, setStage) { + setStage('prepare an empty anchor in B so the target stays unselected there') + const anchor = await createSession(b, null) + const emptyRev = await readBack(b, anchor, empty, 'empty ordinary anchor exists in the public state') + await rename(b, anchorName) + const anchorRev = await readBack(b, anchor, { ...empty, title: anchorName, customTitle: anchorName }, 'empty anchor has a custom title', emptyRev) + const stable = { anchor, name: anchorName, document: await b.browser.execute('return performance.timeOrigin;') } + await b.rows([anchorName], 'B shows only its selected anchor', stable) + await a.rows([anchorName], 'A sees the anchor before creating the target') + + setStage('create a conversation in A and see it live in B without selecting it') + const target = await createSession(a, await a.selected()) + await a.rows([anchorName, untitled], 'A shows a newly created empty conversation') + await b.rows([anchorName, untitled], 'B automatically shows the new unselected conversation', stable) + let revision = await readBack(b, target, empty, 'B can read the new conversation and empty title') + mock.assertRequestCount(0) + + setStage('send one ordinary text turn and observe the actual automatic title') + const composer = await a.element(draft, 'editable composer for the selected target') + await a.browser.click(composer) + await a.browser.keys(composer, firstText) + await a.click(send, 'send the single ordinary text turn') + const call = await mock.expectRequest(1, { messages: [{ role: 'user', content: firstText }], signal }) + call.delta(reply) + call.finish() + await a.element(`${hook('turn-status')}[data-status="completed"]`, 'completed local synthetic reply') + await a.element(`${chat} [data-role="assistant"] .msg__text`, 'rendered local synthetic reply', reply) + await a.element(header, 'selected header uses the automatic title', autoTitle) + await b.rows([anchorName, autoTitle], 'B automatically sees the real automatic title', stable) + revision = await readBack(b, target, automatic, 'public transcript and automatically generated title agree', revision) + + setStage('rename in A and observe the unselected row update in B') + await rename(a, customTitle) + await a.element(header, 'A header has the custom title', customTitle) + await a.rows([anchorName, customTitle], 'A list has the custom title') + await b.rows([anchorName, customTitle], 'B automatically sees the custom title', stable) + revision = await readBack(b, target, renamed, 'public readback of custom title', revision) + + setStage('archive in A, inspect archive in B and explicitly restore from B') + await a.click(action('archive'), 'archive the selected conversation in A') + await a.rows([anchorName], 'A active list excludes the archived conversation') + await b.rows([anchorName], 'B active list automatically excludes the archived conversation', stable) + revision = await readBack(b, target, { ...renamed, archived: true }, 'public readback of archive state', revision) + await b.click(hook('archived-chats'), 'open the archive list in B') + await b.rows([customTitle], 'B archive list contains only the target', null, 'archived') + await openSession(b, customTitle, target) + await b.element(action('archived'), 'selected conversation displays the archived marker') + await b.click(action('restore'), 'explicitly restore the selected archived conversation') + await a.rows([anchorName, customTitle], 'A automatically sees the restored conversation in the active list') + await b.rows([], 'B archive list no longer contains the target', null, 'archived') + await b.click(hook('active-chats'), 'open the active list again in B') + await b.rows([anchorName, customTitle], 'B active list contains the restored conversation') + revision = await readBack(b, target, renamed, 'public readback of restored state', revision) + + setStage('clear custom titles for a conversation with messages and an empty conversation') + await openSession(a, customTitle, target) + await rename(a, '') + await a.element(header, 'clearing the title restores the real automatic title in A', autoTitle) + await b.rows([anchorName, autoTitle], 'B sees the restored automatic title') + revision = await readBack(b, target, automatic, 'public readback has a cleared custom title and unchanged transcript', revision) + await openSession(a, anchorName, anchor) + await rename(a, '') + await a.element(header, 'clearing an empty conversation title restores the default label', untitled) + await a.rows([untitled, autoTitle], 'A list uses the empty conversation default label') + await b.rows([untitled, autoTitle], 'B list uses the empty conversation default label') + await readBack(b, anchor, empty, 'empty session stores no label as its custom or automatic title', anchorRev) + return { anchor, target, revision } +} + +function modelOption(ui, model, diagnostic, checked = null) { + return ui.until(() => ui.browser.execute(` + const [menu, provider, model, checked] = arguments; + const visible = node => node.getClientRects().length && getComputedStyle(node).visibility === 'visible'; + const group = [...document.querySelectorAll(menu + ' .cf-mp__group')] + .find(node => visible(node) && node.querySelector('.cf-mp__ghead')?.textContent.trim() === provider); + return [...(group?.querySelectorAll('[role="menuitemradio"]') ?? [])].find(node => visible(node) && + !node.matches(':disabled, [aria-disabled="true"]') && node.textContent.trim() === model && + (checked === null || node.getAttribute('aria-checked') === String(checked))) ?? null; + `, modelMenu, providerName, model, checked), diagnostic) +} + +async function verifyModels(a, b, mock, { anchor, target, revision }, setStage) { + const modelReadBack = (model, diagnostic, before) => readBack(b, target, { ...automatic, model }, diagnostic, before) + const assertSingleTurn = () => { + mock.assertRequestCount(1) + check(mock.successful === 0, 'Session preference controls requested the upstream model catalog') + } + + setStage('pin the other configured model from the real composer chooser') + await openSession(a, autoTitle, target) + await a.click(chip, 'open the composer model menu') + await modelOption(a, defaultModel, 'enabled configured default in the real provider group') + await a.browser.click(await modelOption(a, pinnedModel, 'enabled alternate model in the real provider group', false)) + await a.element(chip, 'composer renders the alternate model after pinning', pinnedModel) + revision = await modelReadBack(modelRef(pinnedModel), 'public preferences persist the exact model pin', revision) + assertSingleTurn() + + setStage('verify the selected model pin after reopening and refreshing') + await openSession(a, untitled, anchor) + await a.element(chip, 'the other session still follows the configured default', followLabel) + await openSession(a, autoTitle, target) + await a.element(chip, 'composer pin survives reopening the conversation', pinnedModel) + await a.browser.refresh() + await a.element(header, 'same conversation is restored after refreshing A', autoTitle) + await a.click(chip, 'open the composer with the persisted pin after refresh', pinnedModel) + await modelOption(a, pinnedModel, 'alternate model is still checked after refresh', true) + check(await modelReadBack(modelRef(pinnedModel), 'pin remains persisted after refresh') === revision, 'Refreshing a pinned conversation changed its revision') + assertSingleTurn() + + setStage('click Follow default and verify it after reopening and refreshing') + await a.click(`${follow}[aria-pressed="false"]`, 'explicit Follow default action from a pinned model') + await a.element(chip, 'composer now explicitly follows the default', followLabel) + revision = await modelReadBack(null, 'public preferences explicitly record Follow default as null', revision) + await openSession(a, untitled, anchor) + await openSession(a, autoTitle, target) + await a.element(chip, 'Follow default survives reopening the conversation', followLabel) + await a.browser.refresh() + await a.element(header, 'same conversation is restored after refreshing A again', autoTitle) + await a.click(chip, 'open the model chooser in the fresh document', followLabel) + await a.element(`${follow}[aria-pressed="true"]`, 'Follow default is still the selected action after refresh', followLabel) + check(await modelReadBack(null, 'Follow default remains persisted after refresh') === revision, 'Refreshing a default-following conversation changed its revision') + assertSingleTurn() +} + +const stop = new AbortController() +const abort = () => stop.abort() +process.once('SIGINT', abort) +process.once('SIGTERM', abort) +let root, workbench, mock, browserA, browserB, failed +let stage = 'validate environment' +const setStage = value => { stage = value } +try { + check(process.argv.length === 2, 'Usage: node scripts/workbench/e2e-sessions.mjs') + check(process.platform === 'linux' && process.getuid?.() > 0 && process.geteuid?.() > 0, 'Run on Linux as a non-root user') + stage = 'check build outputs' + for (const entry of ['provider', 'chat', 'library']) { + await access(new URL(`../../apps/headless/dist/${entry}-core.mjs`, import.meta.url)).catch(() => { + throw new CheckFailure('Build the headless cores with pnpm --filter @deva/headless build') + }) + } + await access(join(DEFAULT_WEB_DIR, 'index.html')).catch(() => { throw new CheckFailure('Build the Workbench with pnpm workbench:build') }) + + stage = 'start a private loopback Workbench and synthetic model fixture' + const prefix = join(await realpath(tmpdir()), 'deva-wb-sessions-') + const created = await mkdtemp(prefix) + check(created.startsWith(prefix) && created.length > prefix.length && await realpath(created) === created, 'Unexpected temporary directory') + root = created + const [keyFile, runDir, dataDir, homeA, homeB] = ['master.key', 'run', 'data', 'browser-a', 'browser-b'].map(name => join(root, name)) + await Promise.all([mkdir(homeA, { mode: 0o700 }), mkdir(homeB, { mode: 0o700 })]) + const password = randomBytes(24).toString('hex'), key = randomBytes(24).toString('hex') + await initializeMasterKey(keyFile) + mock = await startChatFixture({ key, modelId: defaultModel, otherModelId: pinnedModel }) + workbench = await startWorkbench({ dataDir, keyFile, runDir, port: 0, businessOptions: { allowedOrigins: [mock.origin] } }) + const { origin } = workbench + check(workbench.address.address === '127.0.0.1' && + (await fetch(`${origin}/readyz`, { redirect: 'error', signal: AbortSignal.timeout(5_000) })).ok, 'Workbench was not ready on loopback') + + stage = 'start sandboxed Chrome A and claim the fresh owner through its UI' + const { signal } = stop + browserA = await startLocalWebDriver({ root: homeA, profile: join(homeA, 'profile'), origin, signal }) + const a = uiFor(browserA, signal) + const { credential } = await requestControl({ runDir, op: 'claim' }) + await browserA.navigate(`${origin}/#claim=${encodeURIComponent(credential)}`) + await submitPassword(a, 'new', password) + check((await requestControl({ runDir, op: 'status' })).claimed === true, 'Unix control did not report a claimed owner') + await seedModels(a, mock.origin, key) + + stage = 'start sandboxed Chrome B with its own profile and owner login' + browserB = await startLocalWebDriver({ root: homeB, profile: join(homeB, 'profile'), origin, signal }) + const b = uiFor(browserB, signal) + await browserB.navigate(`${origin}/`) + await submitPassword(b, 'current', password) + + const sessions = await verifyTitlesAndArchive(a, b, mock, signal, setStage) + await verifyModels(a, b, mock, sessions, setStage) +} catch (error) { + failed = true + const detail = stop.signal.aborted ? 'interrupted' : + error instanceof CheckFailure || error instanceof ChatFixtureError || error instanceof WebDriverError ? error.message : 'unexpected error (raw diagnostics withheld)' + console.error(`Workbench Sessions browser E2E failed at ${stage}: ${detail}`) +} finally { + for (const [name, close] of [ + ['browser B', () => browserB?.close()], ['browser A', () => browserA?.close()], + ['Workbench', () => workbench?.close()], ['model fixture', () => mock?.close()], + ['temporary directory', async () => { + if (!root) return + check(await realpath(root) === root && (await lstat(root)).isDirectory(), 'Temporary directory has changed') + await rm(root, { recursive: true }) + const exists = await lstat(root).then(() => true, error => { if (error.code === 'ENOENT') return false; throw error }) + check(!exists, 'Temporary directory remained after cleanup') + }] + ]) { + try { await close() } catch { + failed = true + console.error(`Workbench Sessions browser E2E: ${name} cleanup failed`) + } + } + process.removeListener('SIGINT', abort) + process.removeListener('SIGTERM', abort) +} +if (failed || stop.signal.aborted) process.exitCode = 1 +else console.log('Workbench Sessions browser E2E passed: independent owner logins, live session list, title/archive/restore, and persisted pin/Follow default without additional model requests.') diff --git a/scripts/workbench/session-management-ui.test.mjs b/scripts/workbench/session-management-ui.test.mjs new file mode 100644 index 00000000..0cd7c952 --- /dev/null +++ b/scripts/workbench/session-management-ui.test.mjs @@ -0,0 +1,266 @@ +import assert from 'node:assert/strict' +import { readFile } from 'node:fs/promises' +import { createRequire } from 'node:module' +import test from 'node:test' + +const require = createRequire(new URL('../../apps/desktop/package.json', import.meta.url)) +const ts = require('typescript') +const root = new URL('../../apps/desktop/src/workbench/', import.meta.url) +async function compiled(name, imports = {}) { + const source = await readFile(new URL(`${name}.ts`, root), 'utf8') + let js = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext } }).outputText + for (const [from, to] of Object.entries(imports)) js = js.replaceAll(`'${from}'`, `'${to}'`) + return `data:text/javascript;base64,${Buffer.from(js).toString('base64')}` +} +const transportUrl = await compiled('transport') +const { createTransport, HttpFailure } = await import(transportUrl) +const { createChatTransport, sameTurnDraft } = await import(await compiled('chat-transport')) +const { createPreferenceTransport, createSessionPreferences, matchesPreferences, projectSession } = await import( + await compiled('session-preferences', { './transport': transportUrl })) +const { createListRefresh, sessionAfterRefresh } = await import(await compiled('session-list')) +const { createSessionsStream, parseSessionsFrame } = await import(await compiled('sessions-stream')) + +const json = (data, status = 200) => new Response(JSON.stringify(data), { status }) +const flush = () => new Promise((resolve) => setImmediate(resolve)) +const deferred = () => { + let resolve, reject + const promise = new Promise((yes, no) => { resolve = yes; reject = no }) + return { promise, resolve, reject } +} +const snapshot = (revision, p = {}) => ({ revision, preferences: { title: 'First message', customTitle: null, archived: false, model: null, effort: null, ...p } }) +const row = (id, extra = {}) => ({ id, title: 'First message', model: null, updatedAt: 100, writable: true, compatibility: 'text', ...extra }) + +function fakeTransport(fixtures) { + const calls = [] + const transport = createTransport(async (url, init) => { + const [method, path, body, response] = fixtures.shift() ?? [] + assert.equal(init.method, method) + assert.equal(url, `/api/v1${path}`) + assert.equal(init.credentials, 'same-origin') + assert.equal(init.headers['x-deva-csrf'], method === 'GET' ? undefined : 'owner-csrf') + assert.deepEqual(init.body ? JSON.parse(init.body) : undefined, body) + calls.push({ method, path }) + return response + }) + return { transport, calls } +} + +test('only an exact bootstrap capability enables the new owner protocol; PATCH never opens a turn', async () => { + const bootstrap = { protocol: 1, version: '1', platform: 'linux', config: {}, csrf: 'owner-csrf', expiresAt: 1900000000000 } + const base = snapshot('r1') + const pin = snapshot('r2', { model: 'enabled:qwen:8b' }) + const follow = snapshot('r3') + const send = { clientRequestId: 'request-a', text: 'message', model: null } + const fixtures = [ + ['GET', '/bootstrap', undefined, json({ ...bootstrap, capabilities: { sessionPreferences: 'true' } })], + ['GET', '/bootstrap', undefined, json({ ...bootstrap, capabilities: { sessionPreferences: true } })], + ['GET', '/chats', undefined, json({ sessions: [row('a'), row('b', { archived: true })] })], + ['GET', '/chats/a/preferences', undefined, json(base)], + ['PATCH', '/chats/a/preferences', { revision: 'r1', set: { model: 'enabled:qwen:8b' } }, json(pin)], + ['PATCH', '/chats/a/preferences', { revision: 'r2', set: { model: null } }, json(follow)], + ['POST', '/chats/a/turns', send, json({ turnId: 'turn-a', startedAt: 1, status: 'running', reason: null, duplicate: false }, 202)] + ] + const { transport, calls } = fakeTransport(fixtures) + assert.equal((await transport.inspect()).bootstrap.capabilities, undefined) + assert.deepEqual((await transport.inspect()).bootstrap.capabilities, { sessionPreferences: true }) + const chats = createChatTransport(transport, 'owner-csrf') + assert.deepEqual((await chats.list()).map(r => r.archived === true), [false, true]) + const api = createPreferenceTransport(transport, 'owner-csrf') + assert.deepEqual(await api.read('a'), base) + assert.deepEqual(await api.patch('a', base.revision, { model: 'enabled:qwen:8b' }), pin) + assert.deepEqual(await api.patch('a', pin.revision, { model: null }), follow) + assert.ok(calls.every(c => c.method !== 'POST')) + assert.equal((await chats.send('a', send)).turnId, 'turn-a') + assert.equal(sameTurnDraft(send, { ...send }), true) + assert.equal(sameTurnDraft(send, { ...send, model: pin.preferences.model }), false) + await assert.rejects(api.read('../settings'), /Invalid chat id/) + assert.deepEqual(fixtures, []) +}) + +test('stale title CAS retains the draft and latest acknowledged title for its session; reread is explicit', async () => { + const early = snapshot('a1', { title: 'Existing custom', customTitle: 'Existing custom' }) + const external = snapshot('a2', { title: 'Changed elsewhere', customTitle: 'Changed elsewhere' }) + const finalized = snapshot('a3', { title: 'My updated title', customTitle: 'My updated title' }) + const aWrite = deferred() + const seen = [], commits = [], blocked = [] + let aRead = early + const c = createSessionPreferences({ + async read(sid) { seen.push(['read', sid]); return sid === 'a' ? aRead : snapshot('b1', { model: 'enabled:b' }) }, + async patch(sid, rev, set) { seen.push(['patch', sid, rev, set]); return rev === 'a1' ? aWrite.promise : finalized } + }, { beforeWrite: async () => {}, expired: () => assert.fail('not expired'), committed: (...args) => commits.push(args), blocked: (...args) => blocked.push(args) }) + + await c.read('a') + c.beginRename('a') + c.editRename('a', ' My\n updated title ') + await c.read('b') + assert.equal(c.get('b').draft, undefined) + aRead = external + await c.read('a') // Another tab's list invalidation observes the new title, but does not change our edit baseline. + assert.equal(c.get('a').confirmed.revision, 'a2') + assert.equal(c.get('a').draft.revision, 'a1') + const writing = c.saveRename('a') + assert.equal(projectSession(row('a', external.preferences), c.get('a').pending).title, 'My updated title') + assert.equal(projectSession(row('b'), c.get('b').pending).title, 'First message') + aWrite.reject(new HttpFailure(409, 'preferences_conflict')) + assert.equal(await writing, false) + assert.equal(c.get('a').pending, undefined) + assert.equal(c.get('a').issue, 'conflict') + assert.equal(c.get('a').draft.text, ' My\n updated title ') + assert.equal(c.get('a').confirmed.preferences.title, 'Changed elsewhere') + assert.equal(c.get('b').confirmed.preferences.model, 'enabled:b') + assert.deepEqual(commits, []) + assert.deepEqual(blocked, [['a', 'conflict']]) + await c.read('a') + assert.equal(await c.saveRename('a'), false) + assert.deepEqual(seen.at(-1), ['patch', 'a', 'a1', { customTitle: 'My updated title' }]) + await c.read('a', true) + assert.deepEqual(c.get('a').draft, { text: ' My\n updated title ', initial: 'Changed elsewhere', revision: 'a2' }) + assert.equal(await c.saveRename('a'), true) + assert.deepEqual(seen.at(-1), ['patch', 'a', 'a2', { customTitle: 'My updated title' }]) + assert.equal(c.get('a').draft, undefined) + assert.deepEqual(commits, [['a', finalized.preferences]]) +}) + +test('archive CAS rolls back the optimistic row and busy/readonly/storage/expiry responses stay distinct', async () => { + const base = snapshot('r0') + assert.equal(matchesPreferences(row('a'), base), true, 'the server omits archived:false') + const archive = deferred() + let next = () => archive.promise + const blocked = [], commits = [] + let expired = 0 + const c = createSessionPreferences({ read: async () => base, async patch(_sid, rev, set) { + assert.equal(rev, base.revision) + return next(set) + } }, { beforeWrite: async () => {}, expired: () => expired++, committed: (...args) => commits.push(args), blocked: (...args) => blocked.push(args) }) + await c.read('a') + const writing = c.write('a', { archived: true }) + assert.equal(projectSession(row('a'), c.get('a').pending).archived, true) + archive.reject(new HttpFailure(409, 'preferences_conflict')) + assert.equal(await writing, false) + assert.equal(projectSession(row('a'), c.get('a').pending).archived, undefined) + assert.equal(c.get('a').needsRead, true) + await c.read('a', true) + for (const [status, code, issue] of [[409, 'turn_in_progress', 'busy'], [409, 'unsupported_history', 'readOnly'], [503, 'chat_storage_unconfirmed', 'storage']]) { + next = () => { throw new HttpFailure(status, code) } + assert.equal(await c.write('a', { archived: true }), false) + assert.equal(c.get('a').issue, issue) + if (issue !== 'busy') assert.equal(await c.write('a', { archived: true }), false, 'stale authorization requires rereading') + await c.read('a', true) + } + assert.deepEqual(blocked, [['a', 'conflict'], ['a', 'busy'], ['a', 'readOnly'], ['a', 'storage']]) + assert.deepEqual(commits, []) + next = set => { assert.deepEqual(set, { customTitle: null }); return snapshot('r1') } + c.beginRename('a') + c.editRename('a', ' \n ') + assert.equal(await c.saveRename('a'), true) + assert.equal(c.get('a').confirmed.preferences.title, 'First message') + await c.read('b') + next = () => { throw new HttpFailure(401, 'auth') } + assert.equal(await c.write('b', { archived: true }), false) + assert.equal(expired, 1) + next = () => assert.fail('no calls after revocation') + assert.equal(await c.write('b', { archived: true }), false) +}) + +function stream(invalidate, expire = () => assert.fail('not expired')) { + const links = [], timers = [] + const s = createSessionsStream({ origin: 'https://workbench.invalid:4123', invalidate, expired: expire, + open(url) { + const ws = { url, closed: false, close() { this.closed = true }, + frame(data) { this.onmessage?.({ data: JSON.stringify(data) }) }, + drop(code, reason = '') { this.onclose?.({ code, reason }) } } + links.push(ws) + return ws + }, schedule(fn, delay) { + const pending = { fn, delay, cancelled: false } + timers.push(pending) + return () => { pending.cancelled = true } + } }) + return { ...s, links, step() { + const timer = timers.findLast(t => !t.cancelled) + assert.ok(timer) + timer.cancelled = true + timer.fn() + return timer.delay + } } +} +const frame = (t, seq, generation = 'gen-a', epoch = 'epoch-a') => ({ t, cursor: { scope: 'sessions', epoch, generation, seq } }) + +test('a socket is independent of selection: fresh/reconnected/gapped watermarks invalidate GET, duplicates stay quiet', async () => { + let reads = 0 + const first = deferred(), second = deferred(), third = deferred() + const results = [], errors = [] + const active = createListRefresh(() => [first.promise, second.promise, third.promise][reads++], value => results.push(value), e => errors.push(e)) + const h = stream(active.request) + assert.equal(h.links[0].url, 'wss://workbench.invalid:4123/api/v1/chats/stream') + h.links[0].frame(frame('sessions-snapshot', 3)) + await flush() + assert.equal(reads, 1) + h.links[0].frame(frame('sessions-snapshot', 3)) + h.links[0].frame(frame('sessions-changed', 2)) + h.links[0].frame(frame('sessions-changed', 6)) // gap is one invalidation, not three reads + h.links[0].frame(frame('sessions-changed', 6)) + h.links[0].frame(frame('sessions-changed', 10)) // coalesces with seq 6 while GET is pending + await flush() + assert.equal(reads, 1) + first.resolve([row('a')]) + await flush() + assert.equal(reads, 2) + const external = [row('b'), row('a', { archived: true, title: 'Renamed externally' })] + second.resolve(external) + await flush() + assert.equal(sessionAfterRefresh(results.at(-1), 'a', 'a', true), 'a') + assert.equal(sessionAfterRefresh(results.at(-1), null, 'a', true), 'a') + assert.equal(sessionAfterRefresh(results.at(-1), null, null, true), 'b') + h.links[0].drop(1006) + assert.equal(h.step(), 500) + h.links[1].frame(frame('sessions-snapshot', 10)) // unchanged estimate still rereads on a new connection + await flush() + assert.equal(reads, 3) + third.resolve(external) + await flush() + assert.deepEqual(errors, []) + assert.equal(results.length, 3) + h.close() + active.close() + assert.ok(h.links.every(ws => ws.closed)) +}) + +test('unexpected generation or malformed envelope is recovered by GET, and auth close stops reconnecting', () => { + let invalidations = 0, expired = 0 + const h = stream(() => invalidations++, () => expired++) + h.links[0].frame(frame('sessions-snapshot', 0)) + h.links[0].frame(frame('sessions-changed', 1, 'new-gen')) + assert.equal(invalidations, 2) + assert.equal(h.links[0].closed, true) + h.step() + h.links[1].frame({ ...frame('sessions-snapshot', 0), unexpected: 'not a watermark' }) + assert.equal(invalidations, 3) + h.step() + h.links[2].frame(frame('sessions-snapshot', 0, 'new-gen', 'new-epoch')) + assert.equal(invalidations, 4) + h.links[2].drop(1008, 'auth') + assert.equal(expired, 1) + assert.throws(() => h.step()) + assert.equal(parseSessionsFrame(JSON.stringify({ t: 'sessions-changed', cursor: { ...frame('sessions-changed', 1).cursor, scope: 'chat:a' } })), null) +}) + +test('an acknowledged preference mutation suppresses a stale in-flight list result without reselecting', async () => { + const stale = deferred(), fresh = deferred() + const seen = [] + const outstanding = [stale, fresh] + const refresh = createListRefresh(() => outstanding.shift().promise, value => seen.push(value), e => assert.fail(e.message)) + refresh.request() + await flush() + refresh.afterWrite() + refresh.request() + stale.resolve([row('a')]) + await flush() + assert.deepEqual(seen, []) + fresh.resolve([row('b'), row('a', { archived: true })]) + await flush() + assert.equal(seen.length, 1) + assert.equal(sessionAfterRefresh(seen[0], 'a', null, true), 'a') + assert.equal(sessionAfterRefresh([row('b')], 'a', null, true), 'a') + refresh.close() +}) From 300adf2e0fd59a45541b6598694baa8925ee0383 Mon Sep 17 00:00:00 2001 From: Facetomyself <[GIT_EMAIL]> Date: Thu, 26 Nov 2026 16:03:23 +0800 Subject: [PATCH 4/6] =?UTF-8?q?fix(workbench):=20=E4=BB=8E=E6=A1=8C?= =?UTF-8?q?=E9=9D=A2=E6=A8=A1=E5=9E=8B=E8=8F=9C=E5=8D=95=E7=BB=A7=E6=89=BF?= =?UTF-8?q?=E5=8F=AF=E8=AE=BF=E9=97=AE=E8=AF=AD=E4=B9=89=20/=20reuse=20the?= =?UTF-8?q?=20accessible=20desktop=20model=20menu=20for=20preferences?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/renderer/src/redesign/ModelMenu.tsx | 22 +++++++++++++------ .../src/workbench/session-preference-ui.tsx | 20 ++++++----------- apps/desktop/src/workbench/text-workbench.css | 7 +++--- apps/desktop/src/workbench/text-workbench.tsx | 2 +- scripts/workbench/e2e-sessions.mjs | 4 ++-- 5 files changed, 28 insertions(+), 27 deletions(-) diff --git a/apps/desktop/src/renderer/src/redesign/ModelMenu.tsx b/apps/desktop/src/renderer/src/redesign/ModelMenu.tsx index 6e7383bf..b4f65f73 100644 --- a/apps/desktop/src/renderer/src/redesign/ModelMenu.tsx +++ b/apps/desktop/src/renderer/src/redesign/ModelMenu.tsx @@ -4,7 +4,7 @@ * 每行只写模型名(悬停提示写完整 ID)。服务商名是灰色小字、滚动时吸顶;组间不画线、不放色点。 * 列表自己滚动;打开时把当前模型滚到可见范围中间。 */ -import { useLayoutEffect, useRef } from 'react' +import { useLayoutEffect, useRef, type ReactNode } from 'react' import { Check, ChevronDown } from 'lucide-react' import './model-panel.css' import type { ModelDef, Provider } from '../mock/models' @@ -19,8 +19,12 @@ export function ModelMenu({ groups, activePid, activeMid, - onPick + onPick, + leading, + menuId }: { + leading?: ReactNode + menuId?: string groups: ModelGroup[] activePid: string | null activeMid: string | null @@ -39,7 +43,8 @@ export function ModelMenu({ }, []) return ( -
+