diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index b12fdcf0..2d825935 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -180,6 +180,25 @@ jobs:
if-no-files-found: error
retention-days: 14
+ - name: Verify owner read synchronization and the real context meter in two browsers
+ id: conversation_status_ui
+ if: ${{ !cancelled() && steps.host_tests.outcome == 'success' }}
+ timeout-minutes: 6
+ env:
+ DEVA_QA_STATUS_CAPTURE: '1'
+ run: node scripts/workbench/e2e-conversation-status.mjs
+
+ - name: Publish the verified synthetic read indicator and native context meter
+ if: ${{ !cancelled() && steps.conversation_status_ui.outcome == 'success' }}
+ uses: actions/upload-artifact@v4
+ with:
+ name: workbench-conversation-status
+ path: |
+ test-results/conversation-status/pr18-*/read-indicator.png
+ test-results/conversation-status/pr18-*/context-meter.png
+ if-no-files-found: error
+ retention-days: 14
+
- name: Select the same installed Chrome for UI and worker
if: ${{ !cancelled() && steps.host_tests.outcome == 'success' }}
id: handoff_chrome
@@ -379,6 +398,28 @@ jobs:
timeout-minutes: 3
run: node scripts/workbench/container-skill-library.mjs
+ packaged-conversation-status:
+ name: Conversation read marks and measured context across native amd64 containers
+ if: ${{ (github.event_name == 'pull_request' && github.head_ref == 'feat/web-workbench-conversation-status') || (github.event_name == 'workflow_dispatch' && github.ref_name == 'feat/web-workbench-conversation-status') }}
+ runs-on: ubuntu-latest
+ timeout-minutes: 16
+ steps:
+ - uses: actions/checkout@v5
+ - uses: actions/setup-node@v5
+ with:
+ node-version: 22
+ package-manager-cache: false
+ - name: Build the production Linux amd64 runtime image
+ timeout-minutes: 9
+ run: |
+ set -eu
+ test "$(uname -m)" = x86_64
+ docker build --platform linux/amd64 --target runtime -t deva-workbench:conversation-status-verify .
+ docker image inspect -f '{{.Os}}/{{.Architecture}} {{.Id}} {{.Size}} bytes' deva-workbench:conversation-status-verify
+ - name: Verify exact native read state and token receipt across fresh containers
+ timeout-minutes: 5
+ run: node scripts/workbench/container-conversation-status.mjs
+
packaged-project-documents:
name: Exclusive project documents across native amd64 Compose modes
if: ${{ (github.event_name == 'pull_request' && github.head_ref == 'feat/web-workbench-project-documents') || (github.event_name == 'workflow_dispatch' && github.ref_name == 'feat/web-workbench-project-documents') }}
diff --git a/Dockerfile b/Dockerfile
index 50e8dcff..30669912 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -30,7 +30,8 @@ CMD ["serve"]
FROM ${NODE_IMAGE} AS runtime
WORKDIR /opt/deva
ENV NODE_ENV=production DEVA_HOME=/data DEVA_RUN_DIR=/run/deva DEVA_MASTER_KEY_FILE=/keys/master.key DEVA_WEB_DIR=/opt/deva/web DEVA_HOST=127.0.0.1 DEVA_PORT=8787
-RUN test -x /usr/bin/flock && install -d -m 0700 -o node -g node /data /keys /run/deva /run/deva-browser-control /run/deva-pty-control
+# The read marker's xattr check uses only inherited descriptors and a fixed local Perl syscall probe.
+RUN test -x /usr/bin/flock && test -x /usr/bin/perl && install -d -m 0700 -o node -g node /data /keys /run/deva /run/deva-browser-control /run/deva-pty-control
COPY --from=build /src/apps/headless/package.json ./apps/headless/package.json
COPY --from=build /src/apps/desktop/package.json ./apps/desktop/package.json
COPY --from=build /src/apps/headless/src ./apps/headless/src
diff --git a/README.en.md b/README.en.md
index 2cacc152..7d988c1c 100644
--- a/README.en.md
+++ b/README.en.md
@@ -344,6 +344,7 @@ When memory is full, the next write by the model first consolidates the existing
The [amd64 Docker Compose workbench](apps/headless/README.md) runs independently of Electron, a remote desktop or the mobile relay, using the same React components as the desktop application.
- **Conversations:** claim the instance, configure models, stream, stop and reconnect. Use the desktop message menu to copy a selection or quote it in an unsent draft. Clipboard, sidebar shortcuts and page fullscreen belong to the client browser.
+- **Conversation status:** read marks synchronize across the owner’s browser sessions only after the latest messages are visible in the foreground. The desktop context ring distinguishes provider-reported input tokens from a saved-history estimate.
- **Library and projects:** manage profiles, roles, avatars and scoped notes. A conversation can inherit or explicitly attach an approved project; reveal a file’s parent folder in the workspace tree. A separate opt-in allows owners to review and create new Markdown or plain-text documents without replacing an existing file. Browsing or creating a document does not send it to a model.
- **Skill settings:** inspect existing skills under Settings → Extensions and save their enabled preferences and role scopes. Opening a custom skill displays its document; web chat does not load or execute skills.
- **Read-only terminal:** an optional [network-isolated PTY worker](apps/terminal-worker/README.md) displays a confirmed, saved workspace text file in the original file panel. Navigation, resize and exit come from a real native process; this is not a host command shell.
diff --git a/README.md b/README.md
index 784819d1..0c719cc5 100644
--- a/README.md
+++ b/README.md
@@ -335,6 +335,7 @@ IM 机器人支持 `/new [角色名]`、`/list`、`/stop`、`/status`、`/help`
[amd64 Docker Compose 部署与使用](apps/headless/README.md)。这是独立的服务器工作台,复用桌面 React 界面;运行时无需 Electron、远程桌面或手机版中转。
- **对话**:在浏览器认领实例、配置模型,使用原会话列表和编辑器聊天、停止、刷新续接。选中文字可复制或加入当前草稿的引用条;剪贴板、侧栏快捷键和页面全屏都属于操作电脑。
+- **会话状态**:未读标记在同一所有者的浏览器之间同步,只有前台显示到最新消息才确认已读。模型旁的原桌面圆环区分服务商返回的输入用量和根据历史得出的估算。
- **资料与项目**:管理个人资料、角色、头像和分域记忆。会话可继承或显式关联管理员登记的项目;文件页可定位当前文件夹。另行启用创建权限后,所有者可核对目标并新建 Markdown 或纯文本文档,同名文件保持原样。手动打开或创建文档不会将内容发送给模型。
- **技能设置**:在桌面同源的「设置 → 扩展」查看现有技能,保存启用偏好和角色范围。只有打开自定义条目才显示正文;Web 对话不会加载或运行这些技能。
- **只读终端**:可选的[无网络 PTY 工作器](apps/terminal-worker/README.md)在原文件面板中显示已保存的文本。翻页、调整行列、退出都由真实子进程响应;它不会提供宿主命令行。
diff --git a/apps/desktop/src/main/services/compaction.ts b/apps/desktop/src/main/services/compaction.ts
index 9fe2bf1c..628a67d1 100644
--- a/apps/desktop/src/main/services/compaction.ts
+++ b/apps/desktop/src/main/services/compaction.ts
@@ -1,6 +1,6 @@
import type { CompactStatus } from '../../shared/chat-protocol'
import { streamChat } from '../providers'
-import type { ContentPart, Message } from '../providers/types'
+import type { Message } from '../providers/types'
import { getConfig } from './config'
import { save as saveProject, type StoredSession } from './chat-store'
import { todoSnapshotText } from './todos'
@@ -15,12 +15,8 @@ import {
modelMessages,
modelRange
} from './model-view'
-import {
- DEFAULT_CONTEXT_WINDOW,
- autoContextWindow,
- autoOutputBudget,
- estimateTextTokens
-} from '../../shared/context'
+import { DEFAULT_CONTEXT_WINDOW, autoContextWindow, autoOutputBudget } from '../../shared/context'
+import { estimateTokens, messageTokens } from '../../shared/context-estimate'
/**
* 上下文压缩(主进程)。
@@ -179,41 +175,8 @@ export function triggerTokens(model: LimitModelRef, cfg: CompactionCfg = compact
return cfg.triggerRatio !== undefined ? Math.min(window * cfg.triggerRatio, byWindow) : byWindow
}
-// ── token 估算(字符法,中日韩文字另计;图片/文档按固定成本,规避 base64 数长度失真)──────
const CHARS_PER_TOKEN = 3.5
-const IMAGE_TOKENS = 1600
-const DOC_TOKENS = 3000
-
-function partTokens(p: ContentPart): number {
- switch (p.type) {
- case 'text':
- return estimateTextTokens(p.text)
- case 'tool_use':
- return estimateTextTokens(JSON.stringify(p.input ?? {})) + 8
- case 'tool_result':
- return estimateTextTokens(p.content) + 8 + (p.images?.length ?? 0) * IMAGE_TOKENS
- case 'image':
- return IMAGE_TOKENS
- case 'document':
- return DOC_TOKENS
- default:
- return 0
- }
-}
-
-function messageTokens(m: Message): number {
- if (typeof m.content === 'string') return estimateTextTokens(m.content) + 4
- let t = 4
- for (const p of m.content) t += partTokens(p)
- return t
-}
-
-/** 全历史 token 估算(触发判定的字符法回退)。 */
-export function estimateTokens(messages: Message[]): number {
- let t = 0
- for (const m of messages) t += messageTokens(m)
- return Math.round(t)
-}
+export { estimateTokens } from '../../shared/context-estimate'
/** 是否需要压缩:优先真实 usage.input,回退字符估算(只算模型看到的部分),与压缩线(见 triggerTokens)比较。 */
export function needsCompaction(
diff --git a/apps/desktop/src/renderer/src/redesign/ContextRing.tsx b/apps/desktop/src/renderer/src/redesign/ContextRing.tsx
index d09c94e4..39a1e4a5 100644
--- a/apps/desktop/src/renderer/src/redesign/ContextRing.tsx
+++ b/apps/desktop/src/renderer/src/redesign/ContextRing.tsx
@@ -6,7 +6,7 @@
* 卡片优先以圆环为中心弹出;超出窗口时往里挪,左右各留 8px。
* 没有读数(新对话、模型已删)时由 ModelPanel 整个不渲染。
*/
-import { useLayoutEffect, useRef, useState } from 'react'
+import { useLayoutEffect, useRef, useState, type ReactNode } from 'react'
import type { ContextUsage } from '../../../preload'
import { formatTokens } from '../../../shared/context'
import { useI18n } from '../i18n/i18n'
@@ -26,11 +26,15 @@ function usageText(t: T, u: ContextUsage): string {
export function ContextRing({
usage,
open,
- onToggle
+ onToggle,
+ cardId,
+ details
}: {
usage: ContextUsage
open: boolean
onToggle: () => void
+ cardId?: string
+ details?: ReactNode
}): React.JSX.Element {
const { t } = useI18n()
const text = usageText(t, usage)
@@ -62,6 +66,7 @@ export function ContextRing({
aria-label={title}
aria-haspopup="dialog"
aria-expanded={open}
+ aria-controls={open ? cardId : undefined}
onClick={onToggle}
>
@@ -70,6 +75,7 @@ export function ContextRing({
)}
+ {details}
)}
diff --git a/apps/desktop/src/shared/context-estimate.ts b/apps/desktop/src/shared/context-estimate.ts
new file mode 100644
index 00000000..f378e45b
--- /dev/null
+++ b/apps/desktop/src/shared/context-estimate.ts
@@ -0,0 +1,37 @@
+import type { ContentPart, Message } from '../main/providers/types'
+import { estimateTextTokens } from './context'
+
+// Media estimates count model-visible parts, not their wire encoding.
+const IMAGE_TOKENS = 1600
+const DOC_TOKENS = 3000
+
+function partTokens(p: ContentPart): number {
+ switch (p.type) {
+ case 'text':
+ return estimateTextTokens(p.text)
+ case 'tool_use':
+ return estimateTextTokens(JSON.stringify(p.input ?? {})) + 8
+ case 'tool_result':
+ return estimateTextTokens(p.content) + 8 + (p.images?.length ?? 0) * IMAGE_TOKENS
+ case 'image':
+ return IMAGE_TOKENS
+ case 'document':
+ return DOC_TOKENS
+ default:
+ return 0
+ }
+}
+
+export function messageTokens(m: Message): number {
+ if (typeof m.content === 'string') return estimateTextTokens(m.content) + 4
+ let t = 4
+ for (const p of m.content) t += partTokens(p)
+ return t
+}
+
+/** Character-based fallback for a model-visible message sequence. */
+export function estimateTokens(messages: Message[]): number {
+ let t = 0
+ for (const m of messages) t += messageTokens(m)
+ return Math.round(t)
+}
diff --git a/apps/desktop/src/workbench/chat-stream.ts b/apps/desktop/src/workbench/chat-stream.ts
index 154fc71a..18b40ee1 100644
--- a/apps/desktop/src/workbench/chat-stream.ts
+++ b/apps/desktop/src/workbench/chat-stream.ts
@@ -11,9 +11,12 @@ export function applyChatFrame(current: ChatSnapshot | undefined, frame: ChatFra
if (next.seq !== cursor.seq + 1) return null
const { turnId, event } = frame
if (['turn_start', 'done', 'error', 'stream_reset'].includes(event.type)) return null
- if (event.type !== 'text_delta') return { state, cursor: next } // No desktop-only features are projected into the text view.
+ if (event.type === 'context_changed' && state.active?.turnId === turnId) {
+ return { ...current, cursor: next, contextVersion: next.seq }
+ }
+ if (event.type !== 'text_delta') return { ...current, cursor: next } // Desktop-only payloads stay outside this projection.
if (!state.active || state.active.turnId !== turnId || event.text === undefined) return null
- return { cursor: next, state: { ...state, active: { ...state.active, text: state.active.text + event.text } } }
+ return { ...current, cursor: next, state: { ...state, active: { ...state.active, text: state.active.text + event.text } } }
}
export type ChatLink = 'loading' | 'ready' | 'reconnecting' | 'missing' | 'expired'
diff --git a/apps/desktop/src/workbench/chat-transport.ts b/apps/desktop/src/workbench/chat-transport.ts
index 6b58614b..c71dff42 100644
--- a/apps/desktop/src/workbench/chat-transport.ts
+++ b/apps/desktop/src/workbench/chat-transport.ts
@@ -53,7 +53,7 @@ export interface ChatState extends Omit {
lastTurn: ChatTurn | null
}
export interface ChatCursor { epoch: string; scope: string; seq: number; generation: string }
-export interface ChatSnapshot { cursor: ChatCursor; state: ChatState }
+export interface ChatSnapshot { cursor: ChatCursor; state: ChatState; contextVersion?: number }
export type ChatFrame = ({ t: 'snapshot' } & ChatSnapshot) | {
t: 'event'; cursor: ChatCursor; sessionId: string; turnId: string; type: 'chat'; event: { type: string; text?: string }
}
@@ -123,7 +123,7 @@ export function parseChatFrame(data: unknown, sid: string): ChatFrame | null {
const { type, text } = value.event
if (type === 'text_delta' && typeof text !== 'string') return null
return { t: 'event', type: 'chat', cursor: value.cursor, sessionId: sid, turnId: value.turnId,
- event: { type, ...(typeof text === 'string' ? { text } : {}) } }
+ event: { type, ...(type !== 'context_changed' && typeof text === 'string' ? { text } : {}) } }
}
} catch { /* The next authoritative snapshot replaces a malformed stream. */ }
return null
diff --git a/apps/desktop/src/workbench/conversation-status-context.tsx b/apps/desktop/src/workbench/conversation-status-context.tsx
new file mode 100644
index 00000000..fcbb12b0
--- /dev/null
+++ b/apps/desktop/src/workbench/conversation-status-context.tsx
@@ -0,0 +1,125 @@
+import { useId, useLayoutEffect, useRef, useState } from 'react'
+import { ContextRing } from '../renderer/src/redesign/ContextRing'
+import { useI18n } from '../renderer/src/i18n/i18n'
+import type { ChatProjection } from './chat-stream'
+import { fullModelRef, type ContextReport, type ConversationStatusTransport } from './conversation-status-transport'
+
+type ModelGroup = { p: { id: string }; models: readonly { id: string; contextWindow?: number; maxOutput?: number }[] }
+export type ContextTarget = { model: string | null; signature: string; refs: ReadonlySet }
+
+/** The picker only shares IDs and numeric model limits; no draft, provider address or credentials. */
+export function contextTarget(model: string | null | undefined, groups: readonly ModelGroup[], defaultRef: string | null): ContextTarget | undefined {
+ if (model !== null && !fullModelRef(model)) return
+ const settings = groups.flatMap(({ p, models }) => models.flatMap(({ id, contextWindow, maxOutput }) => {
+ const ref = `${p.id}:${id}`
+ return (model === null || model === ref) && fullModelRef(ref) ? [[ref, contextWindow ?? null, maxOutput ?? null] as const] : []
+ }))
+ if (!settings.length) return
+ return { model, signature: JSON.stringify([model === null ? defaultRef : null, settings]), refs: new Set(settings.map(([ref]) => ref)) }
+}
+
+export function contextAuthority(projection: ChatProjection | undefined, sid: string): { scope: string; version: number | null } | undefined {
+ const snapshot = projection?.snapshot
+ const state = snapshot?.state
+ if (projection?.status !== 'ready' || !snapshot || state?.id !== sid || state.compatibility !== 'text' || snapshot.cursor.scope !== `chat:${sid}`) return
+ const { active, lastTurn } = state
+ return {
+ scope: JSON.stringify([snapshot.cursor.epoch, snapshot.cursor.generation, state.updatedAt, active?.turnId, lastTurn?.turnId, lastTurn?.status]),
+ version: snapshot.contextVersion ?? null
+ }
+}
+
+const copy = {
+ en: {
+ measured: 'Previous request · measured input tokens', live: 'Current turn · measured input tokens',
+ estimate: 'Estimate from saved conversation history', none: 'No context usage yet',
+ unavailable: 'Context usage unavailable', loading: 'Loading context usage…', close: 'Close'
+ },
+ 'zh-CN': {
+ measured: '上次请求 · 实测输入 token', live: '当前回合 · 实测输入 token',
+ estimate: '根据已保存的对话历史估算', none: '暂无上下文用量',
+ unavailable: '上下文用量暂不可用', loading: '正在读取上下文用量…', close: '关闭'
+ }
+}
+
+type Props = {
+ api: ConversationStatusTransport
+ sid: string
+ projection?: ChatProjection
+ target?: ContextTarget
+ blocked: boolean
+ modelReady: boolean
+ onExpired: () => void
+}
+
+export function WorkbenchContextMeter({ api, sid, projection, target, blocked, modelReady, onExpired }: Props): React.JSX.Element | null {
+ const { locale } = useI18n()
+ const label = copy[locale]
+ const authority = contextAuthority(projection, sid)
+ const model = target?.model
+ const scope = !blocked && modelReady && target && authority ? JSON.stringify([sid, model, target.signature, authority.scope]) : undefined
+ const version = authority?.version
+ const [result, setResult] = useState<{ api: Props['api']; scope: string; report?: ContextReport }>()
+ const [opened, setOpened] = useState()
+ const root = useRef(null)
+ const closeButton = useRef(null)
+ const expired = useRef(onExpired)
+ const cardId = useId()
+ useLayoutEffect(() => { expired.current = onExpired }, [onExpired])
+ useLayoutEffect(() => {
+ if (model === undefined || !scope) return
+ const controller = new AbortController()
+ void api.usage(sid, model, controller.signal).then((report) => {
+ if (!controller.signal.aborted) setResult({ api, scope, report })
+ }, (error: unknown) => {
+ if (controller.signal.aborted) return
+ setResult({ api, scope })
+ if ((error as { status?: number } | null)?.status === 401) expired.current()
+ })
+ return () => controller.abort()
+ }, [api, sid, model, scope, version])
+
+ const settled = result?.api === api && result.scope === scope ? result : undefined
+ const report = settled?.report
+ const known = !!report?.modelRef && !!target?.refs.has(report.modelRef)
+ const usage = known && report?.usage?.used != null ? report.usage : undefined
+ const source = !target || (settled && !known) ? 'unavailable' : report?.source ?? 'loading'
+ const open = !!usage && !!scope && opened === scope
+ const close = (restoreFocus: boolean): void => {
+ setOpened(undefined)
+ if (restoreFocus) root.current?.querySelector('.cf-mp__ringbtn')?.focus({ preventScroll: true })
+ }
+ useLayoutEffect(() => { setOpened(undefined); setResult(undefined) }, [api, scope])
+ useLayoutEffect(() => {
+ if (!open) return
+ closeButton.current?.focus({ preventScroll: true })
+ const escape = (event: KeyboardEvent): void => {
+ if (event.key !== 'Escape') return
+ event.preventDefault()
+ event.stopPropagation()
+ close(true)
+ }
+ const outside = (event: Event): void => {
+ if (event.target && !root.current?.contains(event.target as Node)) close(false)
+ }
+ document.addEventListener('keydown', escape, true)
+ document.addEventListener('pointerdown', outside, true)
+ document.addEventListener('focusin', outside)
+ return () => {
+ document.removeEventListener('keydown', escape, true)
+ document.removeEventListener('pointerdown', outside, true)
+ document.removeEventListener('focusin', outside)
+ }
+ }, [open])
+
+ if (blocked || !modelReady || !authority) return null
+ if (!usage) return {label[source]}
+ return
+
open ? close(true) : setOpened(scope)} cardId={cardId}
+ details={
+ {label[source]}
+
+
} />
+
+}
diff --git a/apps/desktop/src/workbench/conversation-status-reads.ts b/apps/desktop/src/workbench/conversation-status-reads.ts
new file mode 100644
index 00000000..b0264cfc
--- /dev/null
+++ b/apps/desktop/src/workbench/conversation-status-reads.ts
@@ -0,0 +1,165 @@
+import type { ChatProjection } from './chat-stream'
+import type { ChatCursor, ChatState, ChatSummary } from './chat-transport'
+import type { ConversationStatusTransport, ReadEntry, ReadObservation } from './conversation-status-transport'
+
+const EMPTY = new Map()
+export type ReadView = { entries: ReadonlyMap; phase: 'idle' | 'reading' | 'ready' | 'unavailable'; review?: string }
+export const emptyReadView: ReadView = { entries: EMPTY, phase: 'idle' }
+export const noReadSubscription = () => () => {}
+const maxRemembered = 256
+const isExpired = (error: unknown) => (error as { status?: number } | null)?.status === 401
+
+export function eligibleReadRow>(row: T | undefined): row is T {
+ return !!row && (row.compatibility === 'text' || row.compatibility === 'legacy_text') && !row.archived && !row.id.startsWith('task-')
+}
+
+export function matchingReadEntry(view: ReadView, row: ChatSummary | undefined): ReadEntry | undefined {
+ if (!eligibleReadRow(row)) return
+ const entry = view.entries.get(row.id)
+ return entry?.updatedAt === row.updatedAt ? entry : undefined
+}
+
+export function hasDisplayedMessages(state: ChatState): boolean {
+ return !!state.messages?.some(({ content, attachments }) => !!content.trim() || !!attachments?.length)
+}
+
+export function observeReading(row: ChatSummary | undefined, projection: ChatProjection | undefined, shown: boolean): ReadObservation | undefined {
+ if (!shown || !eligibleReadRow(row) || projection?.status !== 'ready') return
+ const snapshot = projection.snapshot
+ const state = snapshot?.state
+ if (!snapshot || !eligibleReadRow(state) || state.id !== row.id || state.updatedAt !== row.updatedAt || state.compatibility !== row.compatibility ||
+ state.active || state.lastTurn?.status === 'running' || !hasDisplayedMessages(state) || snapshot.cursor.scope !== `chat:${row.id}`) return
+ return { id: row.id, updatedAt: row.updatedAt, cursor: snapshot.cursor }
+}
+
+export function sameReadCursor(a: ChatCursor, b: ChatCursor): boolean {
+ return a.scope === b.scope && a.epoch === b.epoch && a.generation === b.generation && a.seq === b.seq
+}
+
+/** Per login. Map refreshes follow the existing list owner; mutations never retry themselves. */
+export function createConversationReads(api: Pick, expired: () => void) {
+ let rows: readonly ChatSummary[] = []
+ let selected: string | null = null
+ let current = emptyReadView
+ let query: AbortController | undefined
+ let write: { controller: AbortController; observation: ReadObservation } | undefined
+ let explicitRetry: string | undefined
+ const listeners = new Set<() => void>()
+ const attempted = new Map()
+ const held = new Set()
+
+ function remember(map: Map, key: string, value: T): void {
+ map.delete(key)
+ map.set(key, value)
+ if (map.size > maxRemembered) map.delete(map.keys().next().value!)
+ }
+ function hold(id: string): void {
+ held.delete(id)
+ held.add(id)
+ if (held.size > maxRemembered) held.delete(held.values().next().value!)
+ }
+ function publish(phase: ReadView['phase'], entries: ReadView['entries']): void {
+ current = { phase, entries, review: selected && held.has(selected) ? selected : undefined }
+ listeners.forEach((listener) => listener())
+ }
+ function abortWrite(): void {
+ const pending = write
+ write = undefined
+ if (!pending) return
+ hold(pending.observation.id) // Abort cannot tell whether a dispatched write committed.
+ pending.controller.abort()
+ }
+ async function refresh(): Promise {
+ query?.abort()
+ query = undefined
+ if (!rows.some(eligibleReadRow)) { publish('idle', EMPTY); return }
+ const controller = new AbortController()
+ query = controller
+ publish('reading', current.entries)
+ try {
+ const entries = await api.reads(controller.signal)
+ if (query !== controller || controller.signal.aborted) return
+ // Every new owner-list snapshot gets a fresh map, even with the same IDs and timestamps.
+ query = undefined
+ if (selected) {
+ const entry = entries.get(selected)
+ const row = rows.find((candidate) => candidate.id === selected)
+ if (entry && entry.updatedAt === row?.updatedAt && !entry.unread) {
+ if (explicitRetry === selected) explicitRetry = undefined
+ held.delete(selected)
+ }
+ }
+ publish('ready', entries)
+ } catch (error) {
+ if (query !== controller || controller.signal.aborted) return
+ query = undefined
+ explicitRetry = undefined
+ publish('unavailable', EMPTY)
+ if (isExpired(error)) expired()
+ }
+ }
+ async function mark(observation: ReadObservation): Promise {
+ const { id, updatedAt, cursor } = observation
+ const row = rows.find((candidate) => candidate.id === id)
+ const entry = matchingReadEntry(current, row)
+ if (write || current.phase !== 'ready' || selected !== id || !entry?.unread || entry.updatedAt !== updatedAt) return
+ const key = JSON.stringify([id, updatedAt])
+ if (explicitRetry !== id && (held.has(id) || attempted.has(key))) return
+ explicitRetry = undefined
+ remember(attempted, key, cursor)
+ const controller = new AbortController()
+ const job = { controller, observation }
+ write = job
+ try {
+ const { changed: _changed, ...ack } = await api.mark(observation, controller.signal)
+ if (write !== job || controller.signal.aborted) return
+ write = undefined
+ held.delete(id)
+ if (query || ack.readAt === null) { void refresh(); return }
+ const shown = current.entries.get(id)
+ if (current.phase === 'ready' && shown?.updatedAt === updatedAt) {
+ publish('ready', new Map(current.entries).set(id, ack))
+ } else publish(current.phase, current.entries)
+ } catch (error) {
+ if (write !== job || controller.signal.aborted) return
+ write = undefined
+ hold(id)
+ if (isExpired(error)) { publish('unavailable', EMPTY); expired(); return }
+ // Read the authoritative result under this login; a conflict and a lost acknowledgement are both non-replayable.
+ void refresh()
+ }
+ }
+ return {
+ snapshot: () => current,
+ subscribe(listener: () => void) { listeners.add(listener); return () => { listeners.delete(listener) } },
+ scope(nextRows: readonly ChatSummary[], sid: string | null) {
+ if (nextRows === rows && sid === selected) return
+ if (sid !== selected) {
+ abortWrite()
+ explicitRetry = undefined
+ }
+ rows = nextRows
+ selected = sid
+ void refresh()
+ },
+ mark,
+ retry(id: string) {
+ if (id !== selected || write) return
+ explicitRetry = id
+ void refresh()
+ },
+ close() {
+ query?.abort()
+ query = undefined
+ abortWrite()
+ explicitRetry = undefined
+ attempted.clear()
+ held.clear()
+ rows = []
+ selected = null
+ current = emptyReadView
+ }
+ }
+}
+
+export type ConversationReads = ReturnType
diff --git a/apps/desktop/src/workbench/conversation-status-transport.ts b/apps/desktop/src/workbench/conversation-status-transport.ts
new file mode 100644
index 00000000..e5276b24
--- /dev/null
+++ b/apps/desktop/src/workbench/conversation-status-transport.ts
@@ -0,0 +1,97 @@
+import type { ContextUsage } from '../shared/chat-protocol'
+import type { ChatCursor } from './chat-transport'
+import type { Bootstrap, Transport } from './transport'
+
+export type ReadEntry = { id: string; updatedAt: number; readAt: number | null; unread: boolean }
+export type ReadObservation = Pick & { cursor: ChatCursor }
+export type ContextSource = 'none' | 'estimate' | 'measured' | 'live' | 'unavailable'
+export type ContextReport = { modelRef: string | null; usage: ContextUsage | null; source: ContextSource; compaction: 'inactive' }
+
+type Wire = Record
+function exact(value: unknown, ...keys: string[]): value is Wire {
+ return typeof value === 'object' && value !== null && !Array.isArray(value) &&
+ Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key))
+}
+const validId = (value: unknown): value is string => typeof value === 'string' && /^[A-Za-z0-9_-]{1,128}$/u.exec(value)?.[0] === value
+const timestamp = (value: unknown): value is number => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0
+const uuidV4 = (value: unknown): value is string => typeof value === 'string' && value.length === 36 &&
+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u.test(value)
+const modelBytes = new TextEncoder()
+const reservedProviders = new Set(['__proto__', 'constructor', 'prototype'])
+const maxWindow = 20_000_000
+const maxReadEntries = 8192
+
+export function fullModelRef(value: unknown): value is string {
+ // Match the server's context model grammar; /u treats paired surrogates as one code point.
+ if (typeof value !== 'string' || value.length > 609 || value !== value.trim() || /[\x00-\x1f\x7f\ud800-\udfff]/u.test(value)) return false
+ const colon = value.indexOf(':')
+ const provider = value.slice(0, colon)
+ const model = value.slice(colon + 1)
+ return colon > 0 && /^[A-Za-z0-9][A-Za-z0-9_.-]{0,95}$/u.test(provider) && !reservedProviders.has(provider) &&
+ !!model && model === model.trim() && modelBytes.encode(model).length <= 512
+}
+function readEntry(value: Wire): value is Wire & ReadEntry {
+ return validId(value.id) && timestamp(value.updatedAt) && (value.readAt === null || timestamp(value.readAt)) && typeof value.unread === 'boolean'
+}
+function chatPath(id: string): string {
+ if (!validId(id)) throw new Error('Invalid conversation status scope')
+ return `/chats/${id}`
+}
+function contextReport(value: unknown, model: string | null): value is ContextReport {
+ if (!exact(value, 'modelRef', 'usage', 'source', 'compaction') || value.compaction !== 'inactive') return false
+ const { modelRef, usage, source } = value
+ if (source === 'unavailable') return modelRef === null && usage === null
+ if (!fullModelRef(modelRef) || (model !== null && model !== modelRef) ||
+ !exact(usage, 'used', 'estimated', 'window', 'trigger') || !timestamp(usage.window) || usage.window === 0 ||
+ usage.window > maxWindow || usage.trigger !== null) return false
+ if (source === 'none') return usage.used === null && usage.estimated === false
+ if (!timestamp(usage.used)) return false
+ return source === 'estimate' ? usage.estimated === true :
+ (source === 'measured' || source === 'live') && usage.used > 0 && usage.estimated === false
+}
+
+export function createConversationStatusTransport(transport: Transport, bootstrap: Bootstrap) {
+ if (bootstrap.capabilities?.conversationStatus !== true || !bootstrap.csrf) return undefined
+ const { csrf } = bootstrap
+ const post = (path: string, body: object, signal: AbortSignal) =>
+ transport.request(path, 'POST', body, csrf, { signal, referrerPolicy: 'same-origin' })
+ return {
+ async reads(signal: AbortSignal): Promise> {
+ const result = await transport.request('/conversation-status/reads', 'GET', undefined, undefined, { signal })
+ if (!exact(result, 'entries') || !Array.isArray(result.entries) || result.entries.length > maxReadEntries) {
+ throw new Error('Invalid conversation read map')
+ }
+ const entries = new Map()
+ for (const row of result.entries) {
+ if (!exact(row, 'id', 'updatedAt', 'readAt', 'unread') || !readEntry(row) || entries.has(row.id) ||
+ row.unread !== (row.readAt === null || row.readAt < row.updatedAt)) {
+ throw new Error('Invalid conversation read entry')
+ }
+ entries.set(row.id, row)
+ }
+ return entries
+ },
+ async mark({ id, updatedAt, cursor }: ReadObservation, signal: AbortSignal): Promise {
+ const path = chatPath(id)
+ const { scope, epoch, generation, seq } = cursor
+ if (!timestamp(updatedAt) || scope !== `chat:${id}` || !uuidV4(epoch) || !uuidV4(generation) || !timestamp(seq)) {
+ throw new Error('Invalid conversation read observation')
+ }
+ const result = await post(`${path}/read-state`, { updatedAt, cursor: { scope, epoch, generation, seq } }, signal)
+ if (!exact(result, 'id', 'updatedAt', 'readAt', 'unread', 'changed') || !readEntry(result) || result.id !== id ||
+ result.updatedAt !== updatedAt || result.unread !== false || typeof result.changed !== 'boolean' ||
+ (result.changed ? result.readAt !== updatedAt : (result.readAt !== null && result.readAt < updatedAt))) {
+ throw new Error('Invalid conversation read acknowledgement')
+ }
+ return { id, updatedAt, readAt: result.readAt, unread: false, changed: result.changed }
+ },
+ async usage(id: string, model: string | null, signal: AbortSignal): Promise {
+ if (model !== null && !fullModelRef(model)) throw new Error('Invalid context model reference')
+ const result = await post(`${chatPath(id)}/context-usage`, { model }, signal)
+ if (!contextReport(result, model)) throw new Error('Invalid conversation context report')
+ return result
+ }
+ }
+}
+
+export type ConversationStatusTransport = NonNullable>
diff --git a/apps/desktop/src/workbench/conversation-status-ui.tsx b/apps/desktop/src/workbench/conversation-status-ui.tsx
new file mode 100644
index 00000000..b1f327cb
--- /dev/null
+++ b/apps/desktop/src/workbench/conversation-status-ui.tsx
@@ -0,0 +1,111 @@
+import { useLayoutEffect, useMemo, useRef, useSyncExternalStore, type ReactNode, type RefObject } from 'react'
+import type { ChatProjection } from './chat-stream'
+import type { ChatSummary } from './chat-transport'
+import {
+ createConversationReads, eligibleReadRow, emptyReadView, hasDisplayedMessages, matchingReadEntry,
+ noReadSubscription, observeReading, sameReadCursor
+} from './conversation-status-reads'
+import type { ConversationStatusTransport, ReadEntry } from './conversation-status-transport'
+import './conversation-status.css'
+
+const getEmptyView = () => emptyReadView
+
+export function useConversationReadMap(api: ConversationStatusTransport | undefined, rows: readonly ChatSummary[],
+ sid: string | null, onExpired: () => void) {
+ const expired = useRef(onExpired)
+ useLayoutEffect(() => { expired.current = onExpired }, [onExpired])
+ const reads = useMemo(() => api && createConversationReads(api, () => expired.current()), [api])
+ useLayoutEffect(() => () => reads?.close(), [reads])
+ useLayoutEffect(() => { reads?.scope(rows, sid) }, [reads, rows, sid])
+ const snapshot = reads?.snapshot ?? getEmptyView
+ const readView = useSyncExternalStore(reads?.subscribe ?? noReadSubscription, snapshot, snapshot)
+ return { reads, readView }
+}
+
+export function ReadThreadRow({ id, enabled, entry, children }: { id: string; enabled: boolean; entry?: ReadEntry; children: ReactNode }): React.JSX.Element {
+ return enabled ? {children}
: <>{children}>
+}
+
+export function readViewInForeground(doc: Document, scroller: HTMLDivElement | null): boolean {
+ if (!scroller?.isConnected || doc.visibilityState !== 'visible' || !doc.hasFocus() ||
+ (doc.fullscreenElement && !doc.fullscreenElement.contains(scroller)) ||
+ doc.querySelector('[aria-modal="true"], dialog[open]') ||
+ scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight > 64) return false
+ const messages = scroller.querySelectorAll('.cf-msg[data-role]:not([data-streaming])')
+ const newest = messages[messages.length - 1]?.getBoundingClientRect()
+ const viewport = scroller.getBoundingClientRect()
+ return !!newest && newest.bottom > viewport.top && newest.top < viewport.bottom && newest.width > 0 && viewport.width > 0
+}
+
+type ReadDisplay = {
+ row?: ChatSummary
+ projection?: ChatProjection
+ current: () => ChatProjection | undefined
+ refresh: () => void
+ blocked: boolean
+ atBottom: boolean
+ hasContent: boolean
+ scroller: RefObject
+}
+
+export function DisplayedReadStatus({ reads, readView, locale, ...display }: ReturnType & ReadDisplay & {
+ locale: string
+}): React.JSX.Element | null {
+ const { row, projection, blocked, atBottom, hasContent } = display
+ const entry = matchingReadEntry(readView, row)
+ const observation = observeReading(row, projection, !blocked && atBottom && hasContent)
+ const displayed = useRef(display)
+ useLayoutEffect(() => { displayed.current = display })
+ const id = observation?.id
+ const updatedAt = observation?.updatedAt
+ const cursor = observation?.cursor
+ const canObserve = !!reads && !!entry?.unread && readView.phase === 'ready' && !!id && !!cursor
+ useLayoutEffect(() => {
+ if (!reads || !canObserve || !id || !cursor) return
+ let frame: number | undefined
+ const afterPaint = (): void => {
+ if (frame !== undefined) window.cancelAnimationFrame(frame)
+ frame = window.requestAnimationFrame(() => {
+ frame = window.requestAnimationFrame(() => {
+ frame = undefined
+ const view = displayed.current
+ const live = observeReading(view.row, view.current(), !view.blocked && view.atBottom && view.hasContent &&
+ readViewInForeground(document, view.scroller.current))
+ if (live && live.id === id && live.updatedAt === updatedAt && sameReadCursor(live.cursor, cursor)) void reads.mark(live)
+ })
+ })
+ }
+ afterPaint()
+ window.addEventListener('focus', afterPaint)
+ document.addEventListener('visibilitychange', afterPaint)
+ document.addEventListener('fullscreenchange', afterPaint)
+ return () => {
+ if (frame !== undefined) window.cancelAnimationFrame(frame)
+ window.removeEventListener('focus', afterPaint)
+ document.removeEventListener('visibilitychange', afterPaint)
+ document.removeEventListener('fullscreenchange', afterPaint)
+ }
+ }, [reads, canObserve, id, updatedAt, cursor, readView])
+
+ const state = projection?.snapshot?.state
+ if (!reads || !eligibleReadRow(row) || !eligibleReadRow(state) || state.id !== row.id || state.active || !hasDisplayedMessages(state)) return null
+ const review = readView.review === row.id
+ const unavailable = readView.phase === 'unavailable' || (readView.phase === 'ready' && !entry && projection?.status === 'ready' && state.updatedAt === row.updatedAt)
+ const phase = review ? 'review' : unavailable ? 'unavailable' : readView.phase !== 'ready' || !entry ? 'loading' : entry.unread ? 'unread' : 'read'
+ const zh = locale === 'zh-CN'
+ const text = {
+ review: zh ? '请刷新并重新确认已读状态。' : 'Refresh and verify the read status.',
+ unavailable: zh ? '此对话的已读状态暂不可用。' : 'Read status is unavailable for this conversation.',
+ loading: zh ? '正在读取已读状态…' : 'Loading read status…',
+ unread: zh ? '未读' : 'Unread',
+ read: zh ? '已读' : 'Read'
+ }[phase]
+ const feedback = review || unavailable
+ return
+ {text}
+ {feedback && }
+
+}
diff --git a/apps/desktop/src/workbench/conversation-status.css b/apps/desktop/src/workbench/conversation-status.css
new file mode 100644
index 00000000..8ce28844
--- /dev/null
+++ b/apps/desktop/src/workbench/conversation-status.css
@@ -0,0 +1,53 @@
+.wb-read__row {
+ display: contents;
+}
+
+.wb-read__feedback {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px 8px;
+ align-items: baseline;
+ padding: 4px 16px;
+ color: var(--fg-muted);
+ font-size: 12px;
+ line-height: 1.5;
+}
+
+.wb-context__state {
+ color: var(--fg-muted);
+ font-size: 12px;
+ line-height: 1.5;
+ text-align: end;
+}
+
+.wb-context__details {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: space-between;
+ align-items: baseline;
+ gap: 4px 8px;
+ margin-block-start: 8px;
+ color: var(--fg-muted);
+ font-size: 12px;
+ line-height: 1.5;
+}
+
+.wb-context button:focus-visible,
+.wb-read__feedback button:focus-visible {
+ outline: 2px solid var(--fg-muted);
+ outline-offset: 2px;
+}
+
+.wb-read__feedback button:disabled {
+ opacity: 0.55;
+ cursor: default;
+}
+
+.wb-status__sr-only {
+ position: absolute;
+ inline-size: 1px;
+ block-size: 1px;
+ overflow: hidden;
+ clip-path: inset(50%);
+ white-space: nowrap;
+}
diff --git a/apps/desktop/src/workbench/text-workbench.tsx b/apps/desktop/src/workbench/text-workbench.tsx
index 7c1c548f..7e255805 100644
--- a/apps/desktop/src/workbench/text-workbench.tsx
+++ b/apps/desktop/src/workbench/text-workbench.tsx
@@ -18,7 +18,11 @@ import { createManualBrowserPanel, type ManualBrowserPanel } from './browser-man
import { ManualBrowserDialog } from './browser-panel'
import { createBrowserTransport, type BrowserTransport } from './browser-transport'
import { chatCopy, turnLabel, type ChatCopy } from './chat-copy'
-import { createChatTransport, type ChatState } from './chat-transport'
+import { createChatTransport, type ChatState, type ChatSummary } from './chat-transport'
+import { contextTarget, WorkbenchContextMeter } from './conversation-status-context'
+import { eligibleReadRow, matchingReadEntry } from './conversation-status-reads'
+import { createConversationStatusTransport, type ConversationStatusTransport } from './conversation-status-transport'
+import { DisplayedReadStatus, ReadThreadRow, useConversationReadMap } from './conversation-status-ui'
import { ConversationSelectionStatus, useConversationSelection } from './conversation-selection-ui'
import { eligibleDeliveryReplies } from './deliveries-controller'
import { createDeliveriesTransport, type DeliveriesTransport, type DeliveryGroup, type DeliveryLocation } from './deliveries-transport'
@@ -57,6 +61,7 @@ type TextWorkbenchProps = {
}
type Workspace = ReturnType
const EMPTY: NonNullable = []
+const EMPTY_ROWS: ChatSummary[] = []
const PAGE = 80
const WORKSPACE_OPEN = 'workbench-workspace-open'
const emptyVersion = () => 0
@@ -70,7 +75,9 @@ export default function TextWorkbench({ transport, bootstrap, beforeWrite, onExp
const preferenceApi = useMemo(() => preferenceEnabled ? createPreferenceTransport(transport, bootstrap.csrf) : undefined,
[preferenceEnabled, transport, bootstrap.csrf])
const workspacesEnabled = bootstrap.capabilities?.sessionWorkspaces === true
- const wk = useTextWorkbench(api, beforeWrite, onExpired, bootstrap.capabilities?.attachments === true, preferenceApi, workspacesEnabled)
+ const statusApi = useMemo(() => createConversationStatusTransport(transport, bootstrap), [transport, bootstrap])
+ const wk = useTextWorkbench(api, beforeWrite, onExpired, bootstrap.capabilities?.attachments === true, preferenceApi, workspacesEnabled, !!statusApi)
+ const reads = useConversationReadMap(statusApi, locked ? EMPTY_ROWS : wk.sessions, locked ? null : wk.selected, onExpired)
const preferences = wk.preferences
const preferenceVersion = useSyncExternalStore(preferences?.subscribe ?? emptySubscribe, preferences?.version ?? emptyVersion)
const [archivedView, setArchivedView] = useState(false)
@@ -232,6 +239,9 @@ export default function TextWorkbench({ transport, bootstrap, beforeWrite, onExp
shortcutActive: !locked && !tasksVisible && !settingsOpen && !panel && !(renameSid && renameSid === sid) &&
!browserVisible && !filesOpen && !(sid && locatedFilesSid === sid) && !approvedProject,
onToggleSidebar: () => setCompact(value => !value) })
+ const statusBlocked = locked || tasksVisible || settingsOpen || !!panel || (!!renameSid && renameSid === sid) ||
+ !!browserVisible || filesOpen || (!!sid && locatedFilesSid === sid) || !!approvedProject || !!clientShell.fullscreen?.view.busy ||
+ clientShell.fullscreen?.view.state === 'foreign'
const surface =
{c[wk.listIssue]}{' '}
{wk.listIssue === 'listFailure' && }
}
- {visibleRows.length ? visibleRows.map((s) => { wk.select(s.id); if (viewport.w < 780) setCompact(true) }} />)
- : !wk.listLoading && !wk.listIssue && {query && !archivedView ? t('cf.searchNoResults') : t('chat.noSessions')}
}
+ {visibleRows.length ? visibleRows.map((s) => {
+ const entry = !statusApi || archivedView || (state?.id === s.id && !eligibleReadRow(state))
+ ? undefined : matchingReadEntry(reads.readView, s)
+ const streaming = s.id === sid && !!state?.active
+ return { wk.select(s.id); if (viewport.w < 780) setCompact(true) }} />
+ }) : !wk.listLoading && !wk.listIssue && {query && !archivedView ? t('cf.searchNoResults') : t('chat.noSessions')}
}
>}
@@ -313,11 +327,15 @@ export default function TextWorkbench({ transport, bootstrap, beforeWrite, onExp
managedModel={preferences ? {
pinned: preferenceEntry?.pending?.model !== undefined ? preferenceEntry.pending.model : confirmedModel,
disabled: preferenceControlsDisabled || selectedEntry?.model !== confirmedModel,
+ contextReady: !!preferenceEntry?.confirmed && selectedEntry?.model === confirmedModel &&
+ !(preferenceEntry.pending || preferenceEntry.reading || preferenceEntry.needsRead),
choose: (model) => {
if (!preferenceControlsDisabled && model !== preferenceEntry?.confirmed?.preferences.model) void preferences.write(sid, { model })
}
} : undefined}
openSettings={openSettings} openFiles={openFiles} workspaceLabel={workspaceLabel}
+ conversationStatus={statusApi ? { api: statusApi, reads, row: selectedEntry, contextBlocked: statusBlocked,
+ readBlocked: statusBlocked || archivedView || !!projectedEntry?.archived || !!wk.pending || !!wk.listIssue } : undefined}
deliveryApi={deliveryApi} locale={locale} beforeWrite={beforeWrite} onExpired={onExpired}
openInWorkspace={files ? openInWorkspace : undefined} />
:
@@ -351,12 +369,17 @@ export default function TextWorkbench({ transport, bootstrap, beforeWrite, onExp
}}>{surface} : surface
}
-type ManagedModel = { pinned: string | null | undefined; disabled: boolean; choose: (model: string | null) => void }
+type ManagedModel = { pinned: string | null | undefined; disabled: boolean; contextReady: boolean; choose: (model: string | null) => void }
+type StatusOptions = {
+ api: ConversationStatusTransport; reads: ReturnType
; row?: ChatSummary
+ contextBlocked: boolean; readBlocked: boolean
+}
function TextThread({ sid, wk, c, locked, preferred, onPick, managedModel, openSettings, openFiles, workspaceLabel,
- deliveryApi, locale, beforeWrite, onExpired, openInWorkspace }: {
+ deliveryApi, locale, beforeWrite, onExpired, openInWorkspace, conversationStatus }: {
sid: string; wk: Workspace; c: ChatCopy; locked: boolean; preferred: string | null; onPick: (id: string) => void; openSettings: () => void
openFiles?: () => void; workspaceLabel: string; managedModel?: ManagedModel; deliveryApi?: DeliveriesTransport; locale: string
+ conversationStatus?: StatusOptions
beforeWrite: () => Promise; onExpired: () => void; openInWorkspace?: (where: DeliveryLocation, signal: AbortSignal) => Promise
}): React.JSX.Element {
const state = wk.projection?.snapshot?.state
@@ -445,6 +468,10 @@ function TextThread({ sid, wk, c, locked, preferred, onPick, managedModel, openS
: state?.writeBlockReason === 'role_unavailable' ? c.roleUnavailable
: state?.writeBlockReason === 'session_turn_limit' ? c.limit : state && !state.writable ? c.locked : undefined
return <>
+ {conversationStatus && wk.currentReadProjection(sid)} blocked={conversationStatus.readBlocked} atBottom={atBottom}
+ hasContent={visibleMessages.some(({ message, cards }) => !!message.content.trim() || !!cards?.length)} scroller={scroll}
+ refresh={() => { wk.refreshProjection(sid); wk.refreshList() }} />}
{
const el = event.currentTarget
@@ -491,17 +518,19 @@ function TextThread({ sid, wk, c, locked, preferred, onPick, managedModel, openS
writeLocked={!canQuote || !!wk.pending}
stopping={link !== 'ready' || !!wk.pending} active={active} send={wk.send} stop={wk.stop} c={c}
jump={!atBottom ? jump : undefined} openFiles={openFiles} workspaceLabel={workspaceLabel}
+ context={conversationStatus ? { api: conversationStatus.api, projection: wk.projection, blocked: conversationStatus.contextBlocked, onExpired } : undefined}
attachmentDraft={attachmentDraft} add={add} remove={remove} />}
{state?.turnLimit && state.writable && {c.limits.replace('{turns}', String(state.turnLimit))}
}
>
}
function TextComposer({ sid, drafts, focusComposer, clipboardLocked, model, onPick, managedModel, openSettings, writeLocked, stopping, active, send, stop, c, jump, openFiles, workspaceLabel,
- attachmentDraft, add, remove }: {
+ attachmentDraft, add, remove, context }: {
sid: string; drafts: Workspace['drafts']; focusComposer: React.MutableRefObject<(() => void) | undefined>; clipboardLocked: boolean
model: string; onPick: (id: string) => void; managedModel?: ManagedModel; openSettings: () => void
writeLocked: boolean; stopping: boolean; active: ChatState['active'] | undefined; send: Workspace['send']; stop: Workspace['stop']; c: ChatCopy; jump?: () => void
openFiles?: () => void; workspaceLabel: string; attachmentDraft: AttachmentDraft; add?: (files: BrowserFiles) => void; remove?: (key: string) => void
+ context?: Pick[0], 'api' | 'projection' | 'blocked' | 'onExpired'>
}): React.JSX.Element {
const { t } = useI18n()
const { ready, providers, activeModelId } = useModels()
@@ -584,6 +613,8 @@ function TextComposer({ sid, drafts, focusComposer, clipboardLocked, model, onPi
onClick={openFiles} testId={openFiles ? WORKSPACE_OPEN : undefined} />
{open &&
setOpen(false)} />}
+ {context &&
}
{managedModel ?
setOpen((value) => !value)}
onPick={(pid, mid) => { managedModel.choose(`${pid}:${mid}`); setOpen(false) }} follow={() => { managedModel.choose(null); setOpen(false) }} />
diff --git a/apps/desktop/src/workbench/transport.ts b/apps/desktop/src/workbench/transport.ts
index fb670757..a347e942 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; workspaceDocumentCreate?: true; attachments?: true; browserPanel?: true; sessionPreferences?: true; deliveries?: true; gitInspect?: true; sessionWorkspaces?: true; taskInspection?: true; terminalViewer?: true; skillLibrary?: true }
+ capabilities?: { textChat?: true; library?: true; workspaceFiles?: true; workspaceDocumentCreate?: true; attachments?: true; browserPanel?: true; sessionPreferences?: true; deliveries?: true; gitInspect?: true; sessionWorkspaces?: true; taskInspection?: true; terminalViewer?: true; skillLibrary?: true; conversationStatus?: true }
}
export type SessionScreen = { mode: 'authenticated'; bootstrap: Bootstrap } | { mode: 'claim' | 'login' }
@@ -136,6 +136,7 @@ export function createTransport(send: Fetch = fetch) {
if (result.capabilities.taskInspection === true) capabilities.taskInspection = true
if (result.capabilities.terminalViewer === true) capabilities.terminalViewer = true
if (result.capabilities.skillLibrary === true) capabilities.skillLibrary = true
+ if (result.capabilities.conversationStatus === true) capabilities.conversationStatus = 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 479e485d..8c87988e 100644
--- a/apps/desktop/src/workbench/use-text-workbench.ts
+++ b/apps/desktop/src/workbench/use-text-workbench.ts
@@ -22,7 +22,7 @@ function remember(id: string | null): void {
}
export function useTextWorkbench(api: ChatTransport, beforeWrite: () => Promise, onExpired: () => void, uploadsEnabled: boolean,
- preferenceApi?: ReturnType, sessionWorkspaces = false) {
+ preferenceApi?: ReturnType, sessionWorkspaces = false, conversationStatus = false) {
const [sessions, setSessions] = useState([])
const [selected, setSelected] = useState(null)
const selectedRef = useRef(null)
@@ -30,6 +30,7 @@ export function useTextWorkbench(api: ChatTransport, beforeWrite: () => Promise<
const [listIssue, setListIssue] = useState()
const [listLoading, setListLoading] = useState(true)
const list = useRef>>()
+ const listAuthority = useRef<{ invalidated: number; applied: number; rows?: ChatSummary[] }>({ invalidated: 0, applied: -1 })
const creating = useRef()
const [createPending, setCreatePending] = useState(false)
const retryCreate = useRef(new Map()).current
@@ -74,7 +75,12 @@ export function useTextWorkbench(api: ChatTransport, beforeWrite: () => Promise<
}
}), [preferenceApi, beforeWrite, onExpired, refreshList])
useEffect(() => {
- const refresh = createListRefresh(api.list, (next) => {
+ const refresh = createListRefresh(async () => {
+ const stamp = listAuthority.current.invalidated
+ return { stamp, rows: await api.list() }
+ }, ({ stamp, rows: next }) => {
+ listAuthority.current.applied = stamp
+ listAuthority.current.rows = next
setSessions(next)
setListIssue((current) => current === 'createFailure' ? current : undefined)
select(sessionAfterRefresh(next, selectedRef.current, lastSession(), managed))
@@ -84,14 +90,19 @@ export function useTextWorkbench(api: ChatTransport, beforeWrite: () => Promise<
else setListIssue('listFailure')
setListLoading(false)
})
- list.current = refresh
- const link = managed || sessionWorkspaces ? createSessionsStream({ origin: window.location.origin,
- invalidate: refresh.request, expired: onExpired }) : undefined
- if (!managed) 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, sessionWorkspaces])
+ const invalidate = (request: () => void): void => {
+ if (conversationStatus) ++listAuthority.current.invalidated
+ request()
+ }
+ const request = () => invalidate(refresh.request)
+ list.current = { request, afterWrite: () => invalidate(refresh.afterWrite), close: refresh.close }
+ const link = managed || sessionWorkspaces || conversationStatus ? createSessionsStream({ origin: window.location.origin,
+ invalidate: request, expired: onExpired }) : undefined
+ if (!managed) request()
+ const timer = window.setInterval(() => { if (document.visibilityState === 'visible') request() }, 20000)
+ window.addEventListener('focus', request)
+ return () => { link?.close(); refresh.close(); list.current = undefined; window.clearInterval(timer); window.removeEventListener('focus', request) }
+ }, [api, managed, onExpired, select, sessionWorkspaces, conversationStatus])
useEffect(() => {
if (!selected) return
const sid = selected
@@ -224,7 +235,12 @@ export function useTextWorkbench(api: ChatTransport, beforeWrite: () => Promise<
end(sid)
}
}
- return { sessions, selected, select, projection: view?.sid === selected ? view?.projection : undefined, listIssue, listLoading,
+ // A GET started before the latest owner invalidation cannot authorize a read mark.
+ const currentReadProjection = (sid: string): ChatProjection | undefined =>
+ isSelected(sid) && listAuthority.current.rows === sessions && listAuthority.current.applied === listAuthority.current.invalidated
+ ? current(sid)?.current() : undefined
+ const refreshProjection = (sid: string): void => { if (isSelected(sid)) void current(sid)?.refresh() }
+ return { sessions, selected, select, projection: view?.sid === selected ? view?.projection : undefined, currentReadProjection, refreshProjection, listIssue, listLoading,
refreshList, preferences, create, createPending, pending: selected ? pending[selected] : undefined, drafts, setDraftQuote, selectionStamp,
attachments, addAttachments, send, stop,
turnIssue: selected ? turnIssues[selected] : undefined }
diff --git a/apps/headless/README.md b/apps/headless/README.md
index df827c1c..3d61cada 100644
--- a/apps/headless/README.md
+++ b/apps/headless/README.md
@@ -8,6 +8,22 @@
已确认的 Web 对话可单独固定一个已启用的模型,也可选择「跟随默认」。更改偏好本身不会向模型发请求。跟随模式在下一次实际发送时按服务端当前角色模型或全局默认解析;同一个已受理请求重试时仍返回原来的回合。两个页面同时修改会返回版本冲突,保留输入供核对;正在进行的回合不被中途切换模型。旧桌面复杂会话维持原来的只读保护,非默认思考档位仍待单独验收。
+### 未读提示与上下文用量
+
+同一工作台所有者在两个浏览器中登录时,共享会话的已读状态。侧栏头像上的红点表示这段对话有尚未确认的新内容。只有当前页面在前台、已选中这段对话、并已显示最新一条消息时,工作台才向服务器确认已读。仅在后台打开页面、查看其他会话或停留在设置面板,都不会替用户清掉红点。新内容先到、旧确认后到时,服务器保留新内容的未读状态。重复确认同一版本不改文件,也不重复通知其他窗口。
+
+点击输入区模型选择器旁的灰色圆环,可查看本对话使用的上下文窗口及读数来源。「上次请求 · 实测输入 token」表示服务商为该会话、该模型、该次请求实际返回的**输入量**,不是累计费用或下一次请求的精确预报。没有可用回执,或切换到其他生效模型时,改用保存历史的字符与媒体估算,并标为估算。模型失效时不沿用旧数字。查看圆环不调用模型,也不触发历史压缩;当前 Web 引擎没有自动压缩阈值。
+
+已读时间保存在数据卷根目录的 `read-state.json`,只存会话 ID 和服务端确认的时间。通过附有当前游标的请求推进水位,重启后仍可读回;失效的登录或上一个进程的游标不能确认新内容。已有文件损坏或写入无法确认时,页面提示重新核对,服务保留已有记录,普通对话仍可使用。备份时与原数据卷一起保存。
+
+**独立验收。** 在已有依赖的仓库中执行 `pnpm --filter @deva/headless build`,然后执行 `node scripts/workbench/container-conversation-status.mjs --fixture-only`。这会在私有临时目录中用两次真实服务进程启动、一次本地合成模型请求,核对用量和已读水位的恢复;这不是 Docker 测试。在专用的非 root Linux/amd64 测试机(Node 22、Docker Engine 28+)上,可用以下命令验收成品镜像,无需改动已有部署:
+
+```sh
+docker build --platform linux/amd64 --target runtime -t deva-workbench:conversation-status-verify .
+image_id=$(docker image inspect --format '{{.Id}}' deva-workbench:conversation-status-verify)
+node scripts/workbench/container-conversation-status.mjs --disposable-image "$image_id"
+```
+
## 在自己的浏览器复制、引用、粘贴和全屏
- 在一条消息的可见正文中选中文字后右键,或在该消息文本获得焦点时按 **Shift+F10**。**复制**只写到当前用户的浏览器剪贴板;只读历史也能复制。**引用**使用与桌面相同的引用条,只出现在可写的普通会话中,引用与已有正文、附件分开保留,点击 × 只移除引用。每个会话的未发送草稿独立,刷新或重新登录不保留这些草稿。
diff --git a/apps/headless/scripts/build-provider.mjs b/apps/headless/scripts/build-provider.mjs
index b28aa4af..6747360a 100644
--- a/apps/headless/scripts/build-provider.mjs
+++ b/apps/headless/scripts/build-provider.mjs
@@ -25,6 +25,9 @@ await mkdir(dest, { recursive: true })
await compile('provider-core', 'apps/desktop/src/main/providers/core.ts')
await compile('chat-core', 'apps/headless/scripts/chat-core.ts')
await compile('library-core', 'apps/headless/scripts/library-core.ts')
+await compile('context-limits', 'apps/headless/scripts/context-limits.ts', {
+ pureInputs: ['apps/headless/scripts/context-limits.ts','apps/desktop/src/shared/context.ts']
+})
const services = 'apps/desktop/src/main/services/'
await compile('schedule-core', `${services}schedule-preview.ts`, {
pureInputs: ['schedule-preview.ts', 'schedule.ts', 'tasks-types.ts'].map(file => `${services}${file}`)
diff --git a/apps/headless/scripts/chat-core.ts b/apps/headless/scripts/chat-core.ts
index 81b99c95..5c26781d 100644
--- a/apps/headless/scripts/chat-core.ts
+++ b/apps/headless/scripts/chat-core.ts
@@ -2,6 +2,7 @@
export { createChatStore, isValidSessionId, deriveTitle } from '../../desktop/src/main/services/chat-store-core'
export { consumeModelStep } from '../../desktop/src/main/services/model-step-stream'
export { modelMessages } from '../../desktop/src/main/services/model-view'
+export { estimateTokens } from '../../desktop/src/shared/context-estimate'
export {
assetKind, isSupported, supportsAttachmentAdapter, maxUploadedAttachmentBytes, buildUploadedPart,
uploadedAttachmentSnapshot, UploadedAttachmentError, ATTACH_TEXT_PREFIX, ATTACHMENTS_ONLY_QUESTION
diff --git a/apps/headless/scripts/context-limits.ts b/apps/headless/scripts/context-limits.ts
new file mode 100644
index 00000000..5fe0914b
--- /dev/null
+++ b/apps/headless/scripts/context-limits.ts
@@ -0,0 +1,2 @@
+// Read-only share. No compaction engine, credential loader, Electron or provider client is imported.
+export { autoContextWindow, DEFAULT_CONTEXT_WINDOW, CONTEXT_WINDOW_RANGE, validLimit } from '../../desktop/src/shared/context'
diff --git a/apps/headless/src/business/context-model.mjs b/apps/headless/src/business/context-model.mjs
new file mode 100644
index 00000000..4d75a4ac
--- /dev/null
+++ b/apps/headless/src/business/context-model.mjs
@@ -0,0 +1,34 @@
+import { autoContextWindow, CONTEXT_WINDOW_RANGE, DEFAULT_CONTEXT_WINDOW, validLimit } from '../../dist/context-limits.mjs'
+import { assertSettingsCurrent, readSettingsFile } from './settings-file.mjs'
+import { hydrate, section, SettingsError } from './settings-schema.mjs'
+
+const adapters = new Set(['openai','responses','anthropic'])
+export function isContextModelRef(ref) {
+ if (typeof ref !== 'string' || !ref.isWellFormed() || ref !== ref.trim() || ref.length>609 || /[\x00-\x1f\x7f]/u.test(ref)) return false
+ const colon=ref.indexOf(':'), provider=ref.slice(0,colon), model=ref.slice(colon+1)
+ return colon>0 && model.length>0 && model===model.trim() && Buffer.byteLength(model)<=512 &&
+ /^[A-Za-z0-9][A-Za-z0-9_.-]{0,95}$/u.test(provider) && !['__proto__','constructor','prototype'].includes(provider)
+}
+
+/** Caller holds the settings-directory queue. Only look up a configured enabled chat
+ * model and its window; do not open the secret vault, request /models or hydrate credentials. */
+export async function contextModelFromFile(directory, ref, previouslyPresent) {
+ if (ref !== null && !isContextModelRef(ref)) throw new SettingsError('INVALID')
+ const {raw,info}=await readSettingsFile(directory)
+ if (!info && previouslyPresent) throw new SettingsError('CORRUPT')
+ const {models}=section(raw,true), catalogue=hydrate(models)
+ const effective=ref ?? catalogue.activeModelId
+ let selected=null
+ if (isContextModelRef(effective)) {
+ const colon=effective.indexOf(':'), pid=effective.slice(0,colon), modelId=effective.slice(colon+1)
+ const p=catalogue.providers.find(p=>p.id===pid && p.purpose==='llm' && p.enabled && adapters.has(p.adapter) && p.apiHost)
+ const model=p?.models.find(m=>m.id===modelId && m.enabled)
+ if (model) {
+ const fallback=raw.compaction?.defaultWindow
+ const window=model.contextWindow ?? autoContextWindow(modelId,validLimit(fallback,CONTEXT_WINDOW_RANGE) ? fallback : DEFAULT_CONTEXT_WINDOW)
+ selected={modelRef:effective,modelId,adapter:p.adapter,contextWindow:window}
+ }
+ }
+ await assertSettingsCurrent(directory,info)
+ return {selected,present:!!info}
+}
diff --git a/apps/headless/src/business/handlers.mjs b/apps/headless/src/business/handlers.mjs
index 03060204..97bff6a6 100644
--- a/apps/headless/src/business/handlers.mjs
+++ b/apps/headless/src/business/handlers.mjs
@@ -6,6 +6,8 @@ import { createEventJournal } from '../events/index.mjs'
import { createChatWebSocket } from '../events/websocket.mjs'
import { createTextTurns } from '../chat/text-turns.mjs'
import { chatRoutes } from '../chat/routes.mjs'
+import { conversationStatusRoutes } from '../chat/conversation-status-routes.mjs'
+import { openReadMarkStore } from '../chat/read-mark-store.mjs'
import { browserRoutes } from '../browser/routes.mjs'
import { gitViewRoutes } from '../git/routes.mjs'
import { openGitService } from '../git/service.mjs'
@@ -61,7 +63,7 @@ export async function openBusiness({ dataDir, vault, auth, version, allowedOrigi
const lifetime = new AbortController()
const journal = createEventJournal()
let library, turns, uploads, browser, closingBrowser, git, closingGit, taskStore, preview, tasks, closingTasks
- let terminalService, closingTerminals, skills, closingSkills, documentIntents, closingDocuments
+ let terminalService, closingTerminals, skills, closingSkills, documentIntents, closingDocuments, readMarks, conversation, closingConversation
try {
library = await openLibrary({ dataDir, workspaceRoot, workspaceWritable, workspaceCreate, privateRoots, gitProjects })
if (library.createDocumentTarget) documentIntents = openProjectDocumentService({auth,openTarget:library.createDocumentTarget})
@@ -74,8 +76,13 @@ export async function openBusiness({ dataDir, vault, auth, version, allowedOrigi
taskStore = openTaskStore({ dataDir }); preview = openTaskPreview()
tasks = taskRoutes({ store: taskStore, preview })
uploads = await openUploadStore({ dataDir })
+ readMarks=openReadMarkStore({dataDir})
turns = createTextTurns({ dataDir, settings, journal, ...opts, resolveRole: library.resolveRole,
- withWorkspace: library.withWorkspace, uploads, deliveries: true })
+ withWorkspace: library.withWorkspace, uploads, deliveries: true,
+ // A desktop-imported clock can be ahead of ours. New content advances past a known read mark.
+ // The turn owner treats unreadable/invalid marks as absent rather than blocking a model request.
+ readWatermark: sid => readMarks.snapshot().get(sid) })
+ conversation=conversationStatusRoutes({turns,marks:readMarks,journal})
// A workspace plus an explicit private control mount enables the human-only viewer.
// Do not start a process here or make app readiness depend on the optional sidecar.
if (terminalRunDir && library.terminalSource) {
@@ -89,7 +96,7 @@ export async function openBusiness({ dataDir, vault, auth, version, allowedOrigi
}
} catch (err) {
journal.close()
- await Promise.allSettled([documentIntents?.close(), skills?.close(), terminalService?.close(), git?.close(), ...(tasks ? [tasks.close()] : [preview?.close(), taskStore?.close?.()]),
+ await Promise.allSettled([conversation ? conversation.close() : readMarks?.close(), documentIntents?.close(), skills?.close(), terminalService?.close(), git?.close(), ...(tasks ? [tasks.close()] : [preview?.close(), taskStore?.close?.()]),
turns?.close(), uploads?.close(), library?.close()]); throw err
}
const documentRoutes = projectDocumentRoutes(documentIntents)
@@ -101,6 +108,7 @@ export async function openBusiness({ dataDir, vault, auth, version, allowedOrigi
const deliveries = deliveryRoutes({ turns, files: library.deliveryFiles })
function beginShutdown() {
lifetime.abort(); attachments.close()
+ if (!closingConversation) { closingConversation=conversation.close();void closingConversation.catch(()=>{}) }
if (!closingDocuments) { closingDocuments=documentRoutes.close();void closingDocuments.catch(()=>{}) }
if (!closingSkills) { closingSkills=skills.close();void closingSkills.catch(()=>{}) }
if (!closingTerminals) { closingTerminals = terminals.close(); void closingTerminals.catch(() => {}) }
@@ -112,13 +120,15 @@ export async function openBusiness({ dataDir, vault, auth, version, allowedOrigi
beginShutdown,
capabilities: Object.freeze({ textChat: true, library: true, workspaceFiles: library.workspaceFilesEnabled, attachments: true,
browserPanel: !!browser, gitInspect: !!git, taskInspection: Boolean(tasks), deliveries: typeof turns.deliverySnapshot === 'function',
- terminalViewer: Boolean(terminalService), skillLibrary: Boolean(skills), workspaceDocumentCreate: Boolean(documentIntents),
+ conversationStatus: Boolean(conversation), terminalViewer: Boolean(terminalService), skillLibrary: Boolean(skills), workspaceDocumentCreate: Boolean(documentIntents),
sessionWorkspaces: typeof turns.getWorkspace === 'function' && typeof turns.setWorkspace === 'function',
sessionPreferences: typeof turns.patchPreferences === 'function' && typeof journal.watchSessions === 'function' }),
createRealtime: ({ auth, policy }) => createChatWebSocket({ turns, journal, auth, policy }),
getConfig: () => settings.getPublicConfig(),
async handle(req, res, { auth, policy }) {
const path = (req.url ?? '').split('?', 1)[0]
+ if ((path==='/api/v1/conversation-status/reads' || path.startsWith('/api/v1/chats/') && (path.endsWith('/context-usage') || path.endsWith('/read-state'))) &&
+ await conversation.handle(req,res,{auth,policy})) return true
if (path.startsWith('/api/v1/workspaces/') && path.includes('/document-intents') && await documentRoutes.handle(req,res,{auth,policy})) return true
if ((path === '/api/v1/skills' || path.startsWith('/api/v1/skills/')) && await skills.handle(req,res,{auth,policy})) return true
if ((path === '/api/v1/terminal/profiles' || (path.startsWith('/api/v1/workspaces/') && path.includes('/terminals'))) &&
@@ -176,7 +186,7 @@ export async function openBusiness({ dataDir, vault, auth, version, allowedOrigi
try { await turns.close() } finally {
journal.close()
try {
- const results = await Promise.allSettled([closingBrowser, closingGit, closingTasks, closingTerminals, closingSkills, closingDocuments])
+ const results = await Promise.allSettled([closingBrowser, closingGit, closingTasks, closingTerminals, closingSkills, closingDocuments, closingConversation])
if (results.some(row => row.status === 'rejected')) throw Error('Optional service shutdown unconfirmed')
} finally { try { await uploads.close() } finally { await library.close() } }
}
diff --git a/apps/headless/src/business/settings-file.mjs b/apps/headless/src/business/settings-file.mjs
index b14402c9..b57f4224 100644
--- a/apps/headless/src/business/settings-file.mjs
+++ b/apps/headless/src/business/settings-file.mjs
@@ -92,7 +92,7 @@ function expectSnapshot(expected, current) {
if ((!expected !== !current) || (expected && !sameSnapshot(expected, current))) throw new SettingsError('CONFLICT')
}
-async function assertSettingsCurrent(directory, expected) {
+export async function assertSettingsCurrent(directory, expected) {
let current = null
try { current = await fs.lstat(childPath(directory, CONFIG), { bigint: true }) }
catch (error) { if (error.code !== 'ENOENT') throw error }
diff --git a/apps/headless/src/business/settings.mjs b/apps/headless/src/business/settings.mjs
index 2447172d..36590ddd 100644
--- a/apps/headless/src/business/settings.mjs
+++ b/apps/headless/src/business/settings.mjs
@@ -2,6 +2,7 @@ import { randomBytes } from 'node:crypto'
import { homedir } from 'node:os'
import { join, resolve } from 'node:path'
import { isDeepStrictEqual } from 'node:util'
+import { contextModelFromFile } from './context-model.mjs'
import { assertWritable, encodeSettings, publishSettingsFile, readSettingsFile, revisionFor, withSettingsDirectory } from './settings-file.mjs'
import { HEADER_MASK, MAX_PROVIDERS, SettingsError, assertRevision, credentialBinding, headerValues,
hydrate, patchInput, providerId, record, section, validateApiKey } from './settings-schema.mjs'
@@ -301,6 +302,11 @@ export async function openSettings(options = {}) {
async getPublicConfig() {
return access((_directory, state) => projection(state))
},
+ async getContextModel(ref) {
+ const {selected,present}=await withSettingsDirectory(path,identity,dir=>contextModelFromFile(dir,ref,seen),{create:false})
+ if (present) seen=true
+ return selected
+ },
async patch(input) {
const edit = patchInput(input)
return access(async (directory, state) => {
diff --git a/apps/headless/src/chat/README.md b/apps/headless/src/chat/README.md
index 179af64c..1443fd17 100644
--- a/apps/headless/src/chat/README.md
+++ b/apps/headless/src/chat/README.md
@@ -12,6 +12,9 @@
| `PATCH /api/v1/chats/:sid/workspace` | `{workspaceId,revision}`,其中 `workspaceId:null` 是明确解除关联。目录路径不是请求字段;条件写入和严格落盘成功后才使其他窗口的列表失效。此操作不会读取项目文件或改变模型请求。|
| `GET /api/v1/chats/:sid/preferences` | 当前会话标题、自定义标题、归档状态、模型选项和该会话版本。版本用于条件写入,不是访问凭证。|
| `PATCH /api/v1/chats/:sid/preferences` | `{revision,set}` 只改指定字段(如 `customTitle:null`、`archived:true` 或 `model:null`)。取得持久化回执后更新 UI,同版本并发写不能静默覆盖。普通 `model` 字符串请求保持兼容;`model:null` 发送表示由服务端选择该时刻的默认模型。|
+| `GET /api/v1/conversation-status/reads` | 返回当前所有者可确认、已落盘且有可见内容的会话 `{id,updatedAt,readAt,unread}`。空会话、在途回合、无法展示的历史和孤立的原生已读记录不会被当作已看过。 |
+| `POST /api/v1/chats/:sid/read-state` | `{updatedAt,cursor}` 只确认当前已显示的持久版本。忙碌、陈旧游标或错误会话均不会推进标记。返回确切水位;仅新写入才使会话列表失效,文件仅包含时间戳。 |
+| `POST /api/v1/chats/:sid/context-usage` | 只读。`{model:null}` 使用当前会话固定模型、角色偏好或全局默认;传完整引用只核对是否仍与生效模型相符,不会覆写设置。`source` 为 `none`、`estimate`、`live`、`measured` 或 `unavailable`;模型不存在时不虚构窗口或读数。`compaction` 固定为 `inactive`。 |
| `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 和显示元数据,不触发模型请求。|
@@ -22,6 +25,10 @@
| `GET /api/v1/chats/:sid/deliveries/:gid/items/:index/download` | 按交付记录和 `If-Match` 版本下载,响应使用 `Content-Disposition: attachment`。`preview` 同样验版本且仅返回经校验的静态图片;`POST …/locate` 提供当前受权项目的相对定位。|
| `WS /api/v1/chats/:sid/stream` | 只读、同源、按登录会话校验。首次订阅取快照;刷新可用最后实际应用的游标衔接,旧游标转为新快照。退出、会话过期、消费超时或服务关闭时释放连接。|
+上下文占用的窗口沿用桌面模型配置和同源自动窗口表。有效的标准化输入量写入桌面原生 `lastInputTokens`,另有只供服务核验的会话、模型与回合凭据;后续回合没有自己的有效用量时,即使旧数字仍在原生文件中,也只返回估算。图片和 PDF 采用桌面分摊常数,文本附件按已保存的体积近似,不为展示读数去解码媒体。没有服务端压缩流程、费用计算或工具调用。某些协议只在整个响应结束时提供 usage,此时不会为了显示「实时」而提前推算成实测。
+
+已读标记使用平坦的原生 JSON 映射,单文件最多 1 MiB / 8192 个标记;损坏、重复键、超限或无法验证的状态会返回错误,不用空映射覆盖。面向已验证的本地 Linux 常规卷:真实写入前使用固定的 `flock` 和只接收已打开文件描述符的扩展属性检查,遇到可见 ACL、xattr 或无法检查时保持只读;普通查询和同水位的重复确认不运行这些辅助程序。在生产配置中本服务持有数据卷的单写者锁,不应与桌面进程并行写同一份原件。
+
写入需要工作台登录 Cookie、匹配的 Origin 与 CSRF。通过反代访问时,对 WS 路径一并保留 Host、Origin、HTTP/1.1 Upgrade 和 Connection。不要把聊天数据、访问凭据或控制命令放入 WS URL;可选的 `cursor` 只是进度,不授予访问权。
当前限制:每轮输入 12 KiB,输出与思考通道各 64 Ki UTF-16 单元,每轮最长 5 分钟,每实例至多 8 个并行回合。每会话保留全部最多 256 个已受理请求以防重新计费;达到上限后仍可读、仍可重查旧请求,须另建会话才能发新消息。由本服务创建并通过索引校验的附件会话可续聊,快照只给出文件卡的元数据。已有普通桌面文本历史只读;缺少可验证索引的旧附件、工具和交互卡等复杂历史标记不兼容,不将残缺内容当作完整历史,也不覆盖原件。这些是开发阶段限制,不代表已实现完整桌面能力。
diff --git a/apps/headless/src/chat/conversation-context-storage.mjs b/apps/headless/src/chat/conversation-context-storage.mjs
new file mode 100644
index 00000000..ead75faf
--- /dev/null
+++ b/apps/headless/src/chat/conversation-context-storage.mjs
@@ -0,0 +1,119 @@
+import { constants, openSync, opendirSync, readSync } from 'node:fs'
+import { resolve } from 'node:path'
+import { DIRECTORY, PATH, close, decodeUtf8, fdPath, mountId, openAbsoluteDirectory, sameInode, stat } from '../files/workspace-files-fd.mjs'
+import { HttpError } from '../http/policy.mjs'
+import { parseNativeJSON } from './delivery-records-storage.mjs'
+
+export const readUnavailable = () => new HttpError(409, 'read_unavailable')
+export const readLimit = () => new HttpError(413, 'read_state_limit')
+export const MAX_NATIVE_BYTES = 128 * 1024 * 1024
+const uid = BigInt(process.geteuid())
+const mode = info => info.mode & 0o7777n
+const readFlags = constants.O_RDONLY | constants.O_NONBLOCK
+const isMissing = error => error?.code === 'ENOENT'
+
+function directoryInfo(fd) {
+ const info = stat(fd)
+ if (!info.isDirectory() || info.uid !== uid || (mode(info) & 0o7022n) !== 0n) throw readUnavailable()
+ return { info, mount: mountId(fd) }
+}
+
+function fileStamp(fd, directory) {
+ const info = stat(fd)
+ if (!info.isFile() || info.uid !== uid || info.nlink !== 1n || info.size < 1n ||
+ info.size > MAX_NATIVE_BYTES || (mode(info) & 0o7133n) !== 0n || (mode(info) & 0o400n) === 0n ||
+ mountId(fd) !== directory.mount) throw readUnavailable()
+ return [info.dev, info.ino, info.mode, info.uid, info.gid, info.size, info.nlink, info.mtimeNs, info.ctimeNs].join(':')
+}
+
+/** Pin the three native storage directories, and reject a renamed/remounted chain before returning.
+ * Read only the exact named main file, never a legacy sidecar, media, or tool-result path. */
+export function withConversationFiles(dataDir, use) {
+ const root = resolve(dataDir)
+ const dirs = []
+ try {
+ function openDirectory(parent, name) {
+ return parent ? openSync(fdPath(parent.fd, name), DIRECTORY) : openAbsoluteDirectory(root)
+ }
+ for (const name of [null, 'data', 'chats']) {
+ const parent = dirs.at(-1)
+ let fd
+ try { fd = openDirectory(parent, name) }
+ catch (error) { if (isMissing(error)) break; throw error }
+ const entry = { fd, name }
+ dirs.push(entry)
+ Object.assign(entry, directoryInfo(fd))
+ if (parent && entry.mount !== parent.mount) throw readUnavailable()
+ }
+
+ function verifyDirs() {
+ for (const [index, entry] of dirs.entries()) {
+ const current = openDirectory(dirs[index - 1], entry.name)
+ try {
+ const { info, mount } = directoryInfo(current)
+ if (!sameInode(info, entry.info) || mount !== entry.mount) throw readUnavailable()
+ } finally { close(current) }
+ }
+ }
+
+ const directory = dirs[2]
+ const scope = directory && dirs.map(({ info, mount }) => `${info.dev}:${info.ino}:${mount}`).join('/')
+ function read(sid, useFile) {
+ const name = `${sid}.json` // Callers validate sid before deriving this single component.
+ function pin() {
+ try { return openSync(fdPath(directory.fd, name), PATH) }
+ catch (error) { if (isMissing(error)) return undefined; throw error }
+ }
+ const fd = pin()
+ if (fd === undefined) return null
+ try {
+ const stamp = fileStamp(fd, directory)
+ const info = stat(fd)
+ const result = useFile({
+ stamp: `${scope}/${stamp}`, size: Number(info.size), privateMode: mode(info) === 0o600n || mode(info) === 0o400n,
+ parse() {
+ const input = openSync(fdPath(fd), readFlags)
+ try {
+ if (fileStamp(input, directory) !== stamp) throw readUnavailable()
+ const bytes = Buffer.allocUnsafe(Number(info.size))
+ for (let offset = 0; offset < bytes.length;) {
+ const count = readSync(input, bytes, offset, bytes.length - offset, offset)
+ if (!count) throw readUnavailable()
+ offset += count
+ }
+ if (fileStamp(input, directory) !== stamp) throw readUnavailable()
+ try { return parseNativeJSON(decodeUtf8(bytes)) } catch { throw readUnavailable() }
+ } finally { close(input) }
+ }
+ })
+ const named = pin()
+ try {
+ if (named === undefined || fileStamp(named, directory) !== stamp || fileStamp(fd, directory) !== stamp) throw readUnavailable()
+ } finally { close(named) }
+ return result
+ } finally { close(fd) }
+ }
+
+ function *scan(limit) {
+ const stream = opendirSync(fdPath(directory.fd), { bufferSize: 64 })
+ try {
+ for (let i = 0; ; i++) {
+ const entry = stream.readSync()
+ if (!entry) break
+ if (i === limit) throw readLimit()
+ if (entry.isFile() && entry.name.endsWith('.json')) yield entry.name.slice(0, -5)
+ }
+ } finally { stream.closeSync() }
+ }
+
+ verifyDirs()
+ const result = use(directory ? { read, scan } : null)
+ verifyDirs()
+ return result
+ } catch (error) {
+ if (error instanceof HttpError) throw error
+ throw readUnavailable()
+ } finally {
+ for (const { fd } of dirs.reverse()) close(fd)
+ }
+}
diff --git a/apps/headless/src/chat/conversation-context.mjs b/apps/headless/src/chat/conversation-context.mjs
new file mode 100644
index 00000000..bf2bfc1e
--- /dev/null
+++ b/apps/headless/src/chat/conversation-context.mjs
@@ -0,0 +1,171 @@
+import { chatScope } from '../events/index.mjs'
+import { HttpError } from '../http/policy.mjs'
+import { isDeepStrictEqual } from 'node:util'
+import { MAX_NATIVE_BYTES, readLimit, readUnavailable, withConversationFiles } from './conversation-context-storage.mjs'
+
+const MAX_DIRECTORY_ENTRIES = 16384
+const MAX_CANDIDATES = 8192
+const MAX_MESSAGES = 4096
+const MAX_PARTS = 16384
+const missing = () => new HttpError(404, 'session_not_found')
+const unsupported = () => new HttpError(409, 'unsupported_history')
+const busy = () => new HttpError(409, 'read_view_busy')
+const stale = () => new HttpError(409, 'read_view_stale')
+const time = n => Number.isSafeInteger(n) && n >= 0
+const sameCursor = (a, b) => a?.scope === b.scope && a.epoch === b.epoch && a.generation === b.generation && a.seq === b.seq
+const contentsMatch = (native, s) => isDeepStrictEqual(native, Object.fromEntries(Object.entries(s).filter(([_key, value]) => value !== undefined)))
+
+// A desktop read marker is a Date timestamp. Its representable ceiling leaves room for
+// monotonic admission and finalization even on a skewed or deliberately fixed wall clock.
+export const MAX_CONVERSATION_WATERMARK = 8_640_000_000_000_000
+export function nextConversationUpdatedAt(previous, wallTime = Date.now(), watermark) {
+ const native = time(watermark) && watermark <= MAX_CONVERSATION_WATERMARK ? watermark : 0
+ const next = Math.max(previous + 1, wallTime, native + 1)
+ if (!time(previous) || !time(wallTime) || !time(next)) throw new HttpError(503, 'chat_storage_unconfirmed')
+ return next
+}
+
+// One user entry and at most one assistant reply per receipt. Admitted-but-unfinished
+// records are visible after restart as interrupted, never as a fabricated latest reply.
+export function matchesTurnLayout(messages, requests) {
+ let at = 0
+ for (const request of requests) {
+ if (messages[at++]?.role !== 'user') return false
+ if (messages[at]?.role === 'assistant') {
+ if (request.status === 'running' || request.status === 'interrupted') return false
+ at++
+ }
+ }
+ return at === messages.length
+}
+
+function checkShape(s, sid) {
+ if (s === null || typeof s !== 'object' || Array.isArray(s) || s.id !== sid || typeof s.title !== 'string' ||
+ !time(s.createdAt) || !time(s.updatedAt) || !Array.isArray(s.messages)) throw readUnavailable()
+ if (s.compacted !== undefined || s.messages.length > MAX_MESSAGES) throw unsupported()
+ let parts = 0
+ for (const m of s.messages) {
+ if (!m || !['user', 'assistant'].includes(m.role)) throw unsupported()
+ if (typeof m.content === 'string') continue
+ if (!Array.isArray(m.content) || (parts += m.content.length) > MAX_PARTS ||
+ m.content.some(p => !p || typeof p.type !== 'string')) throw unsupported()
+ }
+}
+
+/** Independent read-only proof; the chat-store loader can repair the index or clean up sidecars,
+ * so these endpoints never use it to populate the writer's cache. */
+export function createConversationContext({ dataDir, validSid, journal, cached, blocked, closing, active, inspect, unreadable }) {
+ const candidates = new Map() // bounded stamps and booleans only; never retain another copy of a transcript
+ const forgetCandidate = sid => candidates.delete(sid)
+ function assertAvailable(sid) {
+ if (!validSid(sid)) throw new HttpError(400, 'invalid_session_id')
+ if (closing()) throw new HttpError(503, 'chat_closed')
+ if (blocked(sid)) throw readUnavailable()
+ if (unreadable(sid)) throw unsupported()
+ }
+
+ function view(file, sid, expected) {
+ const session = file.parse()
+ checkShape(session, sid)
+ const layout = inspect(session, expected)
+ if (!layout) throw unsupported()
+ if ((!file.privateMode && layout.owned) || (expected && !contentsMatch(session, expected))) throw readUnavailable()
+ return { session, layout, stamp: file.stamp, expected }
+ }
+
+ function read(sid) {
+ assertAvailable(sid)
+ const expected = cached(sid)
+ const value = withConversationFiles(dataDir, files => files?.read(sid, file => view(file, sid, expected)))
+ if (!value) throw expected ? readUnavailable() : missing()
+ return value
+ }
+
+ // Only use this for a strict-save readback, before advertising a terminal measurement.
+ function confirm(s) {
+ const ok = withConversationFiles(dataDir, files => files?.read(s.id, file => file.privateMode && contentsMatch(file.parse(), s)))
+ if (!ok) throw readUnavailable()
+ }
+
+ function stable(sid, stamp, updatedAt, expected) {
+ assertAvailable(sid)
+ const now = cached(sid)
+ if ((expected && expected !== now) || (now && now.updatedAt !== updatedAt)) return false
+ return withConversationFiles(dataDir, files => files?.read(sid, file => file.stamp === stamp)) === true
+ }
+
+ function refresh(sid, current) {
+ return stable(sid, current.stamp, current.session.updatedAt, current.expected) ? current : read(sid)
+ }
+
+ function readCandidates() {
+ if (closing()) return []
+ return withConversationFiles(dataDir, files => {
+ if (!files) return []
+ let budget = MAX_NATIVE_BYTES
+ const result = []
+ for (const id of files.scan(MAX_DIRECTORY_ENTRIES)) {
+ if (!validSid(id) || blocked(id) || active(id) || unreadable(id)) continue
+ let proof
+ try {
+ const expected = cached(id)
+ proof = files.read(id, file => {
+ const previous = candidates.get(id)
+ if (previous?.stamp === file.stamp && previous.cached === (expected !== undefined) &&
+ (!expected || expected.updatedAt === previous.updatedAt)) return previous
+ if (file.size > budget) throw readLimit()
+ budget -= file.size
+ const identity = { stamp: file.stamp, cached: expected !== undefined, updatedAt: expected?.updatedAt }
+ try {
+ const { session, layout } = view(file, id, expected)
+ return { ...identity, updatedAt: session.updatedAt, eligible: layout.eligible }
+ } catch (error) {
+ if (!(error instanceof HttpError) || error.status !== 409) throw error
+ return { ...identity, eligible: false }
+ }
+ })
+ } catch (error) {
+ if (!(error instanceof HttpError) || error.status !== 409) throw error
+ }
+ forgetCandidate(id)
+ if (!proof) continue
+ if (candidates.size >= MAX_DIRECTORY_ENTRIES) forgetCandidate(candidates.keys().next().value)
+ candidates.set(id, proof)
+ if (proof.eligible) {
+ if (result.length === MAX_CANDIDATES) throw readLimit()
+ result.push({ id, updatedAt: proof.updatedAt })
+ }
+ }
+ return result.sort((a, b) => b.updatedAt - a.updatedAt || a.id.localeCompare(b.id))
+ })
+ }
+
+ function readObservation(sid) {
+ if (!validSid(sid)) throw new HttpError(400, 'invalid_session_id')
+ if (active(sid)) throw busy()
+ const scope = chatScope(sid)
+ const { session: { updatedAt }, layout: { eligible }, stamp, expected } = read(sid)
+ let initial
+ try {
+ initial = journal.snapshot(scope, () => stable(sid, stamp, updatedAt, expected))
+ } catch (error) {
+ if (error instanceof HttpError) throw error
+ throw error?.code === 'SNAPSHOT_CHANGED' ? stale() : readUnavailable()
+ }
+ if (active(sid)) throw busy()
+ if (!initial.state) throw stale()
+ const cursor = Object.freeze({ ...initial.cursor })
+ if (cursor.scope !== scope || typeof cursor.epoch !== 'string' || typeof cursor.generation !== 'string' || !time(cursor.seq)) throw readUnavailable()
+ return Object.freeze({ id: sid, updatedAt, cursor, eligible, verify() {
+ if (active(sid)) throw busy()
+ let now
+ try { now = journal.snapshot(scope, () => stable(sid, stamp, updatedAt, expected)) }
+ catch { throw stale() }
+ if (active(sid)) throw busy()
+ if (!now.state || !sameCursor(now.cursor, cursor)) throw stale()
+ return true
+ } })
+ }
+
+ return { read, refresh, confirm, readCandidates, readObservation }
+}
diff --git a/apps/headless/src/chat/conversation-status-routes.mjs b/apps/headless/src/chat/conversation-status-routes.mjs
new file mode 100644
index 00000000..eed3b786
--- /dev/null
+++ b/apps/headless/src/chat/conversation-status-routes.mjs
@@ -0,0 +1,108 @@
+import { isContextModelRef } from '../business/context-model.mjs'
+import { chatScope } from '../events/journal.mjs'
+import { MAX_CONVERSATION_WATERMARK } from './conversation-context.mjs'
+import { HttpError, json, readJson } from '../http/policy.mjs'
+
+const listPath='/api/v1/conversation-status/reads'
+const chatPath=/^\/api\/v1\/chats\/([A-Za-z0-9_-]{1,128})\/(read-state|context-usage)$/u
+const uuid=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u
+const exact=(obj,fields)=>obj!==null && typeof obj==='object' && !Array.isArray(obj) &&
+ Object.keys(obj).length===fields.length && fields.every(k=>Object.hasOwn(obj,k))
+const integer=n=>Number.isSafeInteger(n) && n>=0
+const id=s=>typeof s==='string' && s.length===36 && uuid.test(s)
+const codes=Object.freeze({
+ auth:401, origin:403, unexpected_query:400, json_required:415, invalid_json:400, too_large:413,
+ invalid_session_id:400, session_not_found:404, invalid_read_view:400, invalid_model_ref:400,
+ read_view_stale:409, read_view_busy:409, unsupported_history:409, read_unavailable:409,
+ read_state_read_only:403, read_state_conflict:409, read_state_unsupported:409, read_state_limit:413,
+ read_state_unconfirmed:503, chat_model_unavailable:503, chat_storage_unconfirmed:503,
+ conversation_status_busy:429, conversation_status_unavailable:503, chat_closed:503,
+})
+const unavailable=()=>new HttpError(503,'conversation_status_unavailable')
+function sameCursor(a,b) {return a.epoch===b.epoch && a.generation===b.generation && a.scope===b.scope && a.seq===b.seq}
+function storedTime(value) {
+ if (value===null) return null
+ if (!integer(value) || value>MAX_CONVERSATION_WATERMARK) throw new HttpError(409,'read_state_unsupported')
+ return value
+}
+function seenInput(body,sid) {
+ const c=body.cursor
+ if (!exact(body,['updatedAt','cursor']) || !integer(body.updatedAt) || !exact(c,['epoch','generation','scope','seq']) ||
+ !id(c.epoch) || !id(c.generation) || !integer(c.seq) || c.scope!==chatScope(sid)) throw new HttpError(400,'invalid_read_view')
+}
+
+/** Read status is a shared owner preference, not a grant on a transcript. A foreground
+ * page may acknowledge only the durable snapshot it actually had, not a client clock. */
+export function conversationStatusRoutes({turns,marks,journal}) {
+ const active=new Set()
+ let closed=false,drain
+ function list(verify) {
+ const rows=turns.readCandidates()
+ const stored=marks.snapshot()
+ const entries=rows.map(({id,updatedAt})=>{
+ const readAt=storedTime(stored.get(id)??null)
+ return {id,updatedAt,readAt,unread:readAt===null || readAt{
+ verify()
+ if (observed.updatedAt!==body.updatedAt || !sameCursor(observed.cursor,body.cursor)) throw new HttpError(409,'read_view_stale')
+ if (observed.verify()!==true) throw new HttpError(409,'read_view_stale')
+ return verify()
+ }
+ assertCurrent()
+ if (!observed.eligible) return {id:sid,updatedAt:observed.updatedAt,readAt:null,unread:false,changed:false}
+ const {changed,readAt}=marks.advance({id:sid,through:observed.updatedAt},assertCurrent)
+ storedTime(readAt)
+ assertCurrent()
+ if (changed) journal.publishSessionsChanged()
+ return {id:sid,updatedAt:observed.updatedAt,readAt,unread:false,changed}
+ }
+ async function serve(req,res,{auth,policy},path,match) {
+ const method=path===listPath?'GET':'POST'
+ try {
+ policy.check(req,req.method!=='GET' && req.method!=='HEAD')
+ if (req.url!==path) throw new HttpError(400,'unexpected_query')
+ if (req.method!==method) {json(res,405,{error:'method'},{allow:method,connection:'close'});return}
+ const cookie=policy.cookie(req);let actor
+ const verify=()=>{
+ if (closed || res.destroyed) throw unavailable()
+ const current=method==='GET'? auth.identify(cookie):auth.identify(cookie,req.headers['x-deva-csrf'])
+ if (!current || current.role!=='owner' || (actor && (current.ownerId!==actor.ownerId || current.loginSessionId!==actor.loginSessionId))) throw new HttpError(401,'auth')
+ actor??=current;return true
+ }
+ verify();let result
+ if (method==='GET') result=list(verify)
+ else {
+ const [,sid,operation]=match
+ const body=await readJson(req,operation==='read-state'?1024:4096,{uniqueMembers:'deep'});verify()
+ if (operation==='read-state') result=mark(sid,body,verify)
+ else {
+ if (!exact(body,['model']) || !(body.model===null || isContextModelRef(body.model))) throw new HttpError(400,'invalid_model_ref')
+ result=await turns.contextUsage(sid,body,verify)
+ }
+ }
+ verify();json(res,200,result)
+ } catch(error) {
+ // A malformed stored file is not bad client input. Preserve that file and
+ // leave every unrelated chat route operational rather than fabricating empty marks.
+ const code=error?.code==='AUTH_FAILED'?'auth':error instanceof HttpError && error.code==='invalid_read_state'?'read_state_unconfirmed':
+ error instanceof HttpError && Object.hasOwn(codes,error.code) && codes[error.code]===error.status ? error.code:'conversation_status_unavailable'
+ if (!res.destroyed && !res.headersSent) json(res,codes[code],{error:code},method==='POST'?{connection:'close'}:{})
+ }
+ }
+ return Object.freeze({
+ async handle(req,res,ctx) {
+ const path=(req.url??'').split('?',1)[0],match=chatPath.exec(path)
+ if (path!==listPath && (!match || match[0]!==path)) return false
+ if (closed || active.size>=16) {json(res,closed?503:429,{error:closed?'conversation_status_unavailable':'conversation_status_busy'},{connection:'close'});return true}
+ const job=serve(req,res,ctx,path,match);active.add(job)
+ try {await job} finally {active.delete(job)}return true
+ },
+ close(){if(!drain){closed=true;drain=Promise.allSettled([...active]).then(()=>marks.close())}return drain}
+ })
+}
diff --git a/apps/headless/src/chat/conversation-usage.mjs b/apps/headless/src/chat/conversation-usage.mjs
new file mode 100644
index 00000000..1708dfb5
--- /dev/null
+++ b/apps/headless/src/chat/conversation-usage.mjs
@@ -0,0 +1,155 @@
+import { createHash } from 'node:crypto'
+import { ATTACH_TEXT_PREFIX, estimateTokens, modelMessages } from '../../dist/chat-core.mjs'
+import { HttpError } from '../http/policy.mjs'
+import { splitModel } from './session-preferences.mjs'
+
+export const USAGE_META = '_devaHeadlessConversationUsage'
+const adapters = new Set(['openai', 'responses', 'anthropic'])
+const unavailable = Object.freeze({ modelRef: null, usage: null, source: 'unavailable', compaction: 'inactive' })
+const positiveInt = n => Number.isSafeInteger(n) && n > 0
+const digestMessages = messages => createHash('sha256').update(JSON.stringify(messages)).digest('hex')
+const isPromise = value => typeof value?.then === 'function'
+
+function authenticate(verifyOwner, sid) {
+ if (verifyOwner === undefined) return
+ const result = verifyOwner(sid)
+ if (isPromise(result)) void Promise.resolve(result).catch(() => {})
+ if (result !== true) throw new HttpError(401, 'auth')
+}
+
+function modelInfo(value, ref) {
+ if (!value || !positiveInt(value.contextWindow) || !adapters.has(value.adapter)) return null
+ const { modelRef, modelId, contextWindow, adapter } = value
+ try {
+ if ((ref !== null && ref !== modelRef) || splitModel(modelRef).modelId !== modelId) return null
+ } catch { return null }
+ return { modelRef, contextWindow, adapter }
+}
+
+function matchingModel(a, b) {
+ return a?.modelRef === b.modelRef && a?.adapter === b.adapter
+}
+
+// Resolve a model only once; retry the *local* projection if that read outlived a
+// native transcript change or if history changed during a potentially large estimate.
+// Never pair an older input count or selected model with an unverified newer history.
+function finishConversationUsage({ sid, view, start, model, requested, active, refresh, check }) {
+ for (let attempt=0;attempt<2;attempt++) {
+ check()
+ view=refresh(sid,view)
+ const now=selection(view)
+ const changed=now.ownerLayout!==start.ownerLayout || now.createdAt!==start.createdAt || now.pin!==start.pin || now.role!==start.role
+ const report=changed || !model || (requested!==null && requested!==model.modelRef) ? unavailable : projection(view,model,active(sid))
+ const confirmed=refresh(sid,view)
+ check()
+ if(confirmed===view) return report
+ view=confirmed
+ }
+ throw new HttpError(409,'read_unavailable')
+}
+
+export function captureConversationUsage(slot, input, notify) {
+ if (!slot.record || !slot.model || !adapters.has(slot.model.adapter) || !positiveInt(input) || input === slot.inputTokens) return
+ slot.inputTokens = input
+ notify()
+}
+
+export function conversationUsagePatch(slot, messages, updatedAt) {
+ if (!positiveInt(slot.inputTokens)) return null
+ const { session, record, model, inputTokens } = slot
+ return {
+ lastInputTokens: inputTokens,
+ [USAGE_META]: {
+ version: 1, sessionId: session.id, turnId: record.turnId, modelRef: model.modelRef, adapter: model.adapter,
+ updatedAt, inputTokens, digest: digestMessages(messages)
+ }
+ }
+}
+
+function recordedInput(s, last, model) {
+ const meta = s[USAGE_META]
+ if (!meta || Object.keys(meta).length !== 8 || meta.version !== 1 || meta.sessionId !== s.id || !last || last.status === 'running' ||
+ meta.turnId !== last.turnId || meta.updatedAt !== s.updatedAt || !matchingModel(meta, model) ||
+ !positiveInt(s.lastInputTokens) || s.lastInputTokens !== meta.inputTokens ||
+ (Object.hasOwn(last, 'model') && last.model !== meta.modelRef) || meta.digest !== digestMessages(s.messages)) return null
+ return s.lastInputTokens
+}
+
+function estimate(s, attachmentIndex) {
+ if (!attachmentIndex) return estimateTokens(modelMessages(s.messages))
+ let approximateText = 0
+ const messages = s.messages.map((message, index) => {
+ const row = attachmentIndex.byMessage.get(index)
+ if (!row) return message
+ const content = message.content.map((part, at) => {
+ const attachment = row.items[at]
+ // Native image/PDF costs are already charged by their part types. Text blob bytes
+ // supply only an approximate character count; include the original text-part framing.
+ if (attachment?.kind !== 'text') return part
+ approximateText += attachment.size / 3.5
+ return { type: 'text', text: `${ATTACH_TEXT_PREFIX}${attachment.name}\n\`\`\`\n\n\`\`\`` }
+ })
+ return { role: message.role, content }
+ })
+ return Math.round(estimateTokens(modelMessages(messages)) + approximateText)
+}
+
+function projection(view, model, slot) {
+ const { session, layout } = view
+ const usage = (source, used, estimated = false) => ({
+ modelRef: model.modelRef, usage: { used, estimated, window: model.contextWindow, trigger: null }, source, compaction: 'inactive'
+ })
+ if (slot && slot.session.id === session.id && slot.record && slot.record.turnId === layout.last?.turnId && layout.last.status === 'running' &&
+ matchingModel(slot.model, model) && positiveInt(slot.inputTokens)) return usage('live', slot.inputTokens)
+ const measured = !slot && layout.owned ? recordedInput(session, layout.last, model) : null
+ if (measured !== null) return usage('measured', measured)
+ if (!layout.eligible) return usage('none', null)
+ return usage('estimate', estimate(session, layout.attachments), true)
+}
+
+const selection = ({ session, layout }) => ({
+ ownerLayout: layout.owned,
+ createdAt: session.createdAt,
+ pin: typeof session.model === 'string' && session.model ? session.model : null,
+ role: layout.owned ? session.personaId : undefined
+})
+
+/** A non-null request is a guard on the authoritative pin / role / global model, not an override. */
+export function createConversationUsage({ settings, read, refresh, active, roleForTurn }) {
+ return async function contextUsage(sid, input, verifyOwner) {
+ authenticate(verifyOwner, sid)
+ const item = input && Object.getOwnPropertyDescriptor(input, 'model')
+ if (!item?.enumerable || !Object.hasOwn(item, 'value') || Reflect.ownKeys(input).length !== 1) {
+ throw new HttpError(400, 'invalid_context_request')
+ }
+ const requested = item.value
+ if (requested !== null) splitModel(requested)
+ const view = read(sid)
+ const start = selection(view)
+ const finish = model => finishConversationUsage({sid,view,start,model,requested,active,refresh,
+ check:()=>authenticate(verifyOwner,sid)})
+ if (typeof settings.getContextModel !== 'function') return finish(null)
+ let effective = start.pin
+ if (!effective && start.role !== undefined) {
+ let role
+ try { role = await roleForTurn(start.role) } catch { /* unusable role remains unavailable */ }
+ finally { authenticate(verifyOwner, sid) }
+ if (!role) return finish(null)
+ effective = role.model || null
+ }
+ if (effective !== null) {
+ try { splitModel(effective) } catch { return finish(null) }
+ if (requested !== null && requested !== effective) return finish(null)
+ }
+ let config, awaited = false
+ try {
+ config = settings.getContextModel(effective)
+ if (isPromise(config)) {
+ awaited = true
+ config = await config
+ }
+ } catch { config = null }
+ finally { if (awaited) authenticate(verifyOwner, sid) }
+ return finish(modelInfo(config, effective))
+ }
+}
diff --git a/apps/headless/src/chat/read-mark-errors.mjs b/apps/headless/src/chat/read-mark-errors.mjs
new file mode 100644
index 00000000..cfaa6717
--- /dev/null
+++ b/apps/headless/src/chat/read-mark-errors.mjs
@@ -0,0 +1,19 @@
+import { HttpError } from '../http/policy.mjs'
+
+export const invalidReadState = () => new HttpError(400, 'invalid_read_state')
+export const readStateReadOnly = () => new HttpError(403, 'read_state_read_only')
+export const readStateConflict = () => new HttpError(409, 'read_state_conflict')
+export const readStateUnsupported = () => new HttpError(409, 'read_state_unsupported')
+export const readStateLimit = () => new HttpError(413, 'read_state_limit')
+export const readStateUnconfirmed = () => new HttpError(503, 'read_state_unconfirmed')
+
+export function readStateError(error) {
+ if (error instanceof HttpError) return error
+ switch (error?.code) {
+ case 'EACCES': case 'EPERM': case 'EROFS': return readStateReadOnly()
+ case 'ENOENT': case 'EEXIST': case 'ESTALE': return readStateConflict()
+ case 'ENOTDIR': case 'ELOOP': case 'EXDEV': case 'ENOTSUP': case 'EOPNOTSUPP': return readStateUnsupported()
+ case 'EFBIG': return readStateLimit()
+ default: return readStateUnconfirmed()
+ }
+}
diff --git a/apps/headless/src/chat/read-mark-file.mjs b/apps/headless/src/chat/read-mark-file.mjs
new file mode 100644
index 00000000..cf2d1648
--- /dev/null
+++ b/apps/headless/src/chat/read-mark-file.mjs
@@ -0,0 +1,238 @@
+import { randomBytes } from 'node:crypto'
+import {
+ constants as C, fchmodSync, fchownSync, fsyncSync, linkSync, openSync, readSync, renameSync, unlinkSync, writeFileSync
+} from 'node:fs'
+import { PATH, close, fdPath, mountId, openAbsoluteDirectory, sameInode, stat } from '../files/workspace-files-fd.mjs'
+import { readStateConflict, readStateLimit, readStateReadOnly, readStateUnconfirmed, readStateUnsupported } from './read-mark-errors.mjs'
+import { MAX_READ_STATE_BYTES } from './read-mark-format.mjs'
+import { assertPlainMetadata, lockReadState } from './read-mark-unix.mjs'
+
+const NAME = 'read-state.json'
+const readFlags = C.O_RDONLY | C.O_NONBLOCK
+const newFlags = C.O_RDWR | C.O_CREAT | C.O_EXCL | C.O_NOFOLLOW | C.O_NONBLOCK
+const mode = info => info.mode & 0o7777n
+const sameOwnership = (a, b) => a.uid === b.uid && a.gid === b.gid && a.mode === b.mode
+const sameContentStamp = (a, b) => sameInode(a, b) && sameOwnership(a, b) && a.size === b.size && a.mtimeNs === b.mtimeNs
+const sameFileStamp = (a, b) => sameContentStamp(a, b) && a.nlink === b.nlink && a.ctimeNs === b.ctimeNs
+
+function mounted(fd) {
+ try { return mountId(fd) } catch { throw readStateUnsupported() }
+}
+
+function safeDirectory(info) {
+ if (!info.isDirectory() || info.uid !== BigInt(process.geteuid()) || (mode(info) & 0o7022n)) throw readStateUnsupported()
+ if ((mode(info) & 0o500n) !== 0o500n) throw readStateReadOnly()
+}
+
+function safeFile(info) {
+ // Desktop can produce 0644. Group/other writes, executes and special bits widen this
+ // policy; a safe owner-read-only file can be inspected but never replaced by Workbench.
+ if (!info.isFile() || info.nlink !== 1n || info.uid !== BigInt(process.geteuid()) || (mode(info) & ~0o644n)) {
+ throw readStateUnsupported()
+ }
+ if (!(mode(info) & 0o400n)) throw readStateReadOnly()
+ if (info.size > BigInt(MAX_READ_STATE_BYTES)) throw readStateLimit()
+}
+
+function openRoot(root) {
+ try { return openAbsoluteDirectory(root) }
+ catch (error) { if (error?.code !== 'ENOENT') throw error }
+}
+
+export function pinReadMarkRoot(root) {
+ if (process.platform !== 'linux') throw readStateUnsupported()
+ const fd = openRoot(root)
+ if (fd === undefined) return undefined
+ try {
+ const info = stat(fd)
+ safeDirectory(info)
+ return { fd, info, mount: mounted(fd) }
+ } catch (error) { close(fd); throw error }
+}
+
+function validateRoot(root, pin, expected) {
+ let current
+ try { current = openRoot(root) }
+ catch (error) {
+ // An existing pin must still resolve by its original binding, including no new symlink.
+ if (error?.code === 'ENOTDIR' || error?.code === 'ELOOP') throw readStateConflict()
+ throw error
+ }
+ try {
+ if (current === undefined) throw readStateConflict()
+ const held = stat(pin.fd)
+ const live = stat(current)
+ // A held O_PATH descriptor fixes the inode lifetime. Directory ctime (and synthetic
+ // birthtime on older kernels) can change while publishing into the *same* directory.
+ if (!sameInode(pin.info, live) || !sameInode(held, live) || held.nlink === 0n || mounted(current) !== pin.mount ||
+ !sameOwnership(held, live) || (expected && !sameOwnership(live, expected))) throw readStateConflict()
+ safeDirectory(live)
+ return live
+ } finally { close(current) }
+}
+
+function probe(dir, name) {
+ try { return openSync(fdPath(dir, name), PATH) }
+ catch (error) { if (error?.code !== 'ENOENT') throw error }
+}
+
+function readBytes(fd, expected) {
+ const bytes = Buffer.allocUnsafe(Number(expected.size))
+ // Local regular files: a short read is a concurrent change (or an unconfirmed I/O
+ // result). Never loop on the attacker-controlled count or read beyond the stat limit.
+ if ((bytes.length && readSync(fd, bytes, 0, bytes.length, 0) !== bytes.length) || !sameFileStamp(expected, stat(fd))) {
+ throw readStateConflict()
+ }
+ return bytes
+}
+
+function checkName(dir, mount, name, expected) {
+ const pin = probe(dir, name)
+ try {
+ if (expected === null ? pin !== undefined : pin === undefined || !sameFileStamp(expected, stat(pin)) || mounted(pin) !== mount) {
+ throw readStateConflict()
+ }
+ } finally { close(pin) }
+}
+
+function openNative(dir, mount) {
+ // Pin without opening the data plane of a possible symlink, FIFO or device.
+ const pin = probe(dir, NAME)
+ if (pin === undefined) return null
+ let fd
+ try {
+ const info = stat(pin)
+ if (mounted(pin) !== mount) throw readStateUnsupported()
+ safeFile(info)
+ fd = openSync(fdPath(pin), readFlags)
+ if (!sameFileStamp(info, stat(fd)) || mounted(fd) !== mount) throw readStateConflict()
+ const source = { fd, info, bytes: readBytes(fd, info) }
+ fd = undefined
+ return source
+ } finally { try { close(fd) } finally { close(pin) } }
+}
+
+function stageFile(dir, source, bytes) {
+ const name = `.${NAME}.${randomBytes(16).toString('hex')}.tmp`
+ const fd = openSync(fdPath(dir, name), newFlags, 0o600)
+ const stage = { fd, name }
+ try {
+ const created = stat(fd)
+ if (!created.isFile() || created.nlink !== 1n || created.uid !== BigInt(process.geteuid())) throw readStateConflict()
+ // Probe before writing even the temporary bytes: a directory default ACL can affect
+ // the empty staging inode, and chmod of an inherited ACL can widen its group mask.
+ assertPlainMetadata(dir, fd, ...(source ? [source.fd] : []))
+ if (!sameFileStamp(created, stat(fd))) throw readStateConflict()
+ const intendedMode = source ? mode(source.info) : 0o600n
+ const intendedGid = source?.info.gid ?? created.gid
+ if (created.gid !== intendedGid) fchownSync(fd, Number(created.uid), Number(intendedGid))
+ fchmodSync(fd, Number(intendedMode))
+ writeFileSync(fd, bytes)
+ fsyncSync(fd)
+ const info = stat(fd)
+ safeFile(info)
+ if (mode(info) !== intendedMode || info.gid !== intendedGid || !readBytes(fd, info).equals(bytes)) throw readStateConflict()
+ return { ...stage, info }
+ } catch (error) {
+ try { removeStage(dir, stage) } catch { /* leave unconfirmed staging names alone */ }
+ close(fd)
+ throw error
+ }
+}
+
+function removeStage(dir, stage) {
+ const pin = probe(dir, stage.name)
+ try {
+ // A same-UID, noncooperating writer can replace the name; do not delete an observed
+ // replacement. Linux does not expose inode-conditional unlink through Node.
+ if (pin !== undefined && sameInode(stat(stage.fd), stat(pin))) unlinkSync(fdPath(dir, stage.name))
+ } finally { close(pin) }
+}
+
+function attachStage(dir, stage, replace) {
+ const target = fdPath(dir, NAME)
+ const temporary = fdPath(dir, stage.name)
+ try {
+ if (replace) {
+ // flock + the final comparison serialize cooperating writers, even across processes.
+ // Plain rename has no compare-inode precondition against a same-UID writer ignoring flock.
+ renameSync(temporary, target)
+ } else {
+ // Publish an initially absent file without ever overwriting a newly appeared name.
+ linkSync(temporary, target)
+ }
+ } catch (error) {
+ let observed
+ try {
+ observed = probe(dir, NAME)
+ if (observed !== undefined && sameInode(stage.info, stat(observed))) throw readStateUnconfirmed()
+ } catch { throw readStateUnconfirmed() }
+ finally { close(observed) }
+ throw error
+ }
+}
+
+function publish(dir, mount, verifyRoot, source, bytes, verify) {
+ if (!(mode(verifyRoot()) & 0o200n) || (source && !(mode(source.info) & 0o200n))) throw readStateReadOnly()
+ lockReadState(dir)
+ verifyRoot()
+ checkName(dir, mount, NAME, source?.info ?? null)
+ const stage = stageFile(dir, source, bytes)
+ let pending = true
+ let installed
+ try {
+ verify() // Staging and fsync are done; only bounded CAS reads precede publication.
+ verifyRoot()
+ // Check bytes as well as metadata after the callback: some Unix filesystems expose
+ // coarse timestamps. Keep the source and stage inodes pinned until the commit completes.
+ if (!readBytes(stage.fd, stage.info).equals(bytes) || (source && !readBytes(source.fd, source.info).equals(source.bytes))) {
+ throw readStateConflict()
+ }
+ checkName(dir, mount, stage.name, stage.info)
+ checkName(dir, mount, NAME, source?.info ?? null)
+ attachStage(dir, stage, source !== null)
+ pending = source === null
+ try {
+ if (pending) {
+ removeStage(dir, stage)
+ pending = false
+ }
+ fsyncSync(dir)
+ installed = openNative(dir, mount)
+ if (!installed || !sameContentStamp(stage.info, installed.info) || !installed.bytes.equals(bytes)) throw readStateUnconfirmed()
+ verifyRoot()
+ checkName(dir, mount, NAME, installed.info)
+ } catch { throw readStateUnconfirmed() }
+
+ // The commit was observed and durable. Propagate the exact approved verify error,
+ // but never roll back or acknowledge a publication after revoked/stale access.
+ verify()
+ try {
+ verifyRoot()
+ if (!readBytes(installed.fd, installed.info).equals(bytes)) throw readStateUnconfirmed()
+ checkName(dir, mount, NAME, installed.info)
+ } catch { throw readStateUnconfirmed() }
+ } finally {
+ // Cleanup never masks a fresh authorization/domain error, nor targets the native name.
+ try { if (pending) removeStage(dir, stage) } catch { /* leave unconfirmed staging names alone */ }
+ try { close(installed?.fd) } finally { close(stage.fd) }
+ }
+}
+
+export function withReadMarkFile(root, pin, operation) {
+ const before = validateRoot(root, pin)
+ const dir = openSync(fdPath(pin.fd), readFlags | C.O_DIRECTORY)
+ let source
+ try {
+ if (!sameInode(before, stat(dir)) || mounted(dir) !== pin.mount) throw readStateConflict()
+ const verifyRoot = () => validateRoot(root, pin, before)
+ verifyRoot()
+ source = openNative(dir, pin.mount)
+ const confirm = () => {
+ verifyRoot()
+ if (source && !readBytes(source.fd, source.info).equals(source.bytes)) throw readStateConflict()
+ checkName(dir, pin.mount, NAME, source?.info ?? null)
+ }
+ return operation(source?.bytes ?? null, confirm, (bytes, verify) => publish(dir, pin.mount, verifyRoot, source, bytes, verify))
+ } finally { try { close(source?.fd) } finally { close(dir) } }
+}
diff --git a/apps/headless/src/chat/read-mark-format.mjs b/apps/headless/src/chat/read-mark-format.mjs
new file mode 100644
index 00000000..963e1595
--- /dev/null
+++ b/apps/headless/src/chat/read-mark-format.mjs
@@ -0,0 +1,86 @@
+import { isSessionId } from '../events/chat-event.mjs'
+import { decodeUtf8 } from '../files/workspace-files-fd.mjs'
+import { invalidReadState, readStateLimit } from './read-mark-errors.mjs'
+
+export const MAX_READ_STATE_BYTES = 1024 * 1024
+export const MAX_READ_STATE_IDS = 8192
+export const validReadMark = (id, time) => isSessionId(id) && Number.isSafeInteger(time) && time >= 0
+
+// JSON hardens neither duplicate keys nor rounded decimal input. Keep the raw form of every
+// unrelated byte and require an exact safe integer in the mathematical value of each token.
+function exactTimestamp(token) {
+ const [, minus, whole, fraction = '', exponent = '0'] = token
+ const digits = whole + fraction
+ const first = digits.search(/[1-9]/)
+ if (first < 0) return 0 // Includes the valid legacy representation -0.
+ const point = whole.length + Number(exponent)
+ if (minus || point <= first || point - first > 16 || /[1-9]/.test(digits.slice(point))) throw invalidReadState()
+ const value = Number(token[0])
+ if (!Number.isSafeInteger(value)) throw invalidReadState()
+ return value
+}
+
+export function parseReadState(bytes, targetId) {
+ if (bytes.length > MAX_READ_STATE_BYTES) throw readStateLimit()
+ let text
+ try { text = decodeUtf8(bytes) } catch { throw invalidReadState() }
+ // The shared fatal decoder deliberately retains BOM; retain it in the output, if present.
+ let cursor = text.charCodeAt(0) === 0xfeff ? 1 : 0
+ const values = new Map()
+ const white = /[\x20\t\r\n]*/y
+ const key = /"(?:[^"\\\u0000-\u001f]|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4})){0,128}"/y
+ const number = /(-?)(0|[1-9][0-9]*)(?:\.([0-9]+))?(?:[eE]([+-]?[0-9]+))?/y
+ function match(pattern) {
+ pattern.lastIndex = cursor
+ const token = pattern.exec(text)
+ if (!token) throw invalidReadState()
+ cursor = pattern.lastIndex
+ return token
+ }
+ const ws = () => match(white)
+ ws()
+ if (text[cursor++] !== '{') throw invalidReadState()
+ let insertion = cursor
+ let target
+ ws()
+ if (text[cursor] !== '}') {
+ for (;;) {
+ const spelling = match(key)[0]
+ if (spelling.length > 770) throw invalidReadState() // 128 ASCII characters, up to six bytes each, plus quotes.
+ const id = JSON.parse(spelling)
+ ws()
+ if (text[cursor++] !== ':') throw invalidReadState()
+ ws()
+ const start = cursor
+ const time = exactTimestamp(match(number))
+ if (!validReadMark(id, time) || values.has(id)) throw invalidReadState()
+ if (values.size >= MAX_READ_STATE_IDS) throw readStateLimit()
+ values.set(id, time)
+ if (id === targetId) target = { start, end: cursor }
+ insertion = cursor
+ ws()
+ if (text[cursor] !== ',') break
+ cursor++
+ ws()
+ }
+ }
+ if (text[cursor++] !== '}') throw invalidReadState()
+ ws()
+ if (cursor !== text.length) throw invalidReadState()
+ return { text, values, insertion, target }
+}
+
+export function advanceReadState(state, id, through) {
+ let text
+ if (!state) text = `{${JSON.stringify(id)}:${through}}`
+ else if (state.target) {
+ const { text: raw, target: { start, end } } = state
+ text = `${raw.slice(0, start)}${through}${raw.slice(end)}`
+ } else {
+ const { text: raw, values, insertion } = state
+ if (values.size >= MAX_READ_STATE_IDS) throw readStateLimit()
+ text = `${raw.slice(0, insertion)}${values.size ? ',' : ''}${JSON.stringify(id)}:${through}${raw.slice(insertion)}`
+ }
+ if (Buffer.byteLength(text) > MAX_READ_STATE_BYTES) throw readStateLimit()
+ return Buffer.from(text, 'utf8')
+}
diff --git a/apps/headless/src/chat/read-mark-store.mjs b/apps/headless/src/chat/read-mark-store.mjs
new file mode 100644
index 00000000..e0e1f63b
--- /dev/null
+++ b/apps/headless/src/chat/read-mark-store.mjs
@@ -0,0 +1,105 @@
+import { isAbsolute, resolve } from 'node:path'
+import { isPromise } from 'node:util/types'
+import { close } from '../files/workspace-files-fd.mjs'
+import { HttpError } from '../http/policy.mjs'
+import { invalidReadState, readStateConflict, readStateError, readStateReadOnly, readStateUnconfirmed } from './read-mark-errors.mjs'
+import { pinReadMarkRoot, withReadMarkFile } from './read-mark-file.mjs'
+import { advanceReadState, parseReadState, validReadMark } from './read-mark-format.mjs'
+
+function authorize(verify) {
+ if (typeof verify !== 'function') throw new HttpError(401, 'auth')
+ let result
+ try {
+ result = verify()
+ // Reject asynchronous authorization without invoking arbitrary thenable implementations.
+ if (isPromise(result)) Promise.prototype.then.call(result, undefined, () => {})
+ } catch (error) {
+ if (error instanceof HttpError && ((error.status === 401 && error.code === 'auth') ||
+ (error.status === 409 && (error.code === 'read_view_stale' || error.code === 'read_view_busy')) ||
+ (error.status === 503 && error.code === 'conversation_status_unavailable'))) throw error
+ throw new HttpError(401, 'auth')
+ }
+ if (result !== true) throw new HttpError(401, 'auth')
+}
+
+/** One Workbench instance owner's native read marks, shared across that owner's logins.
+ * The caller authorizes disclosures and filters the private snapshot to visible sessions.
+ * `through` comes only from the authorized durable session revision, never the request clock.
+ * Methods are synchronous; no snapshot, callback or parsed map is retained between operations. */
+export function openReadMarkStore(options) {
+ const { dataDir } = options ?? {}
+ if (typeof dataDir !== 'string' || !isAbsolute(dataDir) || dataDir.includes('\0') || Buffer.byteLength(dataDir) > 4095) {
+ throw invalidReadState()
+ }
+ const root = resolve(dataDir)
+ if (root === '/') throw invalidReadState()
+ let pin
+ let active = false
+ let closed = false
+
+ function release() {
+ const held = pin
+ pin = undefined
+ close(held?.fd)
+ }
+ function assertOpen() { if (closed) throw readStateUnconfirmed() }
+
+ function run(operation) {
+ assertOpen()
+ if (active) throw readStateConflict()
+ active = true
+ try { return operation() }
+ catch (error) { throw readStateError(error) }
+ finally {
+ active = false
+ // `verify` can close the store reentrantly; keep the anchor live until its current
+ // operation winds down so no descriptors are recycled under active filesystem work.
+ if (closed) release()
+ }
+ }
+
+ function rootPin() {
+ if (!pin) pin = pinReadMarkRoot(root) ?? pinReadMarkRoot(root)
+ return pin
+ }
+
+ return Object.freeze({
+ snapshot() {
+ return run(() => {
+ const held = rootPin()
+ if (!held) return new Map()
+ return withReadMarkFile(root, held, (bytes, confirm) => {
+ const snapshot = bytes === null ? new Map() : parseReadState(bytes).values
+ confirm()
+ return snapshot
+ })
+ })
+ },
+ advance(input, verify) {
+ return run(() => {
+ const reauthorize = () => { authorize(verify); assertOpen() }
+ reauthorize()
+ const { id, through } = input ?? {}
+ if (!validReadMark(id, through)) throw invalidReadState()
+ const held = rootPin()
+ if (!held) throw readStateReadOnly()
+ return withReadMarkFile(root, held, (bytes, confirm, publish) => {
+ const state = bytes === null ? null : parseReadState(bytes, id)
+ const previous = state?.values.get(id)
+ if (previous !== undefined && previous >= through) {
+ reauthorize()
+ confirm()
+ return { changed: false, readAt: previous }
+ }
+ publish(advanceReadState(state, id, through), reauthorize)
+ return { changed: true, readAt: through === 0 ? 0 : through }
+ })
+ })
+ },
+ close() {
+ if (closed) return
+ closed = true
+ if (!active) release()
+ }
+ })
+}
diff --git a/apps/headless/src/chat/read-mark-unix.mjs b/apps/headless/src/chat/read-mark-unix.mjs
new file mode 100644
index 00000000..c0998280
--- /dev/null
+++ b/apps/headless/src/chat/read-mark-unix.mjs
@@ -0,0 +1,31 @@
+import { spawnSync } from 'node:child_process'
+import { readStateConflict, readStateReadOnly, readStateUnsupported } from './read-mark-errors.mjs'
+
+const HELPER_TIMEOUT_MS = 1000
+const getXattrListSize = { x64: 196, arm64: 13 }[process.arch]
+
+function run(program, args, fds) {
+ return spawnSync(program, args, {
+ stdio: ['ignore', 'ignore', 'ignore', ...fds], env: {}, timeout: HELPER_TIMEOUT_MS, killSignal: 'SIGKILL'
+ })
+}
+
+export function lockReadState(fd) {
+ // flock operates on the inherited open file description, not the child process's lifetime.
+ // Lock the directory itself only for writes: no stale marker or extra path.
+ const res = run('/usr/bin/flock', ['-n', '-x', '-E', '73', '3'], [fd])
+ if (res.status === 73) throw readStateConflict()
+ if (res.status !== 0 || res.error) throw readStateUnsupported()
+}
+
+// Node fs has no flistxattr. Debian's Essential perl-base (including bookworm-slim) supplies
+// a fixed syscall shim; it probes only inherited descriptors, not a file path or a shell.
+// POSIX ACLs, capabilities, labels and other *visible* xattrs are unsupported. The storage
+// contract is a conventional local Unix volume without privileged/hidden metadata; Linux
+// can hide trusted.* from unprivileged owners. Fail closed if the helper/probe is unavailable.
+const probe = 'my $n = shift; for my $fd (3..(2+shift)) { exit 73 if syscall($n,$fd,0,0) != 0 } exit 0;'
+export function assertPlainMetadata(...fds) {
+ if (process.platform !== 'linux' || getXattrListSize === undefined) throw readStateReadOnly()
+ const res = run('/usr/bin/perl', ['-e', probe, String(getXattrListSize), String(fds.length)], fds)
+ if (res.status !== 0 || res.error) throw readStateReadOnly()
+}
diff --git a/apps/headless/src/chat/text-turns.mjs b/apps/headless/src/chat/text-turns.mjs
index c728bf78..219ab94e 100644
--- a/apps/headless/src/chat/text-turns.mjs
+++ b/apps/headless/src/chat/text-turns.mjs
@@ -4,6 +4,8 @@ import { consumeModelStep, createChatStore, isValidSessionId, modelMessages } fr
import { connectProvider } from '../business/model-connection.mjs'
import { chatScope } from '../events/index.mjs'
import { HttpError } from '../http/policy.mjs'
+import { createConversationContext, matchesTurnLayout, nextConversationUpdatedAt } from './conversation-context.mjs'
+import { captureConversationUsage, conversationUsagePatch, createConversationUsage, USAGE_META } from './conversation-usage.mjs'
import { createDeliveryRecords } from './delivery-records.mjs'
import { confirmPreferenceStorage, preflightPreferenceStorage } from './session-preferences-storage.mjs'
import {
@@ -37,7 +39,7 @@ const terminalReasons = new Map([
])
const nativeTextFields = new Set([
'id', 'title', 'createdAt', 'updatedAt', 'focusRoot', 'personaId', 'model', 'messages', 'notices',
- 'archived', 'effort', META, PREFERENCES_META, WORKSPACE_META
+ 'archived', 'effort', 'lastInputTokens', META, PREFERENCES_META, WORKSPACE_META, USAGE_META
])
const complexFields = [
'compacted', 'members', 'parentId', 'proposals', 'asks', 'summaries', 'delivered', 'background',
@@ -45,6 +47,8 @@ const complexFields = [
'baselines', 'restoreNote'
]
+const legacyContextFields = new Set([...nativeTextFields, ...complexFields, 'bucket', 'lastCacheRead', 'lastCacheWrite', 'lastRequestAt'])
+const desktopHistoryMarker = /^⟦deva:(?:compaction|auto|notify|insert)⟧/u
const validSid = id => isValidSessionId(id) && id.length <= 128 // The journal has a narrower ID range.
const desktopSid = /^sess_[0-9a-z]{1,12}_[0-9a-z]{1,8}$/
const uuidSid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
@@ -191,7 +195,7 @@ function appendNotice(notices, after, status, reason, text) {
/** One instance per data directory and journal. The owner closes the journal after awaiting close().
* resolveRole reads trusted library state. withWorkspace only supplies live pinned catalog grants. */
-export function createTextTurns({ dataDir, settings, journal, version, allowedOrigins, resolveRole, uploads, deliveries, withWorkspace }) {
+export function createTextTurns({ dataDir, settings, journal, version, allowedOrigins, resolveRole, uploads, deliveries, withWorkspace, readWatermark }) {
if (typeof settings?.getProvider !== 'function' || !['snapshot', 'snapshotAndSubscribe', 'publishChat', 'publishSessionsChanged']
.every(fn => typeof journal?.[fn] === 'function')) throw new TypeError('Text turns require settings and an event journal')
if (resolveRole !== undefined && typeof resolveRole !== 'function') throw new TypeError('resolveRole must be a function')
@@ -199,6 +203,7 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr
let warned = false
const incomplete = new WeakSet()
const mediaUnconfirmed = new WeakSet()
+ const unreadableHistory = new WeakSet()
const classifications = new WeakMap()
const store = createChatStore({
dataDir, onWarning() { warned = true },
@@ -208,7 +213,7 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr
const active = new Map()
const unconfirmed = new Map() // Quarantine ambiguous writes until restart; never replay a charged request.
const hidden = new Set() // A failed create may leave a session only in the core's cache.
- const deliverySessions = deliveries === true ? new Map() : undefined
+ const knownSessions = new Map() // The native read projection must reconcile with the original loaded cache.
let closing
const workspace = createSessionWorkspaceDomain({
dataDir, withWorkspace, validSid, isClosing: () => Boolean(closing), isActive: sid => active.has(sid),
@@ -220,14 +225,24 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr
}
})
+ const context = createConversationContext({
+ dataDir, validSid, journal, cached: sid => knownSessions.get(sid), active: sid => active.has(sid),
+ blocked: sid => hidden.has(sid) || unconfirmed.has(sid),
+ unreadable: sid => unreadableHistory.has(knownSessions.get(sid)) || mediaUnconfirmed.has(knownSessions.get(sid)),
+ closing: () => Boolean(closing), inspect: contextLayout
+ })
+ const contextUsage = createConversationUsage({ settings, read: context.read, refresh: context.refresh, active: sid => active.get(sid), roleForTurn })
+
function lookupSession(sid) {
warned = false
const s = hidden.has(sid) ? undefined : store.getSession(sid)
- if (s && warned) incomplete.add(s)
- if (s && Object.hasOwn(s, META)) {
- workspace.note(s)
- deliverySessions?.set(sid, s)
- workspace.stable(s)
+ if (s) {
+ if (warned) incomplete.add(s)
+ knownSessions.set(sid, s)
+ if (Object.hasOwn(s, META)) {
+ workspace.note(s)
+ workspace.stable(s)
+ }
}
return s
}
@@ -269,9 +284,26 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr
return kind
}
+ function contextLayout(s, cached) {
+ if ((cached && incomplete.has(cached)) || s.messages.some(m => typeof m.content === 'string' && desktopHistoryMarker.test(m.content))) return null
+ const kind = compatibility(s)
+ if (kind === 'unsupported' || (kind === 'legacy_text' && Object.keys(s).some(key => !legacyContextFields.has(key)))) return null
+ const owned = kind === 'text'
+ const requests = owned ? s[META].requests : null
+ if (requests && !matchesTurnLayout(s.messages, requests)) return null
+ const index = owned ? attachedIndex(s) : null
+ const eligible = s.messages.some((m, at) => index?.byMessage.has(at) || Boolean(plainText(m.content)?.trim()))
+ return { owned, eligible, attachments: index || null, last: requests?.at(-1) ?? null }
+ }
+
function summary(s, kind = compatibility(s)) {
const index = kind === 'text' && attachedIndex(s)
- if (index && (mediaUnconfirmed.has(s) || !attachments.available(index))) kind = 'unsupported'
+ if (index) {
+ if (mediaUnconfirmed.has(s) || !attachments.available(index)) {
+ unreadableHistory.add(s)
+ kind = 'unsupported'
+ } else unreadableHistory.delete(s)
+ }
let writeBlockReason = null
if (kind === 'unsupported') writeBlockReason = 'unsupported_history'
else if (kind !== 'text') writeBlockReason = 'read_only_session'
@@ -318,7 +350,7 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr
store.saveStrict(id)
workspace.afterSave(s, true)
workspace.note(s)
- deliverySessions?.set(id, s)
+ knownSessions.set(id, s)
return summary(s)
} catch { throw storageError() }
}
@@ -476,6 +508,14 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr
catch { /* a journal fault does not change the outcome of the confirmed store write */ }
}
+ function nextUpdatedAt(s) {
+ let watermark
+ try { if (typeof readWatermark === 'function') watermark = readWatermark(s.id) }
+ catch { /* a broken read-state map never blocks ordinary chat */ }
+ if (typeof watermark?.then === 'function') void Promise.resolve(watermark).catch(() => {})
+ return nextConversationUpdatedAt(s.updatedAt, Date.now(), watermark)
+ }
+
function priorResult(record, fingerprint) {
if (record.fingerprint !== fingerprint) throw new HttpError(409, 'client_request_conflict')
return { ...result(record), duplicate: true }
@@ -535,12 +575,12 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr
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) {
+ const binding = { async getProvider(id) {
const provider = await settings.getProvider(id)
if (provider == null) return provider
adapter = provider.adapter
return { ...provider, adapter }
- } } : settings
+ } }
try {
client = await connectProvider(binding, providerId, { version, allowedOrigins, signal: controller.signal, modelId })
} catch (err) {
@@ -577,15 +617,15 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr
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
+ const updatedAt = nextUpdatedAt(s)
commit(s, {
- ...modelPatch, messages, notices, title, updatedAt: record.startedAt,
+ ...modelPatch, messages, notices, title, updatedAt,
[META]: { version: 1, messageCount: messages.length, requests }, ...prepared?.patch
})
slot.record = record
+ slot.model = { modelRef: model, adapter }
publish(slot, { type: 'turn_start' })
- if (listChanged) publishSessionsChanged()
+ 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') {
@@ -631,6 +671,9 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr
if (typeof delta !== 'string') throw modelError
if ((thinkingSize += delta.length) > MAX_OUTPUT) throw outputLimit
},
+ onUsage({ input }) {
+ if (!controller.signal.aborted) captureConversationUsage(slot, input, () => publish(slot, { type: 'context_changed' }))
+ },
onError() { throw modelError }
// No tool callbacks: the shared consumer closes at the first normalized tool call.
})
@@ -647,13 +690,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
+ const updatedAt = nextUpdatedAt(s)
+ const usage = conversationUsagePatch(slot, messages, updatedAt)
commit(s, {
- messages, notices, updatedAt,
+ messages, notices, updatedAt, ...usage,
[META]: { version: 1, messageCount: messages.length, requests: [...s[META].requests.slice(0, -1), ended] }
- }, { ...record, status: 'failed', reason: 'storage_unconfirmed' })
- if (listChanged) publishSessionsChanged()
+ }, { ...record, status: 'failed', reason: 'storage_unconfirmed' }, usage ? () => context.confirm(s) : undefined)
+ publishSessionsChanged()
} catch {
status = 'failed'
stopReason = 'error'
@@ -719,11 +762,15 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr
const s = lookupSession(sid)
return !!s && compatibility(s) === 'text'
}
- const records = deliverySessions && createDeliveryRecords({
+ const deliveryCached = sid => {
+ const s = knownSessions.get(sid)
+ return s && Object.hasOwn(s, META) ? s : undefined
+ }
+ const records = deliveries === true && createDeliveryRecords({
dataDir, validSid, ledgerKey: META,
active: sid => active.has(sid), closing: () => Boolean(closing),
- blocked: sid => hidden.has(sid) || unconfirmed.has(sid) || incomplete.has(deliverySessions.get(sid)),
- cached: sid => deliverySessions.get(sid), classify: compatibility, attachedIndex,
+ blocked: sid => hidden.has(sid) || unconfirmed.has(sid) || incomplete.has(deliveryCached(sid)),
+ cached: deliveryCached, classify: compatibility, attachedIndex,
hasMedia(cached, source) {
const index = attachedIndex(source)
return !index || (!mediaUnconfirmed.has(cached) && attachments.available(index))
@@ -731,6 +778,7 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr
})
return Object.freeze({
create, list, attach, snapshot, send, stop, close, getPreferences, patchPreferences, getWorkspace: workspace.getWorkspace, setWorkspace,
- attachmentScope, describeCommittedAttachment, readCommittedAttachment, hasBrowserSession, ...records
+ attachmentScope, describeCommittedAttachment, readCommittedAttachment, hasBrowserSession, ...records,
+ contextUsage, readCandidates: context.readCandidates, readObservation: context.readObservation
})
}
diff --git a/apps/headless/src/events/chat-event.mjs b/apps/headless/src/events/chat-event.mjs
index 6e7cbf60..d23ef567 100644
--- a/apps/headless/src/events/chat-event.mjs
+++ b/apps/headless/src/events/chat-event.mjs
@@ -23,6 +23,8 @@ function selectOutput(input) {
}
case 'turn_start':
case 'stream_reset':
+ // Usage is read from the authoritative session+model projection. Broadcast only an invalidation.
+ case 'context_changed':
case 'member_report':
case 'error':
return { type }
diff --git a/apps/headless/src/http/policy.mjs b/apps/headless/src/http/policy.mjs
index 0819800b..16203381 100644
--- a/apps/headless/src/http/policy.mjs
+++ b/apps/headless/src/http/policy.mjs
@@ -56,10 +56,10 @@ export function json(res, status, payload, headers = {}) {
res.end(bytes)
}
-// Called only on successfully parsed JSON. Count outer object members without
-// interpreting colons in strings or in nested objects. JSON.parse alone silently
-// chooses the last value of a duplicated key, including differently escaped spellings.
-function outerMemberCount(raw) {
+// Called only on successfully parsed JSON. Count object members without interpreting
+// colons in strings. JSON.parse silently chooses the last value of a duplicate key,
+// including differently escaped spellings. Existing callers can opt into root checking.
+function wireMemberCount(raw, nested) {
let members=0, depth=0, quoted=false
for (let i=0;i{
+ const parent=await realpath(tmpdir()), root=await mkdtemp(join(parent,'deva-context-settings-')), info=await lstat(root,{bigint:true})
+ const name=join(root,'config.json')
+ t.after(async()=>{
+ const now=await lstat(root,{bigint:true})
+ assert.equal(await realpath(root),root);assert.equal(dirname(root),parent)
+ assert.deepEqual([now.dev,now.ino,now.uid,now.mode&0o777n],[info.dev,info.ino,BigInt(process.geteuid()),0o700n]);await rm(root,{recursive:true})
+ })
+ const providers=[{id:'editorial',name:'Fixture',enabled:true,kind:'custom',purpose:'llm',adapter:'openai',apiHost:'https://example.invalid/v1',
+ models:[{id:'notes-unknown',enabled:true},{id:'selected-64k',enabled:true},{id:'pinned',enabled:true,contextWindow:15111},{id:'off',enabled:false}]},
+ {id:'disabled',enabled:false,adapter:'openai',apiHost:'https://example.invalid/v1',models:[{id:'visible',enabled:true}]},
+ {id:'judge',purpose:'decision',adapter:'jev',enabled:true,apiHost:'https://example.invalid/v1',models:[{id:'private',enabled:true}]}]
+ const encoded=Buffer.from(JSON.stringify({models:{activeModelId:'editorial:notes-unknown',providers},compaction:{defaultWindow:17423,triggerRatio:0.3},futureKey:'unchanged'}))
+ await writeFile(name,encoded,{mode:0o600,flag:'wx'})
+ let canary=false, contacted=0
+ const guard=()=>{if(canary){contacted++;throw Error('Unexpected private read')}}
+ const settings=await openSettings({dataDir:root,vault:{list:()=>{guard();return []},get:guard,set:guard}})
+ const before=await lstat(name,{bigint:true});canary=true
+ for(const [ref,model,contextWindow] of [[null,'notes-unknown',17423],['editorial:selected-64k','selected-64k',64000],['editorial:pinned','pinned',15111]]){
+ const row=await settings.getContextModel(ref)
+ assert.deepEqual(row,{modelRef:`editorial:${model}`,modelId:model,adapter:'openai',contextWindow})
+ }
+ for(const ref of ['editorial:off','editorial:missing','disabled:visible','judge:private'])assert.equal(await settings.getContextModel(ref),null)
+ for(const ref of ['', 'editorial: spaced','other:abc\n']) await assert.rejects(settings.getContextModel(ref))
+ assert.equal(contacted,0);assert.deepEqual(await readFile(name),encoded)
+ const after=await lstat(name,{bigint:true});assert.deepEqual([after.ino,after.ctimeNs,after.mtimeNs],[before.ino,before.ctimeNs,before.mtimeNs])
+})
diff --git a/apps/headless/test/context-usage-stability.test.mjs b/apps/headless/test/context-usage-stability.test.mjs
new file mode 100644
index 00000000..0c181a45
--- /dev/null
+++ b/apps/headless/test/context-usage-stability.test.mjs
@@ -0,0 +1,30 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import {createConversationUsage} from '../src/chat/conversation-usage.mjs'
+
+const model={modelRef:'local:fixture',modelId:'fixture',adapter:'openai',contextWindow:12000}
+const initial={session:{id:'a',createdAt:1,model:model.modelRef,messages:[{role:'user',content:'first'}]},layout:{owned:false,eligible:true}}
+const revised={session:{...initial.session,messages:[{role:'user',content:'new content '.repeat(400)}]},layout:initial.layout}
+function endpoint(refresh) {
+ let configReads=0
+ const usage=createConversationUsage({read:()=>initial,refresh,active:()=>undefined,
+ settings:{async getContextModel(){configReads++;return model}}})
+ return {query:()=>usage('a',{model:null},()=>true),reads:()=>configReads}
+}
+
+test('after expensive estimation a new durable file stamp forces a fresh local projection, never another upstream request',async()=>{
+ let disk=initial,checks=0
+ const api=endpoint((_sid,prior)=>{
+ if (++checks===2) disk=revised // The named file changed during the first projection.
+ return prior===disk?prior:disk
+ })
+ const result=await api.query()
+ assert.equal(result.source,'estimate');assert.ok(result.usage.used>1000)
+ assert.equal(api.reads(),1);assert.equal(checks,4)
+})
+
+test('a continuously changing protected session fails boundedly rather than returning a stale estimate',async()=>{
+ let checks=0
+ const api=endpoint((_sid,old)=>{checks++;return {...old}})
+ await assert.rejects(api.query(),{status:409,code:'read_unavailable'});assert.equal(api.reads(),1);assert.equal(checks,4)
+})
diff --git a/apps/headless/test/conversation-context.test.mjs b/apps/headless/test/conversation-context.test.mjs
new file mode 100644
index 00000000..de217e49
--- /dev/null
+++ b/apps/headless/test/conversation-context.test.mjs
@@ -0,0 +1,396 @@
+import assert from 'node:assert/strict'
+import { createHash, 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 test from 'node:test'
+import { buildUploadedPart, createChatStore, estimateTokens } from '../dist/chat-core.mjs'
+import { withConversationFiles } from '../src/chat/conversation-context-storage.mjs'
+import { USAGE_META } from '../src/chat/conversation-usage.mjs'
+import { createTextTurns } from '../src/chat/text-turns.mjs'
+import { chatScope, createEventJournal } from '../src/events/index.mjs'
+
+const fixtureKey = 'usage-fixture-private-key'
+const unavailable = { modelRef: null, usage: null, source: 'unavailable', compaction: 'inactive' }
+const ref = (adapter, modelId = 'mini:latest') => `${adapter}:${modelId}`
+const error = (status, code) => ({ status, code })
+const ok = () => true
+const usage = (modelRef, source, used, window = 128_000) => ({
+ modelRef, source, usage: { used, estimated: source === 'estimate', window, trigger: null }, compaction: 'inactive'
+})
+const timeout = { timeout: 10_000 }
+const textPart = text => ({ type: 'text', text })
+
+function respond(adapter, res, input) {
+ const optional = fields => input === undefined ? {} : fields
+ let frames
+ if (adapter === 'anthropic') frames = [
+ { type: 'message_start', message: { usage: optional({ input_tokens: input, cache_creation_input_tokens: 5, cache_read_input_tokens: 9 }) } },
+ { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'Completed answer' } },
+ { type: 'message_delta', delta: { stop_reason: 'end_turn' }, usage: { output_tokens: 7 } }, { type: 'message_stop' }
+ ]
+ else if (adapter === 'responses') frames = [
+ { type: 'response.output_text.delta', delta: 'Completed answer' },
+ { type: 'response.completed', response: { usage: optional({ input_tokens: input, output_tokens: 7, input_tokens_details: { cached_tokens: 6 } }) } }
+ ]
+ else frames = [
+ { choices: [{ index: 0, delta: { content: 'Completed answer' }, finish_reason: 'stop' }] },
+ { choices: [], usage: optional({ prompt_tokens: input, completion_tokens: 7, prompt_tokens_details: { cached_tokens: 6 } }) }, '[DONE]'
+ ]
+ res.writeHead(200, { 'content-type': 'text/event-stream' })
+ res.end(frames.map(frame => `data: ${typeof frame === 'string' ? frame : JSON.stringify(frame)}\n\n`).join(''))
+}
+
+async function fixture(t, { onUsageEvent, journalOptions, resolveRole, uploads, readWatermark } = {}) {
+ const dataDir = await fs.mkdtemp(join(await fs.realpath(tmpdir()), 'deva-context-'))
+ const chats = join(dataDir, 'data', 'chats')
+ const sessionPath = sid => join(chats, `${sid}.json`)
+ const disk = async sid => JSON.parse(await fs.readFile(sessionPath(sid), 'utf8'))
+ const upstream = [], failures = [], sent = [], providerReads = [], modelReads = []
+ let input = 113, getProviderGate, nextReplyGate
+ const server = createServer((req, res) => {
+ void (async () => {
+ const chunks = []
+ for await (const chunk of req) chunks.push(chunk)
+ const body = JSON.parse(Buffer.concat(chunks))
+ upstream.push({ url: req.url, body })
+ if (nextReplyGate) { const gate = nextReplyGate; nextReplyGate = null; await gate }
+ respond(req.url.split('/')[1], res, input)
+ })().catch(err => { failures.push(err); res.destroy() })
+ })
+ await once(server.listen(0, '127.0.0.1'), 'listening')
+ const origin = `http://127.0.0.1:${server.address().port}`
+ let defaultRef = ref('openai')
+ let getContextGate
+ const getContextModel = modelRef => {
+ modelReads.push(modelRef)
+ modelRef ??= defaultRef
+ const colon = modelRef?.indexOf(':') ?? -1
+ const adapter = modelRef?.slice(0, colon)
+ const modelId = modelRef?.slice(colon + 1)
+ if (!['openai', 'anthropic', 'responses'].includes(adapter) || !['mini:latest', 'other'].includes(modelId)) return null
+ const result = { modelRef, adapter, modelId, contextWindow: 128_000, extraPrivateConfig: fixtureKey }
+ return getContextGate ? getContextGate.then(() => result) : result
+ }
+ const settings = {
+ getContextModel,
+ getPublicConfig() { return { models: { activeModelId: defaultRef } } },
+ async getProvider(id) {
+ providerReads.push(id)
+ if (getProviderGate) await getProviderGate
+ return { id, adapter: id, purpose: 'llm', apiHost: `${origin}/${id}/v1`, apiKey: fixtureKey, enabled: true,
+ models: ['mini:latest', 'other'].map(id => ({ id, enabled: true })) }
+ }
+ }
+ let journal, turns
+ function open() {
+ journal = createEventJournal(journalOptions)
+ const observed = { ...journal, publishChat(payload) {
+ sent.push(payload)
+ if (payload.event.type === 'context_changed') onUsageEvent?.(turns, payload)
+ return journal.publishChat(payload)
+ } }
+ turns = createTextTurns({ dataDir, settings, journal: observed, version: 'fixture', allowedOrigins: [origin], resolveRole, uploads, readWatermark })
+ }
+ open()
+ t.after(async () => {
+ await turns.close()
+ journal.close()
+ server.closeAllConnections()
+ await new Promise(resolve => server.close(resolve))
+ await fs.rm(dataDir, { force: true, recursive: true })
+ assert.deepEqual(failures, [])
+ })
+ function send(sid, clientRequestId, model = ref('openai'), extra = {}) {
+ return turns.send({ sid, clientRequestId, model, text: `private prompt ${clientRequestId}`, ...extra })
+ }
+ function waitDone(sid) {
+ const { promise, resolve } = Promise.withResolvers()
+ const published = []
+ const { subscription } = turns.attach(sid, { onEvent(event) {
+ published.push(event)
+ if (event.event.type === 'done') { subscription.close(); resolve(published) }
+ } })
+ assert.equal(subscription.status, 'subscribed')
+ return promise
+ }
+ return { dataDir, chats, sessionPath, disk, sent, upstream, providerReads, modelReads, settings, send, waitDone,
+ get turns() { return turns }, get journal() { return journal },
+ setUsage(value) { input = value }, setDefault(value) { defaultRef = value }, setContextGate(value) { getContextGate = value },
+ setProviderGate(value) { getProviderGate = value }, setReplyGate(value) { nextReplyGate = value },
+ async restart() { await turns.close(); journal.close(); open() }
+ }
+}
+
+for (const adapter of ['openai', 'anthropic', 'responses']) test(`${adapter} reports one scoped normalized live and durable input reading`, timeout, async t => {
+ let live
+ const fx = await fixture(t, { onUsageEvent(turns, payload) { live = turns.contextUsage(payload.sessionId, { model: null }, ok) } })
+ const sid = fx.turns.create().id
+ const other = fx.turns.create().id
+ const before = await fx.turns.contextUsage(sid, { model: null }, ok)
+ assert.deepEqual(before, usage(ref('openai'), 'none', null))
+ assert.deepEqual(fx.providerReads, [])
+ assert.deepEqual(fx.upstream, [])
+ const done = fx.waitDone(sid)
+ const ack = await fx.send(sid, 'measurement', ref(adapter))
+ const events = await done
+ const input = adapter === 'anthropic' ? 127 : 113
+ assert.deepEqual(fx.sent.filter(({ event }) => event.type === 'context_changed'), [{ sessionId: sid, turnId: ack.turnId, event: { type: 'context_changed' } }])
+ assert.deepEqual(events.filter(({ event }) => event.type === 'context_changed').map(({ event }) => event), [{ type: 'context_changed' }])
+ assert.deepEqual(await live, usage(ref(adapter), 'live', input))
+ assert.deepEqual(await fx.turns.contextUsage(sid, { model: ref(adapter) }, ok), usage(ref(adapter), 'measured', input))
+ assert.deepEqual(await fx.turns.contextUsage(other, { model: null }, ok), usage(ref('openai'), 'none', null))
+ assert.deepEqual(await fx.turns.contextUsage(sid, { model: ref(adapter, 'other') }, ok), unavailable)
+ const stored = await fx.disk(sid)
+ assert.equal(stored.lastInputTokens, input)
+ assert.deepEqual(stored[USAGE_META], { version: 1, sessionId: sid, turnId: ack.turnId, adapter,
+ modelRef: ref(adapter), updatedAt: stored.updatedAt, inputTokens: input, digest: stored[USAGE_META].digest })
+ assert.match(stored[USAGE_META].digest, /^[0-9a-f]{64}$/)
+ assert.ok(!JSON.stringify([stored[USAGE_META], events]).includes('private prompt'))
+ assert.ok(!JSON.stringify([stored[USAGE_META], events]).includes(fixtureKey))
+ await fx.restart()
+ assert.deepEqual(await fx.turns.contextUsage(sid, { model: null }, ok), usage(ref(adapter), 'measured', input))
+ assert.equal(fx.upstream.length, 1)
+ assert.deepEqual(fx.providerReads, [adapter])
+})
+
+test('new turns and invalid provider input never pass an earlier receipt as exact', timeout, async t => {
+ const fx = await fixture(t)
+ const sid = fx.turns.create().id
+ let done = fx.waitDone(sid)
+ await fx.send(sid, 'first')
+ await done
+ const previousReading = (await fx.disk(sid))[USAGE_META]
+ for (const [n, invalid] of [undefined, 0, -1, 4.5, Number.MAX_SAFE_INTEGER + 1, '88'].entries()) {
+ fx.setUsage(invalid)
+ done = fx.waitDone(sid)
+ const gate = Promise.withResolvers()
+ if (n === 0) fx.setReplyGate(gate.promise)
+ try {
+ await fx.send(sid, `turn-${n}`)
+ if (n === 0) {
+ const live = await fx.turns.contextUsage(sid, { model: null }, ok)
+ assert.equal(live.source, 'estimate')
+ }
+ } finally { gate.resolve() }
+ await done
+ const d = await fx.disk(sid)
+ assert.equal(d.lastInputTokens, previousReading.inputTokens)
+ assert.deepEqual(d[USAGE_META], previousReading)
+ assert.deepEqual(await fx.turns.contextUsage(sid, { model: null }, ok), usage(ref('openai'), 'estimate', estimateTokens(d.messages)))
+ }
+ assert.equal(fx.sent.filter(({ event }) => event.type === 'context_changed').length, 1)
+ const pref = fx.turns.getPreferences(sid)
+ await fx.turns.patchPreferences(sid, { revision: pref.revision, set: { model: ref('openai', 'other') } }, ok)
+ assert.deepEqual(await fx.turns.contextUsage(sid, { model: ref('openai') }, ok), unavailable)
+ assert.equal((await fx.turns.contextUsage(sid, { model: null }, ok)).source, 'estimate')
+})
+
+test('context resolution observes the owner after asynchronous lookups and uses the trusted pin, role, or default', timeout, async t => {
+ let role = { id: 'reader', enabled: true, name: 'Private role', prompt: 'private role content', model: ref('anthropic') }
+ let roleReadCount = 0
+ const fx = await fixture(t, { resolveRole(id) { assert.equal(id, 'reader'); roleReadCount++; return role } })
+ const sid = fx.turns.create().id
+ const pinned = fx.turns.create({}, role).id
+ const unpinned = fx.turns.create({}, { ...role, model: undefined }).id
+ assert.deepEqual(await fx.turns.contextUsage(pinned, { model: null }, ok), usage(ref('anthropic'), 'none', null))
+ assert.equal(roleReadCount, 0)
+ assert.deepEqual(await fx.turns.contextUsage(unpinned, { model: null }, ok), usage(ref('anthropic'), 'none', null))
+ assert.equal(roleReadCount, 1)
+ role = { ...role, model: ref('anthropic', 'disabled') }
+ assert.deepEqual(await fx.turns.contextUsage(unpinned, { model: null }, ok), unavailable)
+ fx.setDefault(null)
+ assert.deepEqual(await fx.turns.contextUsage(sid, { model: null }, ok), unavailable)
+ fx.setDefault(ref('openai'))
+ assert.deepEqual(await fx.turns.contextUsage(sid, { model: ref('openai', 'other') }, ok), unavailable)
+ let authCalls = 0, current = true
+ const gate = Promise.withResolvers()
+ fx.setContextGate(gate.promise)
+ const pending = fx.turns.contextUsage(sid, { model: null }, observedSid => { assert.equal(observedSid, sid); authCalls++; return current })
+ current = false
+ gate.resolve()
+ await assert.rejects(pending, error(401, 'auth'))
+ assert.ok(authCalls >= 2)
+ await assert.rejects(fx.turns.contextUsage(sid, { model: null }, () => Promise.resolve(true)), error(401, 'auth'))
+ delete fx.settings.getContextModel
+ assert.deepEqual(await fx.turns.contextUsage(sid, { model: null }, ok), unavailable)
+ assert.deepEqual(fx.upstream, [])
+ assert.deepEqual(fx.providerReads, [])
+})
+
+test('read observations name the original journal snapshot and reject busy, seq, generation and file changes', timeout, async t => {
+ const fx = await fixture(t, { journalOptions: { maxChatStreams: 2 } })
+ const { id: sid, updatedAt } = fx.turns.create()
+ const empty = fx.turns.readObservation(sid)
+ assert.deepEqual({ ...empty, verify: undefined }, { id: sid, updatedAt, cursor: fx.turns.snapshot(sid).cursor, eligible: false, verify: undefined })
+ assert.equal(empty.verify(), true)
+ assert.deepEqual(fx.turns.readCandidates(), [])
+ t.mock.method(Date, 'now', () => updatedAt)
+ const wanted = fx.waitDone(sid)
+ const gate = Promise.withResolvers()
+ fx.setProviderGate(gate.promise)
+ const send = fx.send(sid, 'same-clock')
+ try {
+ assert.throws(() => fx.turns.readObservation(sid), error(409, 'read_view_busy'))
+ assert.throws(() => empty.verify(), error(409, 'read_view_busy'))
+ assert.deepEqual(fx.turns.readCandidates(), [])
+ } finally { gate.resolve() }
+ const ack = await send
+ assert.equal(ack.startedAt, updatedAt)
+ const events = await wanted
+ assert.equal(events.at(-1).turnId, ack.turnId)
+ assert.equal(events.at(-1).event.durationMs, 0)
+ const observed = fx.turns.readObservation(sid)
+ assert.equal(observed.updatedAt, updatedAt + 2)
+ assert.equal(observed.eligible, true)
+ assert.deepEqual(observed.cursor, fx.turns.snapshot(sid).cursor)
+ assert.throws(() => empty.verify(), error(409, 'read_view_stale'))
+ assert.deepEqual(fx.turns.readCandidates(), [{ id: sid, updatedAt: updatedAt + 2 }])
+ fx.journal.publishChat({ sessionId: sid, turnId: ack.turnId, event: { type: 'stream_reset' } })
+ assert.throws(() => observed.verify(), error(409, 'read_view_stale'))
+ const sequenced = fx.turns.readObservation(sid)
+ fx.journal.snapshot(chatScope('other-a'))
+ fx.journal.snapshot(chatScope('other-b'))
+ assert.throws(() => sequenced.verify(), error(409, 'read_view_stale'))
+ const named = fx.turns.readObservation(sid)
+ await fs.writeFile(`${fx.sessionPath(sid)}.swap`, await fs.readFile(fx.sessionPath(sid)), { mode: 0o600 })
+ assert.equal(`${fx.sessionPath(sid)}.swap`, join(fx.chats, `${sid}.json.swap`))
+ await fs.rename(`${fx.sessionPath(sid)}.swap`, fx.sessionPath(sid))
+ assert.throws(() => named.verify(), error(409, 'read_view_stale'))
+ assert.equal(fx.turns.readObservation(sid).verify(), true)
+ const changed = await fx.disk(sid)
+ changed.messages[0].content[0].text = 'changed without updatedAt'
+ await fs.writeFile(fx.sessionPath(sid), JSON.stringify(changed))
+ assert.throws(() => fx.turns.readObservation(sid), error(409, 'read_unavailable'))
+ assert.deepEqual(fx.turns.readCandidates(), [])
+})
+
+test('legacy information is read only; hidden, compacted, missing, and unowned layouts fail closed', timeout, async t => {
+ const fx = await fixture(t)
+ const desktop = createChatStore({ dataDir: fx.dataDir })
+ const ordinary = desktop.ensureSession('sess_ordinary_1')
+ ordinary.messages.push({ role: 'user', content: '可见的历史' }, { role: 'assistant', content: [textPart('visible reply')] })
+ ordinary.lastInputTokens = 999
+ desktop.saveStrict(ordinary.id)
+ const compacted = desktop.ensureSession('sess_compact_1')
+ compacted.messages.push({ role: 'user', content: 'Hidden prefix' }, { role: 'user', content: '⟦deva:compaction⟧ summary' })
+ desktop.saveStrict(compacted.id)
+ assert.ok((await fx.disk(compacted.id)).compacted)
+ const tool = desktop.ensureSession('sess_tool_1')
+ tool.messages.push({ role: 'assistant', content: [{ type: 'tool_use', id: 'call', name: 'tool', input: {} }] })
+ desktop.saveStrict(tool.id)
+ const orphan = join(fx.chats, `${ordinary.id}.compacted-orphan.jsonl`)
+ await fs.writeFile(orphan, 'preserve orphan', { mode: 0o600 })
+ const outsider = join(fx.dataDir, 'outside.json')
+ await fs.writeFile(outsider, JSON.stringify({ ...ordinary, id: 'naked' }), { mode: 0o600 })
+ await fs.symlink(outsider, fx.sessionPath('naked'))
+ const before = await fs.readdir(fx.chats)
+ assert.deepEqual(await fx.turns.contextUsage(ordinary.id, { model: null }, ok), usage(ref('openai'), 'estimate', estimateTokens(ordinary.messages)))
+ assert.equal(fx.turns.readObservation(ordinary.id).eligible, true)
+ assert.deepEqual(fx.turns.readCandidates(), [{ id: ordinary.id, updatedAt: ordinary.updatedAt }])
+ for (const [id, status, code] of [[compacted.id, 409, 'unsupported_history'], [tool.id, 409, 'unsupported_history'],
+ ['naked', 409, 'read_unavailable'], ['missing', 404, 'session_not_found']]) {
+ await assert.rejects(fx.turns.contextUsage(id, { model: null }, ok), error(status, code))
+ assert.throws(() => fx.turns.readObservation(id), error(status, code))
+ }
+ assert.deepEqual(await fs.readdir(fx.chats), before)
+ assert.equal(await fs.readFile(orphan, 'utf8'), 'preserve orphan')
+ assert.equal((await fx.disk(ordinary.id)).lastInputTokens, 999)
+ await fx.turns.close()
+ await assert.rejects(fx.turns.contextUsage(ordinary.id, { model: null }, ok), error(503, 'chat_closed'))
+ assert.throws(() => fx.turns.readObservation(ordinary.id), error(503, 'chat_closed'))
+ assert.deepEqual(fx.turns.readCandidates(), [])
+})
+
+test('metadata never confuses IDs or credits a changed transcript, even after restart', timeout, async t => {
+ const fx = await fixture(t)
+ const sid = fx.turns.create().id
+ const other = fx.turns.create().id
+ const done = fx.waitDone(sid)
+ await fx.send(sid, 'usage-correspondence')
+ await done
+ const source = await fx.disk(sid)
+ const changed = structuredClone(source)
+ changed.messages.at(-1).content[0].text = 'Modified reply with the same timestamp'
+ await fs.writeFile(fx.sessionPath(sid), JSON.stringify(changed))
+ await fs.writeFile(fx.sessionPath(other), JSON.stringify({ ...source, id: other }))
+ await fx.restart()
+ assert.deepEqual(await fx.turns.contextUsage(sid, { model: null }, ok), usage(ref('openai'), 'estimate', estimateTokens(changed.messages)))
+ assert.deepEqual(await fx.turns.contextUsage(other, { model: null }, ok), usage(ref('openai'), 'estimate', estimateTokens(source.messages)))
+})
+
+test('normalized input never becomes durable on a failed pre-publication save', timeout, async t => {
+ const fx = await fixture(t)
+ const sid = fx.turns.create().id
+ const gate = Promise.withResolvers()
+ fx.setReplyGate(gate.promise)
+ const done = fx.waitDone(sid)
+ await fx.send(sid, 'failed-save')
+ try { await fs.mkdir(join(fx.chats, '_index.pending')) }
+ finally { gate.resolve() }
+ assert.equal((await done).at(-1).event.stopReason, 'error')
+ assert.equal((await fx.disk(sid)).lastInputTokens, undefined)
+ assert.equal((await fx.disk(sid))[USAGE_META], undefined)
+ await assert.rejects(fx.turns.contextUsage(sid, { model: null }, ok), error(409, 'read_unavailable'))
+ assert.throws(() => fx.turns.readObservation(sid), error(409, 'read_unavailable'))
+ assert.deepEqual(fx.turns.readCandidates(), [])
+})
+
+test('attachment estimates use shared part costs and text byte counts without opening media', timeout, async t => {
+ const items = [
+ { name: 'notes.txt', mime: 'text/plain', kind: 'text', bytes: Buffer.from('a'.repeat(14_000)) },
+ { name: 'chart.png', mime: 'image/png', kind: 'image', bytes: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAEklEQVQImWNYZ/B3ncFfBggFADLGB23aTHV6AAAAAElFTkSuQmCC', 'base64') }
+ ].map(({ bytes, ...entry }) => ({ bytes, meta: { ...entry, id: randomUUID(), size: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') } }))
+ const fx = await fixture(t, { uploads: { read(_sid, id) { return items.find(x => x.meta.id === id) } } })
+ fx.setUsage(undefined)
+ const sid = fx.turns.create().id
+ const done = fx.waitDone(sid)
+ await fx.send(sid, 'multimodal-reading', ref('openai'), { attachments: items.map(x => x.meta.id) })
+ await done
+ const stored = await fx.disk(sid)
+ const parts = items.map(({ bytes, meta: { name, mime, size } }) => buildUploadedPart({ name, mime, size }, bytes, 'openai').part)
+ const expected = estimateTokens([{ role: 'user', content: [...parts, stored.messages[0].content.at(-1)] }, stored.messages[1]])
+ const media = join(fx.dataDir, 'data', 'media')
+ await fs.rename(media, `${media}-saved`)
+ assert.deepEqual(await fx.turns.contextUsage(sid, { model: null }, ok), usage(ref('openai'), 'estimate', expected))
+ assert.equal(fx.turns.snapshot(sid).state.messages, null)
+ assert.throws(() => fx.turns.readObservation(sid), error(409, 'unsupported_history'))
+ assert.deepEqual(fx.turns.readCandidates(), [])
+})
+
+test('a missing directory is empty but unsafe roots and scan overflow explicitly fail', timeout, async t => {
+ const fx = await fixture(t)
+ assert.deepEqual(fx.turns.readCandidates(), [])
+ fx.turns.create()
+ fx.turns.create()
+ assert.throws(() => withConversationFiles(fx.dataDir, files => [...files.scan(1)]), error(413, 'read_state_limit'))
+ await fs.chmod(fx.chats, 0o777)
+ assert.throws(() => fx.turns.readCandidates(), error(409, 'read_unavailable'))
+})
+
+test('legacy future read timestamps cannot swallow new content or replace real receipt time', timeout, async t => {
+ let sid, watermark
+ const fx = await fixture(t, { readWatermark(id) { assert.equal(id, sid); return watermark } })
+ const created = fx.turns.create()
+ sid = created.id
+ const wall = created.updatedAt
+ t.mock.method(Date, 'now', () => wall)
+ watermark = wall + 10_000
+ let done = fx.waitDone(sid)
+ const gate = Promise.withResolvers()
+ fx.setReplyGate(gate.promise)
+ try {
+ const ack = await fx.send(sid, 'watermark')
+ assert.equal(ack.startedAt, wall)
+ assert.equal((await fx.disk(sid)).updatedAt, watermark + 1)
+ } finally { gate.resolve() }
+ await done
+ assert.equal(fx.turns.readObservation(sid).updatedAt, watermark + 2)
+ watermark = Number.MAX_SAFE_INTEGER
+ done = fx.waitDone(sid)
+ assert.equal((await fx.send(sid, 'impossible-legacy-mark')).startedAt, wall)
+ await done
+ assert.equal(fx.turns.readObservation(sid).updatedAt, wall + 10_004)
+})
diff --git a/apps/headless/test/conversation-status-fixture.mjs b/apps/headless/test/conversation-status-fixture.mjs
new file mode 100644
index 00000000..82cec82d
--- /dev/null
+++ b/apps/headless/test/conversation-status-fixture.mjs
@@ -0,0 +1,262 @@
+import assert from 'node:assert/strict'
+import { randomBytes } from 'node:crypto'
+import { once } from 'node:events'
+import { mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises'
+import { createServer, get as httpGet } from 'node:http'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { setTimeout as delay } from 'node:timers/promises'
+import { requestControl } from '../src/control/socket.mjs'
+import { startWorkbench } from '../src/server.mjs'
+import { initializeMasterKey } from '../src/storage/vault.mjs'
+
+export const bounds = { timeout: 20_000 }
+export const networkTimeout = () => AbortSignal.timeout(4_000)
+export const reads = 'conversation-status/reads'
+export const chat = sid => `chats/${sid}`
+export const read = sid => `${chat(sid)}/read-state`
+export const usage = sid => `${chat(sid)}/context-usage`
+export const observed = ({ state, cursor }) => ({ updatedAt: state.updatedAt, cursor })
+export const reply = 'Private synthetic provider answer.'
+export const question = 'Private synthetic conversation text.'
+export const rolePrompt = 'Private synthetic role instruction.'
+const fixtureKey = 'local-fixture-key-only'
+export const fixtures = {
+ openai: { model: 'fixture-chat', path: '/chat/v1/chat/completions', host: '/chat/v1', used: 1234, window: 12000 },
+ anthropic: { model: 'fixture-claude', path: '/anthropic/v1/messages', host: '/anthropic', used: 1550, window: 14000 },
+ responses: { model: 'fixture-responses', path: '/responses/v1/responses', host: '/responses/v1', used: 1666, window: 16000 }
+}
+export const modelRef = adapter => `qa-${adapter}:${fixtures[adapter].model}`
+const disabled = { id: 'disabled', name: 'Disabled fixture', enabled: false, contextWindow: 18000 }
+export const disabledRef = 'qa-openai:disabled'
+
+const sse = data => `data: ${typeof data === 'string' ? data : JSON.stringify(data)}\n\n`
+
+function wire(adapter, mode) {
+ const { used } = fixtures[adapter]
+ if (adapter === 'anthropic') return [
+ [
+ { type: 'message_start', message: { id: 'msg_fixture', type: 'message', role: 'assistant', content: [],
+ usage: { input_tokens: 1100, cache_creation_input_tokens: 150, cache_read_input_tokens: 300, output_tokens: 1 } } },
+ { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } },
+ { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: reply } }
+ ], [
+ { type: 'content_block_stop', index: 0 },
+ { type: 'message_delta', delta: { stop_reason: 'end_turn' }, usage: { output_tokens: 7 } },
+ { type: 'message_stop' }
+ ]
+ ]
+ if (adapter === 'responses') return [
+ [{ type: 'response.output_text.delta', delta: reply }],
+ [{ type: 'response.completed', response: { id: 'resp_fixture', status: 'completed',
+ usage: { input_tokens: used, output_tokens: 7, input_tokens_details: { cached_tokens: 400 } } } }]
+ ]
+ return [
+ [{ choices: [{ index: 0, delta: { content: reply }, finish_reason: null }] }],
+ [
+ { choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] },
+ ...(mode === 'missing' ? [] : [{ choices: [], usage: {
+ prompt_tokens: mode === 'invalid' ? -123 : used, completion_tokens: 7, prompt_tokens_details: { cached_tokens: 300 }
+ } }]), '[DONE]'
+ ]
+ ]
+}
+
+function providerConfigs(origin) {
+ return Object.entries(fixtures).map(([adapter, { model, host, window }]) => ({
+ id: `qa-${adapter}`, name: `Local ${adapter} fixture`, kind: 'custom', purpose: 'llm', accent: '#234567',
+ adapter, apiHost: `${origin}${host}`, enabled: true,
+ models: [{ id: model, name: model, enabled: true, contextWindow: window }, ...(adapter === 'openai' ? [disabled] : [])]
+ }))
+}
+
+function loopbackModel() {
+ const calls = [], failures = []
+ let nextMode = 'measured', finish
+ const server = createServer((req, res) => {
+ void (async () => {
+ const chunks = []; for await (const chunk of req) chunks.push(chunk)
+ const body = JSON.parse(Buffer.concat(chunks))
+ calls.push({ path: req.url, body })
+ const adapter = Object.keys(fixtures).find(name => fixtures[name].path === req.url)
+ assert.ok(adapter, `unexpected fixture path: ${req.url}`)
+ assert.equal(req.method, 'POST')
+ assert.equal(body.model, fixtures[adapter].model)
+ assert.equal(body.stream, true)
+ assert.equal(body.tools?.length ?? 0, 0)
+ assert.equal(req.headers.cookie, undefined)
+ if (adapter === 'anthropic') assert.equal(req.headers['x-api-key'], fixtureKey)
+ else assert.equal(req.headers.authorization, `Bearer ${fixtureKey}`)
+ const mode = nextMode
+ nextMode = 'measured'
+ const [start, end] = wire(adapter, mode)
+ res.writeHead(200, { 'content-type': 'text/event-stream' })
+ res.write(start.map(sse).join(''))
+ if (mode === 'hold') {
+ const hold = Promise.withResolvers()
+ finish = hold.resolve
+ res.once('close', hold.resolve)
+ await hold.promise
+ finish = undefined
+ }
+ if (!res.destroyed) res.end(end.map(sse).join(''))
+ })().catch(error => { failures.push(error); res.destroy() })
+ })
+ return {
+ calls, failures,
+ async listen() {
+ server.listen(0, '127.0.0.1')
+ await once(server, 'listening', { signal: networkTimeout() })
+ return `http://127.0.0.1:${server.address().port}`
+ },
+ async close() {
+ finish?.()
+ if (server.listening) {
+ server.closeAllConnections()
+ await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve()))
+ }
+ },
+ mode(mode) { nextMode = mode },
+ release() { assert.ok(finish, 'fixture is holding a stream'); finish() }
+ }
+}
+
+// The session-list stream sends unmasked, single-frame text messages. Use a real upgrade with
+// owner credentials without requiring package-mounted tests to import a WebSocket client library.
+async function openListPeer(origin, cookie, peers) {
+ const req = httpGet(`${origin}/api/v1/chats/stream`, { signal: networkTimeout(), headers: {
+ origin, cookie, connection: 'Upgrade', upgrade: 'websocket', 'sec-websocket-version': '13',
+ 'sec-websocket-key': randomBytes(16).toString('base64')
+ } })
+ req.once('response', response => { response.resume(); req.destroy(Error(`list upgrade: ${response.statusCode}`)) })
+ const [response, socket, head] = await once(req, 'upgrade', { signal: networkTimeout() })
+ peers.add(socket)
+ socket.once('close', () => peers.delete(socket))
+ socket.setTimeout(4_000, () => socket.destroy())
+ assert.equal(response.statusCode, 101)
+ const input = socket.iterator({ destroyOnReturn: false })
+ let buffer = head
+ async function fill(size) {
+ while (buffer.length < size) {
+ const { value, done } = await input.next()
+ assert.equal(done, false, 'session-list stream closed before the expected frame')
+ buffer = Buffer.concat([buffer, value])
+ }
+ }
+ return {
+ close: () => socket.destroy(),
+ async next() {
+ await fill(2)
+ assert.equal(buffer[0], 0x81, 'expected a single text frame')
+ assert.equal(buffer[1] & 0x80, 0, 'server frames must be unmasked')
+ let len = buffer[1], offset = 2
+ if (len === 126) { offset = 4; await fill(offset); len = buffer.readUInt16BE(2) }
+ assert.ok(len < 1024, 'only small session-list invalidations are expected')
+ await fill(offset + len)
+ const frame = JSON.parse(buffer.subarray(offset, offset + len).toString('utf8'))
+ buffer = buffer.subarray(offset + len)
+ return frame
+ }
+ }
+}
+
+export async function workbench(t, { seed } = {}) {
+ const root = await mkdtemp(join(await realpath(tmpdir()), 'deva-conversation-status-'))
+ const opts = { dataDir: join(root, 'home'), runDir: join(root, 'run'), keyFile: join(root, 'master.key'),
+ webDir: join(root, 'web'), port: 0 }
+ const chatsDir = join(opts.dataDir, 'data', 'chats')
+ const readFilePath = join(opts.dataDir, 'read-state.json')
+ const configPath = join(opts.dataDir, 'config.json')
+ const sessionFile = sid => join(chatsDir, `${sid}.json`)
+ const password = randomBytes(24).toString('base64url'), upstream = loopbackModel(), peers = new Set()
+ let app
+ const closeApp = async () => {
+ for (const peer of peers) peer.destroy()
+ await app?.close()
+ }
+ t.after(async () => {
+ try { await closeApp() }
+ finally {
+ await upstream.close()
+ await rm(root, { recursive: true, force: true })
+ }
+ assert.deepEqual(upstream.failures, [])
+ })
+ const providerOrigin = await upstream.listen()
+ opts.businessOptions = { allowedOrigins: [providerOrigin] }
+ await mkdir(chatsDir, { recursive: true, mode: 0o700 })
+ await seed?.({ readFilePath, configPath, sessionFile })
+ await initializeMasterKey(opts.keyFile)
+ app = await startWorkbench(opts)
+
+ function raw(path, { method = 'GET', body, headers = {} } = {}, login) {
+ const fields = { ...(method === 'GET' || method === 'HEAD' ? {} : { origin: app.origin, 'content-type': 'application/json' }),
+ ...(login ? { cookie: login.cookie, 'x-deva-csrf': login.csrf } : {}), ...headers }
+ for (const key of Object.keys(fields)) if (fields[key] == null) delete fields[key]
+ return fetch(`${app.origin}/api/v1/${path}`, { method, headers: fields, signal: networkTimeout(),
+ ...(body === undefined ? {} : { body: typeof body === 'string' ? body : JSON.stringify(body) }) })
+ }
+ function client(cookie, csrf) {
+ const login = { cookie, csrf }
+ return {
+ ...login,
+ raw: (path, options) => raw(path, options, login),
+ async request(path, { status = 200, ...options } = {}) {
+ const res = await raw(path, options, login)
+ const data = await res.json()
+ assert.equal(res.status, status, `${options.method ?? 'GET'} ${path}: ${JSON.stringify(data)}`)
+ return data
+ },
+ listPeer: () => openListPeer(app.origin, cookie, peers)
+ }
+ }
+ async function login(path = 'auth/login', body = { password }) {
+ const res = await raw(path, { method: 'POST', body })
+ const data = await res.json()
+ assert.equal(res.status, 200, JSON.stringify(data))
+ return client(res.headers.get('set-cookie').split(';', 1)[0], data.csrf)
+ }
+ const { credential } = await requestControl({ runDir: opts.runDir, op: 'claim' })
+ const owner = await login('auth/claim', { credential, password })
+ const providers = providerConfigs(providerOrigin)
+ const { revision } = await owner.request('settings')
+ let saved = await owner.request('settings', { method: 'PATCH', body: {
+ revision, set: { models: { providers, activeModelId: modelRef('openai'), activeEffort: 'default' } }
+ } })
+ for (const { id } of providers) saved = await owner.request(`provider-keys/${id}`, {
+ method: 'PUT', body: { value: fixtureKey, revision: saved.revision }
+ })
+ async function untilSnapshot(sid, predicate, browser = owner) {
+ for (let i = 0; i < 100; ++i) {
+ const snap = await browser.request(chat(sid))
+ if (predicate(snap.state)) return snap
+ await delay(10)
+ }
+ assert.fail(`chat ${sid} did not reach the requested stream state`)
+ }
+ async function complete(sid, turnId, browser = owner) {
+ const snap = await untilSnapshot(sid, state => !state.active && state.lastTurn?.turnId === turnId, browser)
+ assert.equal(snap.state.lastTurn.status, 'completed')
+ return snap
+ }
+ return {
+ owner, login, raw, upstream, providers, providerOrigin, configPath, readFilePath, sessionFile, untilSnapshot, complete,
+ get origin() { return app.origin },
+ async restart(beforeOpen) { await closeApp(); await beforeOpen?.(); app = await startWorkbench(opts) },
+ async create(sid, fields = {}) { return (await owner.request('chats', { method: 'POST', body: { sessionId: sid, ...fields } })).session },
+ async send(sid, clientRequestId, model = null, text = question) {
+ const ack = await owner.request(`${chat(sid)}/turns`, { method: 'POST', body: { clientRequestId, text, model }, status: 202 })
+ assert.equal(ack.duplicate, false)
+ return ack
+ },
+ async native(sid) { return JSON.parse(await readFile(sessionFile(sid), 'utf8')) },
+ async nativeReads() { return JSON.parse(await readFile(readFilePath, 'utf8')) }
+ }
+}
+
+export const writeJson = (path, data) => writeFile(path, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 })
+export const post = (body, status = 200, headers) => ({ method: 'POST', body, status, headers })
+export function assertPrivate(value, secrets) {
+ const json = JSON.stringify(value)
+ for (const secret of [fixtureKey, question, reply, rolePrompt, ...secrets]) assert.equal(json.includes(secret), false, `unexpected private fixture marker: ${secret}`)
+}
diff --git a/apps/headless/test/conversation-status-http-meter.test.mjs b/apps/headless/test/conversation-status-http-meter.test.mjs
new file mode 100644
index 00000000..350365ec
--- /dev/null
+++ b/apps/headless/test/conversation-status-http-meter.test.mjs
@@ -0,0 +1,155 @@
+import assert from 'node:assert/strict'
+import { randomUUID } from 'node:crypto'
+import { readFile, stat } from 'node:fs/promises'
+import test from 'node:test'
+import {
+ assertPrivate, bounds, chat, disabledRef, fixtures, modelRef, post, question, reads, reply,
+ rolePrompt, usage, workbench
+} from './conversation-status-fixture.mjs'
+
+const unavailable = { modelRef: null, usage: null, source: 'unavailable', compaction: 'inactive' }
+const meter = (adapter, source, used) => ({ modelRef: modelRef(adapter),
+ usage: { used, estimated: source === 'estimate', window: fixtures[adapter].window, trigger: null }, source, compaction: 'inactive' })
+const meterFor = (browser, sid, model = null) => browser.request(usage(sid), post({ model }))
+
+function estimate(adapter, value) {
+ assert.ok(Number.isSafeInteger(value.usage?.used) && value.usage.used > 0)
+ assert.deepEqual(value, meter(adapter, 'estimate', value.usage.used))
+ assert.notEqual(value.usage.used, fixtures[adapter].used)
+ return value.usage.used
+}
+
+async function pin(owner, sid, model) {
+ const path = `${chat(sid)}/preferences`
+ const { revision } = await owner.request(path)
+ return owner.request(path, { method: 'PATCH', body: { revision, set: { model } } })
+}
+
+async function models(owner, set) {
+ const { revision } = await owner.request('settings')
+ return owner.request('settings', { method: 'PATCH', body: { revision, set: { models: set } } })
+}
+
+test('authenticated meter follows real OpenAI Chat, Anthropic and Responses usage without upstream status requests', bounds, async t => {
+ const fx = await workbench(t)
+ const { owner, upstream } = fx
+ const roleName = 'Private synthetic fixture role'
+ const { role } = await owner.request('personas', post({ name: roleName, prompt: rolePrompt, enabled: true, model: modelRef('anthropic') }))
+ const sid = Object.fromEntries(Object.keys(fixtures).map(adapter => [adapter, randomUUID()]))
+ await fx.create(sid.openai)
+ await fx.create(sid.anthropic, { personaId: role.id })
+ await pin(owner, sid.anthropic, null) // Follow the role default rather than keeping its initial pin.
+ await fx.create(sid.responses)
+ await pin(owner, sid.responses, modelRef('responses'))
+
+ for (const adapter of Object.keys(fixtures)) {
+ assert.deepEqual(await meterFor(owner, sid[adapter]), meter(adapter, 'none', null))
+ assert.deepEqual(await meterFor(owner, sid[adapter], modelRef(adapter)), meter(adapter, 'none', null))
+ }
+ assert.deepEqual(await meterFor(owner, sid.openai, disabledRef), unavailable)
+ assert.deepEqual(await meterFor(owner, sid.openai, 'qa-openai:removed-fixture-model'), unavailable)
+ assert.deepEqual(await meterFor(owner, sid.openai, modelRef('responses')), unavailable)
+ assert.deepEqual(await owner.request(reads), { entries: [] })
+ assert.equal(upstream.calls.length, 0)
+
+ for (const [adapter, { used, path }] of Object.entries(fixtures)) {
+ const id = sid[adapter]
+ const { turnId } = await fx.send(id, `measured-${adapter}`, adapter === 'responses' ? modelRef(adapter) : null)
+ const finished = await fx.complete(id, turnId)
+ assert.deepEqual(finished.state.messages.map(message => message.content), [question, reply])
+ const native = await fx.native(id)
+ assert.equal(native.lastInputTokens, used, `normalized ${adapter} input persists in the native field`)
+ assert.equal(native._devaHeadlessTextTurns.requests.at(-1).turnId, turnId)
+ assert.equal(upstream.calls.at(-1).path, path)
+ const chatBytes = await readFile(fx.sessionFile(id), 'utf8')
+ const count = upstream.calls.length
+ const measured = await meterFor(owner, id, modelRef(adapter))
+ assert.deepEqual(measured, meter(adapter, 'measured', used))
+ assert.deepEqual(await meterFor(owner, id), measured)
+ assertPrivate(measured, [fx.configPath, fx.sessionFile(id), fx.providerOrigin, roleName])
+ assert.deepEqual(await owner.request(chat(id)), finished)
+ assert.equal(await readFile(fx.sessionFile(id), 'utf8'), chatBytes, 'metering does not persist or edit history')
+ assert.equal(upstream.calls.length, count)
+ }
+ assert.deepEqual(upstream.calls.map(call => call.path), Object.values(fixtures).map(adapter => adapter.path))
+ const roleCall = upstream.calls.find(call => call.path === fixtures.anthropic.path)
+ assert.ok(JSON.stringify(roleCall.body.messages).includes(rolePrompt), 'the trusted role actually participates in the ordinary Send')
+ assertPrivate(await owner.request(reads), [fx.configPath, fx.providerOrigin, roleName, role.id])
+ assert.equal(upstream.calls.length, 3)
+
+ await models(owner, { activeModelId: modelRef('responses') })
+ estimate('responses', await meterFor(owner, sid.openai))
+ assert.deepEqual(await meterFor(owner, sid.openai, modelRef('openai')), unavailable)
+ assert.equal((await fx.native(sid.openai)).lastInputTokens, fixtures.openai.used,
+ 'a stored measurement for the old model is untouched but unavailable for the newly effective model')
+ await models(owner, { activeModelId: modelRef('openai') })
+ assert.deepEqual(await meterFor(owner, sid.openai), meter('openai', 'measured', fixtures.openai.used))
+ assert.equal(upstream.calls.length, 3)
+
+ // Same chat and same model: an in-progress turn and then a new turn lacking usage must not
+ // report the prior valid measured receipt. A second measured Send then challenges invalid data.
+ upstream.mode('hold')
+ const running = await fx.send(sid.openai, 'running')
+ await fx.untilSnapshot(sid.openai, state => state.active?.text === reply)
+ estimate('openai', await meterFor(owner, sid.openai))
+ assert.equal(upstream.calls.length, 4)
+ upstream.release()
+ await fx.complete(sid.openai, running.turnId)
+ assert.deepEqual(await meterFor(owner, sid.openai), meter('openai', 'measured', fixtures.openai.used))
+
+ const estimates = []
+ for (const mode of ['missing', 'invalid']) {
+ if (mode === 'invalid') {
+ await fx.complete(sid.openai, (await fx.send(sid.openai, 'remeasure')).turnId)
+ assert.deepEqual(await meterFor(owner, sid.openai), meter('openai', 'measured', fixtures.openai.used))
+ }
+ upstream.mode(mode)
+ const text = `Synthetic ${mode} token receipt. `.repeat(40)
+ const { turnId } = await fx.send(sid.openai, mode, null, text)
+ const finished = await fx.complete(sid.openai, turnId)
+ assert.equal(finished.state.messages.at(-2).content, text)
+ const native = await fx.native(sid.openai)
+ assert.equal(native._devaHeadlessTextTurns.requests.at(-1).turnId, turnId)
+ assert.ok(native.lastInputTokens === undefined || native.lastInputTokens === fixtures.openai.used,
+ 'invalid or absent usage must not replace the prior native measurement with a new number')
+ const count = upstream.calls.length
+ estimates.push(estimate('openai', await meterFor(owner, sid.openai)))
+ assert.equal(upstream.calls.length, count)
+ }
+ assert.ok(estimates[1] > estimates[0], 'fallback includes current, growing conversation history')
+ assert.equal(upstream.calls.length, 7)
+
+ // A global model update affects only followers of that default. A different requested
+ // model never gets a measured result from the history's old match or a misleading estimate.
+ await models(owner, { activeModelId: modelRef('responses') })
+ estimate('responses', await meterFor(owner, sid.openai))
+ assert.deepEqual(await meterFor(owner, sid.openai, modelRef('openai')), unavailable)
+ assert.deepEqual(await meterFor(owner, sid.anthropic), meter('anthropic', 'measured', fixtures.anthropic.used))
+ assert.deepEqual(await meterFor(owner, sid.responses), meter('responses', 'measured', fixtures.responses.used))
+ await pin(owner, sid.openai, modelRef('anthropic'))
+ estimate('anthropic', await meterFor(owner, sid.openai))
+ assert.deepEqual(await meterFor(owner, sid.openai, modelRef('responses')), unavailable)
+
+ // Both requested and server-selected unavailable paths, including a disabled actual pin
+ // and a role default whose formerly measured provider was removed.
+ const altered = fx.providers.filter(provider => provider.id !== 'qa-anthropic').map(provider => provider.id === 'qa-responses'
+ ? { ...provider, models: provider.models.map(model => ({ ...model, enabled: false })) } : provider)
+ await models(owner, { providers: altered, activeModelId: modelRef('openai') })
+ assert.deepEqual(await meterFor(owner, sid.openai), unavailable)
+ assert.deepEqual(await meterFor(owner, sid.anthropic, modelRef('anthropic')), unavailable)
+ assert.deepEqual(await meterFor(owner, sid.responses), unavailable)
+ assert.deepEqual(await meterFor(owner, sid.responses, modelRef('responses')), unavailable)
+ await models(owner, { providers: fx.providers, activeModelId: modelRef('openai') })
+ const stable = await meterFor(owner, sid.responses)
+ assert.deepEqual(stable, meter('responses', 'measured', fixtures.responses.used))
+ assert.equal(upstream.calls.length, 7)
+
+ await fx.restart()
+ assert.deepEqual(await owner.request(usage(sid.responses), post({ model: null }, 401)), { error: 'auth' })
+ const fresh = await fx.login()
+ assert.deepEqual(await meterFor(fresh, sid.responses), stable)
+ assert.deepEqual(await meterFor(fresh, sid.anthropic), meter('anthropic', 'measured', fixtures.anthropic.used))
+ estimate('anthropic', await meterFor(fresh, sid.openai))
+ await assert.rejects(stat(fx.readFilePath), { code: 'ENOENT' })
+ assert.equal(upstream.calls.length, 7)
+})
diff --git a/apps/headless/test/conversation-status-http.test.mjs b/apps/headless/test/conversation-status-http.test.mjs
new file mode 100644
index 00000000..075b0a93
--- /dev/null
+++ b/apps/headless/test/conversation-status-http.test.mjs
@@ -0,0 +1,289 @@
+import assert from 'node:assert/strict'
+import { randomUUID } from 'node:crypto'
+import { readFile, stat, writeFile } from 'node:fs/promises'
+import { IncomingMessage, request as httpRequest } from 'node:http'
+import test from 'node:test'
+import {
+ assertPrivate, bounds, chat, modelRef, networkTimeout, observed, post, question, read, reads,
+ reply, usage, workbench, writeJson
+} from './conversation-status-fixture.mjs'
+
+const fileVersion = async path => {
+ const { ino, mtimeNs, ctimeNs } = await stat(path, { bigint: true })
+ return { ino, mtimeNs, ctimeNs, content: await readFile(path, 'utf8') }
+}
+const entry = (snap, readAt = null) => ({ id: snap.state.id, updatedAt: snap.state.updatedAt,
+ readAt, unread: readAt === null || readAt < snap.state.updatedAt })
+const marked = (snap, changed = true) => ({ ...entry(snap, snap.state.updatedAt), changed })
+const methodError = { error: 'method' }
+const authError = { error: 'auth' }
+const originError = { error: 'origin' }
+const stale = { error: 'read_view_stale' }
+const busy = { error: 'read_view_busy' }
+
+async function listWatermark(client) {
+ const peer = await client.listPeer()
+ try {
+ const snap = await peer.next()
+ assert.deepEqual(Object.keys(snap).sort(), ['cursor', 't'])
+ assert.equal(snap.t, 'sessions-snapshot')
+ assert.equal(snap.cursor.scope, 'sessions')
+ return snap.cursor
+ } finally { peer.close() }
+}
+
+test('two owner logins mark only a confirmed observed read view, with quiet no-ops and a durable native map', bounds, async t => {
+ const [sid, emptySid, orphanId, configId] = Array.from({ length: 4 }, randomUUID)
+ const nativeSeed = { [orphanId]: 37, sess_external_keep: 13 }
+ const fx = await workbench(t, { async seed(paths) {
+ await writeJson(paths.readFilePath, nativeSeed)
+ await writeJson(paths.configPath, { privateFixtureSection: { [configId]: 'private config payload' } })
+ } })
+ const { owner, upstream } = fx
+ const tab = await fx.login()
+ assert.notEqual(tab.cookie, owner.cookie)
+ assert.notEqual(tab.csrf, owner.csrf)
+ await fx.create(sid)
+ await fx.create(emptySid)
+ assert.deepEqual(await tab.request(reads), { entries: [] })
+ const empty = await owner.request(chat(emptySid))
+ const initialVersion = await fileVersion(fx.readFilePath)
+ const beforeEmpty = await listWatermark(tab)
+ assert.deepEqual(await tab.request(read(emptySid), post(observed(empty))), {
+ id: emptySid, updatedAt: empty.state.updatedAt, readAt: null, unread: false, changed: false
+ })
+ assert.deepEqual(await listWatermark(tab), beforeEmpty)
+ assert.deepEqual(await fileVersion(fx.readFilePath), initialVersion)
+ assert.equal(upstream.calls.length, 0)
+
+ const first = await fx.complete(sid, (await fx.send(sid, 'initial', modelRef('openai'))).turnId)
+ assert.deepEqual(first.state.messages.map(message => message.content), [question, reply])
+ const listing = await owner.request(reads)
+ assert.deepEqual(listing, { entries: [entry(first)] })
+ assert.deepEqual(await tab.request(reads), listing)
+ assertPrivate(listing, [orphanId, configId, fx.configPath, fx.providerOrigin, 'private config payload'])
+ assert.deepEqual(await tab.request(read(sid), post(observed(first), 401, { 'x-deva-csrf': owner.csrf })), authError)
+ assert.deepEqual(await owner.request(read(sid), post({ ...observed(first), cursor: empty.cursor }, 400)), { error: 'invalid_read_view' })
+ assert.deepEqual(await owner.request(read(sid), post({ ...observed(first), updatedAt: first.state.updatedAt + 1 }, 409)), stale)
+ assert.deepEqual(await fileVersion(fx.readFilePath), initialVersion)
+
+ const peer = await owner.listPeer()
+ try {
+ const initial = await peer.next()
+ assert.equal(initial.t, 'sessions-snapshot')
+ // The tab did not obtain this snapshot with its own cookie. Its independently owned login and CSRF suffice.
+ assert.deepEqual(await tab.request(read(sid), post(observed(first))), marked(first))
+ const broadcast = await peer.next()
+ assert.deepEqual(broadcast, { t: 'sessions-changed', cursor: { ...initial.cursor, seq: initial.cursor.seq + 1 } })
+ assertPrivate(broadcast, [sid, emptySid, orphanId, configId, fx.providerOrigin])
+ assert.deepEqual(await owner.request(chat(sid)), first, 'a list mark is not a conversation event or content update')
+ assert.deepEqual(await fx.nativeReads(), { ...nativeSeed, [sid]: first.state.updatedAt })
+ assert.deepEqual(await owner.request(reads), { entries: [entry(first, first.state.updatedAt)] })
+ const afterMark = await fileVersion(fx.readFilePath)
+ assert.deepEqual(await owner.request(read(sid), post(observed(first))), marked(first, false))
+ assert.deepEqual(await fileVersion(fx.readFilePath), afterMark)
+ assert.deepEqual(await listWatermark(tab), broadcast.cursor, 'no-op did not invalidate the list')
+ assert.equal(upstream.calls.length, 1)
+ } finally { peer.close() }
+
+ upstream.mode('hold')
+ const next = await fx.send(sid, 'later', modelRef('openai'), 'Later synthetic text')
+ const active = await fx.untilSnapshot(sid, state => state.active?.text === reply, tab)
+ assert.deepEqual(await tab.request(reads), { entries: [] })
+ assert.deepEqual(await tab.request(read(sid), post(observed(active), 409)), busy)
+ assert.equal(upstream.calls.length, 2)
+ upstream.release()
+ const second = await fx.complete(sid, next.turnId, tab)
+ assert.ok(second.state.updatedAt > first.state.updatedAt)
+ const beforeLate = await fileVersion(fx.readFilePath)
+ assert.deepEqual(await tab.request(read(sid), post(observed(first), 409)), stale)
+ assert.deepEqual(await owner.request(reads), { entries: [entry(second, first.state.updatedAt)] })
+ assert.deepEqual(await fileVersion(fx.readFilePath), beforeLate)
+
+ const beforeRace = await listWatermark(owner)
+ const raced = await Promise.all([owner.request(read(sid), post(observed(second))), tab.request(read(sid), post(observed(second)))])
+ assert.deepEqual(raced.sort((a, b) => Number(a.changed) - Number(b.changed)), [marked(second, false), marked(second)])
+ assert.deepEqual(await listWatermark(owner), { ...beforeRace, seq: beforeRace.seq + 1 })
+ assert.deepEqual(await fx.nativeReads(), { ...nativeSeed, [sid]: second.state.updatedAt })
+ const durableVersion = await fileVersion(fx.readFilePath)
+
+ await fx.restart()
+ assert.deepEqual(await owner.request(reads, { status: 401 }), authError)
+ assert.deepEqual(await tab.request(read(sid), post(observed(second), 401)), authError)
+ const reopened = await fx.login()
+ assert.deepEqual(await reopened.request(reads), { entries: [entry(second, second.state.updatedAt)] })
+ const viewAfterRestart = await reopened.request(chat(sid))
+ assert.deepEqual(viewAfterRestart.state, second.state)
+ assert.notEqual(viewAfterRestart.cursor.epoch, second.cursor.epoch)
+ assert.deepEqual(await reopened.request(read(sid), post(observed(second), 409)), stale)
+ assert.deepEqual(await reopened.request(read(sid), post(observed(viewAfterRestart))), marked(viewAfterRestart, false))
+ assert.deepEqual(await fileVersion(fx.readFilePath), durableVersion)
+
+ // A later native desktop mark can legitimately be ahead of the observed content time.
+ const desktopReadAt = second.state.updatedAt + 1000
+ await writeJson(fx.readFilePath, { ...nativeSeed, [sid]: desktopReadAt })
+ const desktopVersion = await fileVersion(fx.readFilePath)
+ const beforeNativeNoop = await listWatermark(reopened)
+ assert.deepEqual(await reopened.request(reads), { entries: [entry(viewAfterRestart, desktopReadAt)] })
+ assert.deepEqual(await reopened.request(read(sid), post(observed(viewAfterRestart))), {
+ ...entry(viewAfterRestart, desktopReadAt), changed: false
+ })
+ assert.deepEqual(await fileVersion(fx.readFilePath), desktopVersion)
+ assert.deepEqual(await listWatermark(reopened), beforeNativeNoop)
+ assert.equal(upstream.calls.length, 2)
+
+ // A desktop's wall clock can be ahead of ours. It must not silently consume a future reply.
+ const ahead=Date.now()+60_000
+ await writeJson(fx.readFilePath,{...nativeSeed,[sid]:ahead})
+ const sentAt=Date.now()
+ const later=await reopened.request(`${chat(sid)}/turns`,post({clientRequestId:'after-desktop-clock',model:modelRef('openai'),text:'One new observation'},202))
+ const finished=await fx.complete(sid,later.turnId,reopened)
+ assert.ok(finished.state.updatedAt>ahead)
+ assert.ok(finished.state.lastTurn.startedAt>=sentAt && finished.state.lastTurn.startedAt {
+ const fx = await workbench(t)
+ const { owner } = fx
+ const sid = randomUUID()
+ await fx.create(sid)
+ const valid = observed(await owner.request(chat(sid)))
+ const meterBody = { model: null }
+ for (const [path, wrong, allowed] of [[reads, 'POST', 'GET'], [read(sid), 'GET', 'POST'], [usage(sid), 'PUT', 'POST']]) {
+ const response = await owner.raw(path, { method: wrong })
+ assert.equal(response.status, 405)
+ assert.equal(response.headers.get('allow'), allowed)
+ assert.deepEqual(await response.json(), methodError)
+ }
+ const head = await owner.raw(reads, { method: 'HEAD' })
+ assert.equal(head.status, 405)
+ assert.equal(await head.text(), '')
+ for (const path of [reads, read(sid), usage(sid)]) {
+ const isList = path === reads
+ const body = isList ? undefined : path === read(sid) ? valid : meterBody
+ const method = isList ? 'GET' : 'POST'
+ for (const cookie of [null, `${owner.cookie}; ${owner.cookie}`, `${owner.cookie.split('=')[0]}=invalid`]) {
+ assert.deepEqual(await owner.request(path, { method, body, status: 401, headers: { cookie } }), authError)
+ }
+ for (const headers of [{ origin: fx.providerOrigin }, { 'sec-fetch-site': 'cross-site' }]) {
+ assert.deepEqual(await owner.request(path, { method, body, status: 403, headers }), originError)
+ }
+ assert.deepEqual(await owner.request(`${path}?extra=1`, { method, body, status: 400 }), { error: 'unexpected_query' })
+ if (!isList) {
+ for (const csrf of [null, 'wrong']) {
+ assert.deepEqual(await owner.request(path, post(body, 401, { 'x-deva-csrf': csrf })), authError)
+ }
+ assert.deepEqual(await owner.request(path, post(body, 403, { origin: null })), originError)
+ assert.deepEqual(await owner.request(path, post(body, 415, { 'content-type': 'text/plain' })), { error: 'json_required' })
+ assert.deepEqual(await owner.request(path, post(body, 415, { 'content-encoding': 'gzip' })), { error: 'json_required' })
+ assert.deepEqual(await owner.request(path, post(' '.repeat(80 * 1024) + JSON.stringify(body), 413)), { error: 'too_large' })
+ for (const raw of ['[]', '{}', JSON.stringify({ ...body, extra: 1 })]) {
+ const data = await owner.request(path, post(raw, 400))
+ assert.equal(typeof data.error, 'string')
+ }
+ }
+ }
+ const cursor = JSON.stringify(valid.cursor)
+ for (const raw of [
+ `{"updatedAt":0,"updat\\u0065dAt":${valid.updatedAt},"cursor":${cursor}}`,
+ `{"updatedAt":${valid.updatedAt},"cursor":{"seq":999,${cursor.slice(1)}}}`,
+ `{"updatedAt":${valid.updatedAt},"cursor":${cursor},"cursor":${cursor}}`
+ ]) {
+ assert.deepEqual(await owner.request(read(sid), post(raw, 400)), { error: 'invalid_json' })
+ }
+ assert.deepEqual(await owner.request(usage(sid), post('{"model":"wrong","m\\u006fdel":null}', 400)), { error: 'invalid_json' })
+ assert.deepEqual(await owner.request(reads), { entries: [] })
+ assert.equal(fx.upstream.calls.length, 0)
+})
+
+test('logout of an original login during an authenticated read POST defeats its pending native write', bounds, async t => {
+ const fx = await workbench(t)
+ const { owner } = fx
+ const tab = await fx.login()
+ const sid = randomUUID()
+ await fx.create(sid)
+ const snap = await fx.complete(sid, (await fx.send(sid, 'revocation')).turnId)
+ const payload = JSON.stringify(observed(snap)), path = `/api/v1/${read(sid)}`
+
+ // Observe the real JSON reader starting after authentication; hold the final bytes on the wire.
+ // This hook neither fakes the authentication service nor moves the commit point.
+ const admitted = Promise.withResolvers()
+ const iterator = IncomingMessage.prototype.iterator
+ const trace = t.mock.method(IncomingMessage.prototype, 'iterator', function (...args) {
+ if (this.url === path) admitted.resolve()
+ return iterator.apply(this, args)
+ })
+ const transport = Promise.withResolvers()
+ const req = httpRequest(`${fx.origin}${path}`, { method: 'POST', agent: false, signal: networkTimeout(), headers: {
+ origin: fx.origin, cookie: owner.cookie, 'x-deva-csrf': owner.csrf,
+ 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload)
+ } }, res => {
+ void (async () => {
+ const chunks = []; for await (const chunk of res) chunks.push(chunk)
+ return [res.statusCode, JSON.parse(Buffer.concat(chunks))]
+ })().then(transport.resolve, transport.reject)
+ })
+ req.once('error', transport.reject)
+ t.after(() => req.destroy())
+ req.write(payload.slice(0, 1))
+ assert.equal(await Promise.race([admitted.promise.then(() => 'reading'), transport.promise]), 'reading')
+ trace.mock.restore()
+ assert.deepEqual(await owner.request('auth/logout', post(undefined)), { ok: true })
+ req.end(payload.slice(1))
+ assert.deepEqual(await transport.promise, [401, authError])
+ assert.deepEqual(await tab.request(reads), { entries: [entry(snap)] })
+ await assert.rejects(stat(fx.readFilePath), { code: 'ENOENT' })
+ assert.deepEqual(await tab.request(read(sid), post(observed(snap))), marked(snap))
+ assert.equal(fx.upstream.calls.length, 1)
+})
+
+test('unsupported history and a broken native read map are surfaced without changing ordinary conversations', bounds, async t => {
+ const [sid, unsupported] = Array.from({ length: 2 }, randomUUID)
+ const privatePath = '/status-fixture/private-focus-root'
+ const fx = await workbench(t, { async seed({ sessionFile }) {
+ await writeJson(sessionFile(unsupported), { id: unsupported, title: 'Synthetic desktop-only chat',
+ createdAt: 10, updatedAt: 11, focusRoot: privatePath,
+ messages: [{ role: 'user', content: question }], members: [{ sessionId: sid }] })
+ } })
+ const { owner } = fx
+ await fx.create(sid)
+ const snap = await fx.complete(sid, (await fx.send(sid, 'unaffected-native')).turnId)
+ const unsupportedSnap = await owner.request(chat(unsupported))
+ assert.equal(unsupportedSnap.state.compatibility, 'unsupported')
+ assert.deepEqual(await owner.request(read(unsupported), post(observed(unsupportedSnap), 409)), { error: 'unsupported_history' })
+ assert.deepEqual(await owner.request(usage(unsupported), post({ model: null }, 409)), { error: 'unsupported_history' })
+ assert.deepEqual(await owner.request(reads), { entries: [entry(snap)] })
+
+ const broken = '{"truncated-map":';
+ await fx.restart(() => writeFile(fx.readFilePath, broken, { mode: 0o600 }))
+ const newLogin = await fx.login()
+ const fresh = await newLogin.request(chat(sid))
+ assert.deepEqual(fresh.state, snap.state)
+ const error = await newLogin.request(reads, { status: 503 })
+ assert.deepEqual(error, { error: 'read_state_unconfirmed' })
+ assertPrivate(error, [privatePath, fx.readFilePath, 'truncated-map'])
+ assert.deepEqual(await newLogin.request(read(sid), post(observed(fresh), 503)), error)
+ assert.equal(await readFile(fx.readFilePath, 'utf8'), broken)
+ assert.deepEqual((await newLogin.request(chat(sid))).state.messages.map(message => message.content), [question, reply])
+
+ await writeJson(fx.readFilePath, {})
+ const prior = await newLogin.request(chat(unsupported))
+ const damaged = '{"incomplete-chat":'
+ await writeFile(fx.sessionFile(unsupported), damaged)
+ assert.deepEqual(await newLogin.request(usage(unsupported), post({ model: null }, 409)), { error: 'read_unavailable' })
+ assert.deepEqual(await newLogin.request(read(unsupported), post(observed(prior), 409)), { error: 'read_unavailable' })
+ assert.equal(await readFile(fx.sessionFile(unsupported), 'utf8'), damaged)
+ assert.deepEqual(await newLogin.request(reads), { entries: [entry(fresh)] })
+ assert.equal(fx.upstream.calls.length, 1)
+})
diff --git a/apps/headless/test/read-mark-races.test.mjs b/apps/headless/test/read-mark-races.test.mjs
new file mode 100644
index 00000000..9bef8348
--- /dev/null
+++ b/apps/headless/test/read-mark-races.test.mjs
@@ -0,0 +1,362 @@
+import assert from 'node:assert/strict'
+import childProcess, { spawnSync } from 'node:child_process'
+import fs, { chmodSync, existsSync, fstatSync, linkSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'
+import { syncBuiltinESMExports } from 'node:module'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { test } from 'node:test'
+import { HttpError } from '../src/http/policy.mjs'
+import { openReadMarkStore } from '../src/chat/read-mark-store.mjs'
+
+const allow = () => true
+const isError = (status, code) => error => error instanceof HttpError && error.status === status && error.code === code && error.message === code
+const auth = isError(401, 'auth')
+const readOnly = isError(403, 'read_state_read_only')
+const conflict = isError(409, 'read_state_conflict')
+const unsupported = isError(409, 'read_state_unsupported')
+const unconfirmed = isError(503, 'read_state_unconfirmed')
+
+function setup(t, initial) {
+ const base = realpathSync(mkdtempSync(join(tmpdir(), 'deva-read-mark-races-')))
+ const dataDir = join(base, 'state')
+ mkdirSync(dataDir, { mode: 0o700 })
+ const file = join(dataDir, 'read-state.json')
+ if (initial !== undefined) writeFileSync(file, initial, { mode: 0o600 })
+ const store = openReadMarkStore({ dataDir })
+ t.after(() => { store.close(); rmSync(base, { force: true, recursive: true }) })
+ return { base, dataDir, file, store }
+}
+
+function externalReplace(dataDir, file, text) {
+ const swap = join(dataDir, 'external-pending')
+ writeFileSync(swap, text, { mode: 0o600 })
+ renameSync(swap, file)
+}
+
+const inode = path => statSync(path, { bigint: true }).ino
+
+test('fresh verify rejects async/false/unknown errors and preserves approved HttpError identities', t => {
+ const { dataDir, file, store } = setup(t)
+ const input = { id: 's', through: 1 }
+ const stale = new HttpError(409, 'read_view_stale')
+ const busy = new HttpError(409, 'read_view_busy')
+ const revoked = new HttpError(401, 'auth')
+ const disconnected = new HttpError(503, 'conversation_status_unavailable')
+ const wrongCode = new HttpError(503, 'some_internal_detail')
+ const wrongStatus = new HttpError(401, 'conversation_status_unavailable')
+ for (const verify of [undefined, () => false, () => undefined, () => ({ then() { assert.fail() } }),
+ async () => true, async () => { throw stale }, () => { throw Error(file) }, () => { throw wrongCode }, () => { throw wrongStatus }]) {
+ assert.throws(() => store.advance(input, verify), auth)
+ assert.deepEqual(readdirSync(dataDir), [])
+ }
+ for (const approved of [stale, busy, revoked, disconnected]) {
+ for (const checkpoint of [1, 2]) {
+ let checks = 0
+ assert.throws(() => store.advance(input, () => {
+ if (++checks === checkpoint) throw approved
+ return true
+ }), error => error === approved)
+ assert.equal(checks, checkpoint)
+ assert.deepEqual(readdirSync(dataDir), [])
+ }
+ }
+})
+
+test('revocation immediately before publish leaves original inode; revocation afterward leaves committed inode', t => {
+ const { dataDir, file, store } = setup(t, '{"s":1}')
+ const original = inode(file)
+ const input = { id: 's', through: 3 }
+ let checks = 0
+ assert.throws(() => store.advance(input, () => {
+ checks++
+ assert.equal(inode(file), original)
+ if (checks === 2) assert.equal(readdirSync(dataDir).some(name => name.startsWith('.read-state.json.')), true)
+ return checks === 1
+ }), auth)
+ assert.equal(checks, 2)
+ assert.equal(inode(file), original)
+ checks = 0
+ assert.throws(() => store.advance(input, () => {
+ if (++checks !== 3) return true
+ assert.notEqual(inode(file), original)
+ assert.equal(readFileSync(file, 'utf8'), '{"s":3}')
+ return false
+ }), auth)
+ assert.equal(checks, 3)
+ assert.notEqual(inode(file), original)
+ assert.deepEqual(store.snapshot(), new Map([['s', 3]]))
+ assert.deepEqual(readdirSync(dataDir), ['read-state.json'])
+ const postStale = new HttpError(409, 'read_view_stale')
+ checks = 0
+ assert.throws(() => store.advance({ id: 's', through: 4 }, () => {
+ if (++checks === 3) throw postStale
+ return true
+ }), error => error === postStale)
+ assert.equal(readFileSync(file, 'utf8'), '{"s":4}')
+ const disconnected = new HttpError(503, 'conversation_status_unavailable')
+ checks = 0
+ assert.throws(() => store.advance({ id: 's', through: 5 }, () => {
+ if (++checks === 3) throw disconnected
+ return true
+ }), error => error === disconnected)
+ assert.equal(checks, 3)
+ assert.equal(readFileSync(file, 'utf8'), '{"s":5}')
+})
+
+test('out-of-band replacements or in-place edits are observed before publish; a later older read never regresses', t => {
+ const { dataDir, file, store } = setup(t, '{}')
+ assert.equal(store.snapshot().size, 0)
+ externalReplace(dataDir, file, '{"s":80}')
+ const newest = inode(file)
+ assert.deepEqual(store.advance({ id: 's', through: 40 }, allow), { changed: false, readAt: 80 })
+ assert.equal(inode(file), newest)
+ let checks = 0
+ assert.throws(() => store.advance({ id: 's', through: 90 }, () => {
+ if (++checks === 2) externalReplace(dataDir, file, '{"s":95,"out_of_band":1}')
+ return true
+ }), conflict)
+ assert.equal(checks, 2)
+ assert.equal(readFileSync(file, 'utf8'), '{"s":95,"out_of_band":1}')
+ assert.deepEqual(store.advance({ id: 's', through: 90 }, allow), { changed: false, readAt: 95 })
+ const race = inode(file)
+ checks = 0
+ assert.throws(() => store.advance({ id: 's', through: 94 }, () => {
+ if (++checks === 2) writeFileSync(file, '{"s":96,"out_of_band":1}')
+ return true
+ }), conflict)
+ assert.equal(inode(file), race)
+ assert.equal(readFileSync(file, 'utf8'), '{"s":96,"out_of_band":1}')
+ assert.deepEqual(readdirSync(dataDir), ['read-state.json'])
+})
+
+test('initial publication never overwrites a name that appears in the link syscall window', t => {
+ const { dataDir, file, store } = setup(t)
+ const originalLink = fs.linkSync
+ t.after(() => { fs.linkSync = originalLink; syncBuiltinESMExports() })
+ fs.linkSync = (temporary, destination) => {
+ writeFileSync(file, '{"native_other":5}', { mode: 0o600, flag: 'wx' })
+ return originalLink(temporary, destination)
+ }
+ syncBuiltinESMExports()
+ assert.throws(() => store.advance({ id: 's', through: 1 }, allow), conflict)
+ assert.equal(readFileSync(file, 'utf8'), '{"native_other":5}')
+ assert.deepEqual(readdirSync(dataDir), ['read-state.json'])
+})
+
+test('a replaced staging name is neither published nor removed as local cleanup', t => {
+ const { dataDir, file, store } = setup(t, '{"s":1}')
+ let checks = 0
+ let staged
+ assert.throws(() => store.advance({ id: 's', through: 2 }, () => {
+ if (++checks === 2) {
+ staged = join(dataDir, readdirSync(dataDir).find(name => name.startsWith('.read-state.json.')))
+ externalReplace(dataDir, staged, '{"external":3}')
+ }
+ return true
+ }), conflict)
+ assert.equal(checks, 2)
+ assert.equal(readFileSync(file, 'utf8'), '{"s":1}')
+ assert.equal(readFileSync(staged, 'utf8'), '{"external":3}')
+})
+
+test('post-publication replacement and ambiguous fsync/rename results never roll back external data', t => {
+ const { dataDir, file, store } = setup(t, '{"s":1}')
+ let checks = 0
+ assert.throws(() => store.advance({ id: 's', through: 2 }, () => {
+ if (++checks === 3) externalReplace(dataDir, file, '{"s":4}')
+ return true
+ }), unconfirmed)
+ assert.equal(readFileSync(file, 'utf8'), '{"s":4}')
+ const originalFsync = fs.fsyncSync
+ const originalRename = fs.renameSync
+ t.after(() => { fs.fsyncSync = originalFsync; fs.renameSync = originalRename; syncBuiltinESMExports() })
+ fs.fsyncSync = fd => {
+ if (!fstatSync(fd).isDirectory()) return originalFsync(fd)
+ externalReplace(dataDir, file, '{"native_other":8}')
+ throw Object.assign(Error('private fsync path information'), { code: 'EIO' })
+ }
+ syncBuiltinESMExports()
+ assert.throws(() => store.advance({ id: 's', through: 5 }, allow), unconfirmed)
+ assert.equal(readFileSync(file, 'utf8'), '{"native_other":8}')
+ fs.fsyncSync = originalFsync
+ fs.renameSync = (a, b) => {
+ originalRename(a, b)
+ throw Object.assign(Error('reported error after rename'), { code: 'EPERM' })
+ }
+ syncBuiltinESMExports()
+ assert.throws(() => store.advance({ id: 's', through: 6 }, allow), unconfirmed)
+ assert.equal(readFileSync(file, 'utf8'), '{"native_other":8,"s":6}')
+ assert.deepEqual(readdirSync(dataDir), ['read-state.json'])
+})
+
+test('directory inode remains pinned even if path is rebound; detached staging is cleaned', t => {
+ const { base, dataDir, file, store } = setup(t, '{"s":4}')
+ const detached = join(base, 'away')
+ assert.deepEqual(store.snapshot(), new Map([['s', 4]]))
+ let checks = 0
+ assert.throws(() => store.advance({ id: 's', through: 5 }, () => {
+ if (++checks === 2) {
+ renameSync(dataDir, detached)
+ mkdirSync(dataDir, { mode: 0o700 })
+ writeFileSync(file, '{"replacement":8}', { mode: 0o600 })
+ }
+ return true
+ }), conflict)
+ assert.equal(readFileSync(join(detached, 'read-state.json'), 'utf8'), '{"s":4}')
+ assert.equal(readFileSync(file, 'utf8'), '{"replacement":8}')
+ assert.deepEqual(readdirSync(detached), ['read-state.json'])
+ assert.throws(() => store.snapshot(), conflict)
+ const restart = openReadMarkStore({ dataDir })
+ t.after(() => restart.close())
+ assert.equal(restart.snapshot().get('replacement'), 8)
+})
+
+test('a pinned empty root conflicts after disappearance and remains pinned across recreation', t => {
+ const { base, dataDir, file, store } = setup(t)
+ assert.equal(Object.isFrozen(store), true)
+ assert.deepEqual(store.snapshot(), new Map())
+ renameSync(dataDir, join(base, 'renamed'))
+ assert.throws(() => store.snapshot(), conflict)
+ assert.throws(() => store.advance({ id: 's', through: 1 }, allow), conflict)
+ mkdirSync(dataDir, { mode: 0o700 })
+ writeFileSync(file, '{"replacement":8}', { mode: 0o600 })
+ assert.throws(() => store.snapshot(), conflict)
+ assert.throws(() => store.advance({ id: 's', through: 1 }, allow), conflict)
+ assert.equal(readFileSync(file, 'utf8'), '{"replacement":8}')
+})
+
+test('cooperating writer locks across real processes, while snapshots and no-op start no helpers', t => {
+ const { dataDir, file, store } = setup(t, '{"s":4}')
+ const originalSpawn = childProcess.spawnSync
+ const launched = []
+ childProcess.spawnSync = (program, args, options) => {
+ launched.push({ program, args, options })
+ return originalSpawn(program, args, options)
+ }
+ syncBuiltinESMExports()
+ t.after(() => { childProcess.spawnSync = originalSpawn; syncBuiltinESMExports() })
+ assert.equal(store.snapshot().get('s'), 4)
+ assert.deepEqual(store.advance({ id: 's', through: 4 }, allow), { changed: false, readAt: 4 })
+ assert.deepEqual(launched, [])
+ let checks = 0
+ const module = new URL('../src/chat/read-mark-store.mjs', import.meta.url).href
+ assert.deepEqual(store.advance({ id: 's', through: 5 }, () => {
+ if (++checks !== 2) return true
+ const child = originalSpawn(process.execPath, ['--input-type=module', '-e', `import { openReadMarkStore } from ${JSON.stringify(module)};
+ const s = openReadMarkStore({ dataDir: process.argv[1] });
+ try { s.advance({ id: 's', through: 99 }, () => true); process.exitCode = 2 }
+ catch (e) { if (e?.code !== 'read_state_conflict') process.exitCode = 3 }
+ finally { s.close() }`, dataDir], { timeout: 3000 })
+ assert.equal(child.status, 0)
+ assert.equal(readFileSync(file, 'utf8'), '{"s":4}')
+ return true
+ }), { changed: true, readAt: 5 })
+ assert.equal(checks, 3)
+ assert.deepEqual(launched.map(item => item.program), ['/usr/bin/flock', '/usr/bin/perl'])
+ for (const { args, options } of launched) {
+ assert.equal(args.some(arg => arg.includes(dataDir)), false)
+ assert.deepEqual(options.env, {})
+ assert.equal(options.timeout, 1000)
+ }
+})
+
+test('unsafe symlinks, FIFOs, extra links and modes fail closed; owner-read-only files stay readable', t => {
+ const { base, dataDir, file, store } = setup(t)
+ const sensitive = join(base, 'external')
+ writeFileSync(sensitive, '{"native":7}', { mode: 0o600 })
+ symlinkSync(sensitive, file)
+ assert.throws(() => store.snapshot(), unsupported)
+ assert.throws(() => store.advance({ id: 's', through: 2 }, allow), unsupported)
+ rmSync(file)
+ linkSync(sensitive, file)
+ assert.throws(() => store.snapshot(), unsupported)
+ assert.equal(statSync(sensitive).nlink, 2)
+ rmSync(file)
+ assert.equal(spawnSync('/usr/bin/mkfifo', [file], { timeout: 1000 }).status, 0)
+ assert.throws(() => store.snapshot(), unsupported)
+ assert.throws(() => store.advance({ id: 's', through: 2 }, allow), unsupported)
+ rmSync(file)
+ mkdirSync(file, { mode: 0o700 })
+ assert.throws(() => store.snapshot(), unsupported)
+ rmSync(file, { recursive: true })
+ writeFileSync(file, '{}', { mode: 0o600 })
+ for (const mode of [0o666, 0o620, 0o701, 0o4600]) {
+ chmodSync(file, mode)
+ assert.throws(() => store.snapshot(), unsupported)
+ assert.throws(() => store.advance({ id: 's', through: 2 }, allow), unsupported)
+ }
+ chmodSync(file, 0o000)
+ assert.throws(() => store.snapshot(), readOnly)
+ chmodSync(file, 0o400)
+ assert.equal(store.snapshot().size, 0)
+ assert.throws(() => store.advance({ id: 's', through: 2 }, allow), readOnly)
+ chmodSync(file, 0o600)
+ chmodSync(dataDir, 0o550)
+ assert.equal(store.snapshot().size, 0)
+ assert.throws(() => store.advance({ id: 's', through: 2 }, allow), readOnly)
+ chmodSync(dataDir, 0o700)
+ assert.equal(readFileSync(sensitive, 'utf8'), '{"native":7}')
+ assert.equal(readFileSync(file, 'utf8'), '{}')
+ assert.deepEqual(readdirSync(dataDir), ['read-state.json'])
+ const alias = join(base, 'alias')
+ symlinkSync(dataDir, alias)
+ const aliased = openReadMarkStore({ dataDir: alias })
+ t.after(() => aliased.close())
+ assert.throws(() => aliased.snapshot(), unsupported)
+})
+
+test('mutations fail closed on native xattrs and POSIX ACLs without dropping metadata', t => {
+ const { dataDir, file, store } = setup(t, '{"s":1}')
+ const script = `import os, sys, struct
+path, mode = sys.argv[1:]
+if mode == 'xattr': os.setxattr(path, 'user.read_mark_test', b'retain')
+else:
+ acl = struct.pack(' spawnSync('/usr/bin/python3', ['-c', script, path, mode], { timeout: 1000 })
+ if (probe(file, 'xattr').status !== 0) return t.skip('xattr test setup requires Python and a filesystem supporting user xattrs')
+ const before = inode(file)
+ assert.equal(store.snapshot().get('s'), 1)
+ assert.throws(() => store.advance({ id: 's', through: 2 }, allow), readOnly)
+ assert.equal(inode(file), before)
+ assert.equal(readFileSync(file, 'utf8'), '{"s":1}')
+ assert.deepEqual(readdirSync(dataDir), ['read-state.json'])
+ // A clean new inode is still blocked when the directory would inherit an extended ACL.
+ externalReplace(dataDir, file, '{"s":3}')
+ const acl = probe(dataDir, 'acl')
+ if (acl.status !== 0) { t.diagnostic('POSIX default ACL test setup is unavailable; verified native xattrs'); return }
+ const real = inode(file)
+ assert.throws(() => store.advance({ id: 's', through: 4 }, allow), readOnly)
+ assert.equal(inode(file), real)
+ assert.equal(readFileSync(file, 'utf8'), '{"s":3}')
+ assert.deepEqual(readdirSync(dataDir), ['read-state.json'])
+})
+
+test('an unconfirmed metadata probe leaves the native file read-only and reveals no helper details', t => {
+ const { dataDir, file, store } = setup(t, '{"s":1}')
+ const originalSpawn = childProcess.spawnSync
+ childProcess.spawnSync = (program, ...args) => program === '/usr/bin/perl'
+ ? { status: null, error: Object.assign(Error('private infrastructure details'), { code: 'ETIMEDOUT' }) }
+ : originalSpawn(program, ...args)
+ syncBuiltinESMExports()
+ t.after(() => { childProcess.spawnSync = originalSpawn; syncBuiltinESMExports() })
+ const before = inode(file)
+ assert.equal(store.snapshot().get('s'), 1)
+ assert.throws(() => store.advance({ id: 's', through: 2 }, allow), readOnly)
+ assert.equal(inode(file), before)
+ assert.deepEqual(readdirSync(dataDir), ['read-state.json'])
+})
+
+test('reentrant close neither leaks staged bytes nor allows the store to resurrect', t => {
+ const { dataDir, file, store } = setup(t)
+ let checks = 0
+ assert.throws(() => store.advance({ id: 's', through: 10 }, () => {
+ if (++checks === 2) store.close()
+ return true
+ }), unconfirmed)
+ assert.equal(checks, 2)
+ assert.equal(existsSync(file), false)
+ assert.deepEqual(readdirSync(dataDir), [])
+ assert.throws(() => store.snapshot(), unconfirmed)
+})
diff --git a/apps/headless/test/read-mark-store.test.mjs b/apps/headless/test/read-mark-store.test.mjs
new file mode 100644
index 00000000..4b9271e7
--- /dev/null
+++ b/apps/headless/test/read-mark-store.test.mjs
@@ -0,0 +1,149 @@
+import assert from 'node:assert/strict'
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { test } from 'node:test'
+import { HttpError } from '../src/http/policy.mjs'
+import { openReadMarkStore } from '../src/chat/read-mark-store.mjs'
+
+const allow = () => true
+const isError = (status, code) => error => error instanceof HttpError && error.status === status && error.code === code && error.message === code
+const invalid = isError(400, 'invalid_read_state')
+const limited = isError(413, 'read_state_limit')
+const unavailable = isError(503, 'read_state_unconfirmed')
+
+function setup(t, name) {
+ const base = realpathSync(mkdtempSync(join(tmpdir(), 'deva-read-mark-')))
+ const dataDir = name ? join(base, name) : base
+ const store = openReadMarkStore({ dataDir })
+ const file = join(dataDir, 'read-state.json')
+ t.after(() => { store.close(); rmSync(base, { force: true, recursive: true }) })
+ return { base, dataDir, store, file }
+}
+
+function pins(path) {
+ return readdirSync('/proc/self/fd').flatMap(name => {
+ try { return readlinkSync(`/proc/self/fd/${name}`) === path ? [name] : [] }
+ catch (error) { if (error.code !== 'ENOENT') throw error; return [] }
+ })
+}
+
+function stamp(file) {
+ const { ino, dev, mode, uid, gid, nlink, size, mtimeNs, ctimeNs } = statSync(file, { bigint: true })
+ return { ino, dev, mode, uid, gid, nlink, size, mtimeNs, ctimeNs }
+}
+
+test('factory is lazy; absent snapshots create nothing; close releases the directory pin and is final', t => {
+ const { base, dataDir, file, store } = setup(t, 'deva')
+ assert.deepEqual(pins(dataDir), [])
+ assert.deepEqual(store.snapshot(), new Map())
+ assert.deepEqual(readdirSync(base), [])
+ assert.throws(() => store.advance({ id: 'sessionA', through: 0 }, allow), isError(403, 'read_state_read_only'))
+ assert.equal(existsSync(dataDir), false)
+ mkdirSync(dataDir, { mode: 0o700 })
+ const before = stamp(dataDir)
+ assert.deepEqual(store.snapshot(), new Map())
+ assert.equal(existsSync(file), false)
+ assert.deepEqual(stamp(dataDir), before)
+ assert.equal(pins(dataDir).length, 1)
+ store.close()
+ store.close()
+ assert.deepEqual(pins(dataDir), [])
+ assert.throws(() => store.snapshot(), unavailable)
+ assert.throws(() => store.advance({ id: 'sessionA', through: 1 }, allow), unavailable)
+ assert.deepEqual(pins(dataDir), [])
+})
+
+test('two owner sessions and restart see the same durable marks; no-op leaves the inode and mtime unchanged', t => {
+ const { dataDir, file, store } = setup(t)
+ const other = openReadMarkStore({ dataDir })
+ t.after(() => other.close())
+ assert.deepEqual(store.advance({ id: 'chat_1', through: 100_001 }, allow), { changed: true, readAt: 100_001 })
+ assert.equal(readFileSync(file, 'utf8'), '{"chat_1":100001}')
+ const first = stamp(file)
+ assert.equal(first.uid, BigInt(process.geteuid()))
+ assert.equal(first.mode & 0o7777n, 0o600n)
+ assert.equal(first.nlink, 1n)
+ const copied = other.snapshot()
+ assert.deepEqual(copied, new Map([['chat_1', 100_001]]))
+ copied.set('chat_1', 0)
+ assert.deepEqual(other.snapshot(), new Map([['chat_1', 100_001]]))
+ let checks = 0
+ for (const through of [100_000, 100_001]) {
+ assert.deepEqual(other.advance({ id: 'chat_1', through }, () => { checks++; return true }), { changed: false, readAt: 100_001 })
+ assert.deepEqual(stamp(file), first)
+ }
+ assert.equal(checks, 4)
+ assert.deepEqual(other.advance({ id: 'chat_1', through: 100_002 }, allow), { changed: true, readAt: 100_002 })
+ assert.notEqual(stamp(file).ino, first.ino)
+ assert.equal(stamp(file).nlink, 1n)
+ assert.deepEqual(readdirSync(dataDir), ['read-state.json'])
+ store.close()
+ other.close()
+ const restart = openReadMarkStore({ dataDir })
+ t.after(() => restart.close())
+ assert.deepEqual(restart.snapshot(), new Map([['chat_1', 100_002]]))
+})
+
+test('legacy mode and bytes of unrelated native rows survive replacement and insertion', t => {
+ const { file, store } = setup(t)
+ const raw = '\ufeff\n { "n\\u0061tive_other" \t: 7.20e+2 ,\r\n\t"foo\\u002d1": 1.00E3, "zero": -0.000e9, "big": 900719925474099100e-2 \t }\r\n'
+ writeFileSync(file, raw)
+ chmodSync(file, 0o644)
+ const before = stamp(file)
+ assert.deepEqual(store.snapshot(), new Map([['native_other', 720], ['foo-1', 1000], ['zero', 0], ['big', Number.MAX_SAFE_INTEGER]]))
+ assert.deepEqual(store.advance({ id: 'foo-1', through: 1001 }, allow), { changed: true, readAt: 1001 })
+ const next = raw.replace('1.00E3', '1001')
+ assert.equal(readFileSync(file, 'utf8'), next)
+ const updated = stamp(file)
+ assert.notEqual(updated.ino, before.ino)
+ assert.deepEqual(store.advance({ id: 'new_chat', through: 2000 }, allow), { changed: true, readAt: 2000 })
+ assert.equal(readFileSync(file, 'utf8'), next.replace('e-2 \t }', 'e-2,"new_chat":2000 \t }'))
+ const after = stamp(file)
+ assert.notEqual(after.ino, updated.ino)
+ for (const key of ['uid', 'gid', 'mode', 'nlink']) assert.equal(after[key], before[key])
+})
+
+test('one durable number bounded to [0, MAX_SAFE_INTEGER]; duplicate keys and rounded decimals fail closed', t => {
+ const { file, store } = setup(t)
+ for (const id of ['', 'with/slash', 'green\n', 'a'.repeat(129)]) {
+ assert.throws(() => store.advance({ id, through: 1 }, allow), invalid)
+ }
+ for (const through of [-1, 1.01, Infinity, NaN, '123', null, undefined, new Date(123), 9007199254740992, 1n]) {
+ assert.throws(() => store.advance({ id: 's', through }, allow), invalid)
+ }
+ assert.equal(existsSync(file), false)
+ for (const raw of [
+ '', '{', '[]', 'null', 'false', '{}\v', '{"a":1,}', '{"a":1,"a":2}', '{"a":1,"\\u0061":2}',
+ '{"s":true}', '{"s":null}', '{"s":"1"}', '{"s":[]}', '{"s":{}}', '{"s":-10}', '{"s":1e99999}',
+ '{"s":9007199254740992}', '{"s":9007199254740991.1}', '{"s":1.00000000000000000000001}', '{"s":1e-99999}',
+ '{"s":1.2}', '{"s":01}', '{"../s":1}', '{"\\uD800":1}', Buffer.from([0x7b, 0x80, 0x7d])
+ ]) {
+ writeFileSync(file, raw, { mode: 0o600 })
+ const before = stamp(file)
+ assert.throws(() => store.snapshot(), invalid)
+ assert.throws(() => store.advance({ id: 's', through: 100 }, allow), invalid)
+ assert.deepEqual(stamp(file), before)
+ }
+ writeFileSync(file, '{"zero":0e99999999, "half_scaled":0.50e1, "max":9007199254740991}')
+ assert.deepEqual(store.snapshot(), new Map([['zero', 0], ['half_scaled', 5], ['max', Number.MAX_SAFE_INTEGER]]))
+})
+
+test('limit is exactly 1 MiB and 8192 rows; hitting an output cap leaves the file unchanged', t => {
+ const { file, store } = setup(t)
+ const maxBytes = 1024 * 1024
+ writeFileSync(file, '{"s":9}' + ' '.repeat(maxBytes - 7), { mode: 0o600 })
+ assert.equal(store.snapshot().get('s'), 9)
+ const before = stamp(file)
+ assert.throws(() => store.advance({ id: 's', through: 10 }, allow), limited)
+ assert.deepEqual(stamp(file), before)
+ writeFileSync(file, '{}'.padEnd(maxBytes + 1, ' '))
+ assert.throws(() => store.snapshot(), limited)
+ const allIds = Object.fromEntries(Array.from({ length: 8192 }, (_, i) => [`id${i}`, i]))
+ writeFileSync(file, JSON.stringify(allIds))
+ assert.equal(store.snapshot().size, 8192)
+ assert.throws(() => store.advance({ id: 'some_other_id', through: 10 }, allow), limited)
+ assert.deepEqual(store.advance({ id: 'id7711', through: 9000 }, allow), { changed: true, readAt: 9000 })
+ writeFileSync(file, JSON.stringify({ ...allIds, too_many: 1 }))
+ assert.throws(() => store.snapshot(), limited)
+})
diff --git a/docs/development/web-workbench/README.md b/docs/development/web-workbench/README.md
index 87c96bd5..94999430 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`**。当前有 **48 个 `implemented`**:模型与设置 9 项、个人资料 3 项、分域记忆 4 项、角色管理 7 项、授权项目文件读取 2 项、网页定位目录 1 项、网页文件选择与粘贴上传 2 项、会话模型与归档及列表订阅 3 项、授权交付清单与定位 2 项、Git 只读能力探测 1 项、项目选择与会话绑定 2 项、原生任务详情与日程预览 2 项、客户端页面全屏状态与订阅 2 项、客户端文本复制与粘贴 2 项、PTY 回收与退出事件 2 项、技能目录及已保存的启用和角色偏好与目录失效订阅 4 项;其余 **134 个 `pending`、4 个 `desktop-only`**。其中 37 个 `pending` 有明确的部分实现和测试记录,97 个仍待实现;这些数不是用户工作流的完成百分比。任务列表按需读取,状态变化目前仅支持对既有活动任务的人工确认暂停;这两项登记为部分覆盖。Git 的已跟踪状态、暂存与工作树差异、分支和首父历史按部分覆盖登记;写入及远程操作仍待移植。交付下载覆盖明确的成品格式;静态图预览与整个桌面缩略图机制仍有差别。空闲会话可以改名;在途改名和非默认思考档位仍属部分覆盖。上传格式与模型协议限制在部署说明中列出;目录拖放及图片缩略资源仍按部分覆盖登记。选择授权项目、保存会话关联和手动打开该项目的资料已接通;可以按修订保存已有文本;单独启用文档创建时可在已有目录内新建受支持的 Markdown 或纯文本文件。角色私有默认目录的创建与完整工具授权未计入。角色删除可处理未被引用的自定义角色,对受保护的默认角色和已有引用报冲突;未将其列为桌面级联删除已完成。单独的 `platform` 值已实现:设置显示经过认证的启动投影中的宿主平台,Linux 容器不会因客户端使用 macOS 而显示为 macOS。浏览器全屏、布局和侧栏快捷键使用客户端状态,而不把宿主平台当作操作电脑。已有手机版 PWA/relay 和桌面 IPC 都是参照,不是 Workbench 覆盖证明。
+[能力清单](./parity-manifest.json)按桌面 [preload 运行时 `const api`](../../../apps/desktop/src/preload/index.ts)逐项登记:**21 组、186 个方法(含 18 个订阅)、1 个值 `platform`**。当前有 **49 个 `implemented`**:模型与设置 9 项、个人资料 3 项、分域记忆 4 项、角色管理 7 项、授权项目文件读取 2 项、网页定位目录 1 项、网页文件选择与粘贴上传 2 项、会话模型与归档及列表订阅 3 项、可见会话已读确认 1 项、授权交付清单与定位 2 项、Git 只读能力探测 1 项、项目选择与会话绑定 2 项、原生任务详情与日程预览 2 项、客户端页面全屏状态与订阅 2 项、客户端文本复制与粘贴 2 项、PTY 回收与退出事件 2 项、技能目录及已保存的启用和角色偏好与目录失效订阅 4 项;其余 **133 个 `pending`、4 个 `desktop-only`**。其中 39 个 `pending` 有明确的部分实现和测试记录,94 个仍待实现;这些数不是用户工作流的完成百分比。任务列表按需读取,状态变化目前仅支持对既有活动任务的人工确认暂停;这两项登记为部分覆盖。Git 的已跟踪状态、暂存与工作树差异、分支和首父历史按部分覆盖登记;写入及远程操作仍待移植。交付下载覆盖明确的成品格式;静态图预览与整个桌面缩略图机制仍有差别。空闲会话可以改名;在途改名和非默认思考档位仍属部分覆盖。上传格式与模型协议限制在部署说明中列出;目录拖放及图片缩略资源仍按部分覆盖登记。选择授权项目、保存会话关联和手动打开该项目的资料已接通;可以按修订保存已有文本;单独启用文档创建时可在已有目录内新建受支持的 Markdown 或纯文本文件。角色私有默认目录的创建与完整工具授权未计入。角色删除可处理未被引用的自定义角色,对受保护的默认角色和已有引用报冲突;未将其列为桌面级联删除已完成。单独的 `platform` 值已实现:设置显示经过认证的启动投影中的宿主平台,Linux 容器不会因客户端使用 macOS 而显示为 macOS。浏览器全屏、布局和侧栏快捷键使用客户端状态,而不把宿主平台当作操作电脑。已有手机版 PWA/relay 和桌面 IPC 都是参照,不是 Workbench 覆盖证明。
通用文本阶段另外给七个 `chat` 条目登记了 `web.partial`:`createSession`、`send`、`abort`、`listSessions`、`loadSession`、`attachSession`、`onEvent`。每项记录已验证范围、专有测试和仍缺的桌面行为;它们仍计入 `pending`,不等同于附件、工具、成员或审批均已接通。[通用文本协议与阶段限制](../../../apps/headless/src/chat/README.md)。
@@ -8,6 +8,8 @@
**技能管理与技能执行分别计数。** `skills.list` 返回真实来源、启用和角色范围的目录摘要;`setEnabled` 和 `setRoles` 保存原生配置并读回;`onChanged` 向已打开的设置页发送修订号,页面重取列表,断线后重新确认选中的文档。`skills.get` 针对自定义文档已接通,但不下发内置运行指令,因此登记为部分覆盖。导入和删除仍待实现。此处没有把目录偏好登记为 Web 聊天已能执行技能。
+**会话状态。** `chat.markRead` 核对最新已显示的持久会话、原生游标和登录后才写桌面已读水位;新内容先到或游标失效时不能将其误标。`chat.contextUsage` 已在三个真实适配器上核对实测输入和无回执时的历史估算,但 Web 不启动自动压缩;`chat.onRemoteChange` 已覆盖同一所有者 Web 登录之间的已读刷新,尚非完整远端同步协议。因此后两项仍按部分覆盖。
+
## 本地与 CI
依赖准备好后,从仓库根目录执行;脚本使用桌面已有的 `typescript` 开发依赖,运行无需网络或启动 Electron:
diff --git a/docs/development/web-workbench/parity-manifest.json b/docs/development/web-workbench/parity-manifest.json
index c85cca04..79424f8c 100644
--- a/docs/development/web-workbench/parity-manifest.json
+++ b/docs/development/web-workbench/parity-manifest.json
@@ -143,7 +143,7 @@
{"name":"removeMember","kind":"invoke","channel":"chat:remove-member","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/chat.tsx","use":"成员栏移除成员并停止其任务,保留历史"},"web":{"status":"pending","target":"rpc","semantic":"禁止再派任务且保留成员会话历史,主会话可继续运行。"}},
{"name":"deleteTurns","kind":"invoke","channel":"chat:delete-turns","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/chat.tsx","use":"聊天状态按轮批量删除并重建展示"},"web":{"status":"pending","target":"rpc","semantic":"尊重历史锁;按稳定的轮边界重建视图,不在忙碌时先行删 UI。"}},
{"name":"todos","kind":"invoke","channel":"chat:todos","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/chat.tsx","use":"聊天状态切换时拉取当前会话待办清单"},"web":{"status":"pending","target":"rpc","semantic":"获取作用域为会话的清单与进度,以快照接续后续待办事件。"}},
- {"name":"contextUsage","kind":"invoke","channel":"chat:context-usage","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/redesign/context-usage.ts","host":"apps/desktop/src/main/services/context-usage.ts","use":"上下文指示器查模型窗口、占用和压缩线"},"web":{"status":"pending","target":"rpc","semantic":"以当前生效模型计算窗口和占用;模型无法解析时明确为空。"}},
+ {"name":"contextUsage","kind":"invoke","channel":"chat:context-usage","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/redesign/context-usage.ts","host":"apps/desktop/src/main/services/context-usage.ts","use":"上下文指示器查模型窗口、占用和压缩线"},"web":{"status":"pending","target":"rpc","semantic":"以当前生效模型计算窗口和占用;模型无法解析时明确为空。","partial":{"scope":"复用桌面模型窗口与圆环,区分三种协议的实测输入量和当前可见历史估算;校验会话、模型与回合来源,未启用的模型不复用旧值。","remaining":"Web 尚无自动压缩阈值、桌面进程从超窗错误学习的窗口值或完整复杂历史;这些数据不以估算冒充。","handler":"apps/headless/src/chat/conversation-usage.mjs","test":"apps/headless/test/conversation-status-http-meter.test.mjs"}}},
{"name":"cancelTodoList","kind":"invoke","channel":"chat:todo-cancel","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/chat.tsx","use":"聊天胶囊取消当前清单,下一次回合通知模型"},"web":{"status":"pending","target":"rpc","semantic":"保留忙碌限制,返回已取消状态并在后续轮持久传达取消意图。"}},
{"name":"rewindList","kind":"invoke","channel":"chat:rewind-list","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/redesign/RewindModal.tsx","use":"回滚对话框加载每轮改动量和撤销能力"},"web":{"status":"pending","target":"rpc","semantic":"按会话回传检查点、改动摘要和当前可撤销状态。"}},
{"name":"rewindPreview","kind":"invoke","channel":"chat:rewind-preview","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/redesign/RewindModal.tsx","use":"回滚对话框预览文件计划和无法撤销的命令"},"web":{"status":"pending","target":"rpc","semantic":"只读获取冲突、超限及命令副作用,界面不能自行推导执行计划。"}},
@@ -156,8 +156,8 @@
{"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":"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":"按字段合并跨客户端会话更新,恢复时用服务器状态防止本地陈旧覆盖。"}}
+ {"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":"implemented","target":"rpc","semantic":"仅对当前用户和会话推进已读标记,不覆盖后到的更新。","implementation":{"handler":"apps/headless/src/chat/conversation-status-routes.mjs","test":"apps/headless/test/conversation-status-http.test.mjs"}}},
+ {"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":"按字段合并跨客户端会话更新,恢复时用服务器状态防止本地陈旧覆盖。","partial":{"scope":"其他登录确认已显示的会话后,当前 Web 工作台从列表修订通知重新读取已读水位;已存在的模型和归档偏好沿用各自的服务端版本。","remaining":"完整桌面或手机中转协议中的删除、成员与全部远端字段合并仍待实现,也未把 Web 登录视为手机客户端。","handler":"apps/desktop/src/workbench/conversation-status-reads.ts","test":"scripts/workbench/e2e-conversation-status-browser.mjs"}}}
]
},
{
diff --git a/scripts/workbench/container-conversation-status-docker.mjs b/scripts/workbench/container-conversation-status-docker.mjs
new file mode 100644
index 00000000..80a3a36f
--- /dev/null
+++ b/scripts/workbench/container-conversation-status-docker.mjs
@@ -0,0 +1,207 @@
+import { execFile } from 'node:child_process'
+import { randomUUID } from 'node:crypto'
+import { lstat, mkdtemp, readFile, realpath, rmdir } from 'node:fs/promises'
+import { machine, tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { CheckFailure, check } from './container-client-interactions-docker.mjs'
+import { probeProgram, providerOrigin } from './container-conversation-status-probe.mjs'
+
+export const imageSha = value => typeof value === 'string' && value.length === 71 && /^sha256:[a-f0-9]{64}$/u.test(value)
+const tag = 'deva-workbench:conversation-status-verify', cli = '/opt/deva/apps/headless/src/cli.mjs'
+const idPattern = /^[a-f0-9]{64}$/u, labelKey = 'deva.workbench.conversation-status'
+const same = (a, b) => JSON.stringify(a) === JSON.stringify(b)
+const empty = object => !Object.keys(object ?? {}).length
+const safePath = '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
+const imageEnv = {
+ PATH: safePath, NODE_ENV: 'production', DEVA_HOME: '/data', DEVA_HOST: '127.0.0.1', DEVA_PORT: '8787',
+ DEVA_MASTER_KEY_FILE: '/keys/master.key', DEVA_RUN_DIR: '/run/deva', DEVA_WEB_DIR: '/opt/deva/web'
+}
+const tmpfs = { '/tmp': 'rw,nosuid,nodev,noexec,mode=1777,size=64m', '/run/deva': 'rw,nosuid,nodev,noexec,mode=0700,uid=1000,gid=1000,size=4m' }
+const containerRoles = ['init', 'first', 'second'], volumeRoles = ['data', 'keys']
+const probeStages = new Set(['probe-transport', 'inputs', 'real-cli-ready', 'native-isolation', 'owner-authentication',
+ 'synthetic-model-and-one-turn', 'measured-vs-effective-model', 'authenticated-durable-read',
+ 'fresh-auth-old-cursor', 'fresh-snapshot-and-native-stamp'])
+
+async function verifyRunner(expectedImage) {
+ check(expectedImage === undefined || imageSha(expectedImage), 'Expected a literal prebuilt image SHA256')
+ const hosted = process.env.GITHUB_ACTIONS === 'true' && process.env.RUNNER_ENVIRONMENT === 'github-hosted' &&
+ process.env.RUNNER_OS === 'Linux' && process.env.RUNNER_ARCH === 'X64'
+ check(expectedImage || hosted, 'A disposable local runner requires --disposable-image sha256:<64 lowercase hex>')
+ check(process.platform === 'linux' && process.arch === 'x64' && machine() === 'x86_64' && process.getuid() > 0 &&
+ process.geteuid() === process.getuid() && process.versions.node.split('.')[0] === '22' &&
+ /^vendor_id\s*:\s*(?:GenuineIntel|AuthenticAMD|HygonGenuine)\s*$/mu.test(await readFile('/proc/cpuinfo', 'utf8')),
+ 'Expected a native Linux/amd64 non-root Node 22 runner')
+ const socket = await lstat('/var/run/docker.sock').catch(() => null)
+ check(socket?.isSocket() && socket.uid === 0, 'Expected the local root-owned Docker Engine Unix socket')
+}
+
+export async function productionGate(expectedImage, onCleanupFailure) {
+ await verifyRunner(expectedImage)
+ // An empty private Docker config and a fixed native socket exclude plugin contexts, auth stores, host env and proxies.
+ const root = await mkdtemp(join(await realpath(tmpdir()), 'deva-conversation-docker-'))
+ const rootStamp = await lstat(root, { bigint: true })
+ const project = `deva-conversation-${randomUUID()}`, label = `${labelKey}=${project}`
+ const name = role => `${project}-${role}`
+ const ids = new Map(), tokens = new Map(), volumeStamps = new Map()
+ let image
+
+ function docker(args, stage, input) {
+ return new Promise((resolve, reject) => {
+ const child = execFile('docker', ['--host=unix:///var/run/docker.sock', ...args], {
+ cwd: root, env: { PATH: '/usr/bin:/bin:/usr/local/bin', LANG: 'C.UTF-8', HOME: root, DOCKER_CONFIG: root },
+ encoding: 'utf8', timeout: 28_000, maxBuffer: 256 * 1024
+ }, (error, stdout, stderr) => {
+ if (!error) return resolve((args[0] === 'logs' ? stdout + stderr : stdout).trim())
+ const step = args[0] === 'exec' && /^conversation-status probe: ([a-z-]{1,48})\n?$/u.exec(stderr)?.[1]
+ const cause = error.code === 'ENOENT' ? 'Docker executable missing' : error.killed ? 'Docker command timed out' : 'Docker command failed'
+ reject(new CheckFailure(`${stage}: ${probeStages.has(step) ? step : cause}`))
+ })
+ child.stdin.on('error', () => {})
+ child.stdin.end(input === undefined ? undefined : JSON.stringify(input))
+ })
+ }
+ async function inspect(kind, value) {
+ const rows = JSON.parse(await docker([kind, 'inspect', value], `Inspect ${kind}`))
+ check(Array.isArray(rows) && rows.length === 1, `Expected one ${kind} inspection`)
+ return rows[0]
+ }
+ const list = async (kind, filter) => (await docker([kind, 'ls', ...(kind === 'container' ? ['-a', '--no-trunc'] : []), '-q', '--filter', filter],
+ `List scoped ${kind}`)).split('\n').filter(Boolean)
+ const nameFilter = (kind, role) => `name=^${kind === 'container' ? '/' : ''}${name(role)}$`
+ async function ownedVolume(role) {
+ const v = await inspect('volume', name(role)), stamp = [v.CreatedAt, v.Mountpoint]
+ check(v.Name === name(role) && v.Driver === 'local' && v.Scope === 'local' && empty(v.Options) &&
+ v.Labels?.[labelKey] === project && tokens.has(role) && v.Labels?.[labelKey + '.nonce'] === tokens.get(role) &&
+ Number.isFinite(Date.parse(stamp[0])) && stamp[1]?.startsWith('/') && (!volumeStamps.has(role) || same(volumeStamps.get(role), stamp)),
+ 'Volume identity changed')
+ return stamp
+ }
+ async function ownedContainer(id, role) {
+ check(idPattern.test(id), 'Invalid owned container identifier')
+ const c = await inspect('container', id)
+ const matched = containerRoles.find(kind => c.Name === '/' + name(kind))
+ check(matched && (!role || role === matched) && c.Id === id && c.Image === image.Id && c.Config.Labels?.[labelKey] === project &&
+ (!ids.has(matched) || ids.get(matched) === id), 'Container identity changed')
+ return c
+ }
+ const volumeArg = (role, ro) => `type=volume,source=${name(role)},destination=/${role}${ro ? ',readonly' : ''}`
+ async function create(role) {
+ const init = role === 'init'
+ check(!(await list('container', nameFilter('container', role))).length, 'Container name already exists')
+ for (const volume of volumeRoles) await ownedVolume(volume)
+ const provider = `DEVA_PROVIDER_ORIGINS=${providerOrigin}`
+ const id = await docker(['create', '--pull=never', '--name', name(role), '--label', label, '--platform', 'linux/amd64', '--network', 'none',
+ '--user', '1000:1000', '--read-only', '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges:true', '--init=false',
+ '--cgroupns=private', '--pids-limit', '128', '--log-driver', 'local', ...Object.entries(tmpfs).flatMap(([path, opts]) => ['--tmpfs', `${path}:${opts}`]),
+ '--mount', volumeArg('data', init), '--mount', volumeArg('keys', !init), ...(init ? [] : ['--env', provider]), image.Id,
+ ...(init ? ['init-key'] : [])], `Create ${role} CLI container`)
+ check(idPattern.test(id) && ![...ids.values()].includes(id), 'Fresh CLI identity unconfirmed')
+ ids.set(role, id)
+ const c = await ownedContainer(id, role), h = c.HostConfig
+ const env = init ? image.Config.Env : [...image.Config.Env, provider]
+ const command = init ? 'init-key' : 'serve'
+ check(c.State.Status === 'created' && c.Config.User === '1000:1000' && c.Path === 'node' && same(c.Args, [cli, command]) &&
+ same([...c.Config.Env].sort(), [...env].sort()) && h.NetworkMode === 'none' && h.ReadonlyRootfs === true && h.Privileged === false &&
+ h.Init === false && h.CgroupnsMode === 'private' && ![h.PidMode, h.IpcMode, h.UTSMode, h.UsernsMode].includes('host') &&
+ same(h.CapDrop, ['ALL']) && empty(h.CapAdd) && same(h.SecurityOpt, ['no-new-privileges:true']) && h.PidsLimit === 128 &&
+ !h.PublishAllPorts && [h.PortBindings, h.Binds, h.VolumesFrom, h.Devices, h.DeviceRequests, h.DeviceCgroupRules, h.GroupAdd].every(empty) &&
+ same(Object.entries(h.Tmpfs).sort(), Object.entries(tmpfs).sort()), 'Unexpected CLI command, environment or isolation')
+ const mounts = c.Mounts.filter(m => m.Type === 'volume')
+ for (const volume of volumeRoles) {
+ const [, path] = await ownedVolume(volume)
+ check(mounts.filter(m => m.Name === name(volume) && m.Source === path && m.Destination === '/' + volume && m.Driver === 'local' &&
+ m.RW === (volume === 'data' ? !init : init)).length === 1, 'Incorrect persistent volume or mode')
+ }
+ check(mounts.length === 2 && c.Mounts.every(m => m.Type === 'volume' || (m.Type === 'tmpfs' && Object.hasOwn(tmpfs, m.Destination))),
+ 'Unexpected mount or host bind')
+ return id
+ }
+ async function remove(id, role) {
+ const before = await ownedContainer(id, role)
+ if (before.State.Running) await docker(['stop', '--time', '10', id], 'Stop inspected owned CLI')
+ const after = await ownedContainer(id, role)
+ check(!after.State.Running, 'Owned container is still running')
+ if (role) {
+ check(after.State.Status === 'exited' && after.State.ExitCode === 0 && !after.State.OOMKilled, 'Expected clean production CLI exit')
+ const safeLog = role === 'init' ? 'Master key ready' : 'Workbench listening on 127.0.0.1:8787 for http://127.0.0.1:8787'
+ check(await docker(['logs', id], 'Verify production CLI logs') === safeLog, 'Unexpected production CLI log output')
+ }
+ await docker(['rm', id], 'Remove inspected owned CLI')
+ if (role) check(!(await list('container', nameFilter('container', role))).length, 'Owned CLI still exists after removal')
+ }
+ async function runProbe(role, input) {
+ const id = await create(role)
+ await docker(['start', id], `Start ${role} production serve`)
+ const c = await ownedContainer(id, role)
+ check(c.State.Running && c.RestartCount === 0 && Object.keys(c.NetworkSettings.Networks).every(s => s === 'none') &&
+ Object.values(c.NetworkSettings.Ports ?? {}).every(ports => !ports?.length), 'Unexpected production serve process or network')
+ const result = JSON.parse(await docker(['exec', '-i', id, 'node', '--input-type=module', '--eval', probeProgram, role], `Probe ${role} production serve`, input))
+ await remove(id, role)
+ return result
+ }
+ async function cleanup() {
+ if (!tokens.size) return
+ let clean = true
+ for (const id of await list('container', `label=${label}`).catch(() => { clean = false; return [] })) {
+ try { await remove(id) } catch { clean = false }
+ }
+ for (const volume of await list('volume', `label=${label}`).catch(() => { clean = false; return [] })) {
+ try {
+ const role = volumeRoles.find(kind => name(kind) === volume)
+ check(role && tokens.has(role), 'Unknown owned volume')
+ await ownedVolume(role)
+ await docker(['volume', 'rm', volume], 'Remove inspected owned volume')
+ } catch { clean = false }
+ }
+ for (const [kind, roles] of [['container', containerRoles], ['volume', volumeRoles]]) {
+ if ((await list(kind, `label=${label}`)).length) clean = false
+ for (const role of roles) if ((await list(kind, nameFilter(kind, role))).length) clean = false
+ }
+ check(clean, 'Cleanup could not verify zero residual owned resources')
+ }
+
+ try {
+ const engine = JSON.parse(await docker(['version', '--format', '{{json .Server}}'], 'Check local Docker engine'))
+ const engineMajor = /^(\d+)\.\d+\.\d+(?:[+-][A-Za-z0-9.+-]{1,40})?$/u.exec(engine.Version)?.[1]
+ check(engine.Os === 'linux' && engine.Arch === 'amd64' && Number(engineMajor) >= 28,
+ 'Expected local native Linux/amd64 Docker Engine 28+')
+ const actual = await inspect('image', tag), config = actual.Config
+ const env = Object.fromEntries(config.Env.map(line => [line.split('=', 1)[0], line.slice(line.indexOf('=') + 1)]))
+ check(actual.Os === 'linux' && actual.Architecture === 'amd64' && imageSha(actual.Id) && (!expectedImage || actual.Id === expectedImage) &&
+ Number.isSafeInteger(actual.Size) && actual.Size > 0 && same(config.Entrypoint, ['node', cli]) && same(config.Cmd, ['serve']) &&
+ config.User === 'node:node' && config.WorkingDir === '/opt/deva' && empty(config.Volumes) && !config.Healthcheck &&
+ config.Env.length === Object.keys(env).length && Object.entries(imageEnv).every(([k, v]) => env[k] === v) &&
+ Object.keys(env).every(k => Object.hasOwn(imageEnv, k) || k === 'NODE_VERSION' || k === 'YARN_VERSION') &&
+ /^22\.\d+\.\d+$/u.test(env.NODE_VERSION) && /^\d+\.\d+\.\d+$/u.test(env.YARN_VERSION), 'Expected exact prebuilt production runtime image and pinned ID')
+ image = actual
+ for (const role of volumeRoles) {
+ check(!(await list('volume', nameFilter('volume', role))).length, 'Volume name already exists')
+ const token = randomUUID(); tokens.set(role, token)
+ check(await docker(['volume', 'create', '--driver', 'local', '--label', label, '--label', `${labelKey}.nonce=${token}`, name(role)],
+ 'Create private named volume') === name(role), 'Volume creation unconfirmed')
+ volumeStamps.set(role, await ownedVolume(role))
+ }
+ const init = await create('init')
+ check(await docker(['start', '--attach', init], 'Run production key initialization') === 'Master key ready', 'Production key initialization unconfirmed')
+ await remove(init, 'init')
+ const first = await runProbe('first', {}), second = await runProbe('second', first)
+ check(second.verified === true && first.measured === second.measured && first.observed.updatedAt === second.readAt &&
+ first.evidence.core === second.core && first.evidence.reads[0] === second.readSha && new Set(ids.values()).size === 3,
+ 'Distinct restored CLI and unchanged native measurement/read stamps are unconfirmed')
+ await cleanup()
+ return { image: image.Id, bytes: image.Size, engine: engine.Version, init, first: ids.get('first'), second: ids.get('second'),
+ measured: second.measured, estimate: first.estimate, readAt: second.readAt, core: second.core, readSha: second.readSha }
+ } catch (error) {
+ try { await cleanup() } catch {
+ onCleanupFailure(`Cleanup unconfirmed for label ${label}: containers ${containerRoles.map(name).join(', ')}, volumes ${volumeRoles.map(name).join(', ')}.`)
+ }
+ throw error
+ } finally {
+ try {
+ const now = await lstat(root, { bigint: true })
+ check(await realpath(root) === root && now.isDirectory() && now.ino === rootStamp.ino && now.dev === rootStamp.dev &&
+ now.uid === BigInt(process.getuid()) && (now.mode & 0o777n) === 0o700n, 'Docker configuration directory identity changed')
+ await rmdir(root)
+ } catch { onCleanupFailure('Private Docker configuration directory cleanup is unconfirmed.') }
+ }
+}
diff --git a/scripts/workbench/container-conversation-status-probe.mjs b/scripts/workbench/container-conversation-status-probe.mjs
new file mode 100644
index 00000000..64062f83
--- /dev/null
+++ b/scripts/workbench/container-conversation-status-probe.mjs
@@ -0,0 +1,238 @@
+// The fixed probe is passed to `docker exec node --eval`, never mounted or installed.
+// In the local fixture the same logic runs against a scratch CLI and ephemeral loopback ports.
+export const providerOrigin = 'http://127.0.0.1:18787'
+
+export async function startModel(port) {
+ const { createServer } = await import('node:http')
+ const { once } = await import('node:events')
+ const key = 'container-status-synthetic-provider-key', model = 'fixture-primary'
+ const question = 'Synthetic container context question.', answer = 'Synthetic container context reply.'
+ const used = 2345
+ let calls = 0, failures = 0
+ const server = createServer((req, res) => {
+ calls++
+ void (async () => {
+ if (calls !== 1 || req.method !== 'POST' || req.url !== '/v1/chat/completions' ||
+ req.headers.authorization !== `Bearer ${key}` || req.headersDistinct.authorization?.length !== 1 || req.headers.cookie) throw Error()
+ const chunks = []; let length = 0
+ for await (const chunk of req) { length += chunk.length; if (length > 32_768) throw Error(); chunks.push(chunk) }
+ const body = JSON.parse(Buffer.concat(chunks).toString())
+ const user = body.messages?.filter(item => item.role === 'user')
+ if (!body.stream || body.model !== model || user?.length !== 1 || user[0].content !== question || body.tools?.length || body.functions?.length) throw Error()
+ const chunk = (delta, finish_reason = null) => ({ id: 'chatcmpl-container-status', object: 'chat.completion.chunk',
+ created: 1, model, choices: [{ index: 0, delta, finish_reason }] })
+ res.writeHead(200, { 'content-type': 'text/event-stream' })
+ const frames = [chunk({ content: answer }), chunk({}, 'stop'), {
+ ...chunk({}), choices: [], usage: { prompt_tokens: used, completion_tokens: 7, total_tokens: used + 7 }
+ }]
+ res.end(frames.map(frame => `data: ${JSON.stringify(frame)}\n\n`).join('') + 'data: [DONE]\n\n')
+ })().catch(() => { failures++; if (!res.headersSent) res.writeHead(400).end(); else res.destroy() })
+ })
+ server.listen(port, '127.0.0.1')
+ await once(server, 'listening')
+ return { origin: `http://127.0.0.1:${server.address().port}`, key, model, used, question, answer,
+ expectCalls: count => calls === count && failures === 0,
+ close() {
+ const closed = once(server, 'close')
+ server.close(); server.closeAllConnections()
+ return closed
+ } }
+}
+
+export async function probe({ phase, origin, data, keyFile, run, app, model, input }) {
+ let stage = 'inputs'
+ const check = ok => { if (!ok) throw Error() }
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b)
+ try {
+ const { createHash, randomBytes } = await import('node:crypto')
+ const { lstat, readFile, readdir, realpath, writeFile } = await import('node:fs/promises')
+ const { setTimeout: delay } = await import('node:timers/promises')
+ const { request } = await import('node:http')
+ const { requestControl } = await import(app + '/src/control/socket.mjs')
+ const first = phase === 'first', native = app === '/opt/deva/apps/headless'
+ const cookiePattern = /^deva-workbench-local=[A-Za-z0-9_-]{43}$/u
+ const tokenPattern = /^[A-Za-z0-9_-]{43}$/u
+ const passwordPattern = /^[A-Za-z0-9_-]{32}$/u
+ const sid = 'sess_packaged_status', readFilePath = data + '/read-state.json'
+ const sessionFile = `${data}/data/chats/${sid}.json`
+ const unrelated = 'sess_unrelated_keep', seed = '"sess_unrelated_keep" : 3.700e1'
+ const chat = `chats/${sid}`, reads = 'conversation-status/reads', read = chat + '/read-state', usage = chat + '/context-usage'
+ const time = n => Number.isSafeInteger(n) && n >= 0
+ const uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/u
+ const validObservation = value => time(value?.updatedAt) && value.cursor?.scope === `chat:${sid}` &&
+ uuid.test(value.cursor.epoch) && uuid.test(value.cursor.generation) && time(value.cursor.seq)
+ const observed = ({ state, cursor }) => ({ updatedAt: state.updatedAt, cursor })
+ const entry = (snap, readAt = null) => ({ id: sid, updatedAt: snap.state.updatedAt, readAt, unread: readAt === null })
+ const digest = bytes => createHash('sha256').update(bytes).digest('hex')
+ check((first || phase === 'second') && /^http:\/\/127\.0\.0\.1:\d{1,5}$/u.test(origin) &&
+ /^http:\/\/127\.0\.0\.1:\d{1,5}$/u.test(model.origin))
+ if (first) check(same(input, {}))
+ else check(passwordPattern.test(input.password) && cookiePattern.test(input.cookie) && tokenPattern.test(input.csrf) &&
+ validObservation(input.observed) && uuid.test(input.turnId) && input.measured === model.used)
+
+ let cookie, csrf
+ // Isolated loopback only; a one-shot Node HTTP connection has neither redirect handling nor inherited proxy configuration.
+ function http(path, method = 'GET', headers = {}, body) {
+ return new Promise((resolve, reject) => {
+ const req = request(origin + path, { method, headers, agent: false, signal: AbortSignal.timeout(4000) }, res => {
+ void (async () => {
+ const chunks = []; let length = 0
+ for await (const chunk of res) { length += chunk.length; check(length <= 128 * 1024); chunks.push(chunk) }
+ check(res.headers['content-type'] === 'application/json; charset=utf-8')
+ return { status: res.statusCode, cookie: res.headers['set-cookie']?.[0]?.split(';', 1)[0], body: JSON.parse(Buffer.concat(chunks)) }
+ })().then(resolve, reject)
+ })
+ req.once('error', reject)
+ req.end(body === undefined ? undefined : JSON.stringify(body))
+ })
+ }
+ async function api(path, { body, method = body === undefined ? 'GET' : 'POST', status = 200, auth = { cookie, csrf } } = {}) {
+ check(/^[a-z0-9_/-]+$/u.test(path))
+ const res = await http('/api/v1/' + path, method, {
+ ...(method === 'GET' ? {} : { origin, 'content-type': 'application/json', 'sec-fetch-site': 'same-origin' }),
+ ...(auth.cookie ? { cookie: auth.cookie } : {}), ...(auth.csrf ? { 'x-deva-csrf': auth.csrf } : {})
+ }, body)
+ check(res.status === status)
+ if (path === 'auth/claim' || path === 'auth/login') cookie = res.cookie
+ return res.body
+ }
+ async function waitFor(work) {
+ const deadline = performance.now() + 10_000
+ do {
+ const found = await work()
+ if (found) return found
+ await delay(50)
+ } while (performance.now() < deadline)
+ check(false)
+ }
+ async function privateFile(path, uid = process.getuid()) {
+ const info = await lstat(path, { bigint: true })
+ check(await realpath(path) === path && info.isFile() && info.uid === BigInt(uid) && info.nlink === 1n && (info.mode & 0o7777n) === 0o600n)
+ return { bytes: await readFile(path), stat: [info.dev, info.ino, info.mtimeNs, info.ctimeNs].map(String) }
+ }
+
+ stage = 'real-cli-ready'
+ await waitFor(async () => {
+ try { const res = await http('/readyz'); return res.status === 200 && res.body.status === 'ready' } catch { return false }
+ })
+ const key = await privateFile(keyFile)
+ check(key.bytes.length === 32 && key.bytes.some(n => n !== 0))
+ key.bytes.fill(0)
+ const core = digest(await readFile(app + '/dist/chat-core.mjs'))
+ if (native) {
+ stage = 'native-isolation'
+ check(process.platform === 'linux' && process.arch === 'x64' && process.versions.node.split('.')[0] === '22' &&
+ process.getuid() === 1000 && process.getgid() === 1000 && origin === 'http://127.0.0.1:8787' && model.origin === 'http://127.0.0.1:18787')
+ check((await readFile('/proc/1/cmdline', 'utf8')) === `node\0${app}/src/cli.mjs\0serve\0` &&
+ await realpath('/proc/1/exe') === '/usr/local/bin/node')
+ const status = await readFile('/proc/1/status', 'utf8')
+ check(/^Uid:\s+1000\s+1000\s+1000\s+1000$/mu.test(status) && /^Gid:\s+1000\s+1000\s+1000\s+1000$/mu.test(status) &&
+ /^NoNewPrivs:\s+1$/mu.test(status) && ['Inh', 'Eff', 'Prm', 'Bnd', 'Amb'].every(cap => new RegExp(`^Cap${cap}:\\s+0+$`, 'mu').test(status)))
+ const mounts = (await readFile('/proc/1/mountinfo', 'utf8')).split('\n').map(line => line.split(' '))
+ check([['/', 'ro'], ['/data', 'rw'], ['/keys', 'ro']].every(([mount, mode]) => mounts.some(row => row[4] === mount && row[5].split(',').includes(mode))) &&
+ same(await readdir('/sys/class/net'), ['lo']))
+ const dir = await lstat(data)
+ check(dir.isDirectory() && dir.uid === 1000 && dir.gid === 1000 && (dir.mode & 0o7777) === 0o700)
+ }
+
+ stage = 'owner-authentication'
+ check((await api('auth/state')).claimed === !first)
+ const password = first ? randomBytes(24).toString('base64url') : input.password
+ const staleAuth = first ? {} : { cookie: input.cookie, csrf: input.csrf }
+ check(same(await api(reads, { auth: staleAuth, status: 401 }), { error: 'auth' }))
+ const login = first
+ ? await api('auth/claim', { body: { password, credential: (await requestControl({ runDir: run, op: 'claim' })).credential } })
+ : await api('auth/login', { body: { password } })
+ csrf = login.csrf
+ check(cookiePattern.test(cookie) && tokenPattern.test(csrf) && cookie !== input.cookie && csrf !== input.csrf)
+ const provider = 'packaged-status-fixture', altModel = 'fixture-alternate'
+ const primary = `${provider}:${model.model}`, alternate = `${provider}:${altModel}`
+ const primaryWindow = 16_000, alternateWindow = 20_000
+ const context = (ref, source, used, window) => ({ modelRef: ref, usage: { used, estimated: source === 'estimate', window, trigger: null }, source, compaction: 'inactive' })
+ const meter = () => api(usage, { body: { model: null } })
+ const measured = context(primary, 'measured', model.used, primaryWindow)
+ const settings = async models => {
+ const { revision } = await api('settings')
+ return api('settings', { method: 'PATCH', body: { revision, set: { models } } })
+ }
+ const last = state => state.lastTurn?.turnId
+ let snap, estimate
+ if (first) {
+ stage = 'synthetic-model-and-one-turn'
+ await writeFile(readFilePath, `{\n ${seed}\n}\n`, { flag: 'wx', mode: 0o600 })
+ const installed = await settings({ activeModelId: primary, activeEffort: 'default', providers: [{ id: provider,
+ name: 'Synthetic container fixture', kind: 'custom', purpose: 'llm', accent: '#234567', adapter: 'openai',
+ apiHost: model.origin + '/v1', enabled: true, models: [[model.model, primaryWindow], [altModel, alternateWindow]].map(([id, contextWindow]) =>
+ ({ id, name: id, enabled: true, contextWindow, maxOutput: 512 })) }] })
+ const configured = await api('provider-keys/' + provider, { method: 'PUT', body: { value: model.key, revision: installed.revision } })
+ check(configured.available && model.expectCalls(0))
+ check((await api('chats', { body: { sessionId: sid } })).session?.id === sid)
+ check(same(await api(reads), { entries: [] }))
+ const ack = await api(chat + '/turns', { body: { clientRequestId: 'one-packaged-turn', text: model.question, model: null }, status: 202 })
+ check(ack.duplicate === false && typeof ack.turnId === 'string')
+ snap = await waitFor(async () => { const view = await api(chat); return !view.state.active && last(view.state) === ack.turnId && view })
+ check(snap.state.lastTurn.status === 'completed' && same(snap.state.messages.map(row => row.content), [model.question, model.answer]) && model.expectCalls(1))
+
+ stage = 'measured-vs-effective-model'
+ const before = await privateFile(sessionFile)
+ check(same(await meter(), measured))
+ await settings({ activeModelId: alternate })
+ const approx = await meter()
+ estimate = approx.usage?.used
+ check(Number.isSafeInteger(estimate) && estimate > 0 && estimate !== model.used && same(approx, context(alternate, 'estimate', estimate, alternateWindow)))
+ await settings({ activeModelId: primary })
+ const after = await privateFile(sessionFile)
+ check(same(await meter(), measured) && before.bytes.equals(after.bytes) && same(before.stat, after.stat) && model.expectCalls(1))
+
+ stage = 'authenticated-durable-read'
+ check(same(await api(reads), { entries: [entry(snap)] }))
+ check(same(await api(read, { body: observed(snap) }), { ...entry(snap, snap.state.updatedAt), changed: true }))
+ } else {
+ stage = 'fresh-auth-old-cursor'
+ check(same(await api(read, { auth: staleAuth, body: input.observed, status: 401 }), { error: 'auth' }))
+ snap = await api(chat)
+ check(snap.cursor.epoch !== input.observed.cursor.epoch && snap.state.updatedAt === input.observed.updatedAt && last(snap.state) === input.turnId &&
+ snap.state.lastTurn.status === 'completed' && same(snap.state.messages.map(row => row.content), [model.question, model.answer]))
+ check(same(await api(read, { body: input.observed, status: 409 }), { error: 'read_view_stale' }))
+ }
+
+ stage = 'fresh-snapshot-and-native-stamp'
+ check(validObservation(observed(snap)) && same(await api(chat), snap) &&
+ same(await api(reads), { entries: [entry(snap, snap.state.updatedAt)] }) && same(await meter(), measured))
+ const nativeReads = await privateFile(readFilePath), session = await privateFile(sessionFile)
+ const markers = JSON.parse(nativeReads.bytes.toString()), saved = JSON.parse(session.bytes.toString())
+ const receipt = saved._devaHeadlessConversationUsage
+ check(Number.isSafeInteger(markers[sid]) && markers[sid] === snap.state.updatedAt && markers[unrelated] === 37 &&
+ Object.keys(markers).length === 2 && nativeReads.bytes.includes(seed) &&
+ saved.lastInputTokens === model.used && saved._devaHeadlessTextTurns.requests.at(-1).turnId === last(snap.state) &&
+ receipt?.inputTokens === model.used && receipt.turnId === last(snap.state) && receipt.modelRef === primary && receipt.adapter === 'openai' &&
+ receipt.updatedAt === markers[sid] && receipt.digest === digest(JSON.stringify(saved.messages)))
+ const evidence = { core, key: key.stat, session: [digest(session.bytes), session.stat], reads: [digest(nativeReads.bytes), nativeReads.stat] }
+ if (!first) {
+ check(same(evidence, input.evidence))
+ check(same(await api(read, { body: observed(snap) }), { ...entry(snap, snap.state.updatedAt), changed: false }))
+ const after = await privateFile(readFilePath)
+ check(after.bytes.equals(nativeReads.bytes) && same(after.stat, nativeReads.stat))
+ }
+ if (native) check((await readFile('/proc/1/task/1/children', 'utf8')).trim() === '')
+ check(model.expectCalls(first ? 1 : 0))
+ return first ? { password, cookie, csrf, observed: observed(snap), turnId: last(snap.state), evidence, estimate, measured: model.used }
+ : { verified: true, measured: model.used, readAt: markers[sid], core, readSha: evidence.reads[0] }
+ } catch { throw Error(stage) }
+}
+
+export const probeProgram = `
+let stage = 'probe-transport';
+try {
+ const chunks = []; let bytes = 0;
+ for await (const chunk of process.stdin) { bytes += chunk.length; if (bytes > 8192) throw Error(); chunks.push(chunk); }
+ const input = JSON.parse(Buffer.concat(chunks).toString());
+ const model = await (${startModel.toString()})(18787);
+ try {
+ const result = await (${probe.toString()})({ phase: process.argv[1], origin: 'http://127.0.0.1:8787',
+ data: '/data', keyFile: '/keys/master.key', run: '/run/deva', app: '/opt/deva/apps/headless', model, input });
+ process.stdout.write(JSON.stringify(result));
+ } catch (error) { stage = error.message; throw Error(); }
+ finally { await model.close(); }
+} catch { process.stderr.write('conversation-status probe: ' + stage + '\\n'); process.exitCode = 1; }
+`
diff --git a/scripts/workbench/container-conversation-status.mjs b/scripts/workbench/container-conversation-status.mjs
new file mode 100644
index 00000000..e7d77b41
--- /dev/null
+++ b/scripts/workbench/container-conversation-status.mjs
@@ -0,0 +1,101 @@
+// Production Linux/amd64 container acceptance; independent of the Chrome and local HTTP gates.
+import { execFile, spawn } from 'node:child_process'
+import { access, mkdir, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { CheckFailure, check, privateRoot } from './container-client-interactions-docker.mjs'
+import { imageSha, productionGate } from './container-conversation-status-docker.mjs'
+import { probe, startModel } from './container-conversation-status-probe.mjs'
+
+const usage = 'Usage: node scripts/workbench/container-conversation-status.mjs [--fixture-only | --disposable-image sha256:<64 lowercase hex>]'
+const app = fileURLToPath(new URL('../../apps/headless', import.meta.url))
+const cli = join(app, 'src', 'cli.mjs')
+function options(args) {
+ if (!args.length) return {}
+ if (args.length === 1 && args[0] === '--fixture-only') return { fixtureOnly: true }
+ if (args.length === 2 && args[0] === '--disposable-image' && imageSha(args[1])) return { expectedImage: args[1] }
+ throw new CheckFailure(usage)
+}
+
+function localCli(args, root, env) {
+ return new Promise(resolve => execFile(process.execPath, [cli, ...args], { cwd: root, env, timeout: 5000, maxBuffer: 16384 },
+ (error, stdout, stderr) => resolve([error?.code ?? 0, stdout, stderr])))
+}
+
+async function localServe(root, env, work) {
+ const child = spawn(process.execPath, [cli, 'serve'], { cwd: root, env, stdio: ['ignore', 'pipe', 'pipe'] })
+ const closed = Promise.withResolvers(), ready = Promise.withResolvers()
+ let stdout = '', stderr = ''
+ child.once('error', () => { ready.resolve(false); closed.resolve(false) })
+ child.once('close', code => { ready.resolve(false); closed.resolve(code === 0) })
+ child.stdout.setEncoding('utf8').on('data', line => {
+ stdout = (stdout + line).slice(0, 1024)
+ const port = /^Workbench listening on 127\.0\.0\.1:(\d{1,5}) for http:\/\/127\.0\.0\.1:\1\n$/u.exec(stdout)?.[1]
+ if (port && Number(port) > 0) ready.resolve(`http://127.0.0.1:${port}`)
+ })
+ child.stderr.setEncoding('utf8').on('data', line => { stderr = (stderr + line).slice(0, 1024) })
+ const startup = setTimeout(() => ready.resolve(false), 10_000)
+ try {
+ const origin = await ready.promise
+ check(origin, 'Local fixture CLI did not start')
+ return await work(origin)
+ } finally {
+ clearTimeout(startup)
+ child.kill('SIGTERM')
+ const kill = setTimeout(() => child.kill('SIGKILL'), 5000)
+ const clean = await closed.promise
+ clearTimeout(kill)
+ check(clean && stderr === '', 'Local fixture CLI shutdown unconfirmed')
+ }
+}
+
+async function fixtureGate() {
+ check(process.platform === 'linux', 'The native read-state fixture requires Linux')
+ for (const core of ['provider', 'chat', 'library']) await access(join(app, 'dist', `${core}-core.mjs`)).catch(() => {
+ throw new CheckFailure('Build headless cores with pnpm --filter @deva/headless build')
+ })
+ const root = await privateRoot(), keyFile = join(root.path, 'master.key')
+ const [data, run, web] = ['data', 'run', 'web'].map(s => join(root.path, s))
+ try {
+ for (const dir of [data, run, web]) await mkdir(dir, { mode: 0o700 })
+ for (const [file, bytes] of Object.entries({ 'index.html': 'Synthetic CLI fixture',
+ 'workbench.js': '/* synthetic empty bundle */', 'manifest.json': JSON.stringify({ entry: { file: 'workbench.js', isEntry: true } }) })) {
+ await writeFile(join(web, file), bytes, { mode: 0o600, flag: 'wx' })
+ }
+ const env = { PATH: '/usr/bin:/bin', LANG: 'C.UTF-8', HOME: root.path, NODE_ENV: 'production', DEVA_HOME: data,
+ DEVA_MASTER_KEY_FILE: keyFile, DEVA_RUN_DIR: run, DEVA_WEB_DIR: web, DEVA_HOST: '127.0.0.1', DEVA_PORT: '0' }
+ const [invalid, , invalidError] = await localCli(['serve', '--unexpected'], root.path, env)
+ check(invalid === 1 && invalidError === 'Invalid serve options; see --help\n', 'Local CLI parser did not reject unknown flags')
+ const [code, keyMessage, keyError] = await localCli(['init-key'], root.path, env)
+ check(code === 0 && keyMessage === 'Master key ready\n' && keyError === '', 'Local CLI key initialization failed')
+ const model = await startModel(0)
+ try {
+ const runProbe = (phase, input) => localServe(root.path, { ...env, DEVA_PROVIDER_ORIGINS: model.origin }, async origin => {
+ // A fresh call counter on restore is represented by the delta of the same local fixture server.
+ const fixtureModel = phase === 'first' ? model : { ...model, expectCalls: count => model.expectCalls(1 + count) }
+ try { return await probe({ phase, input, origin, data, keyFile, run, app, model: fixtureModel }) }
+ catch (error) { throw new CheckFailure(`Local synthetic probe: ${error.message}`) }
+ })
+ const first = await runProbe('first', {}), second = await runProbe('second', first)
+ check(second.verified === true && model.expectCalls(1), 'Local restore evidence is incomplete')
+ return { measured: second.measured, estimate: first.estimate, readAt: second.readAt }
+ } finally { await model.close() }
+ } finally { await root.remove() }
+}
+
+let cleanupFailed = false
+try {
+ const { fixtureOnly, expectedImage } = options(process.argv.slice(2))
+ if (fixtureOnly) {
+ const { measured, estimate, readAt } = await fixtureGate()
+ console.log(`PASS fixture-only (local synthetic CLI; zero Docker operations, no packaged evidence): measured=${measured} estimate=${estimate} readAt=${readAt}`)
+ } else {
+ const e = await productionGate(expectedImage, message => { cleanupFailed = true; console.error(message) })
+ check(!cleanupFailed, 'Cleanup evidence is incomplete')
+ console.log(`PASS production conversation status: ${e.image} (${e.bytes} bytes; Linux/amd64 Engine ${e.engine}; Node 22 UID 1000); init=${e.init} serve=${e.first} restore=${e.second}`)
+ console.log(`One first-turn model call, zero restore calls; measured=${e.measured} estimate=${e.estimate} readAt=${e.readAt}; stale cookie=401 stale cursor after fresh login=409; chat-core SHA256=${e.core}, read-state SHA256=${e.readSha}; zero residual owned containers or volumes.`)
+ }
+} catch (error) {
+ console.error(`Conversation status gate: ${error instanceof CheckFailure ? error.message : 'verification failed'}`)
+ process.exitCode = 1
+}
diff --git a/scripts/workbench/conversation-status-ui.test.mjs b/scripts/workbench/conversation-status-ui.test.mjs
new file mode 100644
index 00000000..45d2541c
--- /dev/null
+++ b/scripts/workbench/conversation-status-ui.test.mjs
@@ -0,0 +1,459 @@
+import assert from 'node:assert/strict'
+import { readFile } from 'node:fs/promises'
+import { createRequire } from 'node:module'
+import { setImmediate } from 'node:timers/promises'
+import test from 'node:test'
+
+const require = createRequire(new URL('../../apps/desktop/package.json', import.meta.url))
+const ts = require('typescript')
+const react = require('react')
+const { renderToStaticMarkup } = require('react-dom/server')
+const src = new URL('../../apps/desktop/src/', import.meta.url)
+async function load(name, deps = {}, globals = {}) {
+ const code = ts.transpileModule(await readFile(new URL(name, src), 'utf8'), {
+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.ReactJSX }
+ }).outputText
+ const mod = { exports: {} }
+ new Function('require', 'module', 'exports', ...Object.keys(globals), code)(
+ key => Object.hasOwn(deps, key) ? deps[key] : require(key), mod, mod.exports, ...Object.values(globals))
+ return mod.exports
+}
+const transport = await load('workbench/transport.ts')
+const status = await load('workbench/conversation-status-transport.ts')
+const reads = await load('workbench/conversation-status-reads.ts')
+const chat = await load('workbench/chat-transport.ts')
+const { applyChatFrame } = await load('workbench/chat-stream.ts', { './chat-transport': chat })
+const readUI = await load('workbench/conversation-status-ui.tsx', {
+ './conversation-status-reads': reads, './conversation-status.css': {}
+})
+const i18n = { useI18n: () => ({ locale: 'en', t: (key) => ({ 'chat.panel.context': 'Context',
+ 'chat.panel.usage': '{used}/{window} ({pct})', 'chat.panel.approx': 'About {n}' })[key] ?? key }) }
+const contextHelpers = await load('renderer/src/redesign/context-usage.ts')
+const format = await load('shared/context.ts')
+const ring = await load('renderer/src/redesign/ContextRing.tsx', {
+ '../../../shared/context': format, '../i18n/i18n': i18n, './context-usage': contextHelpers, react: { ...react, useLayoutEffect: react.useEffect }
+})
+const meterDeps = { '../renderer/src/redesign/ContextRing': ring, '../renderer/src/i18n/i18n': i18n, './conversation-status-transport': status }
+
+const sid = 'ordinary-chat'
+const peer = 'another-chat'
+const model = 'model-provider:qwen3:8b'
+const changedModel = 'other-provider:qwen3:8b'
+const boot = { protocol: 1, version: '1', platform: 'linux', config: {}, expiresAt: 20, csrf: 'csrf-ui-test' }
+const enabled = { ...boot, capabilities: { conversationStatus: true } }
+const info = (id = sid, updatedAt = 12) => ({ id, updatedAt, compatibility: 'text', writable: true, title: 'Chat', model: null })
+const readMark = (id = sid, updatedAt = 12, unread = true) => ({ id, updatedAt, readAt: unread ? null : updatedAt, unread })
+const wireReport = (source, ref = model) => ({ modelRef: ref, usage: source === 'unavailable' ? null : {
+ used: source === 'none' ? null : 25_000, window: 100_000, estimated: source === 'estimate', trigger: null
+}, source, compaction: 'inactive' })
+const map = (...entries) => new Map(entries.map(entry => [entry.id, entry]))
+const cursor = (id = sid, seq = 8) => ({ scope: `chat:${id}`, seq,
+ epoch: '00000000-0000-4000-8000-000000000001', generation: '00000000-0000-4000-a000-000000000002' })
+const observation = (updatedAt = 12, id = sid) => ({ id, updatedAt, cursor: cursor(id) })
+const projection = (updatedAt = 12, patch = {}) => ({ status: 'ready', snapshot: { cursor: cursor(), state: {
+ ...info(sid, updatedAt), active: null, lastTurn: null, messages: [{ role: 'assistant', content: 'durable' }], ...patch
+} } })
+const json = (value, code = 200) => new Response(JSON.stringify(value), { status: code })
+const signal = new AbortController().signal
+function deferred() {
+ let resolve, reject
+ const promise = new Promise((yes, no) => { resolve = yes; reject = no })
+ return { promise, resolve, reject }
+}
+
+function queuedTransport(steps) {
+ return transport.createTransport(async (url, init) => {
+ assert.ok(steps.length, `Unexpected request: ${url}`)
+ const [method, path, body, result, code] = steps.shift()
+ assert.equal(url, `/api/v1${path}`)
+ assert.equal(init.method, method)
+ assert.deepEqual(init.body && JSON.parse(init.body), body)
+ assert.equal(init.credentials, 'same-origin')
+ assert.equal(init.mode, 'same-origin')
+ assert.equal(init.cache, 'no-store')
+ assert.equal(init.redirect, 'error')
+ assert.equal(init.referrerPolicy, method === 'POST' ? 'same-origin' : 'no-referrer')
+ assert.equal(init.headers['x-deva-csrf'], method === 'POST' ? boot.csrf : undefined)
+ if (path !== '/bootstrap') assert.equal(init.signal, signal)
+ return json(result, code)
+ })
+}
+
+test('only literal capability opts into owner-scoped no-store requests; exact cursor and full model reference go on the wire', async () => {
+ const steps = [
+ ['GET', '/bootstrap', undefined, { ...boot, capabilities: { conversationStatus: 'true', textChat: true } }],
+ ['GET', '/bootstrap', undefined, enabled],
+ ['GET', '/conversation-status/reads', undefined, { entries: [readMark()] }],
+ ['POST', `/chats/${sid}/read-state`, { updatedAt: 12, cursor: cursor() }, { ...readMark(sid, 12, false), changed: true }],
+ ['POST', `/chats/${sid}/context-usage`, { model: null }, wireReport('none')],
+ ['POST', `/chats/${sid}/context-usage`, { model }, wireReport('measured')]
+ ]
+ const base = queuedTransport(steps)
+ const previous = (await base.inspect()).bootstrap
+ assert.deepEqual(previous.capabilities, { textChat: true })
+ assert.equal(status.createConversationStatusTransport(base, previous), undefined)
+ const api = status.createConversationStatusTransport(base, (await base.inspect()).bootstrap)
+ assert.deepEqual(await api.reads(signal), map(readMark()))
+ await assert.rejects(api.mark({ ...observation(), cursor: cursor(peer) }, signal), /observation/)
+ for (const patch of [{ epoch: 'short' }, { generation: '00000000-0000-5000-8000-000000000001' },
+ { epoch: '00000000-0000-4000-7000-000000000001' }, { seq: Number.MAX_SAFE_INTEGER + 1 }]) {
+ await assert.rejects(api.mark({ ...observation(), cursor: { ...cursor(), ...patch } }, signal), /observation/)
+ }
+ await assert.rejects(api.mark({ ...observation(), id: '../ordinary-chat' }, signal), /scope/)
+ await assert.rejects(api.usage(sid, 'qwen3', signal), /model reference/)
+ assert.deepEqual(await api.mark({ ...observation(), cursor: { ...cursor(), messages: ['local extra'] } }, signal), { ...readMark(sid, 12, false), changed: true })
+ assert.deepEqual(await api.usage(sid, null, signal), wireReport('none'))
+ assert.deepEqual(await api.usage(sid, model, signal), wireReport('measured'))
+ assert.deepEqual(steps, [])
+})
+
+test('read maps cap rows, enforce native unread comparison, and reject mismatched revision acknowledgements', async () => {
+ const failures = [
+ { entries: [{ ...readMark(), transcript: [] }] }, { entries: [readMark(), readMark()] },
+ { entries: [{ ...readMark(), readAt: 12 }] }, { entries: [{ ...readMark(sid, 12, false), readAt: 11 }] },
+ { entries: [{ ...readMark(sid, 12, false), readAt: null }] },
+ { entries: Array.from({ length: 8193 }, (_, index) => readMark(`c${index}`)) }
+ ]
+ const marks = [
+ { ...readMark(peer, 12, false), changed: true },
+ { ...readMark(sid, 12, false), readAt: 13, changed: true },
+ { ...readMark(sid, 12, false), readAt: 11, changed: false },
+ { ...readMark(sid, 12, false), readAt: null, changed: true }
+ ]
+ const newer = { ...readMark(sid, 12, false), readAt: 13 }
+ const empty = { ...readMark(sid, 12, false), readAt: null, changed: false }
+ const wire = [...failures, { entries: [newer, { ...readMark(peer), readAt: 11 }] }, ...marks, { ...newer, changed: false }, empty]
+ const api = status.createConversationStatusTransport(transport.createTransport(async () => json(wire.shift())), enabled)
+ for (const _ of failures) await assert.rejects(api.reads(signal), /map|entry/)
+ assert.deepEqual(await api.reads(signal), map(newer, { ...readMark(peer), readAt: 11 }))
+ for (const _ of marks) await assert.rejects(api.mark(observation(), signal), /acknowledgement/)
+ assert.deepEqual(await api.mark(observation(), signal), { ...newer, changed: false })
+ assert.deepEqual(await api.mark(observation(), signal), empty)
+ assert.equal(wire.length, 0)
+})
+
+test('context grammar matches server UTF-8 input and exact unavailable, empty and measured projections', async () => {
+ const valid = ['A_v1.Name-1:Model Name : beta', 'P:星😀', `p:${'😀'.repeat(128)}`, `${'p'.repeat(96)}:${'x'.repeat(512)}`]
+ const bad = ['qwen3', '..:model', 'p: model', 'p:model ', 'p:', 'p:bad\u0001', 'p:a\u007fb', 'p:\ud800bad', 'p:bad\udc00',
+ `p:${'😀'.repeat(129)}`, `${'p'.repeat(97)}:model`, 'constructor:model', 'prototype:model', '__proto__:model']
+ for (const model of valid) assert.equal(status.fullModelRef(model), true, model)
+ for (const model of bad) assert.equal(status.fullModelRef(model), false, model)
+ const usage = (source, patch) => ({ ...wireReport(source), usage: { ...wireReport(source).usage, ...patch } })
+ const failures = [wireReport('estimate', changedModel), wireReport('unavailable'),
+ { ...wireReport('none'), modelRef: null, usage: null }, { ...wireReport('none'), usage: null }, usage('none', { used: 0 }),
+ usage('none', { window: 0 }), usage('none', { window: 20_000_001 }), usage('live', { trigger: 30 }),
+ usage('live', { used: 0 }), usage('measured', { used: 0 }), usage('measured', { used: 5.5 }),
+ usage('estimate', { used: 5.5 }), usage('estimate', { used: Number.MAX_SAFE_INTEGER + 1 })]
+ const maximum = usage('none', { window: 20_000_000 })
+ const zeroEstimate = usage('estimate', { used: 0 })
+ const wire = [...failures, wireReport('unavailable', null), maximum, zeroEstimate]
+ const api = status.createConversationStatusTransport(transport.createTransport(async () => json(wire.shift())), enabled)
+ for (const ref of bad) await assert.rejects(api.usage(sid, ref, signal), /model reference/)
+ for (const _ of failures) await assert.rejects(api.usage(sid, model, signal), /context report/)
+ assert.deepEqual(await api.usage(sid, model, signal), wireReport('unavailable', null))
+ assert.deepEqual(await api.usage(sid, model, signal), maximum)
+ assert.deepEqual(await api.usage(sid, model, signal), zeroEstimate)
+ assert.equal(wire.length, 0)
+})
+
+test('only the selected, durable, actually visible, idle ready revision is a read candidate', () => {
+ const row = info()
+ assert.deepEqual(reads.observeReading(row, projection(), true), observation())
+ assert.equal(reads.observeReading(row, projection(), false), undefined)
+ assert.equal(reads.observeReading(undefined, projection(), true), undefined)
+ const legacy = { compatibility: 'legacy_text', writable: false }
+ assert.deepEqual(reads.observeReading({ ...row, ...legacy }, projection(12, legacy), true), observation())
+ assert.equal(reads.matchingReadEntry({ entries: map(readMark()) }, { ...row, ...legacy }).unread, true)
+ for (const rowPatch of [{ archived: true }, { compatibility: 'unsupported' }, { id: 'task-worker' }]) {
+ assert.equal(reads.matchingReadEntry({ entries: map(readMark(rowPatch.id ?? sid)) }, { ...row, ...rowPatch }), undefined)
+ }
+ const variants = [
+ [{ ...row, archived: true }, projection()], [{ ...row, id: 'task-worker' }, projection()],
+ [{ ...row, compatibility: 'legacy_text' }, projection()], [{ ...row, compatibility: 'unsupported' }, projection()], [row, projection(11)],
+ [row, projection(12, { archived: true })], [row, projection(12, { compatibility: 'unsupported' })],
+ [row, { ...projection(), status: 'reconnecting' }], [row, projection(12, { id: peer })],
+ [row, projection(12, { active: { turnId: 'running' } })], [row, projection(12, { lastTurn: { status: 'running' } })],
+ [row, projection(12, { messages: [{ role: 'assistant', content: ' ' }] })], [row, projection(12, { messages: [] })],
+ [row, { status: 'ready', snapshot: { ...projection().snapshot, cursor: cursor(peer) } }]
+ ]
+ for (const [candidate, view] of variants) assert.equal(reads.observeReading(candidate, view, true), undefined)
+ const doc = { visibilityState: 'visible', hasFocus: () => true, fullscreenElement: null, querySelector: () => null }
+ const scroll = {
+ isConnected: true, scrollHeight: 1400, scrollTop: 1000, clientHeight: 400,
+ querySelectorAll: () => [{ getBoundingClientRect: () => ({ bottom: 250, top: 50, width: 200 }) }],
+ getBoundingClientRect: () => ({ top: 0, bottom: 400, width: 700 })
+ }
+ const visible = readUI.readViewInForeground
+ assert.equal(visible(doc, scroll), true)
+ assert.equal(visible({ ...doc, visibilityState: 'hidden' }, scroll), false)
+ assert.equal(visible({ ...doc, hasFocus: () => false }, scroll), false)
+ assert.equal(visible({ ...doc, querySelector: () => ({ modal: true }) }, scroll), false)
+ assert.equal(visible({ ...doc, fullscreenElement: { contains: () => false } }, scroll), false)
+ assert.equal(visible(doc, { ...scroll, scrollTop: 900 }), false)
+ assert.equal(visible(doc, { ...scroll, querySelectorAll: () => [] }), false)
+ assert.equal(visible(doc, { ...scroll, isConnected: false }), false)
+ assert.equal(visible(doc, { ...scroll, getBoundingClientRect: () => ({ top: 500, bottom: 900, width: 200 }) }), false)
+})
+
+test('fresh owner list snapshots replicate two-window marks and never write if an unrelated row is visible', async () => {
+ const requests = []
+ let backing = map(readMark(), readMark(peer))
+ const api = {
+ reads: async (signal) => { requests.push({ type: 'get', signal }); return new Map(backing) },
+ mark: async ({ id, updatedAt }) => {
+ requests.push({ type: 'post', id, updatedAt })
+ const ack = readMark(id, updatedAt, false)
+ backing = new Map(backing).set(id, ack)
+ return { ...ack, changed: true }
+ }
+ }
+ const first = reads.createConversationReads(api, assert.fail)
+ const second = reads.createConversationReads(api, assert.fail)
+ first.scope([], sid)
+ second.scope([info(), info(peer)], peer)
+ await setImmediate()
+ assert.equal(requests.filter(({ type }) => type === 'get').length, 1)
+ await second.mark(observation())
+ assert.equal(requests.some(({ type }) => type === 'post'), false)
+ first.scope([info(), info(peer)], sid)
+ await setImmediate()
+ await first.mark(observation())
+ await first.mark({ ...observation(), cursor: cursor(sid, 9) })
+ assert.deepEqual(requests.filter(({ type }) => type === 'post'), [{ type: 'post', id: sid, updatedAt: 12 }])
+ assert.equal(second.snapshot().entries.get(sid).unread, true)
+ second.scope([info(), info(peer)], peer) // Owner invalidation yields unchanged rows but a fresh session-list snapshot.
+ await setImmediate()
+ assert.equal(second.snapshot().entries.get(sid).unread, false)
+})
+
+test('ambiguous writes reconcile by authenticated GET without replay or consuming later arrivals; explicit Retry can confirm them', async () => {
+ for (const error of [new Error('response lost'), { status: 409, code: 'read_view_stale' }]) {
+ const attempts = []
+ let updatedAt = 12
+ let gets = 0
+ const ctl = reads.createConversationReads({
+ reads: async () => { gets++; return map(readMark(sid, updatedAt)) },
+ mark: async (value) => {
+ attempts.push(value)
+ if (attempts.length === 1) throw error
+ return { ...readMark(sid, updatedAt, false), changed: true }
+ }
+ }, assert.fail)
+ ctl.scope([info()], sid)
+ await setImmediate()
+ await ctl.mark(observation())
+ assert.equal(gets, 2)
+ assert.equal(ctl.snapshot().review, sid)
+ await ctl.mark(observation())
+ assert.equal(attempts.length, 1)
+ updatedAt = 13
+ ctl.scope([info(sid, updatedAt)], sid)
+ await setImmediate()
+ await ctl.mark(observation(13))
+ assert.equal(attempts.length, 1)
+ assert.equal(ctl.snapshot().entries.get(sid).unread, true)
+ ctl.retry(sid)
+ await setImmediate()
+ await ctl.mark(observation(13))
+ assert.deepEqual(attempts.map(request => request.updatedAt), [12, 13])
+ assert.equal(ctl.snapshot().entries.get(sid).unread, false)
+ }
+})
+
+test('switch and auth cleanup abort stale requests and preserve an honest missing state', async () => {
+ const queue = []
+ const writes = []
+ let expired = 0
+ const ctl = reads.createConversationReads({
+ reads: (signal) => { const pending = deferred(); queue.push({ signal, ...pending }); return pending.promise },
+ mark: (request, signal) => { const pending = deferred(); writes.push({ request, signal, ...pending }); return pending.promise }
+ }, () => expired++)
+ ctl.scope([info(), info(peer)], sid)
+ ctl.scope([info(), info(peer)], peer)
+ assert.equal(queue[0].signal.aborted, true)
+ queue[0].resolve(map(readMark()))
+ await setImmediate()
+ assert.equal(ctl.snapshot().phase, 'reading')
+ queue[1].resolve(map(readMark(peer)))
+ await setImmediate()
+ const marking = ctl.mark(observation(12, peer))
+ assert.equal(writes.length, 1)
+ ctl.scope([info(), info(peer)], sid)
+ assert.equal(writes[0].signal.aborted, true)
+ writes[0].resolve({ ...readMark(peer, 12, false), changed: true })
+ await marking
+ queue[2].reject({ status: 404 })
+ await setImmediate()
+ assert.equal(ctl.snapshot().phase, 'unavailable')
+ assert.equal(ctl.snapshot().entries.size, 0)
+ assert.equal(expired, 0)
+ ctl.retry(sid)
+ queue[3].reject({ status: 401 })
+ await setImmediate()
+ assert.equal(expired, 1)
+ ctl.retry(sid)
+ ctl.close()
+ assert.equal(queue[4].signal.aborted, true)
+ assert.equal(ctl.snapshot().phase, 'idle')
+})
+
+// Exercise layout-effect network dependencies without an installed browser/DOM test library.
+function effectHarness() {
+ let offset = 0
+ let effects = []
+ const slots = []
+ const hooks = {
+ useEffect: layout,
+ useLayoutEffect: layout,
+ useId: () => ':test:',
+ useRef: (value) => slots[offset++] ??= { current: value },
+ useState: (value) => {
+ const i = offset++
+ const slot = slots[i] ??= { value }
+ return [slot.value, next => { slot.value = typeof next === 'function' ? next(slot.value) : next }]
+ }
+ }
+ function layout(callback, deps) {
+ const slot = slots[offset++] ??= {}
+ if (!deps || !slot.deps || deps.some((dep, index) => !Object.is(dep, slot.deps[index]))) {
+ slot.deps = deps
+ effects.push(() => { slot.cleanup?.(); slot.cleanup = callback() })
+ }
+ }
+ return { hooks, render(fn, props) {
+ offset = 0
+ const value = fn(props)
+ const pending = effects
+ effects = []
+ pending.forEach(effect => effect())
+ return value
+ }, close() { slots.forEach(slot => slot.cleanup?.()) } }
+}
+
+test('the mounted read status checks visibility again after paint and never sends a superseded cursor', async () => {
+ const hooks = effectHarness()
+ const frames = new Map()
+ let frameId = 0
+ const notify = new Map()
+ const addEventListener = (event, callback) => notify.set(event, callback)
+ const removeEventListener = (event, callback) => { if (notify.get(event) === callback) notify.delete(event) }
+ const win = { addEventListener, removeEventListener,
+ requestAnimationFrame: (callback) => { frames.set(++frameId, callback); return frameId },
+ cancelAnimationFrame: (id) => frames.delete(id) }
+ const doc = { visibilityState: 'visible', hasFocus: () => true, fullscreenElement: null, querySelector: () => null,
+ addEventListener, removeEventListener }
+ function tick() {
+ const queued = [...frames.values()]
+ frames.clear()
+ queued.forEach(callback => callback())
+ }
+ const { DisplayedReadStatus } = await load('workbench/conversation-status-ui.tsx', {
+ './conversation-status-reads': reads, './conversation-status.css': {}, react: hooks.hooks
+ }, { window: win, document: doc })
+ let current = projection()
+ const marks = []
+ const base = { reads: { mark: async request => marks.push(request) }, locale: 'en', blocked: false,
+ atBottom: true, hasContent: true, row: info(), projection: projection(), current: () => current,
+ refresh: assert.fail, readView: { phase: 'ready', entries: map(readMark()) }, scroller: { current: {
+ isConnected: true, scrollHeight: 400, scrollTop: 0, clientHeight: 400,
+ querySelectorAll: () => [{ getBoundingClientRect: () => ({ top: 30, bottom: 150, width: 300 }) }],
+ getBoundingClientRect: () => ({ top: 10, bottom: 380, width: 500 })
+ } } }
+ const render = (props = {}) => hooks.render(DisplayedReadStatus, { ...base, ...props })
+ render({ blocked: true })
+ tick(); tick()
+ assert.deepEqual(marks, [])
+ render()
+ tick()
+ doc.visibilityState = 'hidden'
+ tick()
+ assert.deepEqual(marks, [])
+ doc.visibilityState = 'visible'
+ notify.get('visibilitychange')()
+ tick()
+ current = { ...current, snapshot: { ...current.snapshot, cursor: cursor(sid, 9) } }
+ tick()
+ assert.deepEqual(marks, [])
+ assert.equal(render({ projection: current, readView: { phase: 'reading', entries: map(readMark()) } }).props['data-state'], 'loading')
+ tick(); tick()
+ assert.deepEqual(marks, [])
+ render({ projection: current })
+ tick(); tick()
+ assert.deepEqual(marks, [{ ...observation(), cursor: cursor(sid, 9) }])
+ render({ projection: current, readView: { phase: 'ready', entries: map() } })
+ tick(); tick()
+ assert.equal(marks.length, 1)
+ const unavailable = render({ projection: current, readView: { phase: 'ready', entries: map() } })
+ assert.equal(unavailable.props['data-testid'], 'workbench-read-status')
+ assert.equal(unavailable.props['data-state'], 'unavailable')
+ assert.equal(unavailable.props.children[1].props.children, 'Retry')
+ hooks.close()
+ assert.equal(notify.size, 0)
+})
+
+const egress = (type, next, turnId = 'T', sessionId = sid) => chat.parseChatFrame(JSON.stringify({
+ t: 'event', type: 'chat', cursor: cursor(sessionId, next), sessionId, turnId, event: { type, text: type === 'text_delta' ? 'x' : 'drop this data', usage: 100_000 }
+}), sid)
+
+test('scoped context_changed only bumps a chat-local marker; no usage query per delta or stale model', async () => {
+ const harness = effectHarness()
+ const ctx = await load('workbench/conversation-status-context.tsx', { ...meterDeps, react: harness.hooks })
+ const groups = [{ p: { id: 'model-provider', apiHost: 'private address' }, models: [{ id: 'qwen3:8b', contextWindow: 100_000 }] },
+ { p: { id: 'other-provider' }, models: [{ id: 'qwen3:8b', contextWindow: 100_000 }] }]
+ assert.equal(ctx.contextTarget('qwen3:8b', groups, null), undefined) // Ollama model nickname alone is not a catalog ref.
+ assert.equal(ctx.contextTarget('missing-provider:qwen3:8b', groups, null), undefined)
+ const first = ctx.contextTarget(model, groups, null)
+ const second = ctx.contextTarget(changedModel, groups, null)
+ assert.notEqual(first.signature, second.signature)
+ assert.doesNotMatch(first.signature, /private address/)
+ const lookups = []
+ const props = {
+ api: { usage: (sid, model, signal) => { const task = deferred(); lookups.push({ sid, model, signal, ...task }); return task.promise } },
+ sid, modelReady: true, target: first, blocked: false, onExpired: assert.fail
+ }
+ let live = projection(12, { active: { turnId: 'T', text: '' } })
+ const render = (extra = {}) => harness.render(ctx.WorkbenchContextMeter, { ...props, projection: live, ...extra })
+ assert.equal(render().props['data-source'], 'loading')
+ assert.equal(lookups.length, 1)
+ const wrong = egress('context_changed', 9, 'old')
+ assert.deepEqual(wrong.event, { type: 'context_changed' })
+ assert.equal(egress('context_changed', 9, 'T', peer), null)
+ const states = state => ({ ...live, snapshot: state })
+ live = states(applyChatFrame(live.snapshot, wrong))
+ assert.equal(live.snapshot.contextVersion, undefined)
+ for (let seq = 10; seq < 20; seq++) {
+ live = states(applyChatFrame(live.snapshot, egress('text_delta', seq)))
+ render()
+ }
+ assert.equal(lookups.length, 1)
+ const stateBefore = live.snapshot.state
+ live = states(applyChatFrame(live.snapshot, egress('context_changed', 20)))
+ assert.equal(live.snapshot.contextVersion, 20)
+ assert.equal(live.snapshot.state, stateBefore)
+ render()
+ assert.equal(lookups.length, 2)
+ assert.equal(lookups[0].signal.aborted, true)
+ lookups[1].resolve(wireReport('live'))
+ await setImmediate()
+ assert.equal(render().props['data-testid'], 'workbench-context-meter')
+ live = projection(13, { lastTurn: { turnId: 'T', status: 'completed' } })
+ render()
+ assert.equal(lookups.length, 3)
+ render({ target: second })
+ assert.equal(lookups[2].signal.aborted, true)
+ assert.equal(lookups[3].model, changedModel)
+ lookups[3].resolve(wireReport('estimate', changedModel))
+ lookups[2].resolve(wireReport('measured'))
+ await setImmediate()
+ const meter = render({ target: second })
+ assert.equal(meter.props.children.type, ring.ContextRing)
+ assert.equal(meter.props.children.props.usage.estimated, true)
+ const card = renderToStaticMarkup(react.createElement(ring.ContextRing, { ...meter.props.children.props, open: true }))
+ assert.match(card, /