diff --git a/.agents/skills/release/SKILL.md b/.agents/skills/release/SKILL.md index 31f2f3ce9..440a69dce 100644 --- a/.agents/skills/release/SKILL.md +++ b/.agents/skills/release/SKILL.md @@ -34,7 +34,7 @@ description: 使用统一产品 Tag 或独立官网 Tag 发布 Vibeface,构建 `ci.yml` 保留 `23 */4 * * *`,UTC 槽位为 00:23、04:23、08:23、12:23、16:23、20:23。GitHub schedule 是 best effort,可能延迟或跳过,不保证每槽运行。仅 main schedule 的 `ci-gate` 成功后运行 `scripts/daily-nightly.py`;手动 CI 和普通 main push 不自动发布 Nightly。 -协调器只用 `GITHUB_TOKEN`,不需要 PAT,不创建版本分支或 PR,不合入 main。以原 schedule run 的精确 main SHA 作唯一 parent,生成普通机械版本提交,只改七个版本文件中的发行版本、Cargo.lock 两个本仓包版本及 Android、iOS 构建号,保留 marketing version、依赖和其他内容。共享验证器对比完整 tree,并运行 `cargo metadata --locked --no-deps`,不以路径白名单放行。 +协调器只用 `GITHUB_TOKEN`,不需要 PAT,不创建版本分支或 PR,不合入 main。以原 schedule run 的精确 main SHA 作唯一 parent,生成普通机械版本提交,只改七个版本文件中的发行版本、Cargo.lock 两个本仓包版本及 Android、iOS 构建号,保留 marketing version、依赖和其他内容。共享验证器对比完整 tree,并运行 `cargo metadata --locked --no-deps` 核对两个本仓包的清单版本(这条命令带 `--no-deps` 时不校验锁文件),不以路径白名单放行。 原 run 的 UTC `created_at` 向下取整到四小时批次,版本日期仍取该 run 的 `YYYYMMDD`。提交记录原 schedule run ID、批次和上一可信产品 Nightly 来源。移动构建号从 main 与上一可信 Nightly 取数值上界后加一;iOS 按数字分段比较,末段溢出时停止,不回绕。协调器全局串行。同批次、延迟或跨日恢复保持原版本、构建号、提交与 artifact;上一来源完整发布且 npm 成功、main 无新提交时跳过。部分 Tag、Release 或 npm 必须先恢复原来源,不新建版本覆盖。 @@ -80,7 +80,7 @@ GitHub 的不可变发布 Tag 规则保护产品 `v*`、官网与历史应用 Ta ## 处理现存 tag 与失败 - 同名本地或远端 tag 已存在:解析 annotated tag 的最终 commit 并核对 SHA。不同提交立即停止,禁止覆盖、强推、删除重建或改保护规则。同一提交的本地 tag 可直接推送;远端已存在则检查已有 Release 和关联 runs,已成功就报告已有结果。 -- 相同 tag、相同源码的构建因基础设施失败时,先对账并保留已有制品,再重跑失败任务。需要重新派发时使用 `gh workflow run release.yml --repo leaperone/vibeface --ref "$TAG" -f app="$APP" -f tag="$TAG" -F publish=true`。不重新打 tag,不覆盖已上传字节;若重建结果与已上传制品不同,停止重试并使用新版本。 +- 相同 tag、相同源码的构建因基础设施失败时,先对账并保留已有制品,再重跑失败任务。需要重新派发时使用 `gh workflow run release.yml --repo leaperone/vibeface --ref "$TAG" -f app="$APP" -f tag="$TAG" -F publish=true`。自动 Nightly 的 tag 不重新派发:协调器要求每个 tag 只有一个 release run,出现第二个 run 就判定该来源未完成并停止,只重跑原 run 的失败 job。不重新打 tag,不覆盖已上传字节;若重建结果与已上传制品不同,停止重试并使用新版本。 - 修复源码必须走新 PR 和新版本、新 tag。构建中的同一 Release 允许追加其他已校验平台的附件;已公开字节和 tag 不覆盖、不删除。回滚也通过新版本交付修正。 - 推送或发布返回结果未知时,先查询远端 tag、Release 和 Actions 对账,再决定下一步。不要直接重发。 diff --git a/.gitignore b/.gitignore index 0623e18ce..198fb0ebf 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,5 @@ node_modules/ .e2e/summary.md .e2e/logs/ .e2e/videos/ +__pycache__/ +.DS_Store diff --git a/.preflight.toml b/.preflight.toml index 0194dc3eb..c6a5e87f5 100644 --- a/.preflight.toml +++ b/.preflight.toml @@ -8,8 +8,8 @@ build = "python3 -c 'import ast,pathlib; [ast.parse(pathlib.Path(p).read_text()) [[domain_check]] name = "Rust workspace" -trigger_paths = ["crates/delivery/**", "apps/core/src/**", "apps/cli/src/**", "crates/control/src/**", "crates/bridge/src/**", "crates/protocol/src/**", "crates/secure/src/**", "crates/*/Cargo.toml", "apps/core/Cargo.toml", "apps/cli/Cargo.toml", "apps/core/build.rs", "apps/core/migrations/**", "apps/core/schema.hcl", "Cargo.toml", "Cargo.lock", "rust-toolchain*", ".cargo/**"] -command = "cargo fmt --all -- --check && python3 scripts/ci.py test --tier fast --packages vibeface-protocol vibeface-bridge vibeface-secure vibeface-core vibeface-control vibeface vibeface-delivery && cargo clippy --workspace --all-targets --locked -- -D warnings" +trigger_paths = ["crates/delivery/**", "apps/core/src/**", "apps/cli/src/**", "crates/control/src/**", "crates/bridge/src/**", "crates/protocol/src/**", "crates/secure/src/**", "crates/secure-ffi/**", "crates/*/tests/**", "apps/core/tests/**", "crates/*/Cargo.toml", "apps/core/Cargo.toml", "apps/cli/Cargo.toml", "apps/core/build.rs", "apps/core/migrations/**", "apps/core/schema.hcl", "Cargo.toml", "Cargo.lock", "rust-toolchain*", ".cargo/**"] +command = "cargo fmt --all -- --check && python3 scripts/ci.py test --tier fast --packages vibeface-protocol vibeface-bridge vibeface-secure vibeface-core vibeface-control vibeface vibeface-delivery vibeface-secure-ffi && cargo clippy --workspace --all-targets --locked -- -D warnings" [[domain_check]] name = "Delivery proof and settlement" diff --git a/Cargo.lock b/Cargo.lock index bd0abbb57..c5b0d601e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1522,9 +1522,9 @@ dependencies = [ [[package]] name = "ctutils" -version = "0.4.3" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03bb0e1cc970d482d121d9a1744999169b69a07470b3d644a7894e53fcaf4574" +checksum = "12218662ccac37d9714f2191252553d67585b97df8c839cbe49e0bde278dc865" dependencies = [ "cmov", ] @@ -1919,7 +1919,6 @@ checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" dependencies = [ "curve25519-dalek 4.1.3", "ed25519 2.2.3", - "rand_core 0.6.4", "serde", "sha2 0.10.9", "subtle", @@ -6689,7 +6688,6 @@ name = "vibeface" version = "0.0.1-nightly.20261110.3" dependencies = [ "anyhow", - "base64 0.22.1", "clap", "crossterm", "flate2", @@ -6704,9 +6702,7 @@ dependencies = [ "sha2 0.10.9", "tar", "tokio", - "tokio-tungstenite 0.28.0", "toml 0.9.12+spec-1.1.0", - "tracing", "uuid", "vibeface-bridge", "vibeface-control", @@ -6743,7 +6739,6 @@ dependencies = [ "anyhow", "futures-util", "hex", - "libc", "rand 0.8.8", "reqwest 0.12.28", "serde", @@ -6773,7 +6768,6 @@ dependencies = [ "chacha20poly1305", "clap", "ed25519-dalek 2.2.0", - "flate2", "futures-util", "hex", "hyper", @@ -6795,7 +6789,6 @@ dependencies = [ "serde_json", "sha2 0.10.9", "socket2", - "tar", "tokio", "tokio-rustls", "tokio-tungstenite 0.28.0", diff --git a/Cargo.toml b/Cargo.toml index 978dadf67..0c9d22e97 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,7 +15,7 @@ axum = { version = "0.8", features = ["ws"] } clap = { version = "4", features = ["derive", "env"] } flate2 = "1" futures-util = { version = "0.3", features = ["sink"] } -ed25519-dalek = { version = "2", features = ["rand_core"] } +ed25519-dalek = "2" hex = "0.4" iroh = "=1.3.0" iroh-relay = { version = "=1.3.0", features = ["server"] } diff --git a/README.md b/README.md index 6a27ab6cf..4062afa39 100644 --- a/README.md +++ b/README.md @@ -136,14 +136,18 @@ The platform package is written to `.artifacts/packages/`. See [source setup](pa │ ├── app/ # Web app │ ├── cli/ # Command line │ ├── core/ # Node service +│ ├── desktop/ # Desktop app │ ├── mobile/ # iOS and Android apps │ └── www/ # Public website ├── crates/ # Shared Rust libraries ├── packages/ │ ├── client/ # Shared app client │ ├── docs/ # User and developer guides +│ ├── secure-native/ # Rust crypto bindings for the mobile apps │ └── theme/ # Shared styles +├── config/ # Official public node address ├── contracts/ # Experimental file delivery contracts +├── deploy/ # Container deployment for the official services ├── scripts/ # Build, package, and verification tools ├── tests/ # Fixtures and end-to-end tests └── install.sh # Package installer diff --git a/README.zh-CN.md b/README.zh-CN.md index e59daf2c7..6a559eed3 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -8,7 +8,7 @@ [![CI](https://github.com/leaperone/vibeface/actions/workflows/ci.yml/badge.svg)](https://github.com/leaperone/vibeface/actions/workflows/ci.yml) [![Release](https://img.shields.io/github/v/release/leaperone/vibeface?include_prereleases&label=release)](https://github.com/leaperone/vibeface/releases) -[![Platforms](https://img.shields.io/badge/platform-macOS%20arm64%20%7C%20Linux%20x64%20%7C%20Linux%20arm64-lightgrey)](packages/docs/install.md) +[![Platforms](https://img.shields.io/badge/platform-macOS%20arm64%20%7C%20Windows%20x64%20%7C%20Linux%20x64%20%7C%20Linux%20arm64-lightgrey)](packages/docs/install.md) @@ -136,14 +136,18 @@ bash scripts/package-node.sh │ ├── app/ # 网页应用 │ ├── cli/ # 命令行 │ ├── core/ # Node 本机服务 +│ ├── desktop/ # 桌面应用 │ ├── mobile/ # iOS 和 Android 应用 │ └── www/ # 公共网站 ├── crates/ # 共享 Rust 库 ├── packages/ │ ├── client/ # 共享应用客户端 │ ├── docs/ # 用户和开发者指南 +│ ├── secure-native/ # 移动应用使用的 Rust 加密绑定 │ └── theme/ # 共享样式 +├── config/ # 官方公共节点地址 ├── contracts/ # 实验性文件交付合约 +├── deploy/ # 官方服务的容器部署 ├── scripts/ # 构建、打包和验证工具 ├── tests/ # 测试夹具和端到端测试 └── install.sh # 安装脚本 diff --git a/apps/app/components.json b/apps/app/components.json index c218fd395..f7f12bf48 100644 --- a/apps/app/components.json +++ b/apps/app/components.json @@ -14,9 +14,9 @@ "rtl": false, "aliases": { "components": "#components", - "utils": "#lib/utils", + "utils": "@/lib/utils", "ui": "#components/ui", - "lib": "#lib", + "lib": "@/lib", "hooks": "#hooks" }, "menuColor": "default", diff --git a/apps/app/package.json b/apps/app/package.json index 103813596..2b5a4ebc0 100644 --- a/apps/app/package.json +++ b/apps/app/package.json @@ -3,11 +3,8 @@ "private": true, "type": "module", "imports": { - "#/*": "./src/*", "#components/*": "./src/components/*", - "#hooks/*": "./src/lib/hooks/*", - "#lib/*": "./src/lib/*", - "#lib/utils": "./src/lib/utils.ts" + "#hooks/*": "./src/lib/hooks/*" }, "scripts": { "dev": "vite dev --port 3000", diff --git a/apps/app/src/components/app/bot-face.tsx b/apps/app/src/components/app/bot-face.tsx index 64d945965..fcbc20b6e 100644 --- a/apps/app/src/components/app/bot-face.tsx +++ b/apps/app/src/components/app/bot-face.tsx @@ -60,7 +60,7 @@ function apply(frame: Frame, parts: { g: SVGGElement; ring: SVGPathElement; body const transformOf = (frame: Frame) => `translate(${50 + frame.dx} ${50 + frame.dy}) rotate(${frame.rotate}) scale(${frame.scale}) translate(-50 -50)` /** Who a face belongs to: its id gives what `avatar` leaves out. */ -export type FaceBot = Pick +type FaceBot = Pick /** A bot's face, picked by its id and avatar and moving with its mood. Hidden from screen readers: the name next to it says who, and lists say the mood. `halo`: a still glow in the bot's tint behind the face, 1.8 times its size. `still` draws one frame and leaves the clock, for previews. */ export function BotFace({ bot, mood, size, halo, still, className }: { bot: FaceBot; mood: Mood; size: number; halo?: string; still?: boolean; className?: string }) { diff --git a/apps/app/src/features/chat/conversation-screen.tsx b/apps/app/src/features/chat/conversation-screen.tsx index 27ab4d073..374d017bb 100644 --- a/apps/app/src/features/chat/conversation-screen.tsx +++ b/apps/app/src/features/chat/conversation-screen.tsx @@ -307,7 +307,6 @@ export function ConversationScreen({ missing = false, active }: { missing?: bool hint={notice} reason={reason} disabled={sendDisabled} - busy={false} sendLabel={intent === 'defer' ? '保存为稍后处理' : intent === 'new_task' ? '发送为新任务' : targetBusy ? '补充当前工作' : '发送'} tools={} onStop={workspace.writable && (inputTarget.kind === 'bot_main' ? stopJob : targetBusy) ? () => { setSendError(null); workspace.stopInputTarget({ target: inputTarget }).catch(setSendError) } : undefined} diff --git a/apps/app/src/features/chat/elements/chat.tsx b/apps/app/src/features/chat/elements/chat.tsx index b32d3e118..b00ae25e2 100644 --- a/apps/app/src/features/chat/elements/chat.tsx +++ b/apps/app/src/features/chat/elements/chat.tsx @@ -18,9 +18,6 @@ export type ChatEntry = | { key: string; anchor?: boolean; message: ChatMessage; conversationId?: string; schedule?: string; retry?: () => Promise; detail?: string } | { key: string; anchor?: undefined; node: ReactNode } -/** Tasks one turn started stack as a group instead of spacing out like separate turns. */ -const stacked = (entry: ChatEntry, previous: ChatEntry) => entry.key.startsWith('task:') && previous.key.startsWith('task:') - /** Opening a chat with 新消息 brings it into view. */ function ToUnread({ shown }: { shown: boolean }) { const { scrollToMessage } = useMessageScroller() @@ -67,7 +64,7 @@ export function Chat({ entries, empty }: { entries: ChatEntry[]; empty: ReactNod {/* Room for a toast over the composer, so the last card can scroll clear of it. */} {entries.map((entry, index) => ( - 0 && (stacked(entry, entries[index - 1]) ? 'mt-2' : 'mt-6'), entered.current.has(entry.key) && 'message-enter')}> + 0 && 'mt-6', entered.current.has(entry.key) && 'message-enter')}> {'message' in entry ? : entry.node} ))} diff --git a/apps/app/src/features/chat/elements/prompt-input.tsx b/apps/app/src/features/chat/elements/prompt-input.tsx index 0e5d08108..5e329114d 100644 --- a/apps/app/src/features/chat/elements/prompt-input.tsx +++ b/apps/app/src/features/chat/elements/prompt-input.tsx @@ -1,6 +1,5 @@ import { useId, useLayoutEffect, useRef, useState, type ChangeEvent, type KeyboardEvent, type MouseEvent, type ReactNode } from 'react' import { ArrowUpIcon, CircleAlertIcon, PaperclipIcon, SquareIcon, XIcon } from 'lucide-react' -import { Spinner } from '@/components/ui/spinner' import { cn } from '@/lib/utils' import { isSubmitKey } from '@vibeface/client/chat/protocol.ts' import { attachmentLimit } from '@vibeface/client/workspace/model.ts' @@ -18,7 +17,6 @@ export function PromptInput({ hint, reason, disabled, - busy, onChange, onSubmit, onStop, @@ -37,7 +35,6 @@ export function PromptInput({ hint: string reason: string disabled: boolean - busy: boolean onChange: (value: string) => void onSubmit: () => void onStop?: () => void @@ -66,7 +63,7 @@ export function PromptInput({ // Caught on pick: the upload would only refuse it after the person pressed Send. const unfits = (file: File) => !file.size || file.size > attachmentLimit const unfit = files.find(unfits) - const sendable = !disabled && !busy && drafting && !unfit + const sendable = !disabled && drafting && !unfit const limit = `${attachmentLimit / 2 ** 20} MiB` const note = disabled && reason ? reason : hint // The box sizes itself to the text (field-sizing), already at its new height when this runs; CSS cannot ease @@ -126,14 +123,14 @@ export function PromptInput({ {onFiles ? <> { onFiles([...files, ...event.target.files ?? []]); event.target.value = '' }} /> - pickerRef.current?.click()}> + pickerRef.current?.click()}> {open && files.map((file, index) => {unfits(file) ? : null} - + )} : null} {tools} @@ -146,14 +143,13 @@ export function PromptInput({ variant="default" size="icon-sm" disabled={!sendable} - aria-busy={busy || undefined} aria-label={sendLabel} title={sendLabel} style={sendable && tint ? { backgroundColor: tint.fill, color: tint.ink } : undefined} className={cn('size-9 rounded-full max-md:size-11', sendable ? 'hover:opacity-88' : 'bg-muted text-muted-foreground disabled:opacity-100')} onMouseDown={keepFocus} > - {busy ? diff --git a/apps/app/src/features/devices/ai-settings.tsx b/apps/app/src/features/devices/ai-settings.tsx index 9b8d9ee3c..405989446 100644 --- a/apps/app/src/features/devices/ai-settings.tsx +++ b/apps/app/src/features/devices/ai-settings.tsx @@ -12,7 +12,7 @@ import { useWorkspace } from "@vibeface/client/workspace/context.tsx" import { terms } from "@/lib/glossary" import { authenticationSourceLabels, canSetProviderEnvironment, localProviderIds, availability, summaryReadiness, botOnChange, folderSuggestions, type Availability, messageOf, modelTyped, parseAppServerLink, parseNodeSettings, parseProvider, probeIssueText, effortOptions, type ModelChoice, providerGroups, providerNames, providerObservationLabels, providerObservationStates, providerIds, type BackupPolicy, type AppServer, type AppServerLink, type AppServerMode, type ManagerSettings, type NodeSettings, type NodeSettingsResponse, type ProviderChange, type ProviderId, type ProviderIssue, type ProviderStatus } from "@vibeface/client/lib/node.ts" -export const docs = "https://github.com/leaperone/vibeface/blob/main/packages/docs/" +const docs = "https://github.com/leaperone/vibeface/blob/main/packages/docs/" export const providerIcons: Record = { codex: SquareTerminal, cursor: MousePointer2, claude: Asterisk, pi: Pi, opencode: Braces } const states: Record = { ready: { label: "可用", tone: "success", icon: CircleCheck }, diff --git a/apps/app/src/features/devices/triage-settings.tsx b/apps/app/src/features/devices/triage-settings.tsx index cf12d48cf..86b142042 100644 --- a/apps/app/src/features/devices/triage-settings.tsx +++ b/apps/app/src/features/devices/triage-settings.tsx @@ -72,7 +72,7 @@ export function TriageSettings() { // Until a chat is connected there is nothing to forward, so only connecting shows. const connected = Boolean(settings.webhook_url) - const webhookForm =
{ event.preventDefault(); void save("webhook", { webhook_url: url }, secret ? { webhook_secret: secret } : {}).then(() => setSecret("")) }}> + const webhookForm = { event.preventDefault(); void save("webhook", { webhook_url: url }, secret ? { webhook_secret: secret } : {}).then((result) => { if (result !== null) setSecret("") }) }}>

diff --git a/apps/app/src/features/identity/recovery-controls.tsx b/apps/app/src/features/identity/recovery-controls.tsx index 2aa45b148..1a7133b4f 100644 --- a/apps/app/src/features/identity/recovery-controls.tsx +++ b/apps/app/src/features/identity/recovery-controls.tsx @@ -197,7 +197,7 @@ export function SaveRecoveryFile({ code, saved, onSaved, download, busy = false * person confirms it is kept apart from its password, which drops the copy. * `landing`: where the focus goes once confirming takes the file, and the box ticked, off the page. */ -export function UnsavedRecoveryFile({ landing }: { landing(): HTMLElement | null | undefined }) { +function UnsavedRecoveryFile({ landing }: { landing(): HTMLElement | null | undefined }) { const { unsavedRecovery: file, downloadUnsavedRecovery, forgetUnsavedRecovery } = useDevice() const [error, setError] = useState('') if (!file) return null diff --git a/apps/app/src/features/workspace/channels.tsx b/apps/app/src/features/workspace/channels.tsx index a5f334a7a..6b7101b66 100644 --- a/apps/app/src/features/workspace/channels.tsx +++ b/apps/app/src/features/workspace/channels.tsx @@ -19,7 +19,7 @@ export function ChannelsOverview() { return

与我的 Bot 协作

让我的多个 Bot 围绕同一件事协作。

{channels.length ?
    {channels.map((channel) =>
  • {channel.purpose ? {channel.purpose} : null}{channel.members.length} 个 Bot · 默认协调 {workspace.bots.find((bot) => bot.bot_id === channel.coordinator_bot)?.name ?? 'Bot 未加载'}
  • )}
: setCreating(true)}>新频道 : undefined} />} - + {creating ? : null}
} diff --git a/apps/app/src/features/workspace/collaboration-panel.tsx b/apps/app/src/features/workspace/collaboration-panel.tsx index 938fe9157..517761a2a 100644 --- a/apps/app/src/features/workspace/collaboration-panel.tsx +++ b/apps/app/src/features/workspace/collaboration-panel.tsx @@ -13,7 +13,7 @@ import type { ConversationPayload, ManagerJob, SessionHandoff, SentBotMessage } import { cn } from "@/lib/utils" /** A read-only view of this conversation's local scheduler and Bot-to-Bot records. */ -export type CollaborationPanelProps = { data: ConversationPayload; botId: string; className?: string } +type CollaborationPanelProps = { data: ConversationPayload; botId: string; className?: string } function schedulerTone(state: string): Tone { if (state === "failed" || state === "interrupted") return "danger" diff --git a/apps/app/src/features/workspace/context-panel.tsx b/apps/app/src/features/workspace/context-panel.tsx index 77d761b4b..b2dd3cc22 100644 --- a/apps/app/src/features/workspace/context-panel.tsx +++ b/apps/app/src/features/workspace/context-panel.tsx @@ -7,7 +7,7 @@ import { Button } from "@/components/ui/button" import { Details, SettingsGroup, SettingsRow, StatusPill, useAction, type Tone } from "@/components/app/kit" import { Textarea } from "@/components/ui/textarea" import { Input } from '@/components/ui/input' -import { messageOf } from "@vibeface/client/lib/node.ts" +import { messageOf, providerNames } from "@vibeface/client/lib/node.ts" import { newId } from "@vibeface/client/workspace/storage.ts" import { memoryBase, memoryResultLabel, memorySaved, memorySyncConflictLabel, type MemoryControls } from "@vibeface/client/workspace/memory.ts" import { formatWhen, changeTitle, scheduleFrequency } from "@vibeface/client/workspace/bot-settings.ts" @@ -28,7 +28,6 @@ type ContextPanelProps = { memory: MemoryControls } -const continuityProviderLabels: Record = { codex: "Codex", cursor: "Cursor", claude: "Claude Code", pi: "pi", opencode: "opencode" } export function ContextPanel({ bot, data, nodes, connected, onBack, memory }: ContextPanelProps) { const workspace = useWorkspace() @@ -289,7 +288,7 @@ export function MemorySummary({ settings, context, memory }: { settings: BotSett } function providerLabel(provider: string) { - return continuityProviderLabels[provider] ?? provider + return (providerNames as Record)[provider] ?? provider } function ContinuityLayer({ step, label, detail, tone, status }: { step: string; label: string; detail: string; tone: Tone; status: string }) { @@ -365,4 +364,3 @@ function CheckSummary({ check }: { check: CoordinationCheck }) { } -export type { ContextPanelProps } diff --git a/apps/app/src/features/workspace/entry-url.test.ts b/apps/app/src/features/workspace/entry-url.test.ts index 40b348146..3309475d0 100644 --- a/apps/app/src/features/workspace/entry-url.test.ts +++ b/apps/app/src/features/workspace/entry-url.test.ts @@ -2483,9 +2483,8 @@ test('both task overviews preserve known records, show their coverage and only n assert.match(componentText(elements), /总览已截断/) assert.match(componentText(elements), /本次总览未返回 1 项任务/) assert.match(componentText(elements), /本次总览未返回 2 项问题/) - assert.doesNotMatch(componentText(elements), /另有.*未列出/) assert.match(componentText(elements), /尚未读取其他设备的后台工作/) - assert.doesNotMatch(componentText(elements), /0 项.*未列出/) + assert.doesNotMatch(componentText(elements), /未返回 0 项/) assert.equal(elements.some(({ type }) => type === 'ConfirmCard'), false, 'another Bot program check cannot settle against the active conversation') assert.equal(nestedElements(elements, ['AttentionActivity', 'OverviewCheckCard']).some(({ type, props }) => type === 'Link' && (platform === 'web' ? (props.params as { botId?: string })?.botId === 'other' : props.href === '/b/other')), true) shared.nodes = [{ ...parityNode, online: false }] @@ -2767,8 +2766,7 @@ test('context shows scheduler observations without promising native resume or re assert.ok(continuity && typeof continuity.type === 'function') let tree = continuity.type(continuity.props) assert.match(componentText(tree), /排队中/) - assert.doesNotMatch(componentText(tree), /正在运行|首次模型|续接记录|设备默认模型 · 设备默认模型/) - assert.equal(elements.filter(({ type }) => typeof type === 'function' && type.name === 'ContinuitySession').length, 0) + assert.doesNotMatch(componentText(tree), /正在运行|设备默认模型 · 设备默认模型/) data.scheduler!.jobs = [{ scope: { kind: 'main' as const }, trigger: 'message:stop', state: 'cancelling' }] tree = continuity.type(continuity.props) assert.match(componentText(tree), /停止中/) @@ -3514,7 +3512,7 @@ test("bot drafts survive a new connection while old create completion cannot clo work = pendingResult(); submit() old.reject(new Error('stale create error')); await settleComponent() assert.equal(render().find(({ props }) => props.type === 'submit')?.props.disabled, true) - assert.equal(render().some(({ props }) => props.role === 'alert'), false) + assert.equal(render().find(({ type }) => type === 'InlineError')?.props.error, '') assert.deepEqual(closed, []) work.resolve({}); await settleComponent() assert.deepEqual(closed, [false]) @@ -3669,7 +3667,7 @@ test("a segmented control is one Tab stop whose arrow keys move and select, wrap assert.deepEqual(render().filter(({ props }) => props.role === 'radio').map(({ props }) => props.tabIndex), [0, -1, -1], "with nothing checked the first option takes the Tab stop") }) -for (const mode of ['restore']) test(`recovery ${mode} clears submitted passwords before waiting and keeps the chosen file and name`, async () => { +test('recovery restore clears submitted passwords before waiting and keeps the chosen file and name', async () => { let generation = 1, work = pendingResult() class Input { value = 'test-only-value'; files: object[] = [{}]; checked = false } const fields = new Map(['bundle', 'password', 'old_password', 'confirmation', 'name', 'bootstrap', 'address', 'device_id', 'relay'].map(name => [name, new Input()])) @@ -3681,7 +3679,7 @@ for (const mode of ['restore']) test(`recovery ${mode} clears submitted password '@vibeface/client/identity/context.tsx': { useDevice: () => device }, '@vibeface/client/lib/node.ts': { parseEntry: (value: unknown) => value, messageOf: (cause: Error) => cause.message }, '@vibeface/client/lib/secure.ts': { passphrase: (value: string) => value }, '@/lib/device-name': { defaultBrowserName: () => 'browser' }, }, { HTMLInputElement: Input, HTMLTextAreaElement: Input }) - const render = () => app.render('RecoveryControls', { only: mode }) + const render = () => app.render('RecoveryControls', { only: 'restore' }) const submit = () => render().find(({ type }) => type === 'form')?.props.onSubmit?.({ preventDefault() {}, currentTarget: form }) try { render(); render(); submit() @@ -4082,7 +4080,7 @@ test("conversation preserves local input while execution devices are unavailable currentWorkspace = workspace([{ device_id: 'gateway', online: true, capabilities: { manager: 'codex', manager_state: 'unverified', roots: [] } }]) assert.equal(composer()?.disabled, false, 'unknown authentication can be tried without claiming readiness') assert.equal(composer()?.reason, '') - assert.doesNotMatch(componentText(composer()?.children), /尚未确认|检查状态|可用性|Codex/) + assert.doesNotMatch(componentText(composer()?.children), /尚未确认|可用性|Codex/) composer()?.onChange?.('third input') composer()?.onSubmit?.() assert.equal(sent, 3) @@ -4184,7 +4182,6 @@ test('merged and in-flight user messages show honest status labels and refresh-o current = build([{ trigger: 'message:m2', state: 'steered', message_id: 'm2', outcome }], [{ message_id: 'm2', event_hash: 'm2', role: 'user', text: outcome, created_at_ms: 2 }]) const tree = harness.messageTree('m2') assert.ok(componentText(tree).includes(label)) - assert.doesNotMatch(componentText(tree), /已接受|已送达/) if (outcome === 'unknown') { refreshed = 0; sent = 0 const action = findActionProps(tree, '再查一次') @@ -4337,7 +4334,6 @@ test("an outstanding clipboard permission cannot keep the add-device sheet busy creation = pendingResult(); labelled('生成链接')?.onClick?.() clipboard.resolve(undefined); await settleComponent() assert.equal(labelled('生成链接')?.disabled, true) - assert.equal(render().some(({ props }) => props.children === '已复制'), false) creation.resolve(invitation); await settleComponent() assert.equal(labelled('复制链接')?.disabled, false) } finally { app.close() } diff --git a/apps/app/src/features/workspace/membership.test.ts b/apps/app/src/features/workspace/membership.test.ts index ef1b92fa6..89c62f547 100644 --- a/apps/app/src/features/workspace/membership.test.ts +++ b/apps/app/src/features/workspace/membership.test.ts @@ -61,7 +61,7 @@ function workspace(source: 'membership' | 'local_session', readBefore: string[] } const connection = { generation: 1, entry: { address: 'https://node.example', device_id: entry }, - principal: source === 'membership' ? { source, network_id: network, device_id: browser, epoch: 1, can_manage: false } : { source, network_id: network, device_id: browser, epoch: 1, can_manage: false }, + principal: { source, network_id: network, device_id: browser, epoch: 1, can_manage: false }, info: { device_id: entry, name: 'node', version: 'test', initialized: true, network_id: network }, isCurrent: () => true, subscribe: () => () => {}, async request(method: string) { if (method === 'write_state') return { state: 'writable', conflicts: [] }; return {} }, diff --git a/apps/app/src/features/workspace/task-detail.tsx b/apps/app/src/features/workspace/task-detail.tsx index f4f6db42c..10bc72bb5 100644 --- a/apps/app/src/features/workspace/task-detail.tsx +++ b/apps/app/src/features/workspace/task-detail.tsx @@ -242,7 +242,7 @@ export function TaskDetail({ botId, workId, from }: { botId: string; workId: str {workspace.pendingMessages.filter((item) => item.target.kind === 'work' && item.target.work_id === workId).map((item) => )}
} - {work ?
补充给 · {work.title || '这个工作'} { const value = event.currentTarget.value; if (value === "continue" || value === "new_task" || value === "defer") setIntent(value) }}>补充这个工作新任务稍后处理} onSubmit={() => { + {work ?
补充给 · {work.title || '这个工作'} { const value = event.currentTarget.value; if (value === "continue" || value === "new_task" || value === "defer") setIntent(value) }}>补充这个工作新任务稍后处理} onSubmit={() => { const submittedDraft = draft if (savingDrafts.current.has(submittedDraft)) return savingDrafts.current.add(submittedDraft) diff --git a/apps/app/src/features/workspace/workspace-chat.tsx b/apps/app/src/features/workspace/workspace-chat.tsx index 1240b58de..9d294ffc0 100644 --- a/apps/app/src/features/workspace/workspace-chat.tsx +++ b/apps/app/src/features/workspace/workspace-chat.tsx @@ -136,7 +136,8 @@ export function ChannelWorkspace({ channelId }: { channelId: string }) { latest.current = workspace useEffect(() => { void latest.current.readWorkspaceState({ channel_id: channelId }).then(() => replyTask ? latest.current.readWorkspaceState({ task_id: replyTask }) : undefined).catch(setReadError) }, [channelId, workspace.generation, replyTask]) const channel = workspace.workspaceState?.channels.find((item) => item.channel_id === channelId) - const botId = recipient || channel?.coordinator_bot + // A remembered recipient that was deleted or left the channel gives way to the coordinator. + const botId = recipient && channel?.members.includes(recipient) && workspace.bots.some((item) => item.bot_id === recipient) ? recipient : channel?.coordinator_bot const bot = workspace.bots.find((item) => item.bot_id === botId) const tasks = (workspace.workspaceState?.tasks ?? []).filter((item) => item.channel_id === channelId) const selectedTask = replyTask ? tasks.find((item) => item.task_id === replyTask) : [...tasks].reverse().find((item) => item.owner_bot === botId && !['completed', 'cancelled'].includes(item.state)) @@ -217,7 +218,7 @@ function ScopedConversation({ target, conversationId, label, task, channelId, ex return
} /> - + {busy ? '补充给' : '发送给'} · {label}
{targetControl} @@ -265,9 +266,9 @@ function WorkspaceTaskContext({ task }: { task: WorkspaceTask }) { const [error, setError] = useState(null) const latest = useRef(workspace) latest.current = workspace + const target: InputTarget = task.channel_id ? { kind: 'channel_task', channel_id: task.channel_id, task_id: task.task_id, bot_id: task.owner_bot } : { kind: 'task', task_id: task.task_id } useEffect(() => { let active = true - const target: InputTarget = task.channel_id ? { kind: 'channel_task', channel_id: task.channel_id, task_id: task.task_id, bot_id: task.owner_bot } : { kind: 'task', task_id: task.task_id } setContext(null); setError(null) void latest.current.readScopeContext({ target }).then((value) => { if (active) { setContext(value); setError(null) } }, (cause) => { if (active) setError(cause) }) return () => { active = false } @@ -280,7 +281,7 @@ function WorkspaceTaskContext({ task }: { task: WorkspaceTask }) {

依赖任务 · {task.dependencies.length ? task.dependencies.map((id) => workspace.workspaceState?.tasks.find((item) => item.task_id === id)?.title ?? id).join('、') : '无'}

任务来源事件 · {task.request_event}

{task.source_events.map((source) =>

引用来源 · {source}

)}{assignment ?

本轮依据 · {JSON.stringify(assignment.basis)}

: null}

任务历史和 Bot 的长期记忆分别保存。执行服务的会话缓存由执行设备管理。本轮采用的内容以来源记录为准,补充的接收与回合归属以输入状态为准。

- + {context?.available ? :

{context ? context.reason || '这个任务尚无已编译的上下文。' : error ? '本次未读到任务上下文。' : '正在查询这个任务的上下文。'}

} diff --git a/apps/app/src/features/workspace/workspace-tasks.tsx b/apps/app/src/features/workspace/workspace-tasks.tsx index f977dd915..ecea03367 100644 --- a/apps/app/src/features/workspace/workspace-tasks.tsx +++ b/apps/app/src/features/workspace/workspace-tasks.tsx @@ -11,7 +11,7 @@ import { useWorkspace } from '@vibeface/client/workspace/context.tsx' import { newId } from '@vibeface/client/workspace/storage.ts' import type { WorkspaceCommand, WorkspaceTask } from '@vibeface/client/workspace/types.ts' -export const workspaceTaskLabels: Record = { +const workspaceTaskLabels: Record = { not_started: '未开始', running: '执行中', waiting_dependencies: '等待依赖', waiting_user: '等待你决定', update_pending: '更新待承接', stop_pending: '停止待确认', needs_reconciliation: '结果待确认', completed: '已完成', cancelled: '已取消', deferred: '稍后处理', diff --git a/apps/app/src/lib/copy.test.ts b/apps/app/src/lib/copy.test.ts index ab6a27430..5082bcb0e 100644 --- a/apps/app/src/lib/copy.test.ts +++ b/apps/app/src/lib/copy.test.ts @@ -21,7 +21,7 @@ const retired: Record = { } const cjk = /[一-鿿]/ -export function violations(source: string, file = "x.tsx") { +function violations(source: string, file = "x.tsx") { const found: string[] = [] const sf = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX) const inDetails = (node: ts.Node): boolean => { diff --git a/apps/app/src/lib/desktop-nav.ts b/apps/app/src/lib/desktop-nav.ts index 64c4bd610..1ec0506e9 100644 --- a/apps/app/src/lib/desktop-nav.ts +++ b/apps/app/src/lib/desktop-nav.ts @@ -1,4 +1,4 @@ -import { getRouter } from '@/router' +import type { AnyRouter } from '@tanstack/react-router' declare global { interface Window { @@ -7,9 +7,9 @@ declare global { } /** Lets the desktop host open in-window routes without a full reload. */ -export function installDesktopNavigation(): void { +export function installDesktopNavigation(router: AnyRouter): void { if (typeof window === 'undefined' || !window.vibefaceClient) return window.__vibefaceNavigate = (path: string) => { - void getRouter().navigate({ to: path }) + void router.navigate({ to: path }) } } diff --git a/apps/app/src/lib/desktop-node-bridge.test.ts b/apps/app/src/lib/desktop-node-bridge.test.ts index d8907318f..e1a8fd831 100644 --- a/apps/app/src/lib/desktop-node-bridge.test.ts +++ b/apps/app/src/lib/desktop-node-bridge.test.ts @@ -3,5 +3,16 @@ import test from 'node:test' import { isDesktopHost } from './desktop-node-bridge.ts' test('desktop node settings are only exposed inside the desktop host', () => { - assert.equal(isDesktopHost(), false) + const host = globalThis as { window?: unknown } + const before = Object.getOwnPropertyDescriptor(host, 'window') + try { + assert.equal(isDesktopHost(), false) + host.window = { vibefaceClient: {} } + assert.equal(isDesktopHost(), false) + host.window = { vibefaceClient: { desktop: {} } } + assert.equal(isDesktopHost(), true) + } finally { + if (before) Object.defineProperty(host, 'window', before) + else delete host.window + } }) diff --git a/apps/app/src/routes/__root.tsx b/apps/app/src/routes/__root.tsx index 3ee400d4f..ca5fe85d7 100644 --- a/apps/app/src/routes/__root.tsx +++ b/apps/app/src/routes/__root.tsx @@ -1,4 +1,4 @@ -import { HeadContent, Outlet, Scripts, createRootRoute } from '@tanstack/react-router' +import { HeadContent, Outlet, Scripts, createRootRoute, useRouter } from '@tanstack/react-router' import { useEffect } from 'react' import { Toaster } from '@/components/app/kit' import { DeviceProvider } from '@vibeface/client/identity/context.tsx' @@ -46,10 +46,11 @@ function RootLayout() { } function RootDocument({ children }: { children: React.ReactNode }) { + const router = useRouter() useEffect(registerShell, []) useEffect(installErrorReporting, []) useEffect(installValidityMessages, []) - useEffect(installDesktopNavigation, []) + useEffect(() => installDesktopNavigation(router), [router]) return ( diff --git a/apps/app/tsconfig.json b/apps/app/tsconfig.json index 0d0803f27..c2272ee98 100644 --- a/apps/app/tsconfig.json +++ b/apps/app/tsconfig.json @@ -5,7 +5,6 @@ "jsx": "react-jsx", "module": "ESNext", "paths": { - "#/*": ["./src/*"], "@/*": ["./src/*"] }, "lib": ["ES2022", "DOM", "DOM.Iterable"], diff --git a/apps/cli/Cargo.toml b/apps/cli/Cargo.toml index b8ed25bfb..fda5deaad 100644 --- a/apps/cli/Cargo.toml +++ b/apps/cli/Cargo.toml @@ -6,7 +6,6 @@ rust-version.workspace = true [dependencies] anyhow.workspace = true -base64 = "0.22" clap = { workspace = true, features = ["wrap_help"] } crossterm = { version = "0.28", features = ["event-stream"] } futures-util.workspace = true @@ -21,9 +20,7 @@ semver.workspace = true sha2.workspace = true tar.workspace = true tokio.workspace = true -tokio-tungstenite.workspace = true toml.workspace = true -tracing.workspace = true uuid.workspace = true vibeface-bridge.workspace = true vibeface-control.workspace = true diff --git a/apps/cli/src/desktop_node.rs b/apps/cli/src/desktop_node.rs index 50cf1c3c9..48d5e180e 100644 --- a/apps/cli/src/desktop_node.rs +++ b/apps/cli/src/desktop_node.rs @@ -276,17 +276,8 @@ async fn inspect(data: &Path, bundled: &Path) -> Result { } fn verify_bundled_source(package: &Path) -> Result<()> { - let build = crate::update::release::verify_sealed_package( - package, - env!("CARGO_PKG_VERSION"), - &target()?, - )?; - crate::update::validate_desktop_package(package)?; - ensure!( - build.version == env!("CARGO_PKG_VERSION"), - "bundled runtime version mismatch" - ); - Ok(()) + crate::update::release::verify_sealed_package(package, env!("CARGO_PKG_VERSION"), &target()?)?; + crate::update::validate_desktop_package(package) } /// The package that contains this signed executable. Callers pass that directory onward; @@ -973,11 +964,7 @@ async fn dispatch(options: DesktopNode, bundled: &Path) -> Result<()> { Some(receipt), Some(true), Some("running".into()), - if inspected.status == "running" { - Some(running_core_version(&inspected)?) - } else { - None - }, + Some(running_core_version(&inspected)?), bundled, )?; return Ok(()); @@ -1081,8 +1068,7 @@ async fn dispatch(options: DesktopNode, bundled: &Path) -> Result<()> { } match update_meta.availability { "current" => { - if native.installed - && native.running + if native.running && (fresh.status != "running" || running_core_version(&fresh)? != bundled_package_version(&source)?) @@ -1115,7 +1101,7 @@ async fn dispatch(options: DesktopNode, bundled: &Path) -> Result<()> { } _ => anyhow::bail!(OperationFailure::UpdateRefused), } - if !native.installed || (fresh.status == "running") != native.running { + if (fresh.status == "running") != native.running { anyhow::bail!(OperationFailure::UpdateRefused); } let bundled_version = bundled_package_version(&source)?; @@ -1422,15 +1408,7 @@ mod tests { serde_json::to_vec(&build).unwrap(), ) .unwrap(); - let mut files = Vec::new(); - let mut names = names.to_vec(); - names.push("BUILD-INFO.json"); - names.sort(); - for name in names { - let bytes = fs::read(package.join(name)).unwrap(); - files.push(format!("{} {name}", hex::encode(Sha256::digest(bytes)))); - } - fs::write(package.join("FILES.sha256"), files.join("\n") + "\n").unwrap(); + reseal(&package); package } @@ -1577,7 +1555,7 @@ mod tests { assert_eq!(conflict.availability, "immutable_conflict"); let mismatch = runtime_update_for_packages( &matching, - Some(&installed), + Some(&matching), Some("0.0.1-nightly.20261106.1"), ) .unwrap(); @@ -1804,11 +1782,6 @@ mod tests { &serde_json::to_vec(&receipt).unwrap(), ) .unwrap(); - privatefs::write_atomic( - &data.join("update-pending.json"), - br#"{"phase":"prepared"}"#, - ) - .unwrap(); for phase in ["prepared", "confirmed"] { privatefs::write_atomic( &data.join("update-pending.json"), @@ -1924,9 +1897,6 @@ mod tests { "{calls_text}" ); assert_eq!(calls_text.lines().count(), 3, "{calls_text}"); - assert!(!calls_text.contains("stop"), "{calls_text}"); - assert!(!calls_text.contains("start"), "{calls_text}"); - assert!(!calls_text.contains("install"), "{calls_text}"); assert_eq!(fs::read(data.join("update-pending.json")).unwrap(), journal); assert_eq!( fs::read_link(managed_root.join("current")).unwrap(), diff --git a/apps/cli/src/main.rs b/apps/cli/src/main.rs index b9e041d8c..7823d47fa 100644 --- a/apps/cli/src/main.rs +++ b/apps/cli/src/main.rs @@ -159,7 +159,7 @@ struct Init { #[arg(long, default_value_t = DEFAULT_LISTEN)] listen: SocketAddr, /// Address for the local control API. - #[arg(long, default_value_t = local_listen())] + #[arg(long, default_value_t = DEFAULT_LOCAL_LISTEN)] local_listen: SocketAddr, /// Public browser entry URL. #[arg(long)] @@ -769,10 +769,7 @@ async fn main() -> Result<()> { let cli = Cli::parse(); match cli.command { None => { - let data_dir = data_dir_or_home( - cli.data_dir - .or_else(|| std::env::var_os("VIBEFACE_DATA_DIR").map(PathBuf::from)), - )?; + let data_dir = data_dir_or_home(cli.data_dir)?; let mut args = vec![ "--data-dir".to_owned(), data_dir.to_string_lossy().into_owned(), @@ -799,12 +796,9 @@ async fn main() -> Result<()> { exec_core(&args.iter().map(String::as_str).collect::>()) } Some(Action::Init(options)) => { - let result = control( - &options.data_dir, - ControlRequest::Init { - options: serde_json::to_value(&*options)?, - }, - ) + let result = control(ControlRequest::Init { + options: serde_json::to_value(&*options)?, + }) .await?; println!("Vibeface 已就绪"); if let Some(open) = result["open"].as_str() { @@ -855,9 +849,9 @@ async fn main() -> Result<()> { println!("{}", serde_json::to_string_pretty(&result)?); Ok(()) } - None => post_triage(&options.local, serde_json::to_value(options.action)?).await, + None => triage_post(&options.local, serde_json::to_value(options.action)?).await, }, - Some(Action::Requests(local)) => post_triage(&local, json!({"action":"requests"})).await, + Some(Action::Requests(local)) => triage_post(&local, json!({"action":"requests"})).await, Some(Action::Respond { request_id, result, @@ -865,7 +859,7 @@ async fn main() -> Result<()> { local, }) => { let result: Value = serde_json::from_str(&result).context("result must be JSON")?; - post_triage( + triage_post( &local, json!({"action":"respond","request_id":request_id,"result":result,"node":node}), ) @@ -913,17 +907,14 @@ fn core_binary() -> Result { vibeface_control::sibling_core(&std::env::current_exe()?) } -async fn control(_data_dir: &Path, request: ControlRequest) -> Result { +async fn control(request: ControlRequest) -> Result { vibeface_control::request(&core_binary()?, &request).await } async fn inspect_socket(data_dir: &Path) -> Result { - let info = control( - data_dir, - ControlRequest::Inspect { - data_dir: data_dir.to_owned(), - }, - ) + let info = control(ControlRequest::Inspect { + data_dir: data_dir.to_owned(), + }) .await?; info["maintenance_socket"] .as_str() @@ -932,12 +923,9 @@ async fn inspect_socket(data_dir: &Path) -> Result { } async fn status(options: Access) -> Result<()> { - let mut result = control( - &options.data_dir, - ControlRequest::Inspect { - data_dir: options.data_dir.clone(), - }, - ) + let mut result = control(ControlRequest::Inspect { + data_dir: options.data_dir.clone(), + }) .await?; result["cli_version"] = json!(env!("CARGO_PKG_VERSION")); if options.json { @@ -1016,13 +1004,10 @@ async fn mesh(options: MeshOptions) -> Result<()> { command: BootstrapAction::Remove { nodes }, } => json!({"op":"bootstrap","remove":nodes}), }; - let result = control( - &options.data_dir, - ControlRequest::Mesh { - data_dir: options.data_dir.clone(), - operation, - }, - ) + let result = control(ControlRequest::Mesh { + data_dir: options.data_dir.clone(), + operation, + }) .await?; match options.command { MeshAction::Status { json: true } | MeshAction::Records { json: true, .. } => { @@ -1091,13 +1076,10 @@ async fn mesh(options: MeshOptions) -> Result<()> { async fn access(options: LocalEntry) -> Result<()> { if options.enable || options.disable { - let result = control( - &options.access.data_dir, - ControlRequest::SetLocalAccess { - data_dir: options.access.data_dir.clone(), - enabled: options.enable, - }, - ) + let result = control(ControlRequest::SetLocalAccess { + data_dir: options.access.data_dir.clone(), + enabled: options.enable, + }) .await?; let running = result["running"].as_bool().unwrap_or(true); if options.disable || !running { @@ -1111,13 +1093,10 @@ async fn access(options: LocalEntry) -> Result<()> { return Ok(()); } } - let result = control( - &options.access.data_dir, - ControlRequest::Access { - data_dir: options.access.data_dir.clone(), - json: options.access.json, - }, - ) + let result = control(ControlRequest::Access { + data_dir: options.access.data_dir.clone(), + json: options.access.json, + }) .await?; if options.access.json { let mut output = json!({ @@ -1145,25 +1124,19 @@ async fn access(options: LocalEntry) -> Result<()> { async fn join(options: Join) -> Result<()> { let data_dir = options.data_dir.clone(); - let running = control( - &data_dir, - ControlRequest::Inspect { - data_dir: data_dir.clone(), - }, - ) + let running = control(ControlRequest::Inspect { + data_dir: data_dir.clone(), + }) .await .ok() .and_then(|value| value["status"].as_str().map(|status| status == "running")) .unwrap_or(false); if !running { - let result = control( - &data_dir, - ControlRequest::Join { - data_dir: data_dir.clone(), - link: options.link.clone(), - name: options.name.clone(), - }, - ) + let result = control(ControlRequest::Join { + data_dir: data_dir.clone(), + link: options.link.clone(), + name: options.name.clone(), + }) .await?; match result["status"].as_str() { Some("joined") => { @@ -1343,13 +1316,10 @@ async fn wallet(options: WalletOptions) -> Result<()> { key_operation(&dir, "revoke", intent_id, gas_cap).await } WalletAction::Backup { output } => { - let result = control( - &dir, - ControlRequest::Wallet { - data_dir: dir.clone(), - operation: json!({"op":"backup","output":output}), - }, - ) + let result = control(ControlRequest::Wallet { + data_dir: dir.clone(), + operation: json!({"op":"backup","output":output}), + }) .await?; if result.is_null() { println!("Encrypted delivery wallet backup saved."); @@ -2265,7 +2235,7 @@ async fn logs(options: Logs) -> Result<()> { } Ok(()) }; - let mut records = Vec::new(); + let mut records = std::collections::VecDeque::new(); for path in log_files(&options.data_dir) { let file = fs::File::open(path)?; for line in std::io::BufReader::new(file).split(b'\n') { @@ -2276,9 +2246,9 @@ async fn logs(options: Logs) -> Result<()> { if let Ok(record) = serde_json::from_slice::(&line) && log_matches(&record, &options, since) { - records.push(record); + records.push_back(record); if records.len() > options.limit.max(1) { - records.remove(0); + records.pop_front(); } } } @@ -2405,10 +2375,6 @@ async fn triage_post(local: &LocalNode, mut body: Value) -> Result<()> { Ok(()) } -async fn post_triage(local: &LocalNode, body: Value) -> Result<()> { - triage_post(local, body).await -} - async fn post_local(local: &LocalNode, path: &str, body: &Value, total: Duration) -> Result { let credential = vibeface_control::LocalHttpCredential::read(&local.data_dir)?; let url = origin(local.node_url.as_deref().unwrap_or(&credential.origin))?; @@ -2515,9 +2481,6 @@ fn data_dir_or_home(dir: Option) -> Result { Ok(dir) } -fn local_listen() -> SocketAddr { - DEFAULT_LOCAL_LISTEN -} fn now_ms() -> i64 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) diff --git a/apps/cli/src/manage.rs b/apps/cli/src/manage.rs index 57c6d38a0..9f1be8ad3 100644 --- a/apps/cli/src/manage.rs +++ b/apps/cli/src/manage.rs @@ -166,27 +166,6 @@ pub async fn node(options: NodeOptions) -> Result<()> { print(&result) } -#[derive(Clone, Copy, ValueEnum)] -pub enum Provider { - Codex, - Claude, - Opencode, - Cursor, - Pi, -} - -impl Provider { - fn name(self) -> &'static str { - match self { - Self::Codex => "codex", - Self::Claude => "claude", - Self::Opencode => "opencode", - Self::Cursor => "cursor", - Self::Pi => "pi", - } - } -} - #[derive(Args)] pub struct ProviderOptions { #[command(flatten)] @@ -200,7 +179,7 @@ pub enum ProviderAction { /// Change a provider: {"bot","execution","execution_model","bin","app_server","connect_local","env"}. Configure { #[arg(value_enum)] - provider: Provider, + provider: crate::triage::Provider, /// The change as a JSON object; absent fields keep their value. `-` reads it from /// standard input, for one holding API keys. change: String, @@ -208,12 +187,12 @@ pub enum ProviderAction { /// Check whether a provider is ready. Probe { #[arg(value_enum)] - provider: Provider, + provider: crate::triage::Provider, }, /// List a provider's models. Models { #[arg(value_enum)] - provider: Provider, + provider: crate::triage::Provider, }, /// Test the Codex App Server connection. TestCodex, @@ -367,14 +346,11 @@ fn config_value(text: &str) -> Value { pub async fn config(options: ConfigOptions) -> Result<()> { let ConfigAction::Set { key, value } = options.command; let dir = options.node.data_dir; - let result = crate::control( - &dir, - ControlRequest::ConfigSet { - data_dir: dir.clone(), - key: key.clone(), - value: config_value(&arg_or_stdin(value)?), - }, - ) + let result = crate::control(ControlRequest::ConfigSet { + data_dir: dir.clone(), + key: key.clone(), + value: config_value(&arg_or_stdin(value)?), + }) .await?; if result["restart_required"] == true { println!("Saved {key}; restart the Node to apply it."); @@ -429,14 +405,26 @@ impl ClientAccess { ClientKey::create(&self.client_dir, passphrase.as_str()) } + /// `--url` with the remembered Node's ID; none without `--url`, for the remembered entry. + fn entry(&self, key: &ClientKey) -> Result> { + let Some(url) = &self.url else { + return Ok(None); + }; + Ok(Some(Entry { + origin: url.clone(), + node_id: key + .entry() + .context("this client is not enrolled yet")? + .node_id + .clone(), + })) + } + /// The local Node's Gateway and device ID, or `--url` with `node`. async fn local_entry(&self, node: Option) -> Result { - let info = crate::control( - &self.data_dir, - ControlRequest::Inspect { - data_dir: self.data_dir.clone(), - }, - ) + let info = crate::control(ControlRequest::Inspect { + data_dir: self.data_dir.clone(), + }) .await; let origin = match (&self.url, &info) { (Some(url), _) => url.clone(), @@ -658,17 +646,7 @@ pub async fn client(options: ClientOptions) -> Result<()> { } command => { let key = access.unlock()?; - let entry = match &access.url { - Some(url) => Some(Entry { - origin: url.clone(), - node_id: key - .entry() - .context("this client is not enrolled yet")? - .node_id - .clone(), - }), - None => None, - }; + let entry = access.entry(&key)?; let mut session = key.connect(entry.as_ref()).await?; signed(&mut session, command).await } @@ -859,7 +837,8 @@ pub async fn bots(options: BotsOptions) -> Result<()> { _ => {} } let key = access.unlock()?; - let mut session = key.connect(None).await?; + let entry = access.entry(&key)?; + let mut session = key.connect(entry.as_ref()).await?; let result = match options.command { BotsAction::Create { name, diff --git a/apps/cli/src/service.rs b/apps/cli/src/service.rs index af529dd10..068fcf534 100644 --- a/apps/cli/src/service.rs +++ b/apps/cli/src/service.rs @@ -221,11 +221,7 @@ pub async fn run(options: Service) -> Result<()> { let data_dir = data_dir_or_home(options.data_dir)?; let data = std::fs::canonicalize(data_dir) .context("initialized data directory is required; run vibeface init first")?; - let inspected = inspect(&data).await?; - ensure!( - inspected.data_dir == data, - "core inspected a different data directory" - ); + inspect(&data).await?; let executable = std::env::current_exe()?; let npm_root = update::npm_install_root(&executable)?; let root = match &npm_root { diff --git a/apps/cli/src/update/release.rs b/apps/cli/src/update/release.rs index 5e46814ea..d63c19f1a 100644 --- a/apps/cli/src/update/release.rs +++ b/apps/cli/src/update/release.rs @@ -171,7 +171,6 @@ fn valid_date(date: &str) -> bool { fn host_target() -> Result<&'static str> { match (std::env::consts::ARCH, std::env::consts::OS) { ("aarch64", "macos") => Ok("aarch64-apple-darwin"), - ("x86_64", "macos") => Ok("x86_64-apple-darwin"), ("aarch64", "linux") => Ok("aarch64-unknown-linux-gnu"), ("x86_64", "linux") => Ok("x86_64-unknown-linux-gnu"), ("x86_64", "windows") => Ok("x86_64-pc-windows-msvc"), diff --git a/apps/core/Cargo.toml b/apps/core/Cargo.toml index e204a2f1b..88097dc04 100644 --- a/apps/core/Cargo.toml +++ b/apps/core/Cargo.toml @@ -16,7 +16,6 @@ base64 = "0.22" clap.workspace = true chacha20poly1305 = "0.10.1" ed25519-dalek.workspace = true -flate2.workspace = true futures-util.workspace = true hex.workspace = true hyper = { version = "1", features = ["http1", "server"] } @@ -37,7 +36,6 @@ serde.workspace = true serde_json.workspace = true sha2.workspace = true socket2 = "0.6" -tar.workspace = true tokio.workspace = true tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12"] } tokio-tungstenite.workspace = true diff --git a/apps/core/src/api.rs b/apps/core/src/api.rs index bbbd01f36..ce3dd6c40 100644 --- a/apps/core/src/api.rs +++ b/apps/core/src/api.rs @@ -1823,8 +1823,6 @@ mod tests { assert_eq!(client.post(&endpoint).json(&json!({})).send().await?.status(), StatusCode::FORBIDDEN); assert_eq!(request().header("x-forwarded-for", "127.0.0.1").send().await?.status(), StatusCode::FORBIDDEN); assert_eq!(client.post(&endpoint).header(header::ORIGIN, "https://hostile.invalid").json(&json!({})).send().await?.status(), StatusCode::FORBIDDEN); - let removed = client.post(format!("{origin}/api/local/join/status")).header(header::ORIGIN, &origin).json(&json!({})).send().await?; - assert_eq!(removed.status(), StatusCode::NOT_FOUND); let public_info: Value = client.get(format!("{origin}/api/info")).send().await?.json().await?; assert!(!public_info.to_string().contains(&capability.capability)); assert!(public_info.get("invitation").is_none()); @@ -1883,14 +1881,10 @@ mod tests { .join("../../.artifacts") .join(format!("hook-boundary-{}", uuid::Uuid::new_v4())); config::private_dir(&dir)?; - Config::local("127.0.0.1:0".parse()?, vec![], false).save(&dir)?; - config::private_write( - &dir.join("data-epoch.json"), - &crate::config::data_epoch_marker(), - )?; - config::private_write( - &dir.join("identity.json"), - &serde_json::to_vec(&crate::crypto::LocalIdentity::generate())?, + initialize_node( + &dir, + &Config::local("127.0.0.1:0".parse()?, vec![], false), + &crate::crypto::LocalIdentity::generate(), )?; let mut runtime = Runtime::open(&dir).await?; runtime.config.web_enabled = web_enabled; diff --git a/apps/core/src/api/static_assets.rs b/apps/core/src/api/static_assets.rs index e26fa868f..e58ebfbdb 100644 --- a/apps/core/src/api/static_assets.rs +++ b/apps/core/src/api/static_assets.rs @@ -87,10 +87,6 @@ impl StaticAssets { headers == static_headers(&receipt.content_security_policy), "static App headers do not match the receipt CSP" ); - ensure!( - !files["_shell.html"].body.is_empty(), - "static App shell is empty" - ); Ok(Self { files, content_security_policy, diff --git a/apps/core/src/client.rs b/apps/core/src/client.rs index 951f10cf0..a16649554 100644 --- a/apps/core/src/client.rs +++ b/apps/core/src/client.rs @@ -3926,14 +3926,10 @@ mod tests { .join("../../.artifacts") .join(format!("node-join-failed-{}", uuid::Uuid::new_v4())); crate::config::private_dir(&dir)?; - crate::config::Config::local("127.0.0.1:4795".parse()?, vec![], false).save(&dir)?; - crate::config::private_write( - &dir.join("data-epoch.json"), - &crate::config::data_epoch_marker(), - )?; - crate::config::private_write( - &dir.join("identity.json"), - &serde_json::to_vec(&LocalIdentity::generate())?, + initialize_node( + &dir, + &crate::config::Config::local("127.0.0.1:4795".parse()?, vec![], false), + &LocalIdentity::generate(), )?; let capability = crate::store::Store::open(dir.join("node.sqlite3"))?.bootstrap_capability()?; @@ -4011,15 +4007,7 @@ mod tests { let mut config = crate::config::Config::local(reservation.local_addr()?, vec![], false); config.local_listen = local.local_addr()?; drop((reservation, local)); - config.save(dir)?; - crate::config::private_write( - &dir.join("identity.json"), - &serde_json::to_vec(&LocalIdentity::generate())?, - )?; - crate::config::private_write( - &dir.join("data-epoch.json"), - &crate::config::data_epoch_marker(), - )?; + initialize_node(dir, &config, &LocalIdentity::generate())?; let node = Arc::new(Runtime::open(dir).await?); let root = LocalIdentity::generate(); node.install_membership(NetworkState::new(Genesis::create( @@ -4325,15 +4313,7 @@ mod tests { config.local_listen = local.local_addr()?; config.allowed_origins = vec!["https://app.example".into()]; drop((public, local)); - config.save(&dir)?; - crate::config::private_write( - &dir.join("identity.json"), - &serde_json::to_vec(&LocalIdentity::generate())?, - )?; - crate::config::private_write( - &dir.join("data-epoch.json"), - &crate::config::data_epoch_marker(), - )?; + initialize_node(&dir, &config, &LocalIdentity::generate())?; let capability = crate::store::Store::open(dir.join("node.sqlite3"))?.bootstrap_capability()?; let node = Arc::new(Runtime::open(&dir).await?); @@ -4668,15 +4648,7 @@ mod tests { config.forwarding.per_ip = std::num::NonZeroUsize::new(1); config.forwarding.trusted_proxies = vec!["127.0.0.1".parse()?]; drop((public, local)); - config.save(&dir)?; - crate::config::private_write( - &dir.join("identity.json"), - &serde_json::to_vec(&LocalIdentity::generate())?, - )?; - crate::config::private_write( - &dir.join("data-epoch.json"), - &crate::config::data_epoch_marker(), - )?; + initialize_node(&dir, &config, &LocalIdentity::generate())?; let node = Arc::new(Runtime::open(&dir).await?); let origin = node.config.public_url.clone(); let server = tokio::spawn(crate::api::serve(node.clone(), None)); diff --git a/apps/core/src/config.rs b/apps/core/src/config.rs index 125337fd4..d2a49849f 100644 --- a/apps/core/src/config.rs +++ b/apps/core/src/config.rs @@ -14,8 +14,6 @@ pub use vibeface_control::DATA_EPOCH; /// SHA-256 of the Core and delivery initial SQL schemas. pub const DATA_EPOCH_SCHEMA_SHA256: &str = "3a010aaa0a9b67d159e42314ed1ab29c34bbb25374de7fbd1a0e31bddebe9401"; -/// Bumped whenever a release package stops being installable by the previous updater. -pub use vibeface_control::UPDATE_PROTOCOL; pub fn data_epoch_marker() -> Vec { format!(r#"{{"data_epoch":{DATA_EPOCH}}}"#).into_bytes() } diff --git a/apps/core/src/control.rs b/apps/core/src/control.rs index f46a455c3..9d2d00096 100644 --- a/apps/core/src/control.rs +++ b/apps/core/src/control.rs @@ -681,7 +681,6 @@ fn initialize(dir: &Path, configuration: Config) -> Result<()> { ); } configuration.validate()?; - configuration.network.validate()?; let identity = LocalIdentity::generate(); config::private_dir(dir)?; let identity_bytes = zeroize::Zeroizing::new(serde_json::to_vec_pretty(&identity)?); @@ -768,9 +767,14 @@ fn start_over(dir: &Path) -> Result { let _ = fs::remove_dir_all(&fresh); return Err(error); } - fs::rename(dir, &archive)?; + if let Err(error) = fs::rename(dir, &archive) { + let _ = fs::remove_dir_all(&fresh); + return Err(error.into()); + } if let Err(error) = fs::rename(&fresh, dir) { - fs::rename(&archive, dir)?; + let restored = fs::rename(&archive, dir); + let _ = fs::remove_dir_all(&fresh); + restored?; return Err(error.into()); } Ok(archive) diff --git a/apps/core/src/control_discovery.rs b/apps/core/src/control_discovery.rs index 382b312a3..6a0397d3b 100644 --- a/apps/core/src/control_discovery.rs +++ b/apps/core/src/control_discovery.rs @@ -514,22 +514,6 @@ mod tests { fs::remove_dir_all(root).unwrap(); } - #[cfg(target_os = "linux")] - #[test] - fn systemd_fixture_extracts_unicode_spaced_data_dir() { - let fixture = "[Service]\nExecStart=\"/opt/Vibeface/vibeface\" serve --data-dir \"/home/user/Node 数据 2\"\n"; - assert_eq!( - parse_linux_service_unit(fixture).unwrap().unwrap(), - PathBuf::from("/home/user/Node 数据 2") - ); - assert!( - parse_linux_service_unit( - "[Service]\nExecStart=/tmp/unrelated serve --data-dir /tmp/node\n" - ) - .is_err() - ); - } - #[cfg(unix)] #[test] fn systemd_fixture_extracts_only_known_node_and_spaced_path() { diff --git a/apps/core/src/delivery/chain.rs b/apps/core/src/delivery/chain.rs index 8811718a7..8bc58e825 100644 --- a/apps/core/src/delivery/chain.rs +++ b/apps/core/src/delivery/chain.rs @@ -359,17 +359,6 @@ impl Chain { }) } - pub async fn order(&self, order_id: Word) -> Result { - self.confirmed_order(order_id).await - } - - pub async fn confirmed_order(&self, order_id: Word) -> Result { - let position = self.confirmed_position().await?; - let result = self.order_at(&position, order_id).await?; - self.verify_position(&position).await?; - Ok(result) - } - pub async fn order_at(&self, position: &ChainPosition, order_id: Word) -> Result { let result = self .call_at( @@ -1502,7 +1491,7 @@ pub(super) mod tests { Ok(RpcFixture { chain: Chain { config, - client: reqwest::Client::new(), + client: reqwest::Client::builder().no_proxy().build()?, request_id: AtomicU64::new(1), }, requests, @@ -1774,6 +1763,9 @@ pub(super) mod tests { .any(|request| request["method"] == "eth_sendRawTransaction"), "configuration changes during awaits cannot reach broadcast" ); + // The RPC fixture's tasks still hold a clone of `delivery`, so dropping + // ours would leave the SQLite file open and Windows could not delete it. + delivery.store.lock().expect("delivery store").take(); std::fs::remove_dir_all(dir)?; Ok(()) } @@ -1894,7 +1886,7 @@ pub(super) mod tests { config.rpc_url = format!("http://{}/", listener.local_addr()?); let chain = Chain { config, - client: reqwest::Client::new(), + client: reqwest::Client::builder().no_proxy().build()?, request_id: AtomicU64::new(1), }; let policy = super::super::budget::PublicationPolicy { diff --git a/apps/core/src/delivery/charity.rs b/apps/core/src/delivery/charity.rs index 699b01c01..a34b91150 100644 --- a/apps/core/src/delivery/charity.rs +++ b/apps/core/src/delivery/charity.rs @@ -388,6 +388,7 @@ impl Delivery { self.with_store(|store| { let previous = store .value("charity-receiving-current")? + .map(Zeroizing::new) .map(|bytes| serde_json::from_slice::(&bytes)) .transpose()?; if let Some(material) = &previous { @@ -872,6 +873,10 @@ impl Delivery { return Ok(()); } } + ensure!( + now() <= stored.order.terms.retain_until, + "charity delivery expired without a receipt" + ); if !stored.notified { self.charity_authorized(stored).await?; charity_request( diff --git a/apps/core/src/delivery/keys.rs b/apps/core/src/delivery/keys.rs index 4c3628271..4476d239e 100644 --- a/apps/core/src/delivery/keys.rs +++ b/apps/core/src/delivery/keys.rs @@ -168,7 +168,7 @@ impl Delivery { ensure!(prior.completed.is_some(),"another receiving key operation is unresolved; reconcile its original intent first"); } let current_label=current_key_label(&config)?; - let current=store.value(¤t_label)?.map(|bytes|serde_json::from_slice::(&bytes)).transpose()?; + let current=store.value(¤t_label)?.map(Zeroizing::new).map(|bytes|serde_json::from_slice::(&bytes)).transpose()?; if action == KeyAction::Rotate { let confirmed_active = match ¤t { Some(material) => material.binding.binding.action == BindingAction::Active diff --git a/apps/core/src/delivery/orders.rs b/apps/core/src/delivery/orders.rs index 79cb97f8a..0eb4136ed 100644 --- a/apps/core/src/delivery/orders.rs +++ b/apps/core/src/delivery/orders.rs @@ -1602,6 +1602,7 @@ mod tests { 1 ); drop(database); + drop(delivery); std::fs::remove_dir_all(dir)?; Ok(()) } diff --git a/apps/core/src/delivery/proof.rs b/apps/core/src/delivery/proof.rs index ea9e80f62..3f007ed23 100644 --- a/apps/core/src/delivery/proof.rs +++ b/apps/core/src/delivery/proof.rs @@ -1430,7 +1430,7 @@ mod tests { #[tokio::test] async fn timeout_terminates_the_whole_process_group() { let dir = Path::new(env!("CARGO_MANIFEST_DIR")) - .join(".artifacts") + .join("../../.artifacts") .join("proof-supervisor-tests"); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join(format!("{}.pid", uuid::Uuid::new_v4())); diff --git a/apps/core/src/delivery/provider.rs b/apps/core/src/delivery/provider.rs index b97899799..15d9093e9 100644 --- a/apps/core/src/delivery/provider.rs +++ b/apps/core/src/delivery/provider.rs @@ -287,9 +287,10 @@ impl Delivery { "delivery offer belongs to another receiver" ); let key_id = hex::encode(order.unsigned.terms.binding.key_id); - let material = self - .with_store(|store| store.value(&format!("receiving-key:{key_id}")))? - .context("historical receiving key is unavailable")?; + let material = Zeroizing::new( + self.with_store(|store| store.value(&format!("receiving-key:{key_id}")))? + .context("historical receiving key is unavailable")?, + ); let key: ReceivingMaterial = serde_json::from_slice(&material)?; ensure!( key.binding.binding == order.unsigned.terms.binding && key.secret.is_some(), diff --git a/apps/core/src/delivery/store.rs b/apps/core/src/delivery/store.rs index 07775c8e0..74ef796ad 100644 --- a/apps/core/src/delivery/store.rs +++ b/apps/core/src/delivery/store.rs @@ -116,7 +116,8 @@ impl ServiceStore { admissions: (std::time::Instant::now(), 0), }) } - pub fn root(&self) -> &Path { + #[cfg(test)] + pub(super) fn root(&self) -> &Path { &self.root } pub fn check_limits(&self, capacity: u64, max_orders: u32) -> Result<()> { @@ -1096,7 +1097,8 @@ impl ServiceStore { )?; Ok(last.is_none_or(|last| last < nonce)) } - pub fn recent_transactions(&self) -> Result> { + #[cfg(test)] + pub(super) fn recent_transactions(&self) -> Result> { let mut query = self .db .prepare("SELECT id FROM transactions ORDER BY rowid DESC LIMIT 128")?; @@ -1233,16 +1235,16 @@ fn capacity_usage(db: &Connection) -> Result<[(u32, u64); 3]> { let (id, bytes) = row?; usage[*owners.get(&id).unwrap_or(&0)].1 += bytes + 256; } - let mut query = db.prepare("SELECT id,body,length(id)+length(body)+128 FROM private_values")?; + let mut query = db.prepare("SELECT id,CASE WHEN substr(id,1,16)='protected-claim:' THEN body END,length(id)+length(body)+128 FROM private_values")?; for row in query.query_map([], |row| { Ok(( row.get::<_, String>(0)?, - row.get::<_, Vec>(1)?, + row.get::<_, Option>>(1)?, row.get::<_, u64>(2)?, )) })? { let (id, body, bytes) = row?; - usage[private_class(db, &id, &body)?].1 += bytes; + usage[private_class(db, &id, body.as_deref().unwrap_or_default())?].1 += bytes; } let proofs: u64 = db.query_row( "SELECT coalesce(sum(length(digest)+length(path)+size+128),0) FROM proof_jobs", diff --git a/apps/core/src/delivery/wallet.rs b/apps/core/src/delivery/wallet.rs index fab4c2cc5..05f3b2d58 100644 --- a/apps/core/src/delivery/wallet.rs +++ b/apps/core/src/delivery/wallet.rs @@ -286,7 +286,12 @@ fn read_keystore(path: &Path) -> Result { fn write_new_private(path: &Path, bytes: &[u8]) -> Result<()> { let result = privatefs::create_durable(path, bytes); - if result.is_err() { + // A file that was already there is not this call's to remove. + if let Err(error) = &result + && !error + .downcast_ref::() + .is_some_and(|e| e.kind() == std::io::ErrorKind::AlreadyExists) + { let _ = std::fs::remove_file(path); } result @@ -360,6 +365,7 @@ mod tests { backup(&dir, &output)?; assert_eq!(std::fs::read(&output)?, encrypted); assert!(backup(&dir, &output).is_err()); + assert_eq!(std::fs::read(&output)?, encrypted); std::fs::remove_dir_all(dir)?; Ok(()) } diff --git a/apps/core/src/discovery.rs b/apps/core/src/discovery.rs index dddfb240e..723580494 100644 --- a/apps/core/src/discovery.rs +++ b/apps/core/src/discovery.rs @@ -274,8 +274,6 @@ impl Host { versions.into_iter().map(|(_, path)| path).collect() } - /// `path` as the owner reads it in a question: under the home folder as `~/…`, elsewhere - /// only its last two parts, so the full path stays on this computer. /// The usual project folders in the home folder that exist, for a first folder to offer. pub fn project_folders(&self) -> Vec { let Some(home) = &self.home else { @@ -299,6 +297,8 @@ impl Host { found } + /// `path` as the owner reads it in a question: under the home folder as `~/…`, elsewhere + /// only its last two parts, so the full path stays on this computer. pub fn display(&self, path: &Path) -> String { self.tilde(path).unwrap_or_else(|| { let parts: Vec<_> = path.components().rev().take(2).collect(); diff --git a/apps/core/src/logging.rs b/apps/core/src/logging.rs index db1fa5f5e..cf3762d5e 100644 --- a/apps/core/src/logging.rs +++ b/apps/core/src/logging.rs @@ -219,7 +219,10 @@ pub struct Sink { impl Sink { pub fn open(dir: &Path, max_bytes: u64, keep: usize) -> Result { - ensure!(keep >= 1, "keep at least the current log file"); + ensure!( + keep >= 2, + "keep the current log file and at least one rotation" + ); let current = path(dir, 0); let file = open(¤t)?; let len = file.metadata()?.len(); diff --git a/apps/core/src/main.rs b/apps/core/src/main.rs index 047f3878f..c24d446cf 100644 --- a/apps/core/src/main.rs +++ b/apps/core/src/main.rs @@ -70,10 +70,10 @@ async fn main() -> Result<()> { let mut desktop_parent = desktop_parent::DesktopParent::watch(args.desktop_parent_stdin)?; let data_dir = args .data_dir - .or_else(|| std::env::var_os("VIBEFACE_DATA_DIR").map(PathBuf::from)) .context("--data-dir or VIBEFACE_DATA_DIR is required")?; - vibeface_core::logging::init(Some(&data_dir), false); + // Opening the log first would leave `node.log` in an empty directory and skip initialization. vibeface_core::control::prepare_start(&data_dir)?; + vibeface_core::logging::init(Some(&data_dir), false); let app_dir = match args.app_dir { Some(path) => { anyhow::ensure!( diff --git a/apps/core/src/manager.rs b/apps/core/src/manager.rs index e21a272d4..2fac7d209 100644 --- a/apps/core/src/manager.rs +++ b/apps/core/src/manager.rs @@ -328,7 +328,7 @@ where "manager workspace must be an existing absolute directory" ); ensure!( - !prompt.trim().is_empty() && prompt.len() <= 65_536, + !prompt.trim().is_empty() && prompt.len() <= MAX_PROMPT, "management prompt must be nonempty and at most 65536 bytes" ); if let Some(id) = previous_session_id { @@ -1010,13 +1010,7 @@ pub(crate) fn secret_values(config: &ManagerConfig) -> Vec { .collect(); values.extend( std::env::vars() - .filter(|(key, value)| { - value.len() >= 8 - && (key.ends_with("_KEY") - || key.ends_with("_TOKEN") - || key.ends_with("_SECRET") - || key.ends_with("_PASSWORD")) - }) + .filter(|(key, value)| value.len() >= 8 && crate::logging::credential_name(key)) .map(|(_, value)| value), ); if let Ok(keys) = config.sdk.provider().key_variables(&config.provider_env) { @@ -1722,8 +1716,8 @@ mod tests { } } - fn workspace() -> PathBuf { - let directory = std::env::temp_dir().join(format!("vf-manager-{}", uuid::Uuid::new_v4())); + fn workspace(parent: &Path) -> PathBuf { + let directory = parent.join(format!("vf-manager-{}", uuid::Uuid::new_v4())); std::fs::create_dir_all(&directory).unwrap(); directory } @@ -1771,7 +1765,7 @@ mod tests { } let error = provider_keys_from_config("model='SYNTHETIC_INLINE_SECRET").unwrap_err(); assert!(!format!("{error:#}").contains("SYNTHETIC_INLINE_SECRET")); - let dir = workspace(); + let dir = workspace(&std::env::temp_dir()); assert!(read_codex_config(&dir)?.is_none()); std::fs::write(dir.join("config.toml"), vec![b'x'; 1_048_577])?; assert!(read_codex_config(&dir).is_err()); @@ -1781,7 +1775,8 @@ mod tests { #[tokio::test] async fn unsupported_cursor_effort_is_rejected_before_launch() { - let mut config = codex(workspace(), PathBuf::from("/unused.sock")); + let dir = workspace(&std::env::temp_dir()); + let mut config = codex(dir.clone(), PathBuf::from("/unused.sock")); config.sdk = Sdk::Cursor { bridge: None, sdk_bin: "/unused-cursor".into(), @@ -1804,6 +1799,7 @@ mod tests { assert_eq!(error.stage, ProviderStage::Validate); assert_eq!(error.start, StartEvidence::NotStarted); assert!(error.failure.detail.contains("effort")); + std::fs::remove_dir_all(dir).unwrap(); } #[tokio::test] @@ -1836,7 +1832,7 @@ mod tests { }), fresh_prompt: None, }), - ..codex(workspace(), fake.socket.clone()) + ..codex(workspace(&fake.directory), fake.socket.clone()) }; let shown = Arc::new(std::sync::Mutex::new(Vec::new())); let progress = shown.clone(); @@ -1896,10 +1892,19 @@ mod tests { (false, ManagerFailure::Unknown), ] { let fake = fake_app_server(Turn::Runs { confirm }).await; - let config = codex(workspace(), fake.socket.clone()); + let config = codex(workspace(&fake.directory), fake.socket.clone()); let (stop, cancel) = watch::channel(false); + let requests = fake.requests.clone(); let stopper = tokio::spawn(async move { - tokio::time::sleep(Duration::from_millis(200)).await; + tokio::time::timeout(Duration::from_secs(10), async { + while !(requests.lock().unwrap().iter()) + .any(|request| request["method"] == "turn/start") + { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .expect("the turn started"); stop.send(true).unwrap(); stop }); @@ -1933,7 +1938,7 @@ mod tests { ("failed", ManagerFailure::Failed), ] { let fake = fake_app_server(Turn::Ends(status)).await; - let config = codex(workspace(), fake.socket.clone()); + let config = codex(workspace(&fake.directory), fake.socket.clone()); let error = run_manager( &config, "fixture", @@ -1967,7 +1972,7 @@ mod tests { record: Arc::new(|_, _| Box::pin(async { Ok(()) })), fresh_prompt: Some("full context".into()), }), - ..codex(workspace(), fake.socket.clone()) + ..codex(workspace(&fake.directory), fake.socket.clone()) }; let result = run_manager( &config, @@ -1990,7 +1995,7 @@ mod tests { #[tokio::test] async fn an_unknown_turn_start_is_not_sent_again() { let fake = fake_app_server(Turn::Drops).await; - let config = codex(workspace(), fake.socket.clone()); + let config = codex(workspace(&fake.directory), fake.socket.clone()); let error = run_manager( &config, "fixture", @@ -2015,7 +2020,7 @@ mod tests { } fn concurrent_codex(fake: &ConcurrentFake, client: &str) -> ManagerConfig { - let mut config = codex(workspace(), fake.socket.clone()); + let mut config = codex(workspace(&fake.directory), fake.socket.clone()); config.timeout_secs = 30; config.codex_turn = Some(CodexTurn { client_id: client.into(), diff --git a/apps/core/src/model.rs b/apps/core/src/model.rs index 731929057..4b09dcfd3 100644 --- a/apps/core/src/model.rs +++ b/apps/core/src/model.rs @@ -797,10 +797,8 @@ pub fn looks_secret(text: &str) -> bool { "hf_", "npm_", ]; - if MARKERS - .iter() - .any(|marker| text.to_lowercase().contains(marker)) - { + let lower = text.to_lowercase(); + if MARKERS.iter().any(|marker| lower.contains(marker)) { return true; } text.split(|c: char| c.is_whitespace() || "\"'`,;()[]{}<>".contains(c)) diff --git a/apps/core/src/net/mesh.rs b/apps/core/src/net/mesh.rs index fa2016434..e94b176ab 100644 --- a/apps/core/src/net/mesh.rs +++ b/apps/core/src/net/mesh.rs @@ -1358,6 +1358,7 @@ impl Mesh { Request::ProbeRelay { url } => { { let mut limits = self.limits.lock().expect("mesh limits"); + forget_idle(&mut limits); let limit = limits.entry(remote).or_default(); ensure!( limit.probe_at.is_none_or(|at| at.elapsed() >= PROBE_EVERY), @@ -1379,14 +1380,7 @@ impl Mesh { fn admit(&self, remote: EndpointId, digest: bool) -> Result<()> { let mut limits = self.limits.lock().expect("mesh limits"); - if limits.len() >= 4096 { - limits.retain(|_, limit| { - [limit.digest_at, limit.lookups.0, limit.probe_at] - .into_iter() - .flatten() - .any(|at| at.elapsed() < Duration::from_secs(60)) - }); - } + forget_idle(&mut limits); let limit = limits.entry(remote).or_default(); if digest { ensure!( @@ -1436,6 +1430,18 @@ impl Mesh { } } +/// Drops the limits of devices idle for a minute once the table is full. +fn forget_idle(limits: &mut HashMap) { + if limits.len() >= 4096 { + limits.retain(|_, limit| { + [limit.digest_at, limit.lookups.0, limit.probe_at] + .into_iter() + .flatten() + .any(|at| at.elapsed() < Duration::from_secs(60)) + }); + } +} + /// Looks `device` up through `net`, which runs no mesh of its own, as a stopped Node's join /// does: in `db`'s records, then asking the Nodes they name and the bootstrap nodes, within 8 s. pub async fn find_through( diff --git a/apps/core/src/runtime/agent_tools.rs b/apps/core/src/runtime/agent_tools.rs index 6f4388bf5..c52bfe446 100644 --- a/apps/core/src/runtime/agent_tools.rs +++ b/apps/core/src/runtime/agent_tools.rs @@ -67,13 +67,6 @@ impl Runtime { .context("missing tool scope")?; self.require_scope(&access, &scope).await?; let name = tool.name(); - if let Some(call_ref) = args["call_ref"].as_str() - && vibeface_protocol::validate_id(call_ref).is_err() - { - bail!( - "call_ref must contain 1-128 ASCII letters, digits, hyphens, dots or underscores, such as create-dokilove; it only keys retries of this call" - ); - } ensure!( tool.effect() == Effect::Read || access.manager.is_some(), "work changes require a live agent invocation" @@ -1859,14 +1852,15 @@ mod tests { Ok(()) } #[tokio::test] - async fn epoch8_directory_is_rejected_before_loading_any_provider_or_history() -> Result<()> { - let dir = std::env::temp_dir().join(format!("vibeface-old-epoch-{}", uuid::Uuid::new_v4())); + async fn a_directory_of_another_data_epoch_is_rejected_before_loading_anything() -> Result<()> { + let dir = + std::env::temp_dir().join(format!("vibeface-other-epoch-{}", uuid::Uuid::new_v4())); crate::config::private_dir(&dir)?; std::fs::write(dir.join("data-epoch.json"), br#"{"data_epoch":8}"#)?; let error = Runtime::open(&dir) .await .err() - .context("old epoch must fail")?; + .context("another epoch must fail")?; assert!(error.to_string().contains(&format!( "requires an initialized data epoch {} directory", crate::config::DATA_EPOCH diff --git a/apps/core/src/runtime/bots.rs b/apps/core/src/runtime/bots.rs index 588e990e7..e28760ed6 100644 --- a/apps/core/src/runtime/bots.rs +++ b/apps/core/src/runtime/bots.rs @@ -547,12 +547,6 @@ mod tests { .contains("version and avatar are required"), "{missing}" ); - let mut forged = pick.clone(); - forged["version"] = json!("0123456789abcdef"); - assert!( - node.rpc(client(None), forged).await.is_err(), - "the signature covers the version" - ); let in_bots = node .rpc(client(None), request("bots", None, Some(cloud))?) .await; @@ -575,6 +569,14 @@ mod tests { ); let count = events(&node).await?; + let mut forged = request("c", None, Some(bean))?; + forged["version"] = json!(picked); + let forged = node.rpc(client(None), forged).await.unwrap_err(); + assert!( + format!("{forged:#}").contains("device signature does not match"), + "the signature covers the version: {forged:#}" + ); + assert_eq!(events(&node).await?, count); let again = node.rpc(client(None), pick.clone()).await?; assert_eq!(again["bot"]["avatar_version"], json!(picked)); assert_eq!( diff --git a/apps/core/src/runtime/claude.rs b/apps/core/src/runtime/claude.rs index 5a0042a4a..cbeae2dbd 100644 --- a/apps/core/src/runtime/claude.rs +++ b/apps/core/src/runtime/claude.rs @@ -4,6 +4,7 @@ //! sight of is read back from Claude Code's own transcript and never sent again. Hooks of the //! owner's own sessions hold permission requests and questions for the bot. use super::executor::{Executor, SteerAck, SteerInput, SteerTrace}; +use super::provider_adapter::bounded; use super::*; use crate::manager::{self, CodexTurn, ManagerConfig, ManagerError, ManagerFailure}; use crate::scheduling::{SteerOutcome, SteerTarget}; @@ -642,15 +643,8 @@ fn tool_kind(name: &str) -> &'static str { } } -fn clip(text: &str, limit: usize) -> String { - text.chars() - .filter(|c| !c.is_control() || matches!(c, '\n' | '\t')) - .take(limit) - .collect() -} - fn tool_progress(id: &str, name: &str, status: &str) -> Value { - json!({"type":"tool","item_id":clip(id, 128),"name":name,"status":status}) + json!({"type":"tool","item_id":bounded(id, 128),"name":name,"status":status}) } /// What the frames of one turn said so far. @@ -671,7 +665,7 @@ impl Turn { Some(json!({"type":"status","status":"running"})) } Frame::Text { id, text } => Some( - json!({"type":"text_snapshot","item_id":clip(&id, 128),"text":clip(&text, 8000)}), + json!({"type":"text_snapshot","item_id":bounded(&id, 128),"text":bounded(&text, 8000)}), ), Frame::ToolStarted { id, name } => { let progress = tool_progress(&id, name, "running"); @@ -1399,10 +1393,6 @@ where break 'turn Err(error(ManagerFailure::Unknown, native, own(&e.to_string()))); } } - if turn.session.is_some() { - stage.enter(ProviderStage::Run); - *start.lock().unwrap() = manager::StartEvidence::Started; - } if let Some(next) = turn.ending.take() { processes.close_input(process.tree.token()); Ending::append(&mut ending, next); @@ -1600,6 +1590,7 @@ async fn follow( node: Weak, network: String, work_id: String, + conversation: String, session: String, message: String, mut process: Process, @@ -1642,12 +1633,11 @@ async fn follow( }; if let Some(progress) = turn.apply(frame) && let Ok(target_node) = node.identity.device_id() - && let Ok(Some(record)) = node.store.lock().await.work_record(&work_id) { let sequence = node.progress_sequence.fetch_add(1, Ordering::Relaxed) + 1; node.publish_progress( &network, - json!({"type":"native_progress","conversation_id":record.conversation, + json!({"type":"native_progress","conversation_id":conversation, "work_id":work_id,"target_node":target_node,"sequence":sequence, "progress":progress}), ); @@ -1853,6 +1843,7 @@ impl Executor for Claude { Arc::downgrade(node), network.to_owned(), work_id.to_owned(), + work.conversation.clone(), session, message, process, @@ -2414,9 +2405,7 @@ pub(super) mod tests { } fn gated_config(place: &Place, client: &str) -> ManagerConfig { - let (record, _) = recorder(); - let mut config = bot_config(place, record); - config.timeout_secs = 30; + let mut config = bot_config(place, Arc::new(|_, _| Box::pin(async { Ok(()) }))); config.codex_turn = Some(CodexTurn { client_id: client.into(), started: None, @@ -2707,7 +2696,6 @@ pub(super) mod tests { Probe::Missing ); let locator_path = reader.processes.reply_locator_path("attempt-a")?; - let locator = std::fs::read(&locator_path)?; std::fs::remove_file(&locator_path)?; assert_eq!( reader.probe_reply(&session, None, "attempt-a").await?, @@ -2718,7 +2706,6 @@ pub(super) mod tests { reader.probe_reply(&session, None, "attempt-a").await?, Probe::Missing ); - config::private_write(&locator_path, &locator)?; Ok(()) } @@ -3049,7 +3036,7 @@ pub(super) mod tests { assert_eq!( log[0]["env"], json!({"VIBEFACE_TOOL_TOKEN":true,"VIBEFACE_NODE_URL":true,"CLAUDECODE":false, - "CLAUDE_CODE_ENTRYPOINT":false,"FAKE_MARK":false}) + "CLAUDE_CODE_ENTRYPOINT":false}) ); assert_eq!(log[1]["uuid"], message.as_str()); assert!( @@ -3367,22 +3354,14 @@ time.sleep(0.05) vec![], now_ms(), )?; - let input = admin.attest( + let input = crate::runtime::test_support::signed_main_input( + admin, network, conversation_id, - EventBody::InputPosted { - message_id: message_id.into(), - target: crate::workspace::InputTarget::BotMain { - bot_id: conversation_id.into(), - }, - intent: crate::workspace::InputIntent::Continue, - sequence: 1, - expected_revision: None, - text: "Run the provider fixture work".into(), - attachments: vec![], - report_results: Some(true), - attestation: None, - }, + message_id, + "Run the provider fixture work", + vec![], + 1, )?; store.append_event( &node.identity, diff --git a/apps/core/src/runtime/codex_server.rs b/apps/core/src/runtime/codex_server.rs index e0cc3186e..9619fdf50 100644 --- a/apps/core/src/runtime/codex_server.rs +++ b/apps/core/src/runtime/codex_server.rs @@ -1372,16 +1372,27 @@ mod tests { #[test] fn app_server_reasons_are_scrubbed_bounded_and_control_free() { - let link = Link::LaunchFailed { - reason: format!("Authorization: Bearer fixture-secret\n{}", "x".repeat(800)), + let link = Link::Connected { + socket: PathBuf::from("/fixture.sock"), + user_agent: format!("Authorization: Bearer fixture-secret\n{}", "x".repeat(800)), } .sanitized(); - let Link::LaunchFailed { reason } = link else { + let Link::Connected { user_agent, .. } = link else { panic!("wrong link state") }; - assert!(!reason.contains("fixture-secret")); - assert!(!reason.chars().any(char::is_control)); - assert!(reason.chars().count() <= 512); + assert!(!user_agent.contains("fixture-secret")); + assert!(!user_agent.chars().any(char::is_control)); + assert_eq!(user_agent.chars().count(), 512); + let failed = Link::LaunchFailed { + reason: "Authorization: Bearer fixture-secret".into(), + } + .sanitized(); + assert_eq!( + failed, + Link::LaunchFailed { + reason: "Codex App Server could not start; check the local Node log".into() + } + ); } #[test] @@ -2199,11 +2210,6 @@ raise SystemExit(7) bins: BTreeMap::from([(Provider::Codex, program)]), env: ProviderEnv::default(), }; - assert_eq!( - local.switches.codex_app_server.mode, - AppServerMode::System, - "an explicit system App Server remains usable" - ); let identity = LocalIdentity::generate(); let (events, _events) = mpsc::unbounded_channel(); let server = CodexServer::open(local.codex_target(false), &identity, &dir, events)?; diff --git a/apps/core/src/runtime/cursor.rs b/apps/core/src/runtime/cursor.rs index 1147addaf..6bbacb43a 100644 --- a/apps/core/src/runtime/cursor.rs +++ b/apps/core/src/runtime/cursor.rs @@ -397,7 +397,7 @@ impl CursorExecutor { return Ok(owner); } let projections = node.store.lock().await.works(network, &work.conversation)?; - let mut by_id: HashMap<_, _> = projections + let by_id: HashMap<_, _> = projections .into_iter() .map(|projection| (projection.work_id.clone(), projection)) .collect(); @@ -410,10 +410,10 @@ impl CursorExecutor { "Cursor continuation lineage contains a cycle" ); let projection = by_id - .remove(&previous) + .get(&previous) .context("continued Cursor work is not on this device")?; root = projection.work_id.clone(); - next = projection.continues; + next = projection.continues.clone(); } let workspace = self .owner_for_work(&root) @@ -502,7 +502,10 @@ impl CursorExecutor { cancel: watch::Receiver, ) { let WorkSpec { - work_id, prompt, .. + work_id, + prompt, + conversation, + .. } = work; let bridge = match self.bridge() { Ok(bridge) => bridge, @@ -597,6 +600,7 @@ impl CursorExecutor { let node = progress_node.clone(); let network = progress_network.clone(); let work_id = progress_work.clone(); + let conversation = conversation.clone(); let text = progress_text.clone(); async move { let Some(node) = node.upgrade() else { @@ -635,7 +639,7 @@ impl CursorExecutor { let target_node = node.identity.device_id()?; node.publish_progress( &network, - json!({"type":"native_progress","conversation_id":node.store.lock().await.work_record(&work_id)?.map(|r| r.conversation).unwrap_or_default(),"work_id":work_id,"target_node":target_node,"sequence":node.progress_sequence.fetch_add(1, Ordering::Relaxed)+1,"progress":update}), + json!({"type":"native_progress","conversation_id":conversation,"work_id":work_id,"target_node":target_node,"sequence":node.progress_sequence.fetch_add(1, Ordering::Relaxed)+1,"progress":update}), ); Ok(()) } @@ -1630,6 +1634,21 @@ mod tests { ); } } + let root = work(&node, &workspace, "not-started", "fixture prompt")?; + let follow = WorkSpec { + continues: Some(root.work_id.clone()), + cwd: dir.join("elsewhere").display().to_string(), + ..work(&node, &workspace, "follow", "more")? + }; + let owner = node + .cursor_executor + .lineage(&node, &network, &follow) + .await?; + assert_eq!( + (owner.root_work, owner.workspace), + (root.work_id, workspace.clone()), + "a follow-up runs where its root work ran" + ); node.shutdown().await; drop(node); std::fs::remove_dir_all(dir)?; diff --git a/apps/core/src/runtime/manager_control.rs b/apps/core/src/runtime/manager_control.rs index 07b5dbb32..9e131dfa4 100644 --- a/apps/core/src/runtime/manager_control.rs +++ b/apps/core/src/runtime/manager_control.rs @@ -856,7 +856,7 @@ pub(super) mod tests { let job = store.claim_next_fixture(&node.identity, &network, "c", &node.boot, "lease-fence")?.context("Task claim")?.job; let attempt = job.state.attempt().context("attempt")?.id.clone(); store.mark_started("c", &job.trigger, &attempt)?; - store.started_workspace_assignment(&node.identity, &network, &job, now_ms())?; + store.settle_workspace_assignment(&node.identity, &network, &job, now_ms())?; (job, first, attempt) }; let _cancel = node.register_manager_attempt_fixture("lease-token".into(), test_access(network.clone(), false, Some("c".into())), &attempt, &job.trigger, crate::providers::Provider::Codex).await?; diff --git a/apps/core/src/runtime/opencode.rs b/apps/core/src/runtime/opencode.rs index 5b5829246..49cae746a 100644 --- a/apps/core/src/runtime/opencode.rs +++ b/apps/core/src/runtime/opencode.rs @@ -193,9 +193,6 @@ struct Live { /// Its first message, which steers name as the turn. turn: String, conn: Conn, - directory: String, - /// What every message of the turn carries besides its own: agent, system and model. - body: Value, /// Our messages in the order sent: the turn's, then the steered ones. sent: Vec, last_post_ms: i64, @@ -996,39 +993,6 @@ impl Opencode { Some(!self.inbox(&conn, session).await.ok()?.is_empty()) } - /// Whether no run or queued input remains in a reply's session; a running turn is aborted. Runs - /// end with their serve, and the Node stops the serve of an earlier run when it opens. - #[cfg(all(test, unix))] - pub(crate) async fn run_ended(&self, session: &str) -> bool { - let ended = async { - let Some(conn) = self.running().await else { - return true; - }; - match self.session(&conn, session).await { - Ok(Some(_)) => {} - Ok(None) => return true, - Err(_) => return false, - } - let pending = match self.inbox(&conn, session).await { - Ok(items) => !items.is_empty(), - Err(_) => return false, - }; - match self.busy(&conn, session).await { - Ok(false) => !pending, - Ok(true) => { - let _ = self.abort(&conn, session).await; - false - } - Err(_) => false, - } - } - .await; - if ended { - self.release_manager(session); - } - ended - } - pub(crate) async fn run_turn( &self, config: &ManagerConfig, @@ -1101,7 +1065,7 @@ impl Opencode { })?, None => None, }; - let (session, directory, prompt) = match (resumed, previous) { + let (session, prompt) = match (resumed, previous) { (Some(found), Some(id)) => { let busy = self .busy(&conn, id) @@ -1120,7 +1084,6 @@ impl Opencode { ), )); } - let directory = found["location"]["directory"].as_str().unwrap_or(workspace); if let Some(model) = model.as_ref() && found["model"] != *model { @@ -1131,7 +1094,7 @@ impl Opencode { ) })?; } - (id.to_owned(), directory.to_owned(), prompt) + (id.to_owned(), prompt) } _ => { let id = (self.create(&conn, workspace, model.as_ref()).await) @@ -1140,7 +1103,7 @@ impl Opencode { let fresh = previous .and(config.codex_turn.as_ref()) .and_then(|turn| turn.fresh_prompt.as_deref()); - (id, workspace.to_owned(), fresh.unwrap_or(prompt)) + (id, fresh.unwrap_or(prompt)) } }; let native = Some(session.as_str()); @@ -1194,17 +1157,14 @@ impl Opencode { &config.custom_tools, &config.instructions, ); - let body = json!({"id":message,"text":if instructions.is_empty() { + let first = json!({"id":message,"text":if instructions.is_empty() { prompt.to_owned() } else { format!("{instructions}\n\n{prompt}") }}); - let first = body.clone(); let live = Live { turn: message.clone(), conn: conn.clone(), - directory: directory.clone(), - body, sent: vec![message.clone()], last_post_ms: now_ms(), open: true, @@ -1387,9 +1347,9 @@ impl Opencode { } let reply = match &last.reply { None => { - let failure = seen.error.take().unwrap_or_else(|| { - own("opencode ended the run without an answer; check that the model exists and its provider is signed in") - }); + let failure = own( + "opencode ended the run without an answer; check that the model exists and its provider is signed in", + ); return Err(failed(native, failure)); } Some(reply) if reply["error"]["type"] == "aborted" => { @@ -1491,7 +1451,6 @@ fn session_of(event: &Value) -> Option<&str> { /// opencode reported. #[derive(Default)] struct Seen { - texts: BTreeSet, tools: HashMap, tool_names: HashMap, error: Option, @@ -1508,7 +1467,6 @@ impl Seen { data["assistantMessageID"].as_str()?, data["ordinal"].as_u64().unwrap_or_default() ); - self.texts.insert(id.clone()); Some( json!({"type":"text_delta","item_id":bounded(&id, 128),"text":bounded(data["delta"].as_str()?, 8000)}), ) @@ -2036,15 +1994,13 @@ impl Executor for Opencode { .map(|turn| { turn.sent.push(id.clone()); turn.last_post_ms = now_ms(); - (turn.conn.clone(), turn.directory.clone(), turn.body.clone()) + turn.conn.clone() }) }; - let Some((conn, _directory, mut body)) = joined else { + let Some(conn) = joined else { return SteerAck::Refused("the reply already ended".into()); }; - body["id"] = json!(id); - body["text"] = json!(input.message(message_id)); - body.as_object_mut().expect("prompt body").remove("files"); + let mut body = json!({"id":id,"text":input.message(message_id)}); if !input.files.is_empty() { let mut files = Vec::new(); for file in &input.files { @@ -2736,12 +2692,16 @@ mod tests { /// The session and message of the bot turn once opencode took it. async fn started(turns: &Turns) -> (String, String) { - loop { - if let Some((session, Some(turn))) = turns.lock().unwrap().last().cloned() { - return (session, turn); + tokio::time::timeout(Duration::from_secs(10), async { + loop { + if let Some((session, Some(turn))) = turns.lock().unwrap().last().cloned() { + return (session, turn); + } + tokio::time::sleep(Duration::from_millis(10)).await; } - tokio::time::sleep(Duration::from_millis(10)).await; - } + }) + .await + .expect("the turn was recorded") } fn spec(target: &str, place: &Place, prompt: &str) -> WorkSpec { @@ -2832,6 +2792,7 @@ mod tests { "XDG_STATE_HOME", "XDG_CACHE_HOME", "OPENCODE_CONFIG", + "OPENCODE_CLI_CONFIG_CONTENT", "OPENCODE_TEST_HOME", ] { env.insert(key.into(), user.join(key).display().to_string()); @@ -2859,11 +2820,10 @@ mod tests { .collect::>()?; let last = recorded.last().context("recorded launch")?; for (key, value) in &expected { - if last.get(key).is_some() { - assert_eq!(last[key], json!(value)); - } + assert_eq!(last[key], json!(value), "{key}"); } assert_eq!(last["OPENCODE_CONFIG"], Value::Null); + assert_eq!(last["OPENCODE_CLI_CONFIG_CONTENT"], Value::Null); assert_eq!(last["OPENCODE_TEST_HOME"], Value::Null); assert_eq!(last["fake_auth_present"], true); assert!(Path::new(&expected["OPENCODE_DB"]).is_file()); @@ -3418,7 +3378,12 @@ mod tests { let config = bot(&place, &server, "attempt-1", &Turns::default()); let (_, never) = watch::channel(false); let (result, _, _) = turn(&place, &config, "hello", None, never).await; - assert!(result.is_err()); + let error = result.err().expect("the turn is refused"); + assert!( + format!("{error:#}").contains("set the tool environment"), + "{error:#}" + ); + assert_eq!(place.fake.lock().unwrap().sessions.len(), 1); assert!(place.prompts().is_empty()); Ok(()) } @@ -4051,38 +4016,6 @@ mod tests { Ok(()) } - #[tokio::test] - async fn an_unknown_turn_keeps_its_serve_until_read_back_confirms_it_ended() -> Result<()> { - let place = Place::new().await?; - let server = place.opencode()?; - let (conn, serving) = server.conn().await?; - let session = server - .create(&conn, place.dir.to_str().unwrap(), None) - .await - .expect("fixture session"); - let start = std::sync::Mutex::new(manager::StartEvidence::Started); - drop(TurnGuard { - owner: &server, - session: session.clone(), - events: tokio::spawn(async {}), - serving: Some(serving), - start: &start, - terminal: false, - }); - assert_eq!(server.users.load(std::sync::atomic::Ordering::SeqCst), 1); - let mut expected = server.launch.lock().expect("launch").current.clone(); - expected - .env - .insert("VIBEFACE_FAKE_LAUNCH".into(), "after-unknown".into()); - server.set_launch(expected.bin.clone(), expected.env.clone()); - assert!(server.configuration_pending(&expected.bin, &expected.env)); - assert!(server.run_ended(&session).await); - assert_eq!(server.users.load(std::sync::atomic::Ordering::SeqCst), 0); - assert!(!server.configuration_pending(&expected.bin, &expected.env)); - server.stop().await; - Ok(()) - } - #[tokio::test] async fn serve_startup_is_serial_and_a_waiting_turn_can_be_cancelled() -> Result<()> { let place = Place::new().await?; @@ -4221,31 +4154,4 @@ mod tests { Err(FailureKind::NoModel) ); } - - #[tokio::test] - async fn pending_input_does_not_prevent_reconciliation_from_stopping_a_running_session() - -> Result<()> { - let place = Place::new().await?; - let server = place.opencode()?; - let (conn, _serving) = server.conn().await?; - let session = server - .create(&conn, &place.dir.join("work").to_string_lossy(), None) - .await - .map_err(|failure| anyhow::anyhow!(failure.detail))?; - server - .send(&conn, &session, &json!({"id":"msg_active","text":"HOLD"})) - .await; - server - .send(&conn, &session, &json!({"id":"msg_pending","text":"INBOX"})) - .await; - assert!(!server.run_ended(&session).await); - assert!(!place.fake.lock().unwrap().sessions[&session].busy); - assert!( - server - .inbox_contains(&conn, &session, "msg_pending") - .await? - ); - assert_eq!(place.fake.lock().unwrap().aborts, 1); - Ok(()) - } } diff --git a/apps/core/src/runtime/peers.rs b/apps/core/src/runtime/peers.rs index ddce654dc..7332e1ad4 100644 --- a/apps/core/src/runtime/peers.rs +++ b/apps/core/src/runtime/peers.rs @@ -582,13 +582,12 @@ impl Runtime { self.merge_addresses(network, records).await?; Ok(json!({"records":self.store.lock().await.address_book()?})) } - "deliver" => self.accept_delivery(network, origin, input).await, "scheduler_jobs" => { self.owner_jobs(network, field(input, "conversation_id")?) .await } "progress_read" => self.read_progress(network, origin, input).await, - "dispatch_work" | "interrupt_work" => { + "deliver" | "dispatch_work" | "interrupt_work" => { self.accept_peer_command(network, origin, input).await } "input_receipt" => self.read_input_receipt(network, input).await, @@ -1236,7 +1235,6 @@ impl Runtime { true } - /// The write state, and the conflicts kept aside here, for the web. /// Each other member Node with whether the last sync reached it and when one last finished. pub(crate) async fn peer_health(&self) -> Vec { let Ok(view) = self @@ -1323,6 +1321,7 @@ impl Runtime { })) } + /// The write state, and the conflicts kept aside here, for the web. pub(crate) async fn write_status(&self, network: &str) -> Result { let state = *self.write_state.borrow(); let conflicts = self.store.lock().await.conflicts(network)?; @@ -2025,10 +2024,6 @@ impl Runtime { detail, now_ms(), )?; - ensure!( - matches!(state, "saved" | "waiting_dependencies"), - "invalid owner admission state" - ); self.store .lock() .await @@ -2049,15 +2044,6 @@ impl Runtime { } } - async fn accept_delivery( - self: &Arc, - network: &str, - origin: &str, - input: &Value, - ) -> Result { - self.accept_peer_command(network, origin, input).await - } - async fn accept_peer_command( self: &Arc, network: &str, @@ -2365,14 +2351,6 @@ impl Runtime { let size = blob.size; tokio::task::spawn_blocking(move || staging_room(&dir, size)).await??; } - let mut file = tokio::fs::OpenOptions::new() - .create(true) - .write(true) - .truncate(false) - .open(&part) - .await?; - file.set_len(committed).await?; - file.seek(std::io::SeekFrom::Start(committed)).await?; let connection = self.net()?.connect(peer, net::BLOB).await?; let (mut send, mut recv) = connection .open_bi() @@ -2390,6 +2368,14 @@ impl Runtime { if let Some(error) = header["error"].as_str() { bail!("{error}"); } + let mut file = tokio::fs::OpenOptions::new() + .create(true) + .write(true) + .truncate(false) + .open(&part) + .await?; + file.set_len(committed).await?; + file.seek(std::io::SeekFrom::Start(committed)).await?; let mut offset = committed; let mut unsynced = 0; while let Some(chunk) = recv @@ -4604,6 +4590,14 @@ mod tests { b.store.lock().await.missing_blobs(&network)?, std::slice::from_ref(&lacked.1) ); + assert!( + !b.store + .lock() + .await + .partial_blob_file(&lacked.1.hash)? + .exists(), + "an attachment the peer lacks stages nothing" + ); a.store.lock().await.put_blob(&lacked.1, &lacked.0)?; b.sync_peer(&network, &ia.device_id()?).await?; assert!( @@ -4652,20 +4646,7 @@ mod tests { .cloned() .context("the peer is listed") }; - a.wake_sync(&peer); - tokio::time::timeout(Duration::from_secs(30), async { - while !a - .sync_peers - .lock() - .expect("sync peers") - .get(&peer) - .is_some_and(|state| state.synced_ms.is_some() && state.failures == 0) - { - tokio::time::sleep(Duration::from_millis(50)).await; - } - }) - .await - .context("first sync")?; + first_sync(&a, &peer).await?; let online = listed(a.rpc(access.clone(), json!({"method":"nodes"})).await?)?; assert_eq!(online["online"], true); assert_eq!(online["capabilities"]["manager"], "cursor"); @@ -5676,14 +5657,18 @@ mod tests { .collect()) }; let mut settled = Vec::new(); - loop { - let now = vec![book(&l).await?, book(&c).await?]; - if now.iter().all(|records| records.len() == 1) && now == settled { - break; + tokio::time::timeout(Duration::from_secs(60), async { + loop { + let now = vec![book(&l).await?, book(&c).await?]; + if now.iter().all(|records| records.len() == 1) && now == settled { + break anyhow::Ok(()); + } + settled = now; + tokio::time::sleep(Duration::from_secs(6)).await; } - settled = now; - tokio::time::sleep(Duration::from_secs(6)).await; - } + }) + .await + .context("the address books settle")??; let records = l.store.lock().await.address_book()?; c.merge_addresses(&network, records).await?; c.sync_peers diff --git a/apps/core/src/runtime/pi.rs b/apps/core/src/runtime/pi.rs index f10863501..8333152e9 100644 --- a/apps/core/src/runtime/pi.rs +++ b/apps/core/src/runtime/pi.rs @@ -926,7 +926,10 @@ impl Pi { if state["sessionId"] != session { return Err(own(format!("pi opened session {}", state["sessionId"]))); } - let file = PathBuf::from(state["sessionFile"].as_str().unwrap_or_default()); + let Some(file) = state["sessionFile"].as_str().filter(|f| !f.is_empty()) else { + return Err(own("pi reported no session file".into())); + }; + let file = PathBuf::from(file); self.keep(session, &file, &launch.cwd, process.tree.token()) .map_err(|error| own(format!("keep where pi writes the session: {error:#}"))) }; @@ -1845,7 +1848,6 @@ mod tests { fn gated_bot(dir: &Path, pi: &Arc, mode: &str, client: &str) -> ManagerConfig { let mut config = bot(dir, pi, mode, None); - config.timeout_secs = 30; config.provider_env = gated_env(dir, mode); config.codex_turn = Some(CodexTurn { client_id: client.into(), @@ -1981,12 +1983,16 @@ mod tests { /// The turn the bot recorded once pi took its prompt. async fn started(turns: &Turns) -> (String, String) { - loop { - if let Some((session, Some(turn))) = turns.lock().unwrap().last().cloned() { - return (session, turn); + tokio::time::timeout(Duration::from_secs(10), async { + loop { + if let Some((session, Some(turn))) = turns.lock().unwrap().last().cloned() { + return (session, turn); + } + tokio::time::sleep(Duration::from_millis(20)).await; } - tokio::time::sleep(Duration::from_millis(20)).await; - } + }) + .await + .expect("the turn was recorded") } fn launch(dir: &Path, mode: &str, session: &str) -> Launch { @@ -2575,7 +2581,6 @@ mod tests { Ok(()) } - #[cfg(unix)] #[tokio::test] async fn a_normal_end_preserves_eof_and_grace_for_a_cooperative_child() -> Result<()> { let dir = scratch("normal-cooperative-end"); diff --git a/apps/core/src/runtime/schedule_delivery.rs b/apps/core/src/runtime/schedule_delivery.rs index 44d66130c..443357778 100644 --- a/apps/core/src/runtime/schedule_delivery.rs +++ b/apps/core/src/runtime/schedule_delivery.rs @@ -96,7 +96,7 @@ impl Runtime { async fn reconcile_workspace_jobs(self: &Arc, network: &str) -> Result<()> { let before = self.store.lock().await.version_vector(network)?; - let jobs = self.store.lock().await.scheduler_jobs_all()?; + let jobs = self.store.lock().await.workspace_scheduler_jobs()?; for job in jobs { let crate::scheduling::SessionScope::WorkspaceTask { task_id } = &job.scope else { continue; diff --git a/apps/core/src/runtime/settings.rs b/apps/core/src/runtime/settings.rs index 6f4bcd0a9..f2ff7ded5 100644 --- a/apps/core/src/runtime/settings.rs +++ b/apps/core/src/runtime/settings.rs @@ -781,7 +781,6 @@ impl Runtime { } let active = self.manager_controls.lock().await; if !active.is_empty() || self.triage.turn.try_lock().is_err() { - self.pending_provider_launches.store(true, SeqCst); return Ok(false); } let store = self.store.lock().await; @@ -792,10 +791,7 @@ impl Runtime { crate::model::WorkKind::Agent(Provider::Codex | Provider::Opencode) ) && !work.state.finished() }), - Err(error) => { - self.pending_provider_launches.store(true, SeqCst); - return Err(error); - } + Err(error) => return Err(error), }; let busy_job = match store.scheduler_jobs_all() { Ok(jobs) => jobs.iter().any(|job| { @@ -804,13 +800,9 @@ impl Runtime { "claimed" | "running" | "cancelling" | "reconciling" | "steering" ) }), - Err(error) => { - self.pending_provider_launches.store(true, SeqCst); - return Err(error); - } + Err(error) => return Err(error), }; if busy_work || busy_job { - self.pending_provider_launches.store(true, SeqCst); return Ok(false); } drop(store); @@ -1041,7 +1033,7 @@ impl ProposalInput { mode: AppServerMode::System, socket: Some(socket), }), - codex_home: existing(self.codex_home, "codex_home", Path::is_dir)?, + codex_home: None, bins: self .bins .into_iter() @@ -1087,12 +1079,7 @@ impl Runtime { .iter() .any(|provider| provider.on_app_server()) || given.app_server.is_some() - || given.codex_home.is_some() || given.codex_sessions.is_some(); - let host = discovery::Host { - codex_home: given.codex_home.clone().or(self.host.codex_home.clone()), - ..self.host.clone() - }; let (mut local, mut manager, mut triage) = ( self.providers(), self.settings_snapshot().manager, @@ -1110,7 +1097,7 @@ impl Runtime { triage: &mut triage, }, codex.then_some(Provider::Codex), - &host, + &self.host, )?; let (mut local, mut manager, mut triage) = ( self.providers(), @@ -1757,7 +1744,7 @@ mod tests { &bin, r#"#!/usr/bin/env python3 import json, os, pathlib, sys -names = ['CODEX_HOME', 'CLAUDE_CONFIG_DIR', 'XDG_DATA_HOME', 'XDG_CONFIG_HOME', 'XDG_STATE_HOME', 'XDG_CACHE_HOME', 'OPENCODE_DB', 'OPENCODE_CONFIG_DIR', 'OPENCODE_CONFIG', 'OPENCODE_CONFIG_CONTENT', 'OPENCODE_CLI_CONFIG_CONTENT', 'OPENCODE_TEST_HOME', 'CURSOR_API_KEY', 'CURSOR_AUTH_TOKEN', 'AGENT_CLI_CREDENTIAL_STORE'] +names = ['CODEX_HOME', 'CLAUDE_CONFIG_DIR', 'XDG_DATA_HOME', 'XDG_CONFIG_HOME', 'XDG_STATE_HOME', 'XDG_CACHE_HOME', 'OPENCODE_DB', 'OPENCODE_CONFIG_DIR', 'OPENCODE_CONFIG', 'OPENCODE_CONFIG_CONTENT', 'OPENCODE_CLI_CONFIG_CONTENT', 'OPENCODE_TEST_HOME', 'OPENCODE_DISABLE_PROJECT_CONFIG', 'OPENCODE_CONFIG_PROJECT_DISABLE', 'OPENCODE_DISABLE_CLAUDE_CODE', 'CURSOR_API_KEY', 'CURSOR_AUTH_TOKEN', 'AGENT_CLI_CREDENTIAL_STORE'] pathlib.Path(__file__).with_name('observed.json').write_text(json.dumps({'args': sys.argv[1:], 'env': {name: os.environ.get(name) for name in names}, 'auth': os.environ.get('FAKE_LOGIN_AUTH')})) "#, )?; @@ -1823,9 +1810,7 @@ pathlib.Path(__file__).with_name('observed.json').write_text(json.dumps({'args': ); } for (name, value) in roots.env(provider) { - if observed["env"].get(&name).is_some() { - assert_eq!(observed["env"][name], value); - } + assert_eq!(observed["env"][&name], value, "{name}"); } if provider == Provider::Opencode { for name in [ diff --git a/apps/core/src/runtime/triage.rs b/apps/core/src/runtime/triage.rs index 5632ae97f..ba1865b0b 100644 --- a/apps/core/src/runtime/triage.rs +++ b/apps/core/src/runtime/triage.rs @@ -2642,6 +2642,11 @@ impl Runtime { |r| r.get(0), ) .optional()?; + if let Some(mark) = mark + && std::fs::metadata(&path).is_ok_and(|meta| meta.len() == mark as u64) + { + continue; + } let Ok(text) = std::fs::read_to_string(&path) else { continue; }; @@ -3556,9 +3561,7 @@ pub(super) mod tests { with_agent(&node); bot(&node, &admin, "c", "前端", &[]).await?; let mut requests = answering_app_server(&node).await?; - while node.codex.status().await["connection"]["state"] != "connected" { - tokio::time::sleep(Duration::from_millis(20)).await; - } + connected(&node).await; let network = node.network_id().await?; let local = node.identity.device_id()?; let spec = crate::work::WorkSpec { @@ -3689,7 +3692,7 @@ pub(super) mod tests { #[tokio::test] async fn a_send_stuck_past_its_window_is_unverified_then_followed() -> Result<()> { use crate::model::{WorkOutcome, WorkStatus}; - use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::atomic::AtomicBool; with_node(async |node, admin, _| { bot(&node, &admin, "c", "前端", &[]).await?; let started = Arc::new(AtomicBool::new(false)); @@ -3840,7 +3843,7 @@ pub(super) mod tests { #[tokio::test] async fn a_held_stop_outlives_a_failed_interrupt_and_ends_with_its_work() -> Result<()> { - use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::atomic::AtomicBool; with_node(async |node, admin, _| { with_agent(&node); bot(&node, &admin, "c", "前端", &[]).await?; @@ -5275,6 +5278,7 @@ pub(super) mod tests { assert_eq!(node.triage_status().await?["unknown_events"], 1); Ok::<_, anyhow::Error>((network, question.to_owned(), request_id.to_owned())) }.await; + node.shutdown().await; drop(node); let reopened = Arc::new(Runtime::reopen(&dir).await?); let result = async { @@ -6285,7 +6289,6 @@ pub(super) mod tests { #[tokio::test] async fn a_work_runs_on_the_provider_it_names() -> Result<()> { - use crate::providers::Provider; with_node(async |node, admin, dir| { assert!(std::ptr::addr_eq( node.executor(Provider::Codex)?, @@ -6406,7 +6409,6 @@ pub(super) mod tests { #[tokio::test] async fn a_work_asking_what_its_agent_cannot_do_is_refused_before_it_is_registered() -> Result<()> { - use crate::providers::Provider; with_node(async |node, admin, dir| { with_agent(&node); node.settings.lock().unwrap().roots = vec![dir.clone()]; @@ -6491,13 +6493,11 @@ pub(super) mod tests { #[tokio::test] async fn a_work_without_agent_goes_on_where_its_thread_or_original_ran() -> Result<()> { use crate::model::WorkKind; - use crate::providers::Provider; with_node(async |node, admin, dir| { with_agent(&node); if let Some(manager) = node.settings.lock().unwrap().manager.as_mut() { manager.provider = Provider::Claude; } - node.settings.lock().unwrap().roots = vec![dir.clone()]; { let mut providers = node.providers.lock().unwrap(); providers.switches.execution.insert(Provider::Claude); @@ -7867,8 +7867,7 @@ pub(super) mod tests { } .await; server.abort(); - drop(node); - std::fs::remove_dir_all(dir)?; + cleanup(node, dir).await?; result } @@ -8429,8 +8428,7 @@ pub(super) mod tests { bot(&node, &admin, "c", "Bot", &[]).await?; let network = node.network_id().await?; let (trigger, attempt) = start_reply(&node, &admin, "m1").await?; - node.register_manager_attempt_fixture("thread-retry-token".into(), test_access(network.clone(), false, Some("c".into())), &attempt, &trigger, Provider::Codex).await?; - let access = node.agent_tokens.lock().await.get("thread-retry-token").cloned().context("access")?; + let access = node.manager_access_fixture("thread-retry-token", test_access(network.clone(), false, Some("c".into())), &attempt, &trigger, Provider::Codex).await?; let mut original = Vec::new(); for (call, explicit, model) in [("explicit", true, Some("frozen")), ("implicit", false, Some("frozen")), ("explicit-default", true, None), ("implicit-default", false, None)] { { @@ -8510,7 +8508,6 @@ pub(super) mod tests { Ok::<_, anyhow::Error>(()) }.await; server.abort(); - node.shutdown().await; cleanup(node, dir).await?; result } @@ -8527,8 +8524,7 @@ pub(super) mod tests { bot(&node, &admin, "c", "Bot", &[]).await?; let network = node.network_id().await?; let (trigger, attempt) = start_reply(&node, &admin, "m1").await?; - node.register_manager_attempt_fixture("retry-token".into(), test_access(network.clone(), false, Some("c".into())), &attempt, &trigger, Provider::Codex).await?; - let access = node.agent_tokens.lock().await.get("retry-token").cloned().context("access")?; + let access = node.manager_access_fixture("retry-token", test_access(network.clone(), false, Some("c".into())), &attempt, &trigger, Provider::Codex).await?; let args = |call: &str, explicit: bool| -> Result { let cwd = dir.join(call); std::fs::create_dir(&cwd)?; @@ -8576,7 +8572,6 @@ pub(super) mod tests { node.finish_manager_attempt(&attempt).await; Ok::<_, anyhow::Error>(()) }.await; - node.shutdown().await; cleanup(node, dir).await?; result } @@ -8723,7 +8718,6 @@ pub(super) mod tests { Ok::<_, anyhow::Error>(()) } .await; - node.shutdown().await; cleanup(node, dir).await?; result?; } @@ -8809,7 +8803,6 @@ pub(super) mod tests { Ok::<_, anyhow::Error>(()) } .await; - node.shutdown().await; cleanup(node, dir).await?; result } @@ -8948,7 +8941,6 @@ pub(super) mod tests { Ok::<_, anyhow::Error>(()) } .await; - node.shutdown().await; cleanup(node, dir).await?; result?; } diff --git a/apps/core/src/runtime/work.rs b/apps/core/src/runtime/work.rs index 65c479d82..31f30cf29 100644 --- a/apps/core/src/runtime/work.rs +++ b/apps/core/src/runtime/work.rs @@ -134,7 +134,7 @@ impl Runtime { .store .lock() .await - .work_records() + .open_work_records() .unwrap_or_default() .into_iter() .filter(|record| live(record) && on_app_server(record)) @@ -814,7 +814,7 @@ impl Runtime { .live_probe_at .compare_exchange(last, at, Relaxed, Relaxed) .is_ok(); - let records = self.store.lock().await.work_records()?; + let records = self.store.lock().await.open_work_records()?; for record in records { if record.kind == WorkKind::Task { continue; @@ -1169,11 +1169,8 @@ impl Runtime { /// Retries waiting dispatches and the stops held for other devices' works. pub(super) async fn deliver_work_requests(self: &Arc, network: &str) -> Result<()> { - let dispatches = self.store.lock().await.dispatches()?; - for dispatch in dispatches - .into_iter() - .filter(|dispatch| dispatch.state == DispatchState::Pending) - { + let dispatches = self.store.lock().await.pending_dispatches()?; + for dispatch in dispatches { let lane = format!("dispatch_worker:{network}:{}", dispatch.spec.work_id); let Some(guard) = self.peer_delivery_locks.try_lock(&lane) else { continue; @@ -1265,7 +1262,7 @@ impl Runtime { let Some(network) = self.store.lock().await.network()? else { return Ok(()); }; - let records = self.store.lock().await.work_records()?; + let records = self.store.lock().await.open_work_records()?; for record in records .into_iter() .filter(|record| live(record) && on_app_server(record)) diff --git a/apps/core/src/scheduler.rs b/apps/core/src/scheduler.rs index 61331f61c..d1004f952 100644 --- a/apps/core/src/scheduler.rs +++ b/apps/core/src/scheduler.rs @@ -749,9 +749,10 @@ async fn turn( } *sessions=filtered; } - if job.scope!=SessionScope::Main { bot["sent"]=json!([]); } + if job.scope!=SessionScope::Main { bot["sent"]=json!([]); bot["sent_omitted"]=json!(0); } bot["configured_bot"] = stable.bot.clone(); bot["skills"] = json!(stable.skills); + bot["skills_omitted"] = json!(0); fit_bot(&mut bot, INDEX_BUDGET); let memories: Vec<_> = store.memory_records(&network, &conversation)? .into_iter().filter(|record| record.essential) @@ -1330,7 +1331,7 @@ pub(crate) fn turn_recorder( TurnExecution::Started, )?; store.record_context_started(&attempt)?; - store.started_workspace_assignment( + store.settle_workspace_assignment( &node.identity, &network, &started, diff --git a/apps/core/src/scheduling.rs b/apps/core/src/scheduling.rs index 252d6b5c1..3d019fed6 100644 --- a/apps/core/src/scheduling.rs +++ b/apps/core/src/scheduling.rs @@ -1,5 +1,5 @@ //! Local scheduling state is never reconstructed by importing shared conversation history. -//! A job is keyed by `(conversation, message_id | work_id)`, so retries and sync never add a second one. +//! A job is keyed by `(conversation, trigger)`, so retries and sync never add a second one. use crate::{ model::{Schedule, VersionVector, WorkOutcome}, providers::Provider, @@ -426,7 +426,7 @@ pub struct TurnRuntime { pub struct SchedulerJob { pub conversation_id: String, pub scope: SessionScope, - /// `message:`, `work:`, `task:`, + /// `message:`, `work:`, `task:`, `assignment:`, /// `bot_message:` or `schedule::`. pub trigger: String, pub kind: TriggerKind, diff --git a/apps/core/src/store.rs b/apps/core/src/store.rs index 0dacf11ff..733d390d2 100644 --- a/apps/core/src/store.rs +++ b/apps/core/src/store.rs @@ -289,6 +289,7 @@ impl Store { )?; Ok(store) } + #[cfg(test)] pub fn install_trust_bundle(&mut self, network_id: &str, state: &NetworkState) -> Result { let tx = self .connection @@ -780,7 +781,9 @@ impl Store { self.verified_blob_path(network, conversation, attachment) } - /// Attachments are files named by their SHA-256; writes are atomic and reads re-verify. + /// Test fixture that stores a whole attachment at once; production writes go through + /// `partial_blob_file` and `blob_file`. + #[cfg(test)] pub fn put_blob(&mut self, expected: &BlobRef, content: &[u8]) -> Result<()> { ensure!( content.len() <= MAX_BLOB_BYTES && content.len() as u64 == expected.size, diff --git a/apps/core/src/store/admission.rs b/apps/core/src/store/admission.rs index a44449afd..30d3bc1a2 100644 --- a/apps/core/src/store/admission.rs +++ b/apps/core/src/store/admission.rs @@ -995,9 +995,8 @@ impl Store { return Ok(None); } let work = self - .works(network, conversation_id)? - .into_iter() - .find(|work| work.work_id == *work_id) + .work(network, work_id)? + .filter(|work| work.conversation_id == *conversation_id) .context("stopped work source not found")?; ensure!( work.target_node == local, diff --git a/apps/core/src/store/mailbox.rs b/apps/core/src/store/mailbox.rs index ac8f6f8a6..5e7e5af81 100644 --- a/apps/core/src/store/mailbox.rs +++ b/apps/core/src/store/mailbox.rs @@ -72,8 +72,9 @@ fn save(connection: &Connection, record: &MailboxRecord) -> Result<()> { } fn records(connection: &Connection) -> Result> { - let mut statement = connection - .prepare("SELECT value FROM identity_meta WHERE key LIKE 'mailbox:%' ORDER BY key")?; + let mut statement = connection.prepare( + "SELECT value FROM identity_meta WHERE key>='mailbox:' AND key<'mailbox;' ORDER BY key", + )?; let rows = statement.query_map([], |row| row.get::<_, String>(0))?; rows.map(|row| Ok(serde_json::from_str(&row?)?)).collect() } @@ -147,7 +148,6 @@ pub(crate) fn queue( params![conversation, trigger], )?; save(connection, &candidate)?; - reconcile(connection, network, now_ms)?; Ok(load_key(connection, &key(network, conversation, trigger))?.unwrap_or(candidate)) } diff --git a/apps/core/src/store/questions.rs b/apps/core/src/store/questions.rs index 4e9d23b58..5199523db 100644 --- a/apps/core/src/store/questions.rs +++ b/apps/core/src/store/questions.rs @@ -438,6 +438,7 @@ impl Store { /// Posts the standing answer. Ordinary questions schedule a turn; held requests return to /// the Node that holds their original transport. + #[cfg(test)] pub fn accept_answer( &mut self, identity: &LocalIdentity, diff --git a/apps/core/src/store/scheduler.rs b/apps/core/src/store/scheduler.rs index ff16370f1..bb6fb0d56 100644 --- a/apps/core/src/store/scheduler.rs +++ b/apps/core/src/store/scheduler.rs @@ -4070,6 +4070,14 @@ impl Store { query_jobs(&self.connection, "1", []) } + pub fn workspace_scheduler_jobs(&self) -> Result> { + query_jobs( + &self.connection, + "scope>='workspace_task:' AND scope<'workspace_task;'", + [], + ) + } + /// Each busy conversation on this device; a reply running outranks messages still waiting. /// An agent task runs in its bot's conversation but is that work, not a reply in the chat. pub fn busy_conversations(&self) -> Result> { @@ -5630,10 +5638,13 @@ impl Store { self.pending_checks()?.is_empty(), crate::maintenance::Busy("an interrupted invocation awaits reconciliation".into()) ); + let open_work: bool = self.connection.query_row( + "SELECT EXISTS(SELECT 1 FROM work_runs WHERE state<>'finished')", + [], + |row| row.get(0), + )?; ensure!( - self.work_records()? - .iter() - .all(|work| work.state.finished()), + !open_work, crate::maintenance::Busy("a dispatched work has not finished".into()) ); Ok(()) diff --git a/apps/core/src/store/sync.rs b/apps/core/src/store/sync.rs index bbd971f34..98d454c1f 100644 --- a/apps/core/src/store/sync.rs +++ b/apps/core/src/store/sync.rs @@ -359,9 +359,8 @@ impl Store { } } Some(("work", work_id)) => { - let outcome = super::reduce::works_from(&tx, network, conversation)? - .into_iter() - .find(|work| work.work_id == work_id) + let outcome = super::reduce::work_from(&tx, network, work_id)? + .filter(|work| work.conversation_id == conversation) .and_then(|work| work.outcome); let Some(outcome) = outcome.filter(|o| *o != WorkOutcome::Unverified) else { return Ok(None); diff --git a/apps/core/src/store/tests.rs b/apps/core/src/store/tests.rs index c0774a632..b7936aea9 100644 --- a/apps/core/src/store/tests.rs +++ b/apps/core/src/store/tests.rs @@ -783,7 +783,6 @@ fn pending_capacity_is_reserved_for_verified_authorized_authors() -> Result<()> |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), )?; assert_eq!(counts, (share + 1, share, 1)); - assert!(counts.0 <= log::MAX_PENDING_EVENTS); Ok(()) } @@ -4287,7 +4286,7 @@ fn a_bot_message_wakes_the_other_bot_once() -> Result<()> { let mut other = store(&net)?; all_accepted(&mut other, &net, &origin)?; assert!(other.scheduler_jobs("d")?.is_empty() && other.scheduler_jobs("c")?.is_empty()); - let forged = net.a.sign_event(Event { + let forged = net.b.sign_event(Event { version: WIRE_VERSION, network_id: net.network.clone(), author: net.b.device_id()?, @@ -4307,10 +4306,8 @@ fn a_bot_message_wakes_the_other_bot_once() -> Result<()> { }, blobs: vec![], }); - assert!( - forged.is_err(), - "hops beyond the limit are not a valid event" - ); + let forged = forged.unwrap_err(); + assert!(forged.to_string().contains("hops deep"), "{forged}"); Ok(()) } @@ -5440,15 +5437,6 @@ fn shared_records_never_carry_a_known_credential() -> Result<()> { Ok(()) } -#[test] -fn autonomy_is_not_an_event() { - let body = serde_json::json!({"type":"autonomy_set","mode":"off","version":1}); - assert!( - serde_json::from_value::(body).is_err(), - "the coordination Agent always runs with full permission; there is no autonomy setting" - ); -} - struct Fleet { net: Net, x: LocalIdentity, @@ -8764,23 +8752,7 @@ fn a_resumed_codex_turn_sends_only_what_changed() -> Result<()> { } let local = net.a.device_id()?; let render = |store: &Store, trigger: &str, resumed: Option<&VersionVector>, thread| { - let job = SchedulerJob { - scope: SessionScope::Main, - conversation_id: "c".into(), - trigger: message_trigger(trigger), - kind: TriggerKind::Human, - sequence: 0, - basis: store.version_vector(&net.network)?, - reply_to: trigger.into(), - message_id: "reply".into(), - state: JobState::Queued, - - runtime: None, - - pending_check: false, - - tool_calls: false, - }; + let job = job_at(store, &net, trigger)?; let history = store.turn_history( &net.network, "c", @@ -9519,7 +9491,7 @@ fn answers_become_checkpoint_decisions_that_later_checkpoints_keep() -> Result<( } #[test] -fn a_turn_marks_attachments_not_on_this_device_pending() -> Result<()> { +fn the_prompt_shows_a_pending_attachment_as_pending_download() -> Result<()> { let net = net()?; let mut store = store(&net)?; bot_conversation(&mut store, &net)?; @@ -11391,7 +11363,7 @@ fn restart_recovers_each_scope_and_unknown_turns_are_never_replayed() -> Result< .into_iter() .find(|check| check.attempt_id == main_attempt.id) .context("pending check")?; - store.confirm_manager_stopped(&net.a, &net.network, &check, crate::runtime::now_ms())?; + store.confirm_manager_stopped(&net.a, &net.network, &check, 20)?; assert_eq!( store.scheduler_job_hold( &net.network, @@ -13482,7 +13454,7 @@ fn workspace_queue_controls_preserve_signed_history_and_reject_started_or_unknow .unwrap() .deferred ); - origin.connection.execute("UPDATE scheduler_jobs SET state='reconciling',attempt_id='attempt' WHERE conversation_id='c' AND trigger='message:defer'",[])?; + assert_eq!(origin.connection.execute("UPDATE scheduler_jobs SET state='reconciling',attempt_id='attempt' WHERE conversation_id='c' AND trigger='message:defer'",[])?, 1); let current = origin .queued_workspace_input(&net.network, "defer")? .unwrap(); @@ -13506,10 +13478,13 @@ fn workspace_queue_controls_preserve_signed_history_and_reject_started_or_unknow .unwrap() .cancelled ); - origin.connection.execute( - "UPDATE scheduler_jobs SET state='running' WHERE trigger='message:defer'", - [], - )?; + assert_eq!( + origin.connection.execute( + "UPDATE scheduler_jobs SET state='running' WHERE trigger='message:defer'", + [], + )?, + 1 + ); let current = origin .queued_workspace_input(&net.network, "defer")? .unwrap(); @@ -14774,7 +14749,7 @@ fn workspace_new_revision_replaces_only_a_proven_never_started_assignment() -> R vibeface_bridge::failure::ProviderStage::TurnStart, crate::scheduling::TurnExecution::Unknown, )?; - uncertain.started_workspace_assignment(&net.a, &net.network, &job, 6)?; + uncertain.settle_workspace_assignment(&net.a, &net.network, &job, 6)?; assert_eq!( assignment_state(&uncertain, &net, &inflight.assignment_id)?, AssignmentState::Proposed @@ -14990,16 +14965,16 @@ fn workspace_lifecycle_waits_for_native_start_and_keeps_revision_adoption_explic let queued = origin .scheduler_job("c", &message_trigger("initial"))? .context("queued job")?; - origin.started_workspace_assignment(&net.a, &net.network, &queued, 6)?; + origin.settle_workspace_assignment(&net.a, &net.network, &queued, 6)?; assert_eq!(task_state(&origin, &net, "task")?, TaskState::NotStarted); let claimed = origin .claim_next_fixture(&net.a, &net.network, "c", "boot", "workspace-start")? .context("claimed job")? .job; let attempt = claimed.state.attempt().context("attempt")?.id.clone(); - origin.started_workspace_assignment(&net.a, &net.network, &claimed, 7)?; + origin.settle_workspace_assignment(&net.a, &net.network, &claimed, 7)?; origin.mark_started("c", &claimed.trigger, &attempt)?; - origin.started_workspace_assignment(&net.a, &net.network, &claimed, 8)?; + origin.settle_workspace_assignment(&net.a, &net.network, &claimed, 8)?; assert_eq!( assignment_state(&origin, &net, &assignment.assignment_id)?, AssignmentState::Proposed @@ -15024,7 +14999,7 @@ fn workspace_lifecycle_waits_for_native_start_and_keeps_revision_adoption_explic ProviderStage::Run, TurnExecution::Started, )?; - origin.started_workspace_assignment(&net.a, &net.network, &claimed, 10)?; + origin.settle_workspace_assignment(&net.a, &net.network, &claimed, 10)?; let started = origin .workspace_assignment(&net.network, &assignment.assignment_id)? .unwrap(); @@ -15035,7 +15010,7 @@ fn workspace_lifecycle_waits_for_native_start_and_keeps_revision_adoption_explic assert!(started.result.is_none()); assert_eq!(task_state(&origin, &net, "task")?, TaskState::Running); let recorded = origin.version_vector(&net.network)?; - origin.started_workspace_assignment(&net.a, &net.network, &claimed, 11)?; + origin.settle_workspace_assignment(&net.a, &net.network, &claimed, 11)?; assert_eq!( origin.version_vector(&net.network)?, recorded, @@ -15062,7 +15037,7 @@ fn workspace_lifecycle_waits_for_native_start_and_keeps_revision_adoption_explic InputIntent::Continue, 13, )?; - origin.started_workspace_assignment(&net.a, &net.network, &claimed, 14)?; + origin.settle_workspace_assignment(&net.a, &net.network, &claimed, 14)?; let unchanged = origin .workspace_assignment(&net.network, &assignment.assignment_id)? .unwrap(); @@ -15719,7 +15694,7 @@ fn a_replaced_assignment_cannot_reauthorize_its_running_work_result() -> Result< .job; let human_attempt = human.state.attempt().unwrap().id.clone(); origin.mark_started("c", &human.trigger, &human_attempt)?; - origin.started_workspace_assignment(&net.a, &net.network, &human, 6)?; + origin.settle_workspace_assignment(&net.a, &net.network, &human, 6)?; assert!(origin.manager_attempt_allowed_with_version( &net.network, &local, @@ -15877,7 +15852,7 @@ fn workspace_task_answer_keeps_the_assignment_from_the_signed_question_basis() - vibeface_bridge::failure::ProviderStage::Run, TurnExecution::Started, )?; - origin.started_workspace_assignment(&net.a, &net.network, &running, 6)?; + origin.settle_workspace_assignment(&net.a, &net.network, &running, 6)?; origin.save_scheduler_native_id( "c", &running.trigger, @@ -16027,7 +16002,7 @@ fn workspace_task_answer_keeps_the_assignment_from_the_signed_question_basis() - vibeface_bridge::failure::ProviderStage::Run, TurnExecution::Started, )?; - origin.started_workspace_assignment(&net.a, &net.network, &answering, 12)?; + origin.settle_workspace_assignment(&net.a, &net.network, &answering, 12)?; let answered = origin.finish_job( &net.a, &net.network, @@ -16252,7 +16227,7 @@ fn workspace_release_retries_only_a_shared_proven_startup_failure_on_the_origina vibeface_bridge::failure::ProviderStage::Run, TurnExecution::Started, )?; - origin.started_workspace_assignment(&net.a, &net.network, &retry, 11)?; + origin.settle_workspace_assignment(&net.a, &net.network, &retry, 11)?; let completed = origin.finish_job( &net.a, &net.network, @@ -16872,7 +16847,7 @@ fn workspace_started_job_fixture(net: &Net, origin: &mut Store, at: i64) -> Resu vibeface_bridge::failure::ProviderStage::Run, crate::scheduling::TurnExecution::Started, )?; - origin.started_workspace_assignment(&net.a, &net.network, &job, at)?; + origin.settle_workspace_assignment(&net.a, &net.network, &job, at)?; origin .scheduler_job("c", &job.trigger)? .context("started job") @@ -17878,7 +17853,7 @@ fn resource_waiting_inputs_keep_their_ids_and_share_the_first_assignment() -> Re vibeface_bridge::failure::ProviderStage::Run, TurnExecution::Started, )?; - origin.started_workspace_assignment(&net.a, &net.network, &job, 17 + index as i64)?; + origin.settle_workspace_assignment(&net.a, &net.network, &job, 17 + index as i64)?; let ended = origin.finish_job( &net.a, &net.network, diff --git a/apps/core/src/store/work.rs b/apps/core/src/store/work.rs index 85260ba4c..17e78c138 100644 --- a/apps/core/src/store/work.rs +++ b/apps/core/src/store/work.rs @@ -517,6 +517,9 @@ impl Store { pub fn work_records(&self) -> Result> { query_runs(&self.connection, "1", []) } + pub fn open_work_records(&self) -> Result> { + query_runs(&self.connection, "state<>'finished'", []) + } /// The runs on one App Server thread, by index: a streamed event reads only these. pub fn work_records_on_thread(&self, thread: &str) -> Result> { query_runs(&self.connection, "thread_id=?", [thread]) @@ -699,6 +702,9 @@ impl Store { pub fn dispatches(&self) -> Result> { query_dispatches(&self.connection, "1", []) } + pub fn pending_dispatches(&self) -> Result> { + query_dispatches(&self.connection, "state='pending'", []) + } /// Whether the user closed this failed work or refused dispatch in 待处理. pub fn closed_in_inbox(&self, network: &str, work_id: &str) -> Result { @@ -767,16 +773,18 @@ impl Store { /// refused, unknown, or accepted but not synced back. pub fn undelivered_dispatches(&self, network: &str, scope: &str) -> Result> { let works = reduce::works_from(&self.connection, network, scope)?; - Ok(self - .dispatches()? - .into_iter() - .filter(|dispatch| { - dispatch.spec.conversation == scope - && !works - .iter() - .any(|work| work.work_id == dispatch.spec.work_id) - }) - .collect()) + Ok(query_dispatches( + &self.connection, + "json_extract(spec,'$.conversation')=?1", + [scope], + )? + .into_iter() + .filter(|dispatch| { + !works + .iter() + .any(|work| work.work_id == dispatch.spec.work_id) + }) + .collect()) } pub fn save_stop_request(&mut self, request: &StopRequest) -> Result<()> { diff --git a/apps/core/src/store/workspace.rs b/apps/core/src/store/workspace.rs index 1d5b273ce..5a2450593 100644 --- a/apps/core/src/store/workspace.rs +++ b/apps/core/src/store/workspace.rs @@ -1376,7 +1376,7 @@ impl Graph { hash: &str, event: &Event, rank: &str, - basis: VersionVector, + basis: impl FnOnce() -> Result, ) -> Result<()> { if let EventBody::InputPosted { message_id, @@ -1404,7 +1404,12 @@ impl Graph { self.last_rank = rank.into(); return Ok(()); } - let EventBody::WorkspaceCommanded { command_id, .. } = &event.body else { + let EventBody::WorkspaceCommanded { + command_id, + command, + .. + } = &event.body + else { return Ok(()); }; let key = request_key( @@ -1416,6 +1421,12 @@ impl Graph { if self.commands.contains_key(command_id) { return Ok(()); } + // Only an assignment stores its causal basis, and computing one walks the whole history. + let basis = if matches!(command, WorkspaceCommand::AssignTask { .. }) { + basis()? + } else { + VersionVector::new() + }; let mut next = self.clone(); let error = next .apply(hash, event, basis) @@ -1455,6 +1466,16 @@ fn ancestors( } Ok(result) } +fn basis(connection: &Connection, network: &str, event: &Event) -> Result { + Ok(ancestors(connection, network, event)?.values().fold( + VersionVector::new(), + |mut vector, event| { + let seq = vector.entry(event.author.clone()).or_default(); + *seq = (*seq).max(event.seq); + vector + }, + )) +} fn graph_at( connection: &Connection, network: &str, @@ -1477,15 +1498,9 @@ fn graph_at( } let envelope: SignedEvent = serde_json::from_str(&envelope)?; let event: Event = serde_json::from_str(&envelope.canonical_body)?; - let basis = ancestors(connection, network, &event)?.values().fold( - VersionVector::new(), - |mut vector, event| { - let seq = vector.entry(event.author.clone()).or_default(); - *seq = (*seq).max(event.seq); - vector - }, - ); - graph.record(&hash, &event, &super::rank(lamport, created, &hash), basis)?; + graph.record(&hash, &event, &super::rank(lamport, created, &hash), || { + basis(connection, network, &event) + })?; } Ok(graph) } @@ -1500,15 +1515,7 @@ pub(crate) fn apply_projection( if rank < graph.last_rank.as_str() { graph = graph_at(connection, network, None)?; } else { - let basis = ancestors(connection, network, event)?.values().fold( - VersionVector::new(), - |mut vector, event| { - let seq = vector.entry(event.author.clone()).or_default(); - *seq = (*seq).max(event.seq); - vector - }, - ); - graph.record(hash, event, rank, basis)?; + graph.record(hash, event, rank, || basis(connection, network, event))?; } graph.save(connection, network)?; if let EventBody::WorkspaceCommanded { @@ -2560,6 +2567,19 @@ pub(crate) fn additional_dependencies( network: &str, body: &EventBody, ) -> Result> { + if !matches!( + body, + EventBody::InputPosted { .. } + | EventBody::WorkspaceCommanded { .. } + | EventBody::MessagePosted { + in_reply_to: Some(_), + role: Role::Assistant, + .. + } + | EventBody::MessageSteered { .. } + ) { + return Ok(Vec::new()); + } let graph = Graph::read(connection, network)?; let mut hashes = BTreeSet::new(); let mut scopes = BTreeSet::new(); @@ -3404,36 +3424,46 @@ fn queued_inputs_from( network: &str, graph: &Graph, ) -> Result> { - let mut inputs = Vec::new(); - for (index, message_id) in graph.queue_order.iter().enumerate() { - let control = graph - .inputs - .get(message_id) - .context("queue input projection is missing")?; - let original = log::event_from(connection, network, &control.source_event)? - .and_then(|event| input_from_event(&control.source_event, event)) - .context("queue input source is missing")?; - let mut input = original.input; - if let Some(text) = &control.text { - input.text = text.clone(); - } - if let Some(attachments) = &control.attachments { - input.attachments = attachments.clone(); - } - if !control.deferred && input.route.intent == InputIntent::Defer { - input.route.intent = InputIntent::Continue; - } - inputs.push(QueuedInput { - input, - conversation_id: original.conversation_id, - source_event: control.source_event.clone(), - control_event: control.control_event.clone(), - effective_order: index as u64 + 1, - deferred: control.deferred, - cancelled: control.cancelled, - }); + graph + .queue_order + .iter() + .enumerate() + .map(|(index, message_id)| queued_input_at(connection, network, graph, index, message_id)) + .collect() +} +fn queued_input_at( + connection: &Connection, + network: &str, + graph: &Graph, + index: usize, + message_id: &str, +) -> Result { + let control = graph + .inputs + .get(message_id) + .context("queue input projection is missing")?; + let original = log::event_from(connection, network, &control.source_event)? + .and_then(|event| input_from_event(&control.source_event, event)) + .context("queue input source is missing")?; + let mut input = original.input; + if let Some(text) = &control.text { + input.text = text.clone(); + } + if let Some(attachments) = &control.attachments { + input.attachments = attachments.clone(); } - Ok(inputs) + if !control.deferred && input.route.intent == InputIntent::Defer { + input.route.intent = InputIntent::Continue; + } + Ok(QueuedInput { + input, + conversation_id: original.conversation_id, + source_event: control.source_event.clone(), + control_event: control.control_event.clone(), + effective_order: index as u64 + 1, + deferred: control.deferred, + cancelled: control.cancelled, + }) } pub(crate) fn queued_workspace_input_from( connection: &Connection, @@ -3441,9 +3471,12 @@ pub(crate) fn queued_workspace_input_from( message_id: &str, ) -> Result> { let graph = Graph::read(connection, network)?; - Ok(queued_inputs_from(connection, network, &graph)? - .into_iter() - .find(|input| input.input.message_id == message_id)) + graph + .queue_order + .iter() + .position(|id| id == message_id) + .map(|index| queued_input_at(connection, network, &graph, index, message_id)) + .transpose() } impl Store { @@ -3672,15 +3705,6 @@ impl Store { )?; self.workspace_assignment(network, &assignment_id) } - pub fn started_workspace_assignment( - &mut self, - identity: &LocalIdentity, - network: &str, - job: &crate::scheduling::SchedulerJob, - at: i64, - ) -> Result<()> { - self.settle_workspace_assignment(identity, network, job, at) - } pub fn settle_workspace_assignment( &mut self, identity: &LocalIdentity, @@ -5218,11 +5242,15 @@ pub(crate) fn bind_waiting_workspace_inputs_from( assignment: &Assignment, ) -> Result<()> { let mut statement = - connection.prepare("SELECT key,value FROM identity_meta WHERE key LIKE ?")?; + connection.prepare("SELECT key,value FROM identity_meta WHERE key>=?1 AND key(0)?, row.get::<_, String>(1)?)) - })? + .query_map( + [ + format!("workspace-input-assignment:{network}:"), + format!("workspace-input-assignment:{network};"), + ], + |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)), + )? .collect::>>()?; let graph = Graph::read(connection, network)?; for (key, value) in bindings { diff --git a/apps/core/src/triage.rs b/apps/core/src/triage.rs index 08abe85f2..e24511a22 100644 --- a/apps/core/src/triage.rs +++ b/apps/core/src/triage.rs @@ -439,9 +439,10 @@ impl TriageConfig { "the webhook must use HTTPS" ); ensure!( - parsed.username().is_empty() && parsed.password().is_none() && url.len() <= 2048, + parsed.username().is_empty() && parsed.password().is_none(), "the webhook URL must not carry credentials" ); + ensure!(url.len() <= 2048, "the webhook URL is too long"); } Ok(()) } diff --git a/apps/core/src/work.rs b/apps/core/src/work.rs index 0f8fa6689..005c801c7 100644 --- a/apps/core/src/work.rs +++ b/apps/core/src/work.rs @@ -739,33 +739,10 @@ mod tests { } #[test] - fn final_work_dispatch_round_trips_and_epoch8_shape_rejects_model_fields() -> anyhow::Result<()> - { - #[derive(Serialize, Deserialize)] - #[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] - enum Epoch8Body { - WorkDispatched { - work_id: String, - trigger: String, - dispatcher: String, - call_ref: String, - kind: WorkKind, - cwd: String, - title: String, - prompt: String, - }, - } - let old = serde_json::json!({"type":"work_dispatched", "work_id":"w", "trigger":"message:m", "dispatcher":"node", "call_ref":"call", "kind":"codex", "cwd":"/tmp", "title":"work", "prompt":"go"}); - let _: Epoch8Body = serde_json::from_value(old.clone())?; - let mut new = old; - new["model"] = serde_json::json!("requested"); - new["resolved"] = serde_json::json!({"provider":"codex", "model":"accepted"}); - let body: EventBody = serde_json::from_value(new.clone())?; - assert_eq!(serde_json::to_value(body)?, new); - let error = serde_json::from_value::(new) - .err() - .ok_or_else(|| anyhow::anyhow!("old shape must reject"))?; - assert!(error.to_string().contains("unknown field")); + fn work_dispatch_round_trips() -> anyhow::Result<()> { + let dispatched = serde_json::json!({"type":"work_dispatched", "work_id":"w", "trigger":"message:m", "dispatcher":"node", "call_ref":"call", "kind":"codex", "cwd":"/tmp", "title":"work", "prompt":"go", "model":"requested", "resolved":{"provider":"codex", "model":"accepted"}}); + let body: EventBody = serde_json::from_value(dispatched.clone())?; + assert_eq!(serde_json::to_value(body)?, dispatched); Ok(()) } diff --git a/apps/core/tests/fixtures/fake-claude b/apps/core/tests/fixtures/fake-claude index b2236f804..a80a5bc55 100755 --- a/apps/core/tests/fixtures/fake-claude +++ b/apps/core/tests/fixtures/fake-claude @@ -10,9 +10,18 @@ the turn goes: die records the prompt, then exits before the turn ends fail ends the turn with an API error abort ends the turn as aborted though nobody asked it to stop + steer waits like hang, holds user frames until three arrived, replays them and answers + "Got all three inputs" + steer-late, steer-late-delayed + waits like hang; the next user frame ends the turn with "initial finished" and runs + as a turn of its own. The delayed one holds that turn's result: it creates + `$FAKE_CLAUDE_RESULT_GATE.waiting` and waits until `$FAKE_CLAUDE_RESULT_GATE` exists other replies, runs one Bash tool, and answers "done: " Every argument list and stdin frame is appended to `$FAKE_CLAUDE_LOG` as one JSON line. +With `$FAKE_CLAUDE_GATE_DIR` and `$FAKE_CLAUDE_GATE_RELEASE` both set, every turn first creates +`$FAKE_CLAUDE_GATE_DIR/.started` and waits until the release file exists, taking +steers meanwhile; an interrupt or EOF ends the turn there. """ import json import os @@ -116,7 +125,7 @@ log({ "guide": guide_text, "guide_private": guide_private, "env": {name: name in os.environ for name in - ("VIBEFACE_TOOL_TOKEN", "VIBEFACE_NODE_URL", "CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "FAKE_MARK")}, + ("VIBEFACE_TOOL_TOKEN", "VIBEFACE_NODE_URL", "CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT")}, }) resumed = option("--resume") session = resumed or option("--session-id") diff --git a/apps/core/tests/fixtures/fake-opencode b/apps/core/tests/fixtures/fake-opencode index 2d74827e1..c63977dcc 100755 --- a/apps/core/tests/fixtures/fake-opencode +++ b/apps/core/tests/fixtures/fake-opencode @@ -13,7 +13,8 @@ with (directory / 'argv').open('a') as output: output.write(' '.join(sys.argv[1:]) + '\n') names = ['XDG_DATA_HOME', 'XDG_CONFIG_HOME', 'XDG_STATE_HOME', 'XDG_CACHE_HOME', 'OPENCODE_DB', 'OPENCODE_CONFIG_DIR', 'OPENCODE_CONFIG', 'OPENCODE_CLI_CONFIG_CONTENT', - 'OPENCODE_TEST_HOME', 'OPENCODE_DISABLE_PROJECT_CONFIG', 'OPENCODE_CONFIG_PROJECT_DISABLE'] + 'OPENCODE_TEST_HOME', 'OPENCODE_DISABLE_PROJECT_CONFIG', 'OPENCODE_CONFIG_PROJECT_DISABLE', + 'OPENCODE_DISABLE_CLAUDE_CODE'] with (directory / 'roots.jsonl').open('a') as output: output.write(json.dumps({**{name: os.environ.get(name) for name in names}, 'fake_auth_present': bool(os.environ.get('FAKE_API_KEY'))}) + '\n') diff --git a/apps/core/tests/fixtures/fake-pi b/apps/core/tests/fixtures/fake-pi index 71ffd4352..456832d51 100755 --- a/apps/core/tests/fixtures/fake-pi +++ b/apps/core/tests/fixtures/fake-pi @@ -6,6 +6,9 @@ PI_CODING_AGENT_SESSION_DIR holds the sessions. FAKE_PI_LOG gets one JSON line p per prompt. FAKE_PI_MODE picks "reply", "wait", "crash", "fail", "fail-key", "refuse", "refuse-model", "prompt-lost", "prompt-pending" or "retry-abort". Standard library only. FAKE_PI_STATE_GATE delays get_state until that file exists, while EOF still ends the process. +With FAKE_PI_GATE_DIR and FAKE_PI_GATE_RELEASE both set, every prompt first creates +`/.started` and waits until the release file exists or the turn is +aborted, and "reply" answers "done: " in place of "Hello". """ import json import os diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 7bcd8a161..9a9596788 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -1,13 +1,12 @@ # vibeface-desktop -Electron 宿主:一个受信任的本机启动器,加上一个只加载 Core 自己提供界面的业务窗口。 +Electron 宿主:一个单窗口客户端,加载运行时内置的业务界面,并可管理本机 Core。 -## 两个窗口 +## 窗口 - **单窗口客户端**(`vibeface-app://app/`):内置 React 业务界面;本机节点管理在 App 设置 `/settings/desktop-node`,经受限 client preload 调用主进程。 - 负责选择数据目录、初始化、启动与停止本机 Core、仅连接已有服务、打开业务窗口和桌面设置。 -- **业务窗口**:`sandbox`、`contextIsolation` 为真,`nodeIntegration` 为假,**没有 preload,也没有任何原生桥**。 - 它加载 Core 在 `local_listen`(默认 `http://127.0.0.1:4791`)提供的真实界面。 + 负责选择数据目录、初始化、启动与停止本机 Core、仅连接已有服务和桌面设置。 + `sandbox`、`contextIsolation` 为真,`nodeIntegration` 为假,preload 只给这个固定来源。 通知、文件选择和下载走 W3C API,由主进程的权限与下载钩子接住。 ## 业务地址如何确定 @@ -17,6 +16,7 @@ Electron 宿主:一个受信任的本机启动器,加上一个只加载 Core `src/main/business-url.ts` 因此把 `access` 的路径与一次性 `#local=` / `#bootstrap=` 片段原样搬到 `inspect.local_listen` 报告的私有 origin 上,并校验回环地址与 `node=` 对应的设备。 片段不写入设置、不打日志。 +窗口不加载这个地址:`src/main/client-host.ts` 只用它核对所选节点的私有 origin,access URL 和片段不经过 IPC。 ## 生命周期 @@ -30,7 +30,7 @@ Electron 宿主:一个受信任的本机启动器,加上一个只加载 Core ## 邀请激活时序 `open-url`、`second-instance` 和初始 `argv` 只接受解析后的 `join` 邀请,先在内存队列里去重并限长缓存。 -队列在 `app.whenReady()` 与 `coreSession.restore()` 完成后统一消费;若当时还没连上本机 Core,邀请会保留并在会话变化后重试,不写入设置文件。 +队列在 `app.whenReady()` 与 `coreSession.restore()` 完成后统一消费,不写入设置文件。 ## 命令 @@ -44,7 +44,7 @@ node apps/desktop/scripts/make-icons.mjs # 仅 macOS:从品牌矢量重新 ## 运行时与开关 -打包后运行时固定为 `process.resourcesPath/runtime`,其中的 `vibeface-core[.exe]` 是唯一可执行的程序。 +打包后运行时固定为 `process.resourcesPath/runtime`,其中的 `vibeface-core[.exe]` 和 `vibeface[.exe]` 是仅有的可执行程序。 下列变量**只在未打包时**生效,打包产物不会读取它们: | 变量 | 作用 | diff --git a/apps/desktop/src/main/business-url.ts b/apps/desktop/src/main/business-url.ts index 4d5ff40f0..4126def9d 100644 --- a/apps/desktop/src/main/business-url.ts +++ b/apps/desktop/src/main/business-url.ts @@ -10,9 +10,6 @@ import type { Access, Inspect } from './control-types.js' -export type BusinessNavigation = { kind: 'business'; url: string } - -export type JoinRequest = { ticket: string } export type PrivateOrigin = { host: string; port: number; origin: string } @@ -74,15 +71,3 @@ export function businessUrl(access: Access, inspect: Inspect): string { return target.toString() } -/** The selected Core's page, at its join form when an invite is being opened. */ -export function businessNavigation( - access: Access, - inspect: Inspect, - invite?: JoinRequest -): BusinessNavigation { - const target = businessUrl(access, inspect) - if (!invite) return { kind: 'business', url: target } - const join = new URL('/join', target) - join.hash = invite.ticket - return { kind: 'business', url: join.toString() } -} diff --git a/apps/desktop/src/main/control-types.ts b/apps/desktop/src/main/control-types.ts index 97912e75a..1db8a2bd1 100644 --- a/apps/desktop/src/main/control-types.ts +++ b/apps/desktop/src/main/control-types.ts @@ -10,8 +10,6 @@ export type ControlRequest = | { command: 'inspect'; data_dir: string } | { command: 'access'; data_dir: string; json: boolean } | { command: 'local_setup'; data_dir: string } - | { command: 'set_local_access'; data_dir: string; enabled: boolean } - | { command: 'join'; data_dir: string; link: string; name: string } /** `vibeface_core::control::InitOptions` with only the fields the desktop sets. */ export type InitOptions = { data_dir: string } diff --git a/apps/desktop/src/main/lifecycle.ts b/apps/desktop/src/main/lifecycle.ts index 945995349..48c0af329 100644 --- a/apps/desktop/src/main/lifecycle.ts +++ b/apps/desktop/src/main/lifecycle.ts @@ -10,7 +10,7 @@ import { PARENT_STDIN_FLAG } from '../shared/contract.js' export type Ownership = | { kind: 'idle' } | { kind: 'attached'; dataDir: string } - | { kind: 'owned'; dataDir: string; startedAt: number } + | { kind: 'owned'; dataDir: string } export type OwnedExit = { code: number | null; signal: NodeJS.Signals | null } @@ -62,9 +62,6 @@ export class CoreLifecycle { this.ownership = { kind: 'attached', dataDir } } - detach(): void { - if (this.ownership.kind === 'attached') this.ownership = { kind: 'idle' } - } /** * Start a Core this app owns. The child keeps the parent's stdin pipe open; closing it, or @@ -90,7 +87,7 @@ export class CoreLifecycle { this.finish(child, { code, signal }) }) this.child = child - this.ownership = { kind: 'owned', dataDir, startedAt: Date.now() } + this.ownership = { kind: 'owned', dataDir } } private finish(child: ChildProcess, exit: OwnedExit): void { diff --git a/apps/desktop/src/main/managed-node.ts b/apps/desktop/src/main/managed-node.ts index 02698a64e..e6eaaaefa 100644 --- a/apps/desktop/src/main/managed-node.ts +++ b/apps/desktop/src/main/managed-node.ts @@ -168,7 +168,7 @@ async function invoke(program: ManagedNodeProgram, args: readonly string[], time child.kill('SIGKILL') reject(new Error('desktop Node command timed out')) }, timeoutMs) - void closePromise.finally(() => clearTimeout(timer)) + void closePromise.then(() => clearTimeout(timer), () => clearTimeout(timer)) }) try { const [text, close] = await Promise.race([Promise.all([outputPromise, closePromise]), timeout]) diff --git a/apps/desktop/src/main/session.ts b/apps/desktop/src/main/session.ts index a951d4a3e..a290ca1a5 100644 --- a/apps/desktop/src/main/session.ts +++ b/apps/desktop/src/main/session.ts @@ -2,8 +2,8 @@ import { existsSync } from 'node:fs' import { lstat } from 'node:fs/promises' import { isAbsolute, join } from 'node:path' import { runControl, type CoreProgram } from './control-client.js' -import { parseAccess, parseInspect, type Inspect } from './control-types.js' -import { businessNavigation, parsePrivateOrigin, type BusinessNavigation, type JoinRequest } from './business-url.js' +import { parseInspect, type Inspect } from './control-types.js' +import { parsePrivateOrigin } from './business-url.js' import { CoreLifecycle } from './lifecycle.js' import { defaultSettings, loadSettings, saveSettings, type Settings } from './settings.js' import type { CoreState, PreferenceKey, RuntimeState } from '../shared/contract.js' @@ -89,16 +89,6 @@ export class CoreSession { this.options.onChange() } - async forgetDataDir(): Promise { - if (this.lifecycle.state().kind === 'owned') { - throw new Error('先停止这台电脑上由 Vibeface 启动的 Core,再切换数据目录。') - } - this.lifecycle.detach() - this.settings = { ...this.settings, lastDataDir: null } - await saveSettings(this.options.profileDir, this.settings) - this.core = { kind: 'none' } - this.options.onChange() - } async useDataDir(dataDir: string): Promise { if (!isAbsolute(dataDir)) throw new Error('请选择一个绝对路径的数据目录。') @@ -246,28 +236,12 @@ export class CoreSession { }) } - /** Resolve the Core-served URL for the business window, canonicalized to Core's private origin. */ - async businessTarget(invite?: JoinRequest): Promise { - const dataDir = this.requireDataDir() - const inspect = await this.inspect(dataDir) - if (inspect.status !== 'running') throw new Error('Core 还没有运行,无法打开 Vibeface 窗口。') - if (!inspect.webEnabled) throw new Error('这个 Core 关闭了网页访问,请在配置中重新开启。') - const access = parseAccess( - await runControl(this.programs.control(), { command: 'access', data_dir: dataDir, json: true }) - ) - this.core = this.stateFromInspect(inspect) - this.options.onChange() - return businessNavigation(access, inspect, invite) - } /** Quit closes only a Core this app started; an attached service is left alone. */ async shutdown(): Promise { await this.lifecycle.stopOwned('quit') } - ownsCore(): boolean { - return this.lifecycle.state().kind === 'owned' - } private requireDataDir(): string { const dataDir = this.dataDir() diff --git a/apps/desktop/tests/business-url.test.ts b/apps/desktop/tests/business-url.test.ts index a450a8e58..0060584b3 100644 --- a/apps/desktop/tests/business-url.test.ts +++ b/apps/desktop/tests/business-url.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { businessNavigation, businessUrl, parsePrivateOrigin } from '../src/main/business-url.js' +import { businessUrl, parsePrivateOrigin } from '../src/main/business-url.js' import type { Access, Inspect } from '../src/main/control-types.js' const DEVICE = 'a'.repeat(64) @@ -89,13 +89,3 @@ describe('businessUrl', () => { }) }) -describe('businessNavigation', () => { - const invite = { ticket: 'vibeface1qq2ww3ee4' } - - it('opens an invite at the selected Node\'s join form', () => { - expect(businessNavigation(access(), inspect(), invite)).toEqual({ - kind: 'business', - url: 'http://127.0.0.1:4791/join#vibeface1qq2ww3ee4', - }) - }) -}) diff --git a/apps/desktop/tests/managed-node.test.ts b/apps/desktop/tests/managed-node.test.ts index 0c2372526..94598a50a 100644 --- a/apps/desktop/tests/managed-node.test.ts +++ b/apps/desktop/tests/managed-node.test.ts @@ -123,4 +123,22 @@ describe('ManagedNodeController deadlines', () => { }) await expect(hung.updateBackground('device')).rejects.toThrow('managed Node operation failed') }) + + it('fails a command that cannot be spawned without leaving an unhandled rejection', async () => { + const unhandled: unknown[] = [] + const record = (reason: unknown): void => { unhandled.push(reason) } + process.on('unhandledRejection', record) + try { + const missing = new ManagedNodeController({ + profileDir: '/tmp/profile', + bundledCli: { command: '/nonexistent/vibeface-cli' }, + commandTimeoutMs: () => 2_000, + }) + await expect(missing.status()).rejects.toThrow() + await new Promise((resolve) => setTimeout(resolve, 20)) + } finally { + process.off('unhandledRejection', record) + } + expect(unhandled).toEqual([]) + }) }) diff --git a/apps/desktop/tests/session.test.ts b/apps/desktop/tests/session.test.ts index ec0da7817..d7f835b6f 100644 --- a/apps/desktop/tests/session.test.ts +++ b/apps/desktop/tests/session.test.ts @@ -61,12 +61,7 @@ describe('CoreSession against protocol fixtures', () => { it('initializes, starts and then serves the Core private origin', async () => { await session.useDataDir(dataDir) await session.startOwned() - expect(session.state().kind).toBe('owned') - expect(session.ownsCore()).toBe(true) - const target = await session.businessTarget() - expect(target.kind).toBe('business') - expect(target.url.startsWith('http://127.0.0.1:4791/')).toBe(true) - expect(target.url).toContain('#local=') + expect(session.state()).toMatchObject({ kind: 'owned', origin: 'http://127.0.0.1:4791' }) }) it('stopping an owned Core leaves the directory offline, and it can start again', async () => { @@ -74,7 +69,6 @@ describe('CoreSession against protocol fixtures', () => { await session.startOwned() await session.stopOwned() expect(session.state().kind).toBe('offline') - expect(session.ownsCore()).toBe(false) await session.startOwned() expect(session.state().kind).toBe('owned') }) @@ -89,7 +83,7 @@ describe('CoreSession against protocol fixtures', () => { const before = await readFile(join(dataDir, 'identity.json'), 'utf8') await expect(session.startOwned()).rejects.toThrow(/更新尚未完成/) await expect(session.startDiscoveredNode(dataDir, 'a'.repeat(64))).rejects.toThrow(/更新尚未完成/) - expect(session.ownsCore()).toBe(false) + expect(session.state().kind).toBe('failed') expect(await readFile(pending, 'utf8')).toBe(journal) expect(await readFile(join(dataDir, 'identity.json'), 'utf8')).toBe(before) }) @@ -155,7 +149,6 @@ describe('CoreSession against protocol fixtures', () => { const next = open() await next.restore() expect(next.state()).toMatchObject({ kind: 'offline', dataDir }) - expect(next.ownsCore()).toBe(false) }) it('refuses a relative data directory', async () => { @@ -165,7 +158,6 @@ describe('CoreSession against protocol fixtures', () => { it('never writes a token or an access URL into its settings file', async () => { await session.useDataDir(dataDir) await session.startOwned() - await session.businessTarget() const settings: unknown = JSON.parse(await readFile(join(profileDir, 'desktop-settings.json'), 'utf8')) expect(settings).toEqual({ lastDataDir: dataDir, preferences: { openBusinessOnConnect: true } }) }) diff --git a/apps/desktop/tests/windows.test.ts b/apps/desktop/tests/windows.test.ts index d2df7cefe..18f4c0453 100644 --- a/apps/desktop/tests/windows.test.ts +++ b/apps/desktop/tests/windows.test.ts @@ -43,8 +43,3 @@ describe.each(['will-navigate', 'will-redirect'])('%s boundary', (eventName) => }) }) -describe('single client window', () => { - it('creates only the sealed client window factory', () => { - expect(typeof createClientWindow).toBe('function') - }) -}) diff --git a/apps/mobile/app/b/[botId]/about.tsx b/apps/mobile/app/b/[botId]/about.tsx index be35593a9..ba0ef8607 100644 --- a/apps/mobile/app/b/[botId]/about.tsx +++ b/apps/mobile/app/b/[botId]/about.tsx @@ -99,7 +99,7 @@ function About({ bot, shared }: { bot: BotRecord; shared: NonNullable shared.controlSchedule(schedule.schedule_id, schedule.enabled ? 'pause' : 'resume')}>{schedule.enabled ? '暂停' : '恢复'} diff --git a/apps/mobile/app/b/[botId]/work/[workId].tsx b/apps/mobile/app/b/[botId]/work/[workId].tsx index ef884247b..9a06ee446 100644 --- a/apps/mobile/app/b/[botId]/work/[workId].tsx +++ b/apps/mobile/app/b/[botId]/work/[workId].tsx @@ -10,7 +10,7 @@ import { agentLaneLabels, fixOnDevice, fixOnDeviceLabel, followUp, followUpCopy, import { messageOf, providerNames } from '@vibeface/client/lib/node.ts' import { projectName, workApproval } from '@vibeface/client/workspace/questions.ts' import { workChecks, type WorkCheck } from '@vibeface/client/workspace/model.ts' -import { ActionButton } from '@/components/action' +import { ActionButton, ErrorText } from '@/components/action' import { CopyableId, Details, EmptyState, providerIcons, toneText, type Tone } from '@/components/kit' import { Button } from '@/components/ui/button' import { Icon } from '@/components/ui/icon' @@ -24,7 +24,6 @@ import { useChatChrome } from '@/features/chat/chrome' import { InputOptions, InputStatus } from '@/features/workspace/workspace' import type { InputIntent, WorkDetail } from '@vibeface/client/workspace/types.ts' import type { Attachment } from '@/data/types' -import { ErrorText } from '@/components/action' const tone = (state: string): Tone => state === 'failed' ? 'danger' : state === 'completed' ? 'success' : ['awaiting_confirmation', 'stop_timed_out'].includes(state) ? 'warning' : 'neutral' type ComposerDraft = { text: string; files: Attachment[]; intent: InputIntent; workId: string; conversationId: string } diff --git a/apps/mobile/app/device/[deviceId].tsx b/apps/mobile/app/device/[deviceId].tsx index 9c9b05eec..60d90646c 100644 --- a/apps/mobile/app/device/[deviceId].tsx +++ b/apps/mobile/app/device/[deviceId].tsx @@ -24,7 +24,7 @@ export default function DeviceDetail() { const device = useDevice() const { members } = useWorkspace() const member = members.find((item) => item.device_id === deviceId) - const { busy, error, run } = useRun() + const { busy, error, run, clear } = useRun() const switching = useRun() const [removing, setRemoving] = useState(false) if (!member) return @@ -75,12 +75,12 @@ export default function DeviceDetail() { {removable ? - setRemoving(true)}> + { clear(); setRemoving(true) }}> {removing ? {deviceCopy.removeNotice(member.bot !== null)} - + diff --git a/apps/mobile/src/features/chat/work.tsx b/apps/mobile/src/features/chat/work.tsx index f6915d2c7..d8fd38055 100644 --- a/apps/mobile/src/features/chat/work.tsx +++ b/apps/mobile/src/features/chat/work.tsx @@ -28,7 +28,7 @@ export type Row = { key: string; node: ReactNode } const cause = (kind: FailureKind | undefined, raw: string | null | undefined) => failureText(kind) || (raw ? taskError(raw).split('\n').at(-1) ?? '' : '') /** Plain-language reason a work needs the person; the device's own words stay out of the card. */ -export function confirmText(check: Pick, device: string): string { +function confirmText(check: Pick, device: string): string { if (check.reason === 'offline') return `${device} 离线了,报不回这个任务的结果。` if (check.reason === 'disconnected') return `${device} 上的 Codex 断开了,报不回这个任务的结果。` if (check.detail.startsWith('设备已移除')) return `${device} 已移除,报不回这个任务的结果。` diff --git a/apps/mobile/src/features/recovery/recovery.tsx b/apps/mobile/src/features/recovery/recovery.tsx index bb920765b..28e7647b9 100644 --- a/apps/mobile/src/features/recovery/recovery.tsx +++ b/apps/mobile/src/features/recovery/recovery.tsx @@ -306,7 +306,7 @@ export function RecoveredStep() { { try { if (value) forgetUnsavedRecovery(); setSaved(value) } catch (cause) { setClearError(messageOf(cause)) } }} save={save} /> {!file && !saved ? : null} - + } diff --git a/apps/www/Dockerfile b/apps/www/Dockerfile index a4f88fd3c..08527f396 100644 --- a/apps/www/Dockerfile +++ b/apps/www/Dockerfile @@ -6,7 +6,6 @@ WORKDIR /workspace COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./ COPY apps/www/package.json apps/www/package.json COPY packages packages -COPY docs docs RUN pnpm install --frozen-lockfile COPY apps/www apps/www RUN pnpm --filter vibeface-www run typecheck \ diff --git a/apps/www/public/sitemap.xml b/apps/www/public/sitemap.xml index feeac066d..4ab51d5e0 100644 --- a/apps/www/public/sitemap.xml +++ b/apps/www/public/sitemap.xml @@ -5,8 +5,12 @@ https://www.vibeface.dev/community https://www.vibeface.dev/security https://www.vibeface.dev/docs/overview + https://www.vibeface.dev/docs/quick-start + https://www.vibeface.dev/docs/onboarding + https://www.vibeface.dev/docs/user-guide https://www.vibeface.dev/docs/comparison https://www.vibeface.dev/docs/install + https://www.vibeface.dev/docs/ios https://www.vibeface.dev/docs/bot-and-execution https://www.vibeface.dev/docs/history-sync https://www.vibeface.dev/docs/privacy-security diff --git a/apps/www/scripts/check-static.mjs b/apps/www/scripts/check-static.mjs index 3d0b9cf4b..06b3cebd3 100644 --- a/apps/www/scripts/check-static.mjs +++ b/apps/www/scripts/check-static.mjs @@ -16,6 +16,7 @@ const required = [ 'docs/user-guide/index.html', 'docs/comparison/index.html', 'docs/install/index.html', + 'docs/ios/index.html', 'docs/bot-and-execution/index.html', 'docs/history-sync/index.html', 'docs/privacy-security/index.html', diff --git a/contracts/delivery/compile.mjs b/contracts/delivery/compile.mjs index 410b98a11..be51be269 100644 --- a/contracts/delivery/compile.mjs +++ b/contracts/delivery/compile.mjs @@ -8,7 +8,7 @@ export const root = path.dirname(fileURLToPath(import.meta.url)); const dependencyRoot = path.resolve(root, '../../.artifacts/vdp/contracts'); export const artifacts = process.env.DELIVERY_CONTRACT_ARTIFACTS || dependencyRoot; export const requireDependency = createRequire(path.join(dependencyRoot, 'package.json')); -export const abiFile = process.env.DELIVERY_ABI_FILE || path.resolve(root, '../../crates/delivery/abi/Statement.sol'); +export const abiFile = path.resolve(root, '../../crates/delivery/abi/Statement.sol'); export const schema = fs.readFileSync(abiFile, 'utf8'); const solc = requireDependency('solc'); diff --git a/contracts/delivery/run.mjs b/contracts/delivery/run.mjs index 91799b02a..d77fec184 100644 --- a/contracts/delivery/run.mjs +++ b/contracts/delivery/run.mjs @@ -185,7 +185,8 @@ try { await reject(() => reserve(b, [c])); const other = await budget(); await reject(() => reserve(other, [a])); await reject(() => escrow.reserveBatch(b.id, [{ ...reservation(a), walletSignature: `0x${'00'.repeat(65)}` }])); - await reject(() => escrow.reserveBatch(b.id, [reservation(c), reservation(c), reservation(c)])); + await reject(() => escrow.reserveBatch(other.id, [reservation(c), reservation(c), reservation(c)])); + await tx(escrow.reserveBatch(other.id, [reservation(c), reservation(c)])); }); await check('source proof, wallet quote, payer, payee, provider and deployment domains are bound before service', async () => { const b = await budget(); const good = await make(); diff --git a/contracts/delivery/verifier-sources.json b/contracts/delivery/verifier-sources.json index 83c087467..ac18d0f82 100644 --- a/contracts/delivery/verifier-sources.json +++ b/contracts/delivery/verifier-sources.json @@ -2,49 +2,41 @@ { "path": "vendor/risc0/contracts/src/groth16/RiscZeroGroth16Verifier.sol", "url": "https://raw.githubusercontent.com/risc0/risc0-ethereum/v3.0.1/contracts/src/groth16/RiscZeroGroth16Verifier.sol", - "http": 200, "sha256": "f24784fb625b8a82232c79f21db28f759593e29a287a4f9865cc6e78d36eb283" }, { "path": "vendor/openzeppelin/contracts/utils/math/SafeCast.sol", "url": "https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/v5.0.2/contracts/utils/math/SafeCast.sol", - "http": 200, "sha256": "089488198de38548e4e8ee7940d307f18396e5b295de5bca7ff7567fd4142cc3" }, { "path": "vendor/risc0/contracts/src/groth16/ControlID.sol", "url": "https://raw.githubusercontent.com/risc0/risc0-ethereum/v3.0.1/contracts/src/groth16/ControlID.sol", - "http": 200, "sha256": "753535e844a84a28b275fe21bd4c30022266b27bcdaa9b189220dece220accfa" }, { "path": "vendor/risc0/contracts/src/groth16/Groth16Verifier.sol", "url": "https://raw.githubusercontent.com/risc0/risc0-ethereum/v3.0.1/contracts/src/groth16/Groth16Verifier.sol", - "http": 200, "sha256": "14bdf78c8b6168b12a5235395d42b8daabb48ee29d49913bb06d20071f156fd6" }, { "path": "vendor/risc0/contracts/src/IRiscZeroVerifier.sol", "url": "https://raw.githubusercontent.com/risc0/risc0-ethereum/v3.0.1/contracts/src/IRiscZeroVerifier.sol", - "http": 200, "sha256": "cfd7c80872313134d028c0250ddc86036448fb4df290ce4dba113ea80646e180" }, { "path": "vendor/risc0/contracts/src/StructHash.sol", "url": "https://raw.githubusercontent.com/risc0/risc0-ethereum/v3.0.1/contracts/src/StructHash.sol", - "http": 200, "sha256": "9fd507fc30726dcecf35a7a1d16b2ffe34561721fa37895bb75b9c3cf07f0131" }, { "path": "vendor/risc0/contracts/src/Util.sol", "url": "https://raw.githubusercontent.com/risc0/risc0-ethereum/v3.0.1/contracts/src/Util.sol", - "http": 200, "sha256": "4711aa3c42754c996278f62091ffd1422132512e0900a9cdea3fe54235fa5896" }, { "path": "vendor/risc0/contracts/src/IRiscZeroSelectable.sol", "url": "https://raw.githubusercontent.com/risc0/risc0-ethereum/v3.0.1/contracts/src/IRiscZeroSelectable.sol", - "http": 200, "sha256": "54a8a39dd427e8ec21db31815d80a3df6df992d3244a2370ba21517dde7dd11b" }, { diff --git a/crates/bridge/src/agent.rs b/crates/bridge/src/agent.rs index 580f303ff..18ba8c6e3 100644 --- a/crates/bridge/src/agent.rs +++ b/crates/bridge/src/agent.rs @@ -1109,9 +1109,9 @@ fn cursor_models(response: &Value, env: &BTreeMap) -> CursorCata !value.is_empty() && value.len() <= 256 && !value.chars().any(char::is_control) - && !env - .values() - .any(|secret| !secret.is_empty() && value.contains(secret)) + && !env.iter().any(|(name, secret)| { + credential_value(name, secret) && value.contains(secret.as_str()) + }) }; let Some(id) = model["modelId"].as_str().filter(valid) else { return CursorCatalog::Unavailable; @@ -1665,7 +1665,10 @@ pub(crate) async fn bounded_line( #[cfg(test)] mod credential_tests { - use super::{credential_value, redact_progress, redact_stream_progress}; + use super::{ + CursorCatalog, CursorModel, credential_value, cursor_models, redact_progress, + redact_stream_progress, + }; use serde_json::json; use std::collections::BTreeMap; @@ -1808,4 +1811,28 @@ mod credential_tests { assert!(!credential_value("API_BASE", "http://host:8080/path")); assert!(!credential_value("ORIGIN", "user@example.com")); } + + #[test] + fn cursor_catalog_rejects_only_echoed_credentials() { + let env = BTreeMap::from([ + ("DEBUG".to_owned(), "1".to_owned()), + ("CURSOR_API_KEY".to_owned(), "k!secret1".to_owned()), + ]); + let catalog = |name: &str| { + cursor_models( + &json!({"models": {"availableModels": [{"modelId": "gpt-5.1", "name": name}]}}), + &env, + ) + }; + assert_eq!( + catalog("GPT 5.1"), + CursorCatalog::Available { + models: vec![CursorModel { + id: "gpt-5.1".into(), + display_name: "GPT 5.1".into(), + }], + } + ); + assert_eq!(catalog("GPT k!secret1"), CursorCatalog::Unavailable); + } } diff --git a/crates/bridge/src/platform/ipc.rs b/crates/bridge/src/platform/ipc.rs index 2a10b4eec..a8377e413 100644 --- a/crates/bridge/src/platform/ipc.rs +++ b/crates/bridge/src/platform/ipc.rs @@ -6,7 +6,7 @@ //! account behind every client by impersonating it. Neither family listens on a network //! socket, so nothing here is reachable from another machine or another account. -use anyhow::{Context, Result, bail, ensure}; +use anyhow::{Context, Result, ensure}; use std::{ path::{Path, PathBuf}, pin::Pin, @@ -123,7 +123,7 @@ impl Endpoint { match &self.address { WindowsAddress::Pipe(name) => Ok(name), WindowsAddress::CodexSocket => { - bail!("the Node's control listener requires a named pipe") + anyhow::bail!("the Node's control listener requires a named pipe") } } } @@ -634,9 +634,5 @@ pub fn runtime_dir(key: &str) -> Result { let base = PathBuf::from("/tmp"); #[cfg(windows)] let base = std::env::temp_dir(); - let directory = base.join(format!("vibeface-{key}")); - if directory.as_os_str().is_empty() { - bail!("this account has no usable temporary directory"); - } - Ok(directory) + Ok(base.join(format!("vibeface-{key}"))) } diff --git a/crates/bridge/src/platform/tree.rs b/crates/bridge/src/platform/tree.rs index 2cd1e927c..3b084b4da 100644 --- a/crates/bridge/src/platform/tree.rs +++ b/crates/bridge/src/platform/tree.rs @@ -411,12 +411,7 @@ fn signal_group(group: i32, signal: i32) -> bool { pub fn root_is_running(process: u32) -> bool { #[cfg(unix)] { - let Ok(group) = libc::pid_t::try_from(process) else { - return false; - }; - // SAFETY: kill with signal 0 performs only the existence and permission check. - let result = unsafe { libc::kill(-group, 0) }; - result == 0 || std::io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH) + libc::pid_t::try_from(process).is_ok_and(|group| signal_group(group, 0)) } #[cfg(windows)] { diff --git a/crates/bridge/src/platform/winjob.rs b/crates/bridge/src/platform/winjob.rs index ba4e23785..83c9c370a 100644 --- a/crates/bridge/src/platform/winjob.rs +++ b/crates/bridge/src/platform/winjob.rs @@ -282,9 +282,14 @@ impl std::str::FromStr for Record { /// because the caller uses the answer to decide whether to refuse rather than to end anything. pub fn process_is_running(process: u32) -> bool { use windows_sys::Win32::{Foundation::STATUS_PENDING, System::Threading::GetExitCodeProcess}; - let Ok(handle) = open_for_query(process) else { - return io::Error::last_os_error().raw_os_error() - != Some(windows_sys::Win32::Foundation::ERROR_INVALID_PARAMETER as i32); + let handle = match open_for_query(process) { + Ok(handle) => handle, + Err(error) => { + return error + .downcast_ref::() + .and_then(io::Error::raw_os_error) + != Some(windows_sys::Win32::Foundation::ERROR_INVALID_PARAMETER as i32); + } }; let mut status = 0_u32; // SAFETY: the handle is open and the status is a live local. diff --git a/crates/bridge/tests/platform.rs b/crates/bridge/tests/platform.rs index 9e7bb0f56..a596a525d 100644 --- a/crates/bridge/tests/platform.rs +++ b/crates/bridge/tests/platform.rs @@ -249,6 +249,8 @@ async fn a_process_tree_is_cleared_when_the_node_ends_it() -> Result<()> { let root = spawned.root(); assert!(spawned.is_running()); assert!(tree::root_is_running(root)); + #[cfg(unix)] + assert!(!tree::root_is_running(0) && !tree::root_is_running(1)); assert!(tree::token_is_running(spawned.token())); let left = tree::stop_recorded(spawned.token(), |_| false)?; diff --git a/crates/bridge/tests/resident_cursor_bridge.rs b/crates/bridge/tests/resident_cursor_bridge.rs index 9abaa2861..b03b6c78d 100644 --- a/crates/bridge/tests/resident_cursor_bridge.rs +++ b/crates/bridge/tests/resident_cursor_bridge.rs @@ -633,6 +633,7 @@ async fn orphan_recovery_checks_the_recorded_process_before_ending_its_tree() -> wrong[0]["identity"]["value"] = serde_json::json!("another-process-start"); vibeface_bridge::platform::privatefs::write_atomic(&file, &serde_json::to_vec(&wrong)?)?; CursorAgent::kill_orphan(&file); + tokio::time::sleep(std::time::Duration::from_secs(1)).await; assert!( !pending.is_finished(), "a stale identifier cannot end another CLI process" diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml index fb5459285..0091ddc3b 100644 --- a/crates/control/Cargo.toml +++ b/crates/control/Cargo.toml @@ -8,7 +8,6 @@ rust-version.workspace = true anyhow.workspace = true futures-util.workspace = true hex.workspace = true -libc = "0.2" rand.workspace = true reqwest.workspace = true serde.workspace = true diff --git a/crates/control/src/maintenance.rs b/crates/control/src/maintenance.rs index 842aaa30b..c52a4e90d 100644 --- a/crates/control/src/maintenance.rs +++ b/crates/control/src/maintenance.rs @@ -362,11 +362,13 @@ mod tests { } #[test] - fn wallet_passphrase_is_not_debug_or_cloneable() { + fn wallet_passphrase_is_sent_as_plain_text_in_the_command() { let command = WalletCommand::Create { passphrase: SecretString::new("a secure passphrase".into()), }; - let bytes = serde_json::to_vec(&command).unwrap(); - assert!(std::str::from_utf8(&bytes).unwrap().contains("passphrase")); + assert_eq!( + serde_json::to_value(&command).unwrap(), + serde_json::json!({"op": "create", "passphrase": "a secure passphrase"}) + ); } } diff --git a/crates/delivery/API.md b/crates/delivery/API.md index ec6b821b1..f8bf2b26a 100644 --- a/crates/delivery/API.md +++ b/crates/delivery/API.md @@ -1,6 +1,6 @@ # Delivery domain API -Draft implementation in `work/vdp-domain`. Product integration, proof resource acceptance, chain settlement and final review remain separate gates. +Domain crate used by `apps/core` and the `proof/` guest. ## Shared ABI @@ -97,8 +97,8 @@ Charity uses the same C and E byte layouts and zeroized random material as paid Native checks from the task worktree. ```sh -cargo test --manifest-path crates/delivery/Cargo.toml --target-dir .artifacts/vdp-domain/target --locked -cargo run --manifest-path crates/delivery/Cargo.toml --target-dir .artifacts/vdp-domain/target --locked --example fixture -- public 35 2 > .artifacts/vdp-domain/public-vectors.json +cargo test --manifest-path crates/delivery/Cargo.toml --target-dir .artifacts/vdp/domain/target --locked +cargo run --manifest-path crates/delivery/Cargo.toml --target-dir .artifacts/vdp/domain/target --locked --example fixture -- public 35 2 > .artifacts/vdp/domain/public-vectors.json ``` The public vector generator reports profile ABI, all journals, transcript payloads, signatures, leaves, C and E. Its synthetic fixture keys are confined to example and unit-test support. These vectors check serialization and native crypto, not guest proofs. diff --git a/crates/protocol/Cargo.toml b/crates/protocol/Cargo.toml index 6102bebb8..a52c8c605 100644 --- a/crates/protocol/Cargo.toml +++ b/crates/protocol/Cargo.toml @@ -6,4 +6,6 @@ rust-version.workspace = true [dependencies] serde.workspace = true + +[dev-dependencies] serde_json.workspace = true diff --git a/crates/secure/src/membership.rs b/crates/secure/src/membership.rs index 1c4b42c35..c0d5eb591 100644 --- a/crates/secure/src/membership.rs +++ b/crates/secure/src/membership.rs @@ -2131,7 +2131,10 @@ mod tests { }, )?; forged.issuer = id(&ordinary); - assert!(state.append(forged.sign(&ordinary)?).is_err()); + refused( + state.append(forged.sign(&ordinary)?), + "management permission required", + ); state.append(GovernanceEvent::grant( &a, &state.project()?, @@ -2172,7 +2175,11 @@ mod tests { refused(GovernanceEvent::revoke(&a, &view, cut(&a, 0)), LAST_MANAGER); let mut forged = GovernanceEvent::revoke(&a, &view, cut(&other, 0))?; forged.issuer = id(&ordinary); - assert!(state.append(forged.sign(&ordinary)?).is_err()); + let error = state.append(forged.sign(&ordinary)?).unwrap_err(); + assert!( + format!("{error:#}").contains("management permission required"), + "{error:#}" + ); state.append(GovernanceEvent::revoke( &ordinary, @@ -2250,19 +2257,16 @@ mod tests { &granted.project()?, Member::client(&b, "b", true)?, )?)?; - let early = GovernanceEvent { - version: 1, - network_id: base.genesis.network_id.clone(), - epoch: 1, - parents: vec![], - issuer: id(&b), - action: GovernanceAction::Grant { + let early = signed_at( + &base, + &b, + 1, + vec![], + GovernanceAction::Grant { member: Member::client(&c, "c", false)?, }, - signature: String::new(), - } - .sign(&b)?; - assert!(granted.append(early).is_err()); + )?; + refused(granted.append(early), "management permission required"); Ok(()) } diff --git a/deploy/README.md b/deploy/README.md index ac101604d..467f8f02f 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -12,7 +12,7 @@ python3 deploy/static-config.py --role app --component .artifacts/deploy/app/com App 使用制品内 `_headers` 的 CSP 和缓存规则,保留 `/_shell.html` 回退,缺失 API、SDK 和资源返回 404。静态容器以 UID/GID 101 运行,只监听容器内 8080,由 Compose 映射到配置中的宿主回环端口。 -远端需有 Docker Compose、Python 3.12 或更新版本和 systemd;静态角色另需 Nginx。脚本只用 `systemctl is-active`、`is-enabled`、`start`、`stop`、`enable`、`disable`,systemd 219(CentOS 7)即可。先导入镜像,再在宿主以 root 执行 `scripts/deploy-activate.py`。将 `deploy/` 放在该脚本同级目录或父目录。镜像参数必须是已导入的 `sha256:` image ID,不使用可移动 tag。 +远端需有 Docker Compose、Python 3.12 或更新版本和 systemd;静态角色另需 Nginx。脚本不启停宿主 systemd 服务;首次安装时只按文本读取 unit 文件和 drop-in 检查是否引用 `data_dir`,静态角色切换后执行 `systemctl reload nginx.service`,systemd 219(CentOS 7)即可。先导入镜像,再在宿主以 root 执行 `scripts/deploy-activate.py`。将 `deploy/` 放在该脚本同级目录或父目录。镜像参数必须是已导入的 `sha256:` image ID,不使用可移动 tag。 ```sh python3 scripts/deploy-activate.py --config /run/private/deploy.json \ @@ -107,7 +107,7 @@ Core 数据目录必须已经初始化,权限为 0700,UID/GID 与配置一 激活日志和 Compose 文件留在私有 `deploy_dir`。旧 Nginx 文件和离线备份只供激活中回滚;确认新容器后删除,同时删除其他旧 release 目录和上一版镜像,主机只保留当前版本。需要留档时在激活前把数据拷到本地。镜像健康需同时满足容器 running/healthy 与 Core inspect 的 running、版本和 device ID。失败时先停新容器,再恢复旧容器,并恢复 Nginx;全新安装没有旧服务,只停新容器;不会自动覆盖现有数据。中断后的非终态日志会先回滚并退出,检查旧服务后可重跑原命令。新容器无法确认停止时拒绝启动旧进程。确认后的同一请求会再次核对实际容器健康。 -`deploy-services` 部署 node 时,无论是否 `apply`,先选择候选发布时间之前最近的完整产品 Release,复用制品与摘要校验后构建旧 Core 镜像。旧 Core 初始化并启动 fixture,再在它运行时原子写入候选 Core 生成的完整配置,随后激活候选镜像并重复激活,核对原身份、bootstrap 文件、epoch 和数据库中的初始化记录保留。两个镜像只替换 fixture 的 `public-bootstrap.json`;数据格式和配置均按各自发布版实际生成,不做兼容迁移。fixture 只用回环地址、独立 mesh 和生成的数据。缺少历史完整产品 Release 时输出 `first_release`,验证首次安装和重复激活;其他查询、校验或升级错误一律停止。演练失败则不触碰主机。 +`deploy-services` 部署 node 时,无论是否 `apply`,先选择候选发布时间之前最近的完整产品 Release,复用制品与摘要校验后构建旧 Core 镜像。旧 Core 初始化并启动 fixture,再在它运行时原子写入候选 Core 生成的完整配置,随后激活候选镜像并重复激活,核对原身份、bootstrap 文件、epoch 和数据库中的初始化记录保留。两个镜像只替换 fixture 的 `public-bootstrap.json`;数据格式和配置均按各自发布版实际生成,不做兼容迁移。fixture 对外公布的地址(`public_url`、`relay_url`、bootstrap anchor)都是回环,Core 仍按公共节点配置以 host network 监听 runner 的 `0.0.0.0:4792` 和 `0.0.0.0:3340`,使用独立 mesh 和生成的数据。缺少历史完整产品 Release 时输出 `first_release`,验证首次安装和重复激活;其他查询、校验或升级错误一律停止。演练失败则不触碰主机。 本地验证入口均不访问生产服务。 diff --git a/deploy/runtime.py b/deploy/runtime.py index 582995b12..74194c492 100644 --- a/deploy/runtime.py +++ b/deploy/runtime.py @@ -146,7 +146,7 @@ def guard(info): return result -def maintenance(command): +def maintenance(): endpoint = Path('/tmp') / ('vibeface-' + os.environ['VIBEFACE_EXPECTED_DEVICE'][:32]) / 'maintenance.sock' metadata = endpoint.lstat() parent = endpoint.parent.lstat() @@ -157,7 +157,7 @@ def maintenance(command): stream = socket.socket(socket.AF_UNIX) stream.settimeout(15) stream.connect(str(endpoint)) - stream.sendall((json.dumps({'protocol': 1, 'command': command}) + '\n').encode()) + stream.sendall((json.dumps({'protocol': 1, 'command': 'acquire'}) + '\n').encode()) response = bytearray() while not response.endswith(b'\n') and len(response) <= 4096: part = stream.recv(4096) @@ -165,7 +165,7 @@ def maintenance(command): response.extend(part) value = json.loads(response) require(len(response) <= 4096 and value.get('protocol') == 1 - and value.get('status') == ('ready' if command == 'acquire' else 'healthy') + and value.get('status') == 'ready' and value['health']['device_id'] == os.environ['VIBEFACE_EXPECTED_DEVICE'], 'maintenance lease refused or identity differs') return stream @@ -297,7 +297,7 @@ def main(): args = [str(ROOT / 'vibeface-core'), '--data-dir', str(DATA)] os.execv(args[0], args) else: - with maintenance('acquire'): + with maintenance(): print(json.dumps({'status': 'ready'}), flush=True) sys.stdin.buffer.read(1) diff --git a/packages/client/src/identity/context.tsx b/packages/client/src/identity/context.tsx index 9765430f4..971625f82 100644 --- a/packages/client/src/identity/context.tsx +++ b/packages/client/src/identity/context.tsx @@ -83,12 +83,13 @@ type DeviceContextValue = { downloadUnsavedRecovery(): Promise /** Drops the kept file once the person confirmed it is saved, or it no longer matters. */ forgetUnsavedRecovery(): void - /** The name this browser last saw a device listed under, kept past its removal. */ joins: JoinRequest[]; joining: Joining | null; review: Review | null; initialInvitation: string; localSetup: LocalSetup | null /** Set on the local page of a removed Node, which alone may start it over. */ removedLocally: boolean; rejoined: boolean; nodeJoining: NodeJoining | null rejoin(): Promise; joinThisComputer(link: string, name: string): Promise<'joined' | 'cancelled'>; cancelNodeJoin(): Promise - connect(entry: ConnectionEntry): Promise; entryName(entry: ConnectionEntry): string; disconnect(): void; leave(): Promise; factoryReset(): Promise; retryNow(): void; saveEntry(entry: ConnectionEntry): void; removeEntry(entry: ConnectionEntry): void + connect(entry: ConnectionEntry): Promise + /** The name this browser last saw a device listed under, kept past its removal. */ + entryName(entry: ConnectionEntry): string; disconnect(): void; leave(): Promise; factoryReset(): Promise; retryNow(): void; saveEntry(entry: ConnectionEntry): void; removeEntry(entry: ConnectionEntry): void replaceLostKey(): Promise; join(link: string, name: string): Promise; checkJoin(): Promise; cancelJoin(): void /** Whether the link's computer would still take it, asked before the person names this device; null: no answer, so the form stays. */ checkInvite(link: string): Promise diff --git a/packages/client/src/identity/copy.ts b/packages/client/src/identity/copy.ts index 83d735d24..041e4ef0a 100644 --- a/packages/client/src/identity/copy.ts +++ b/packages/client/src/identity/copy.ts @@ -26,7 +26,7 @@ export const joinCopy = { /** * Why this computer's join ended and what to do next, from the `reason` the Node reports. The patterns and words follow - * `join_failure_text` in apps/core/src/main.rs, which `vibeface join` prints; only the next step is the page's own. + * `join_failure_text` in apps/cli/src/main.rs, which `vibeface join` prints; only the next step is the page's own. */ export const nodeJoinCopy = { used: '这条加入链接已经用过了。在管理设备上点“添加设备”重新生成,再粘贴新链接。', diff --git a/packages/client/src/lib/errors.ts b/packages/client/src/lib/errors.ts index 86bdf050c..e70a11e2e 100644 --- a/packages/client/src/lib/errors.ts +++ b/packages/client/src/lib/errors.ts @@ -29,7 +29,7 @@ const patterns: [RegExp, string][] = [ [/outcome may be unknown|timed out/i, '设备没有及时回复,结果未知。先确认结果,别重复提交。'], [/no configured management SDK/i, '这个节点没开 Bot。去设备页的「Bot 与任务」里选一个。'], [/question was closed/i, '这个请求已失效,不能再回答。'], - [/answered meanwhile|no App Server request is waiting/i, '这个请求已经回答过或已过期。'], + [/answered meanwhile/i, '这个请求已经回答过或已过期。'], [/no rollout found/i, 'Codex 新对话还没准备好,任务没有开始。再派一次。'], [/has no sessions folder/i, '这个节点的 Codex 还没有会话记录。先用 Codex 跑一次对话,再回来重试。'], [/explicit App Server socket/i, '还没填 Codex 的连接路径。'], @@ -61,9 +61,9 @@ const patterns: [RegExp, string][] = [ [/conversation moved meanwhile/i, '这个对话刚换过负责的设备,已刷新。确认后重试。'], [/management reply changed/i, '回复状态已变化。刷新后再停止。'], [/scheduled on another device/i, '这条回复由另一台设备负责。到那台设备上停止。'], - [/already answered or expired|executor restarted; this request expired/i, '这个请求已经回答过或已过期。'], + [/already answered or expired/i, '这个请求已经回答过或已过期。'], [/not waiting for an answer/i, '这个任务现在不需要回答。'], - [/answer every question|answers? (is|are) (missing|required)|answers must be text/i, '还有问题没回答。都答完再提交。'], + [/answer every question|answers? (is|are) (missing|required)/i, '还有问题没回答。都答完再提交。'], [/message ID reused|work ID reused|conversation ID already exists/i, '这个编号已用于不同的内容,没有重复提交。'], [/send window for this work is over/i, '这个任务等得太久,没有开始。需要的话重试。'], [/schedule this work runs for is paused|the schedule was deleted/i, '这个定时任务已暂停或删除。'], @@ -72,8 +72,8 @@ const patterns: [RegExp, string][] = [ [/not reached the scheduling Node/i, '消息还没送到负责这个对话的设备,送到后会自动排队。'], [/conversation has no scheduling Node|does not schedule the conversation/i, '这个对话不由这个节点负责。'], [/conversation not found/i, '这个节点上还没有这个对话,可能还在同步。'], - [/work not found|no work was dispatched/i, '找不到这个任务,可能还在同步。'], - [/pending check not found|only unverified work/i, '这项确认已处理或不存在。'], + [/work not found/i, '找不到这个任务,可能还在同步。'], + [/pending check not found/i, '这项确认已处理或不存在。'], [/scheduler inbox is full/i, '排队的消息太多,这条没有收下。稍后再发。'], [/attachment|blob/i, '附件还没同步到这个节点,或校验没通过。'], [/artifact/i, '这个产物现在读不了。'], @@ -84,7 +84,7 @@ const patterns: [RegExp, string][] = [ [/project root|execution path|workspace must be|workspace does not exist|manager workspace/i, '文件夹不存在,或不是这个节点上的绝对路径。'], [/No such file or directory|ENOENT|command not found|Missing script|cannot find (the )?(file|path|module)/i, '找不到需要的文件、脚本或命令。确认它在这个节点上,再让 Bot 试。'], [/permission denied|EACCES|operation not permitted/i, '这个节点上没有权限读写需要的文件。'], - [/coordination Agent|manager provider|manager program/i, '这个节点上的 Bot 还没配置好。'], + [/coordination Agent/i, '这个节点上的 Bot 还没配置好。'], [/only the user|requires the user|agents cannot|Agent tokens/i, '只有你自己能做这个操作,Bot 不能代办。'], [/management client|management permission|management control/i, '只有管理设备能做这个操作。'], [/local browser (session|cookie|access)|local (cookie|token) missing|session cookie|local session identity/i, '本机会话已失效。在运行这个节点的电脑或服务器上重新打开。'], diff --git a/packages/client/src/lib/progress.test.ts b/packages/client/src/lib/progress.test.ts index 7e545be58..f94965e7c 100644 --- a/packages/client/src/lib/progress.test.ts +++ b/packages/client/src/lib/progress.test.ts @@ -25,7 +25,6 @@ test('only the normalized progress contract crosses the changed boundary', () => { type: 'manager_progress', conversation_id: 'chat-a', trigger: 'turn-a', progress: { provider: 'arbitrary-json' } }, { type: 'manager_progress', conversation_id: 'chat-a', trigger: 'turn-a', sequence: '1', progress: { type: 'text_delta', text: 'text' } }, { type: 'manager_progress', conversation_id: 'chat-a', trigger: 'turn-a', invocation_id: {}, progress: { type: 'text_delta', text: 'text' } }, - { type: 'execution_progress', conversation_id: 'chat-a', session_id: 'removed', progress: { type: 'status', text: 'running' } }, { type: 'native_progress', conversation_id: 'chat-a', work_id: {}, thread_id: 'thread-a', target_node: 'node-a', progress: { type: 'status', text: 'running' } }, { type: 'native_progress', conversation_id: 'chat-a', work_id: 'work-a', thread_id: 'thread-a', target_node: 'node-a', progress: { type: 'tool', text: { secret: 'value' } } }, { type: 'native_progress', conversation_id: 'chat-a', work_id: 'work-a', thread_id: 'thread-a', progress: { type: 'status', text: 'running' } }, diff --git a/packages/client/src/lib/web-log.test.ts b/packages/client/src/lib/web-log.test.ts index e66dd9ef2..9d63d94fc 100644 --- a/packages/client/src/lib/web-log.test.ts +++ b/packages/client/src/lib/web-log.test.ts @@ -38,4 +38,5 @@ test('a failing device drops the batch instead of throwing', async () => { test('page ids come from the conversation query and the task path', () => { assert.deepEqual(pageIds({ pathname: '/b/bot-1/work/w-9', search: '?conversation=c-1' }), { conversation_id: 'c-1', work_id: 'w-9' }) assert.deepEqual(pageIds({ pathname: '/settings', search: '?conversation=../x' }), { conversation_id: undefined, work_id: undefined }) + assert.deepEqual(pageIds({ pathname: '/b/bot-1/work/%zz', search: '' }), { conversation_id: undefined, work_id: undefined }) }) diff --git a/packages/client/src/lib/web-log.ts b/packages/client/src/lib/web-log.ts index 3eef04522..fc86941c8 100644 --- a/packages/client/src/lib/web-log.ts +++ b/packages/client/src/lib/web-log.ts @@ -41,7 +41,9 @@ export function pageIds(location: { pathname: string; search: string }): Pick id && /^[A-Za-z0-9_.:-]{1,128}$/.test(id) ? id : undefined - return { conversation_id: valid(conversation), work_id: valid(work && decodeURIComponent(work)) } + // A hand-edited address can carry a broken escape; it names no task. + const decoded = (() => { try { return work && decodeURIComponent(work) } catch { return undefined } })() + return { conversation_id: valid(conversation), work_id: valid(decoded) } } /** Sends as soon as a device is connected; records that arrive during a send go in the next batch. */ diff --git a/packages/client/src/workspace/context.tsx b/packages/client/src/workspace/context.tsx index 97342fadd..9da48739c 100644 --- a/packages/client/src/workspace/context.tsx +++ b/packages/client/src/workspace/context.tsx @@ -427,7 +427,6 @@ function useWorkspaceState(platform: Platform, connection: ReadyConnection, open if (item.method === "ack") return !parseNotifications(await connection.rpc("notifications")).some((note) => note.notification_id === item.params.notification_id) if (item.method === "create_bot") return parseBots(await connection.rpc("bots")).some((bot) => bot.bot_id === item.params.bot_id) if (item.method === "delete_bot") return !parseBots(await connection.rpc("bots")).some((bot) => bot.conversation_id === item.params.conversation_id) - // Every unanswered question is listed, so one missing from the list has its answer. if (item.method === "set_primary_bot") return parsePrimary(await connection.rpc("bots")) === item.params.conversation_id if (item.method === "set_bot_project") { const project = parseBots(await connection.rpc("bots")).find((bot) => bot.conversation_id === item.params.conversation_id)?.project ?? null @@ -444,6 +443,7 @@ function useWorkspaceState(platform: Platform, connection: ReadyConnection, open } // Only what still wants the person is listed, so a missing one is closed or answered either way. if (item.method === "dismiss_work") return !parseOpenWorks(await connection.rpc("open_works")).some((work) => work.work_id === item.params.work_id) + // Every unanswered question is listed, so one missing from the list has its answer. if (item.method === "answer") return !parseQuestions(await connection.rpc("questions")).some((question) => question.question_id === item.params.question_id) const id = String(item.params.conversation_id) const context = parseConversation(await connection.rpc("conversation", { conversation_id: id }), id) @@ -570,7 +570,6 @@ function useWorkspaceState(platform: Platform, connection: ReadyConnection, open if (!notificationsRef.current.some((item) => item.notification_id === notification.notification_id)) return await signedWrite("ack", notification.notification_id, "ack", { notification_id: notification.notification_id, - client_id: clientId, attestation: await attest(notification.conversation_id, { type: "notification_acked", notification_id: notification.notification_id, client_id: clientId }), }) requireCurrent() diff --git a/packages/client/src/workspace/inbox.test.ts b/packages/client/src/workspace/inbox.test.ts index 092341597..0216beb39 100644 --- a/packages/client/src/workspace/inbox.test.ts +++ b/packages/client/src/workspace/inbox.test.ts @@ -7,9 +7,9 @@ import { isMainNotification, type BotRecord, type NodeInfo, type NotificationRec import { parseNotifications } from './model.ts' const question = (id: string, closed = false): Question => ({ - question_id: id, conversation_id: 'c', bot: { bot_id: 'b', name: '助手' }, severity: 'normal', text: id, choices: [], about: { kind: 'general' }, - author: 'node', created_at_ms: 1, answer: null, closed: closed ? { reason: 'expired', at_ms: 2 } : null, -} as unknown as Question) + question_id: id, conversation_id: 'c', bot: { bot_id: 'b', name: '助手' }, severity: 'attention', text: id, choices: [], about: { node: 'node', agent: 'codex', session_id: 's', cwd: '/w', summary: '' }, + author: 'node', created_at_ms: 1, answer: null, closed: closed ? 'request_lost' : null, +}) const join = (status: JoinRequest['status']): JoinRequest => ({ join_id: status, status, network_id: 'n', invite_id: 'i', device_id: 'phone', kind: 'client', name: '我的手机', commit: 'c', admin_id: null, admin_nonce: null, joiner_nonce: null, reason: null, expires_at_ms: 1, @@ -267,9 +267,8 @@ test('losing the entry makes active tasks stale without claiming every target is test('manager attention keeps its notification identity and can be hidden locally', () => { const attention = source(true) - const bot = { bot_id: 'b', conversation_id: 'c', name: '助手' } as unknown as BotRecord const note = { notification_id: 'n1', kind: 'manager_attention', text: '看看进展', conversation_id: 'c' } satisfies NotificationRecord - attention.workspace.bots = [bot] + attention.workspace.bots = [botRecord] attention.workspace.notifications = [note] const item = inboxItems(attention).find((candidate) => candidate.kind === 'attention') assert.equal(item?.kind, 'attention') diff --git a/packages/client/src/workspace/model.ts b/packages/client/src/workspace/model.ts index 59d6af0c9..fddabc26e 100644 --- a/packages/client/src/workspace/model.ts +++ b/packages/client/src/workspace/model.ts @@ -828,7 +828,7 @@ export function openWorksFromOverview(overview: WorkspaceOverview, openWorks: re return works } -/** A pushed change: the records it touched, or null when it carries none. */ +/** A pushed change: the records it touched. */ export function parseRecords(value: unknown): ConversationRecords { const data = record(value) const last = data.last_message == null ? null : record(data.last_message) diff --git a/packages/client/src/workspace/overview.test.ts b/packages/client/src/workspace/overview.test.ts index 5a0931859..ffca42dd4 100644 --- a/packages/client/src/workspace/overview.test.ts +++ b/packages/client/src/workspace/overview.test.ts @@ -169,7 +169,7 @@ test("a bounded overview adds observations without deleting known work or replac assert.match(notes, /部分记录/) assert.match(notes, /截断/) assert.match(notes, /尚未读取其他设备的后台工作/) - assert.doesNotMatch(notes, /0 项|另有/, "unknown omission counts are not fabricated") + assert.doesNotMatch(notes, /0 项/, "unknown omission counts are not fabricated") assert.match(overviewScope({ ...overview.coverage, omitted_tasks: 3 }).join(" · "), /本次总览未返回 3 项任务/) }) diff --git a/packages/client/src/workspace/questions.test.ts b/packages/client/src/workspace/questions.test.ts index 737244599..7fe318f9b 100644 --- a/packages/client/src/workspace/questions.test.ts +++ b/packages/client/src/workspace/questions.test.ts @@ -179,7 +179,7 @@ test("work approval belongs to an unfinished work in the same Bot, target device assert.equal(workApproval({ ...input, conversationId: "other-bot" }), undefined) assert.equal(workApproval({ ...input, work: { ...work, target_node: "other-device" } }), undefined) assert.equal(workApproval({ ...input, work: { ...work, thread_id: "other-session" } }), undefined) - assert.equal(workApproval({ ...input, questions: [{ ...approval, about: { ...about, agent: "codex" } }] }), undefined) + assert.equal(workApproval({ ...input, questions: parseQuestions({ questions: [row("approval", 2)] }) }), undefined, "a question without a held request is not an approval") assert.equal(workApproval({ ...input, questions: [{ ...approval, closed: "request_lost" }] }), undefined) assert.equal(workApproval({ ...input, questions: [{ ...approval, answer: { message_id: "a", text: "继续", author: "me", created_at_ms: 3 } }] }), undefined) }) diff --git a/packages/client/src/workspace/types.ts b/packages/client/src/workspace/types.ts index aa101e600..d6297a86e 100644 --- a/packages/client/src/workspace/types.ts +++ b/packages/client/src/workspace/types.ts @@ -384,7 +384,6 @@ export type OverviewNode = Pick --source-commit `。容器内生成 `0600` 最终配置,由入口监督两个同级子进程:native 经既有 `--protected-config` 调用 verify-node 的 `delivery_protected_acceptance` helper,另一个运行 tracked restart observer。它依赖同 run、同 SHA 的 package/crypto/web 检查,不启动旧专属 Android、KVM 或录像前置。现有 gate 在显式选中该模式时仍要求 job success;任何失败都不能忽略。容器的 amd64 目标不能独自证明宿主没有使用 emulation。 -该选项选择专门的 native-only 实验:package matrix 只含 Linux x86_64,保留 `package_mode=node` 的全部制品、真实进程与 Chromium 验收,以及 Rust 快慢组、MSRV、delivery、crypto 和 Web 检查。Linux Mobile/Desktop 源码检查照常执行。非 Linux 包、npm、托管的 Mac/Windows 桌面窗口及 Windows native 验收未选,其跳过不代表这些平台已验收。普通 CI、普通手动运行、定时及产品 Tag 的选择保持原样。计划摘要列出实际 target 和未选范围。 +该选项选择专门的 native-only 实验:package matrix 只含 Linux x86_64,保留该平台上 `package_mode=node` 的制品、真实进程与 Chromium 验收(只在 macOS ARM64 包上运行的 `--chat-agent` 和 `--phase5` 不执行),以及 Rust 快慢组、MSRV、delivery、crypto 和 Web 检查。Linux Mobile/Desktop 源码检查照常执行。非 Linux 包、npm、托管的 Mac/Windows 桌面窗口及 Windows native 验收未选,其跳过不代表这些平台已验收。普通 CI、普通手动运行、定时及产品 Tag 的选择保持原样。计划摘要列出实际 target 和未选范围。 同时设置附加 `desktop=true` 时,`delivery_live` 现在优先选择 native-only,托管的 Mac/Windows 桌面窗口及 Windows native 验收不执行;这改变了原先同时执行两者的组合行为。`desktop_only`、`windows_only` 或非 `none` 的 `mobile_apps` 保持各专门入口优先,native 未选。`delivery_small=true` 与 `delivery_live=true` 仍被 small-prepare 的单模式检查拒绝,不会启动 native。native job 还要求 plan、Linux package、crypto-web 和 web 全部成功,且整次运行未取消;失败、取消或缺少 Linux 包不能启动证明,整体取消后也不启动新证明。 @@ -158,7 +158,7 @@ native 创建 fresh 目录后,在原 start 的任何子进程或业务前等 ## 定期、手动和发布检查 -定时检查保留每 4 小时的 `23 */4 * * *`,UTC 槽位为 00:23、04:23、08:23、12:23、16:23、20:23。GitHub schedule 是 best effort,可能延迟或跳过,不保证每槽运行。定时和 Actions 中普通手动运行 `ci` 强制执行扩展检查,不受路径影响;显式 native-only 实验按前文选择 Linux 包,不选 npm、托管的 Mac/Windows 桌面窗口及 Windows native 验收。merge queue 执行整个工作区的核心检查,不启用慢测试、MSRV 或三平台打包。开发分支 PR 不触发 `ci`。产品 `v` Tag 由 `release.yml` 并行构建全部产品目标,`www-v` 独立构建官网。手动 `ci` 只验证和生成制品,不发布,也不自动补发 Nightly。在 GitHub Actions 选择 `ci` → `Run workflow`,选择待验收分支后运行。 +定时检查保留每 4 小时的 `23 */4 * * *`,UTC 槽位为 00:23、04:23、08:23、12:23、16:23、20:23。GitHub schedule 是 best effort,可能延迟或跳过,不保证每槽运行。定时和 Actions 中普通手动运行 `ci` 强制执行扩展检查,不受路径影响;显式 native-only 实验按前文选择 Linux 包,不选 npm、托管的 Mac/Windows 桌面窗口及 Windows native 验收。merge queue 执行整个工作区的核心检查,不启用慢测试、MSRV 或四平台打包。开发分支 PR 不触发 `ci`。产品 `v` Tag 由 `release.yml` 并行构建全部产品目标,`www-v` 独立构建官网。手动 `ci` 只验证和生成制品,不发布,也不自动补发 Nightly。在 GitHub Actions 选择 `ci` → `Run workflow`,选择待验收分支后运行。 `daily-nightly` 接在同一 main schedule run 的 `ci-gate` 后,要求 `!cancelled()` 和 gate success,不增加第二套定时全量 CI。协调器全局串行,只使用 `GITHUB_TOKEN` 创建不可变 Tag 和精确 dispatch,不需要 PAT、版本分支、PR 或 main merge。 @@ -182,7 +182,7 @@ native 创建 fresh 目录后,在原 start 的任何子进程或业务前等 `--npm-service` 仅允许无既有 Vibeface 数据或默认服务的 GitHub hosted runner,使用真实 launchd 或 systemd user manager,不能在开发者机器运行。Linux job 显式准备 user manager 和 D-Bus;不可用即失败。验收通过公开 npm CLI 执行安装、启动、停止、重启和卸载,核对服务使用 scoped npm vendor 中的原生程序。 -`npm-package` 每次只读取一次公开 `nightly`,固定版本、registry integrity、完整产品 manifest 及全部 vendor 字节,使用共享发布来源门证明基线业务来源是候选源码的祖先。基线单独上传,三个平台按不可变 artifact ID 下载同一份,不混入候选发布 artifact。来源相同、基线业务来源超前或 data epoch 不兼容均失败。 +`npm-package` 每次只读取一次公开 `nightly`,固定版本、registry integrity、完整产品 manifest 及全部 vendor 字节,使用共享发布来源门证明基线业务来源是候选源码的祖先。基线单独上传,三个平台按不可变 artifact ID 下载同一份,不混入候选发布 artifact。基线与候选是同一个源码提交、基线业务来源不是候选的祖先,或 data epoch 不兼容均失败;基线业务来源等于候选提交是允许的,记为 `business_source_relation=same`。 受控 Node 和 App Server 夹具从不可变的公开基线包创建真实非空消息及附件,安装真实服务并核对运行状态与数据,再停服,以独立 prefix 核验的本 CI 候选包替换原 prefix。两包都验证活动 Node、updater 锁、pending journal 和第二 updater 的无修改拒绝。完整的安装、状态、停止、启动、重启换 PID 和卸载生命周期由最终候选包验收;重启后核对原身份、配置、签名历史和附件字节,并确认已完成的受控调用未重放,卸载保留数据。公开基线不承担完整生命周期验收。收据分别记录两包的真实 version、source、摘要和来源关系;候选声明版本相同或较低时如实标注,不称为 SemVer 升级。只验证当前格式,不做跨历史格式迁移,也不据机械版本变化宣称业务升级或真实 Provider 验收。 @@ -296,11 +296,11 @@ Rust 快、慢组在计划生成后直接开始,Clippy 另等待静态快检 ## 缓存与并发 -`ci` 按事件类型和 Git ref 分组,仅 `main` push 的首次运行自动取消旧的同组运行,累计覆盖范围保留旧运行尚未通过的改动。每次手动运行和 `run_attempt > 1` 的重跑再按 `run_id` 分组,因此重跑旧提交不会挤掉新提交的检查,显式 `delivery_live` 不会被后续 push 取消,也不会被另一条手动运行替换其 pending 位置。定时和 merge queue 不取消正在执行的同组运行,同组仍最多保留一个等待运行。主分支核心检查可以与定时完整检查同时进行。应用 tag 不触发普通 `ci`,发布与部署工作流使用各自的并发规则。 `delivery_small` 仍使用前文的跨 ref 串行分组,不按 `run_id` 拆组,也不取消正在执行的实验。 +`ci` 按事件类型和 Git ref 分组,仅 `main` push 的首次运行自动取消旧的同组运行,累计覆盖范围保留旧运行尚未通过的改动。每次手动运行和 `run_attempt > 1` 的重跑再按 `run_id` 分组,因此重跑旧提交不会挤掉新提交的检查,显式 `delivery_live` 不会被后续 push 取消,也不会被另一条手动运行替换其 pending 位置。定时和 merge queue 不取消正在执行的同组运行,同组仍最多保留一个等待运行。主分支核心检查可以与定时完整检查同时进行。产品或官网 Tag 不触发普通 `ci`,发布与部署工作流使用各自的并发规则。 `delivery_small` 仍使用前文的跨 ref 串行分组,不按 `run_id` 拆组,也不取消正在执行的实验。 Linux x64 制品任务使用 pnpm 缓存,并按 runner、架构和 `pnpm-lock.yaml` 缓存 Chromium 二进制。浏览器的系统依赖从 Ubuntu 官方镜像下载,沿用签名仓库配置。每次仍执行冻结依赖安装、浏览器与系统依赖安装以及完整浏览器用例。缓存只包含浏览器文件,不包含测试结果、Node 数据或下载的恢复文件。 -`ci` 工作流中的 Rust 缓存仅在 `refs/heads/main` 或显式 `workflow_dispatch` 时保存。手动运行可为相同 ref 的后续运行预热。新增 profile 或缓存 key 在首次保存前需要冷构建。应用 tag 使用独立发布工作流,不属于本节缓存保存规则。 +`ci` 工作流中的 Rust 缓存仅在 `refs/heads/main` 或显式 `workflow_dispatch` 时保存。手动运行可为相同 ref 的后续运行预热。新增 profile 或缓存 key 在首次保存前需要冷构建。产品或官网 Tag 使用独立发布工作流,不属于本节缓存保存规则。 Rust 缓存命中不表示当前 workspace 无需编译。每次仍由 Cargo 核对源码和构建参数;评估缓存时同时记录编译、保存与还原的耗时。 @@ -314,7 +314,7 @@ Android 使用官方 Gradle 缓存动作和 Gradle build cache,保留 `arm64-v native-only 的选择从真实 workflow_dispatch 输入重新计算,必须与 plan 及 gate 的 `--delivery-live` 一致。不能把普通四平台计划改成 Linux-only 或关闭 npm 后通过 gate。native 被选中时必须实际成功;未选的 npm、托管的 Mac/Windows 桌面窗口与 Windows native 验收,以及非 Linux 包不计为已验证。 -GitHub 主分支规则不要求 PR 先更新到最新 base,也不将 `ci-gate` 列为必需状态。仓库开发流程仍要求相关本地验证、最终 HEAD 的 preflight 和明确合并授权。合并后的 CI 与应用 tag 的制品、发布和部署检查分别记录。 +GitHub 主分支规则不要求 PR 先更新到最新 base,也不将 `ci-gate` 列为必需状态。仓库开发流程仍要求相关本地验证、最终 HEAD 的 preflight 和明确合并授权。合并后的 CI 与产品或官网 Tag 的制品、发布和部署检查分别记录。 产品与官网 Tag 由 `release.yml` 独立校验和发布;main 的普通 CI 不公开产品。参见 [按产品组合发布](releasing.md#按产品组合发布)。 diff --git a/packages/docs/codex-app-server.md b/packages/docs/codex-app-server.md index 5bf6fc074..9a3bc28fd 100644 --- a/packages/docs/codex-app-server.md +++ b/packages/docs/codex-app-server.md @@ -122,7 +122,7 @@ ## 服务端请求 -工作线程用 `approvalPolicy=never` 和 `danger-full-access` 启动,正常不会收到审批。Node 订阅的线程上的请求和不属于线程的请求都没有固定策略:Node 挂起请求,记一行日志(方法和线程,不含命令文本),立即唤醒本机协调 Agent。Agent 用 `vibeface requests` 查看、`vibeface respond ''` 回答;需要本人拍板时用 `vibeface triage raise --request-id` 在负责该线程的助手聊天里提问,提问挂住请求直到有回答,回答后该助手有 120 秒应答。线程不属于任何助手时立即兜底。没有协调 Agent、唤醒失败或 120 秒内没有回答也没有提问时,按下表兜底并记录。Node 没有订阅的线程留给原客户端回答。 +工作线程用 `approvalPolicy=never` 和 `danger-full-access` 启动,正常不会收到审批。Node 订阅的线程上的请求和不属于线程的请求都没有固定策略:Node 挂起请求,记一行日志(方法和线程,不含命令文本),立即唤醒本机协调 Agent。Agent 用 `vibeface requests` 查看、`vibeface respond ''` 回答;需要本人拍板时用 `vibeface triage raise --request-id` 在负责该线程的 Bot 聊天里提问,提问挂住请求直到有回答。本人答案先持久化,再经私有 `HeldAnswerControl` 回到原执行设备递交,普通 Bot 在提问后不能代答。不属于任何 Bot 的会话先归给主 Bot 再按归属处理;没有 Bot、不属于线程或后台线程(`codex exec`、子代理)上的请求立即兜底。没有协调 Agent、唤醒失败或 120 秒内没有回答也没有提问时,按下表兜底并记录。Node 没有订阅的线程留给原客户端回答。 | 方法 | 兜底回复 | |---|---| @@ -150,7 +150,7 @@ | `thread/unarchived` | Thread | 线程状态、名称、归档、设置、目标等进入线程观察状态 | | `thread/closed` | Thread | 线程状态、名称、归档、设置、目标等进入线程观察状态 | | `thread/reverted` | Thread | 线程状态、名称、归档、设置、目标等进入线程观察状态 | -| `skills/changed` | Skills | 记录技能变化时间,网页重新 skills/list | +| `skills/changed` | Skills | 记录技能变化时间 | | `thread/name/updated` | Thread | 线程状态、名称、归档、设置、目标等进入线程观察状态 | | `thread/attachment/updated` | Thread | 线程状态、名称、归档、设置、目标等进入线程观察状态 | | `thread/goal/updated` | Thread | 线程状态、名称、归档、设置、目标等进入线程观察状态 | @@ -175,7 +175,7 @@ | `autoApprovalReview/strictReviewRequired` | Review | 记录最近一次同名事件 | | `item/completed` | Item | 条目按 id 存入当前回合;最终回答进入 last_assistant | | `item/agentMessage/delta` | Item | 条目按 id 存入当前回合;最终回答进入 last_assistant | -| `item/plan/delta` | Plan | 计划步骤与说明进入线程观察状态,并节流写入 WorkProgress | +| `item/plan/delta` | Plan | 追加到该条目的文本 | | `command/exec/outputDelta` | Output | 存入 `hidden`,sanitize 后不送网页 | | `process/outputDelta` | Output | 存入 `hidden`,sanitize 后不送网页 | | `process/exited` | Output | 存入 `hidden`,sanitize 后不送网页 | @@ -185,11 +185,11 @@ | `item/fileChange/patchUpdated` | Output | 存入 `hidden`,sanitize 后不送网页 | | `serverRequest/resolved` | Request | 从待答请求中移除 | | `item/mcpToolCall/progress` | Item | 条目按 id 存入当前回合;最终回答进入 last_assistant | -| `mcpServer/oauthLogin/completed` | Mcp | MCP 启动状态按服务器名进入全局观察状态 | +| `mcpServer/oauthLogin/completed` | Mcp | 记录最近一次同名事件 | | `mcpServer/startupStatus/updated` | Mcp | MCP 启动状态按服务器名进入全局观察状态 | -| `mcpServer/event/stream/notification` | Mcp | MCP 启动状态按服务器名进入全局观察状态 | +| `mcpServer/event/stream/notification` | Mcp | 记录最近一次同名事件 | | `account/updated` | Account | 账户类型与套餐进入全局观察状态,不含凭证 | -| `account/gatewayOAuth/changed` | Account | 账户类型与套餐进入全局观察状态,不含凭证 | +| `account/gatewayOAuth/changed` | Account | 记录最近一次同名事件 | | `account/rateLimits/updated` | RateLimits | 额度进入全局观察状态 | | `app/list/updated` | Apps | 应用列表进入全局观察状态 | | `remoteControl/status/changed` | Platform | 记录最近一次同名事件 | @@ -198,12 +198,12 @@ | `fs/changed` | Output | 存入 `hidden`,sanitize 后不送网页 | | `item/reasoning/summaryTextDelta` | Reasoning | 推理摘要按段累积进入线程观察状态 | | `item/reasoning/summaryPartAdded` | Reasoning | 推理摘要按段累积进入线程观察状态 | -| `item/reasoning/textDelta` | Reasoning | 推理摘要按段累积进入线程观察状态 | +| `item/reasoning/textDelta` | Reasoning | 记录最近一次同名事件 | | `thread/compacted` | Thread | 线程状态、名称、归档、设置、目标等进入线程观察状态 | | `model/rerouted` | Model | 记录最近一次同名事件 | | `model/verification` | Model | 记录最近一次同名事件 | -| `modelProvider/authRecoveryStarted` | Account | 账户类型与套餐进入全局观察状态,不含凭证 | -| `modelProvider/authRecoveryCompleted` | Account | 账户类型与套餐进入全局观察状态,不含凭证 | +| `modelProvider/authRecoveryStarted` | Account | 记录最近一次同名事件 | +| `modelProvider/authRecoveryCompleted` | Account | 记录最近一次同名事件 | | `turn/moderationMetadata` | Turn | 回合开始、结束、错误进入线程观察状态,驱动工作状态机 | | `model/safetyBuffering/updated` | Model | 记录最近一次同名事件 | | `warning` | Warning | 进入最近 20 条警告 | @@ -225,4 +225,4 @@ | `thread/realtime/closed` | Realtime | 记录最近一次同名事件 | | `windows/worldWritableWarning` | Platform | 记录最近一次同名事件 | | `windowsSandbox/setupCompleted` | Platform | 记录最近一次同名事件 | -| `account/login/completed` | Account | 账户类型与套餐进入全局观察状态,不含凭证 | +| `account/login/completed` | Account | 记录最近一次同名事件 | diff --git a/packages/docs/deployment.md b/packages/docs/deployment.md index 41983d8b9..c12e53801 100644 --- a/packages/docs/deployment.md +++ b/packages/docs/deployment.md @@ -64,7 +64,7 @@ vibeface join '<加入链接>' --name '<设备显示名称>' - 默认 App Server 模式是 `spawn`,Node 使用 `/providers/codex` 作为 `CODEX_HOME`,并在 `/providers/codex/sessions` 保存自己的会话。 - Node 不扫描用户的会话或 control socket。只有明确选择 `system` 并填写绝对 socket 才连接外部 App Server。 -- 程序先查 PATH,再查用户安装、Homebrew、npm、Volta 和 NVM 目录。Cursor 使用官方 `agent` 或 `cursor-agent`。Codex 另查 `/Applications/Codex.app/Contents/Resources`。NVM 根取 `NVM_DIR`,默认 `~/.nvm`;Windows 使用 PATHEXT。 +- 程序先查 PATH,再查用户安装、Homebrew、npm、Bun、Volta 和 NVM 目录。Cursor 使用官方 `agent` 或 `cursor-agent`。Codex 另查 `/Applications/Codex.app/Contents/Resources`,Claude Code 另查 `~/.claude/local`,opencode 另查 `~/.opencode/bin`。NVM 根取 `NVM_DIR`,默认 `~/.nvm`;Windows 使用 PATHEXT。 - npm wrapper 使用同一 `bin` 目录下的 Node。无保存程序或 PATH 且常见目录仍找不到时,仅查询登记登录 shell 的 PATH。 已写下的程序路径、模型和用途不被替换。Node-owned Codex 运行目录由 Node 创建和维护,不从用户目录查找,也不在普通 Provider 环境变量中修改。 diff --git a/packages/docs/design/agent-capabilities.md b/packages/docs/design/agent-capabilities.md index 19eb1c480..94ff81a45 100644 --- a/packages/docs/design/agent-capabilities.md +++ b/packages/docs/design/agent-capabilities.md @@ -97,10 +97,10 @@ BotMessaged { | `list_bots {}` | 读 | 每个 bot 的名称、说明前 200 字符、项目设备与目录、模型、启用的 skill ID(启用全部时为 `null`,`uses_all_skills` 为真)、实际显示的长相(`picked` 标出是否挑过)、活动 schedule 概要 | | `read_bot {bot}` | 读 | 一个 bot 的完整配置:名称、说明、项目、模型、启用的每个 skill 的 `{skill_id, name}`(启用全部时是整个库)、实际显示的长相、schedule、笔记;没有任何密钥 | | `create_bot {call_ref, name, instructions?, project_node?, project_cwd?}` | 设置 | 新建 bot 和它的会话,返回的 bot 同样给出实际显示的长相 | -| `configure_bot {call_ref, bot, name?, instructions?, model?, skills? \| all_skills?, avatar? \| default_avatar?}` | 设置 | 改自己或另一个 bot 的名称、说明、模型、启用的 skill 和长相 | +| `configure_bot {call_ref, bot, name?, instructions?, model?, reasoning_effort?, skills? \| all_skills?, avatar? \| default_avatar?}` | 设置 | 改自己或另一个 bot 的名称、说明、模型、推理档位、启用的 skill 和长相 | | `delete_bot {bot}` | 设置 | 删除另一个 bot | -- 可配项是名称、说明、模型、启用的 skill、长相和创建时的项目目录。长相的 `avatar` 只给要改的轮廓、眼睛或颜色,其余按这个 bot 当前显示的补全;`default_avatar: true` 恢复由 ID 派生的长相。新建 bot 后用 `configure_bot` 给新 bot 挑长相,`update_profile` 只改自己。`model` 为空表示跟随运行它的设备的默认模型;非空时覆盖设备默认,provider 不支持就如实失败并在回复里说明这个 bot 设定的模型,不换用别的模型。skill 仍是全网共用的库;bot 的 `skills` 为 `null` 表示启用全部(含之后新存的),新建 bot 就是这样;`skills` 给出集合后只启用这些,之后新存的 skill 要再用 `configure_bot` 加上,删除的 skill 从各 bot 的集合里去掉,`all_skills: true` 恢复全部。provider 和项目目录没有工具,仍在设置页改。 +- 可配项是名称、说明、模型、推理档位、启用的 skill、长相和创建时的项目目录。长相的 `avatar` 只给要改的轮廓、眼睛或颜色,其余按这个 bot 当前显示的补全;`default_avatar: true` 恢复由 ID 派生的长相。新建 bot 后用 `configure_bot` 给新 bot 挑长相,`update_profile` 只改自己。`model` 为空表示跟随运行它的设备的默认模型;非空时覆盖设备默认,provider 不支持就如实失败并在回复里说明这个 bot 设定的模型,不换用别的模型。skill 仍是全网共用的库;bot 的 `skills` 为 `null` 表示启用全部(含之后新存的),新建 bot 就是这样;`skills` 给出集合后只启用这些,之后新存的 skill 要再用 `configure_bot` 加上,删除的 skill 从各 bot 的集合里去掉,`all_skills: true` 恢复全部。provider 和项目目录没有工具,仍在设置页改;设备的可用文件夹等本机设置经 `propose_provider_config` 提议、本人同意后写入。 - 删除 bot:见第 5.1 节。不提供改本人或设备权限的工具。 - 授权:网页建 bot 时 `BotCreated` 和首个 `ConversationOwner` 带本人设备签名。bot 在本人消息的轮次里建 bot 时,这两条事件不带签名,改带 `cause: Cause { conversation_id, message_id }`,指向发起轮次那条本人签名消息,并把它列为父事件;入库时与 `BotChanged` 一样核对。带 `cause` 的 `ConversationOwner` 只能是 epoch 1,且紧跟同一作者在同一会话写的 `ConversationCreated`,所以不能借本人消息改已有会话的调度 Node。新会话由发起轮次的调度 Node 调度。 - `configure_bot` 写一条 `BotChanged::Profile` 到目标 bot 的会话,`cause` 指向发起会话里的本人消息,所以 `cause` 是带会话 ID 的 `Cause`。变更卡片出现在被改的 bot 的聊天里,`ChangeRecord.conversation_id` 标明它。 @@ -115,12 +115,12 @@ BotMessaged { ## 6. 轮次与门控 -| 工具类别 | 工具 | 本人 | 回答 | 工作结果 | schedule | bot 消息 | Agent 任务、路由 | -|---|---|---|---|---|---|---|---| -| 读 | `nodes` `context` `work_status` `call_lookup` `read_skill` `recall` `fetch_url` `list_bots` `read_bot` `list_sessions` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | -| 工作 | `dispatch_work` `interrupt_work` `hand_over_session` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | -| 唤醒 | `remind` `message_bot` | ✓ | ✓ | ✓ | ✓ | ✓ | | -| 设置 | `update_profile` `configure_bot` `create_bot` `delete_bot` `save_skill` `remove_skill` `save_schedule` `remove_schedule` `remember` `forget` | ✓ | | | | | | +| 工具类别 | 工具 | 本人 | 回答 | 工作结果 | schedule | bot 消息 | Agent 任务 | 工作区 Task | +|---|---|---|---|---|---|---|---|---| +| 读 | `workspace_state` `workspace_history` `tool_search` `tool_describe` `tool_call` `nodes` `context` `work_status` `call_lookup` `read_skill` `recall` `fetch_url` `list_bots` `read_bot` `list_sessions` `history_search` `history_read` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | +| 工作 | `workspace_command` `dispatch_work` `interrupt_work` `hand_over_session` `propose_provider_config` `apply_provider_config` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | +| 唤醒 | `remind` `message_bot` | ✓ | ✓ | ✓ | ✓ | ✓ | | | +| 设置 | `update_profile` `configure_bot` `create_bot` `delete_bot` `save_skill` `remove_skill` `save_schedule` `remove_schedule` `remember` `forget` | ✓ | | | | | | | 提供给模型的工具表由 `Effect::offered` 决定;Node 执行工具时再按这一轮任务的类型核对一次,CLI 直接调用也绕不过。 @@ -128,7 +128,7 @@ BotMessaged { `remind` 在本人轮次写的事件 `cause` 指向本人的消息;其他轮次 `cause` 为空,入库时只接受“新建一次性 schedule”这一种无 `cause` 的修改。 -**防循环。** 每个轮次有一个深度:本人消息、回答和路由为 0;schedule 轮取该 schedule 的 `depth`;bot 消息轮取消息的 `hops`;工作结果和 Agent 任务沿派发链取源头轮次的深度。`remind` 新建的提醒深度为当前轮次加 1,`message_bot` 的 `hops` 同样加 1,超过 4 拒绝。于是一条本人消息之后,提醒与互发消息最多再自动唤醒 4 层。另有三道上限: +**防循环。** 每个轮次有一个深度:本人消息和回答为 0;schedule 轮取该 schedule 的 `depth`;bot 消息轮取消息的 `hops`;工作结果和 Agent 任务沿派发链取源头轮次的深度。`remind` 新建的提醒深度为当前轮次加 1,`message_bot` 的 `hops` 同样加 1,超过 4 拒绝。于是一条本人消息之后,提醒与互发消息最多再自动唤醒 4 层。另有三道上限: - 每个 bot 最多 20 个活动 schedule; - 每个 bot 每小时最多发 10 条消息给其他 bot; diff --git a/packages/docs/design/agent-direct-app-server.md b/packages/docs/design/agent-direct-app-server.md index b545c0ed3..4a351d18d 100644 --- a/packages/docs/design/agent-direct-app-server.md +++ b/packages/docs/design/agent-direct-app-server.md @@ -13,14 +13,14 @@ | 客户端请求 | `read` | 只读,可重试,失败不算结果不明 | | | `write` | 有副作用,连接中断时结果不明,不自动重发 | | | `hidden` | 客户端能发,但不经 Node 暴露给网页(文件读写、任意命令执行、凭证刷新) | -| 服务端通知 | 归约类别 | 每个通知归入一个类别(线程、回合、条目、计划、推理摘要、用量、额度、账户、配置、技能、插件、MCP、应用、文件监视、进程、实时、警告等),由观察状态的归约函数处理 | +| 服务端通知 | 归约类别 | 每个通知归入一个类别(线程、回合、条目、计划、推理摘要、用量、额度、账户、技能、应用、MCP、hook、审查、模型、警告、搜索、实时、平台、导入、请求、执行输出),由观察状态的归约函数处理 | | 服务端请求 | 交给协调 Agent | Node 挂起请求并唤醒协调 Agent,由它回答或提问,见 1.2 | ### 1.1 观察状态 -客户端把每条通知归约进 `Observed`:每个线程的状态、名称、模型和推理强度、进行中的回合、最近回合的结果、最后一段回答、计划步骤、推理摘要、token 用量、目标和归档状态,以及全局的账户类型、额度、模型列表、技能、插件、MCP 状态和最近的警告。账户状态只保留类型、套餐和登录与否,不保留任何 token。 +客户端把每条通知归约进观察状态:每个线程的状态、名称、模型和推理强度、进行中的回合、最近回合的结果、最后一段回答、计划步骤、推理摘要、token 用量、目标和归档状态,以及全局的账户类型、额度、模型列表、技能、插件、MCP 状态和最近的警告。账户状态只保留类型、套餐和登录与否,不保留任何 token。 -送往网页之前,Node 用 `sanitize` 去掉执行内容:`commandExecution` 只留 `id`、`type`、`status`;`fileChange` 去掉 `changes`;`turn/diff/updated`、命令输出和进程输出的增量不送出。状态里保留原始内容,供对账和 Agent 使用。 +送往网页之前,Node 用 `sanitize` 去掉执行内容:`commandExecution`、`fileChange`、`functionCallOutput` 只留 `id`、`type`、`status`;`turn/diff/updated`、命令输出和进程输出的增量不送出。状态里保留原始内容,供对账和 Agent 使用。 ### 1.2 服务端请求 @@ -28,7 +28,7 @@ 1. Node 给请求分配 `request_id`,挂起并记入 `node.log`(方法和线程,不含命令文本),然后作为 `needs_input` 事件(带 `request_id`)立即唤醒本机协调 Agent。事件只含方法、原因和问题,命令、补丁和路径不进事件。 2. Agent 用 `vibeface requests` 查看挂起的请求(含完整参数),用 `vibeface respond ''` 回答。只有仍在待处理队列、且没有已提问 `question_id` 的请求能这样回答;同一 `request_id` 只回答一次,重复调用返回第一次的结果。 -3. 需要本人决定时,Agent 用 `vibeface triage raise --request-id --question <问题> --choice 批准 --choice 拒绝` 在负责该线程的 Bot 聊天里提问。提问挂住请求直到有回答,不设超时。本人回答保存为签名消息后,持有原请求的 Node 领取一条独立的私有回答控制(占一次 `daily_decision_limit` 额度),在新的协调会话里核验原请求、传输代次、权限和响应 schema,只向仍活跃的原请求应答一次;它不进入 Bot 的 Main/Task 回合,Agent 不能用 `respond` 替本人回答已提问的请求,结果未知时不重放。线程不属于任何 Bot 时立即兜底。 +3. 需要本人决定时,Agent 用 `vibeface triage raise --request-id --question <问题>` 在负责该线程的 Bot 聊天里提问。挂起的审批只用 Node 给出的“允许本次”(原请求支持时)和“拒绝”,`--choice` 只用于普通提问。提问挂住请求直到有回答,不设超时。本人回答保存为签名消息后,持有原请求的 Node 领取一条独立的私有回答控制(占一次 `daily_decision_limit` 额度),在新的协调会话里核验原请求、传输代次、权限和响应 schema,只向仍活跃的原请求应答一次;它不进入 Bot 的 Main/Task 回合,Agent 不能用 `respond` 替本人回答已提问的请求,结果未知时不重放。线程不属于任何 Bot 时立即兜底。 4. 没有配置协调 Agent、唤醒失败,或 Agent 120 秒内既没回答也没提问时,Node 按方法给出确定的拒绝并记录: | 请求 | 兜底回复 | @@ -149,20 +149,22 @@ Codex Bot 在 App Server 上的协调回合总是用 `sandboxMode=danger-full-ac | 来源 | 方式 | |---|---| | Codex hook | `Stop`、`PermissionRequest` 调用 `vibeface hook codex` | -| Claude Code hook | `Stop`、`StopFailure`、`Notification` 调用 `vibeface hook claude` | +| Claude Code hook | `Stop`、`StopFailure`、`Notification`、`PermissionRequest` 调用 `vibeface hook claude` | +| pi 扩展 | `~/.pi/agent/extensions/vibeface.ts` 调用 `vibeface hook pi` | +| OpenCode 插件 | `~/.config/opencode/plugins/vibeface.ts` 调用 `vibeface hook opencode` | | App Server | 本机 App Server 报告的所有线程的 `turn/completed`(完成、失败、中断) | | 会话扫描 | 默认关闭;显式启用后,每 5 分钟扫描 `triage.codex_sessions` 配置目录下 24 小时内修改的 `rollout-*.jsonl`,按文件记录已读偏移,读 `task_complete`、`turn_aborted` | -`vibeface hook` 从 stdin 读 hook 输入,补上 git 分支和提交,POST 到本机 Node 的 `/api/hooks`。该路由只在本机监听器上,只接受回环地址、没有 `Origin` 和转发头、并带所有者 bearer 的 JSON 请求:`vibeface hook` 读取数据目录私有的 `local-access.json`,按其中记录的 origin 发请求并附 capability,浏览器跨站请求和读不到该目录的进程一律拒绝;同一 OS 账户的完整 Shell 不在此隔离之内。Node 不在线时写入数据目录的 `hook-spool/`,Node 每次扫描(启动 5 秒后,之后每 5 分钟)时读入。Node 第一次见到启动前就存在的 rollout 文件时从文件末尾开始读,不把历史当新事件。hook 总是以 0 退出,连接超时 2 秒,总超时 5 秒。 +`vibeface hook` 从 stdin 读 hook 输入,补上 git 分支和提交,POST 到本机 Node 的 `/api/hooks`。该路由只在本机监听器上,只接受回环地址、没有 `Origin` 和转发头、并带所有者 bearer 的 JSON 请求:`vibeface hook` 读取数据目录私有的 `local-access.json`,按其中记录的 origin 发请求并附 capability,浏览器跨站请求和读不到该目录的进程一律拒绝;同一 OS 账户的完整 Shell 不在此隔离之内。Node 不在线时写入数据目录的 `hook-spool/`,Node 每次扫描(启动 5 秒后,之后每 5 分钟)时读入。Node 第一次见到启动前就存在的 rollout 文件时从文件末尾开始读,不把历史当新事件。hook 总是以 0 退出,连接超时 2 秒,上报总超时 5 秒;事件带 `hold`(会话挂着请求等回答:Claude Code 的 `PermissionRequest`、pi 的回合结束、OpenCode 的 `permission.asked` 和 `question.asked`)时,hook 再向 `/api/hooks/wait` 等最多 40 秒,Node 给这类请求的回答期限是 30 秒(`HOOK_ANSWER_WITHIN`)。 统一事件格式(schema_version 1): ```text { schema_version, event_id, source, host, node, agent, event, status, session_id, turn_id, - cwd, repo, git_branch, git_head, last_message, detail, ts_ms, test } + cwd, repo, git_branch, git_head, last_message, detail, ts_ms, test, request_id, hold } ``` -- `agent`:`codex` 或 `claude`。`event`:`turn_end`、`needs_input`、`notification`。`status`:`completed`、`failed`、`interrupted` 或空。 +- `agent`:`codex`、`claude`、`pi` 或 `opencode`。`event`:`turn_end`、`needs_input`、`notification`。`status`:`completed`、`failed`、`interrupted` 或空。 - `event_id = sha256(node, agent, session_id, turn_key, event)` 的前 32 个十六进制字符。`turn_key` 是回合编号;Claude 没有回合编号,用 transcript 的字节长度。同一回合从 hook、App Server 和扫描进来得到同一个 `event_id`,只处理一次。 - `last_message` 最多 4000 字,`detail` 最多 2000 字。 @@ -190,11 +192,11 @@ Codex Bot 在 App Server 上的协调回合总是用 `sandboxMode=danger-full-ac 密钥只存在数据目录的 `triage-webhook.key`(0600),不进 `config.json`、DAG、日志和诊断包。网页只能设置或清除,读不回来。 -设置是本机的,只有管理设备或本机会话能改,经浏览器会话的方法调用: +设置是本机的,只有管理设备或本机会话能改,经浏览器会话的方法调用,或在本机用 `vibeface triage settings|configure|test-webhook|create-token|revoke-token`: | 方法 | 参数 | 返回 | |---|---|---| -| `triage_settings` | 无 | `{default_outlet, projects, webhook_url, scan_codex_sessions, codex_sessions, webhook_secret_set, decision_url, device_id, decision_tokens: [{token_id, label, created_ms}], outbox: {pending, delivered, dead}}` | +| `triage_settings` | 无 | `{default_outlet, projects, webhook_url, scan_codex_sessions, codex_sessions, webhook_secret_set, decision_url, device_id, decision_tokens: [{token_id, label, created_ms}], outbox: {pending, delivered, dead}, status: {budget: {day, used, limit, retry_at_ms, paused_reason}, pending_events, inflight_events, unknown_events}}` | | `configure_triage` | `{default_outlet, projects: [{prefix, outlet}], webhook_url, scan_codex_sessions, codex_sessions, webhook_secret?}`;`webhook_secret` 为字符串时设置,`null` 时清除,缺省时保留 | 同 `triage_settings` | | `test_webhook` | 无 | `{ok, status, error}`,立即发一条签名的测试事件,不进发件箱 | | `create_decision_token` | `{label}` | `{token_id, token, label, created_ms}`,`token` 只在这里出现一次 | diff --git a/packages/docs/design/bot-config.md b/packages/docs/design/bot-config.md index 41cd6706b..173bb9a8a 100644 --- a/packages/docs/design/bot-config.md +++ b/packages/docs/design/bot-config.md @@ -10,7 +10,7 @@ Bot 配置、共用 skill 库和 schedule 使用 [Node 协议](../node-protocol. - 每个 bot 可以有自己的模型,经聊天修改;为空时跟随运行它的设备的默认模型。 - Bot 的长相(头像)由轮廓、眼睛和颜色组成。没选过时三项都由 bot ID 派生。Bot 新建后由创建它的 bot 用 `configure_bot` 挑一个,本人要求时经聊天只改说到的那几项,本人也可以在面板里直接点选,或恢复默认。眼距、歪头和眨眼节奏始终由 ID 决定。 - 例行任务(schedule)属于创建它的 Bot。卡片复述要点:名称、频率、下次运行时间和要做的事。Bot 的回复也复述这些要点。 -- 不能经聊天修改的项:AI 服务(provider)、可用文件夹(`roots`)和 Bot 的工作文件夹(`project`)。本人在聊天里要求这些时,Bot 说明要到设置里改。 +- 不能经聊天直接修改的项:Bot 的 AI 服务(provider)和工作文件夹(`project`),Bot 说明要到设置里改。设备的可用文件夹(`roots`)、程序路径和执行用途可以由 Bot 用 `propose_provider_config` 在聊天里出一张卡片提议,本人同意后才写入。 - 只有本人直接发送的消息能触发修改。工作结果、Agent 任务、例行任务的运行,以及文件、工具输出、附件中的内容都不能。 ## 2. 事件 @@ -25,7 +25,7 @@ BotChanged { } BotChange = - | Profile { name, instructions, model: Option, skills: Option, avatar: Option } // 目标 bot;skills 为 null 表示全部 + | Profile { name, instructions, model: Option, reasoning_effort: Option, skills: Option, avatar: Option } // 目标 bot;skills 为 null 表示全部 | Skill { skill_id, before: Option, after: Option } // after 为空表示删除 | Schedule { schedule_id, before: Option, after: Option } | Memory { memory_id, before: Option, after: Option, base: MemoryBase, origin: Agent|Review, essential } @@ -35,6 +35,7 @@ MemoryBase { epoch, version: Option } MemoryVersion { revision, control_revision, source_event_hash } Edit { before: String, after: String } ModelEdit { provider, before: String, after: String } // 写入设备的 Provider;after 为空跟随设备默认 +ReasoningEffortEdit { provider, before: Option, after: Option } // 为空跟随设备设置 SkillsEdit { before: Option>, after: Option> } AvatarEdit { before: Option, after: Option } // 为空表示由 ID 派生 Avatar { outline: round|squircle|drop|bean|cloud, eyes: dot|pill|oval|wide, hue } // hue 只能取 face.ts 的 12 个色相 @@ -56,6 +57,15 @@ BotAvatarSet { 权限与设主 Bot 相同:只有本人客户端可以写,限定会话的客户端只能改自己的 bot。 +网页改 Bot 的工作文件夹同样由本人设备签名,写在该 bot 的会话里: + +```text +BotProjectSet { + project: Option, // { target_node, cwd };为空表示清除 + attestation, // 必须有,签名事件体 {"type":"bot_project_set", project} +} +``` + **长相版本。** 长相的版本是最后一次写这项的事件(聊天修改或 `BotAvatarSet`)hash 的前 16 个字符,取自投影行 rank 的末段,与交接会话的版本同一取法;从没改过时为 `null`。`bots` 和 `set_bot_avatar` 返回的 bot 带 `avatar_version`。任何一次修改都换新版本,改回原来的长相也一样。 **按版本写入。** 接收写入的 Node 在同一把存储锁内读投影再追加:当前已是 `avatar` 时不写,按已生效返回;否则只有当前版本等于请求的 `version` 才写,不等就拒绝。签名覆盖 `version`,所以改写版本会验签失败。由此重发不会造成 ABA:请求已写入时当前就是 `avatar`,重发不写;X 改 Y 写入后别处又改回 X,或改成 Z,版本都已变,重发被拒;请求没写入而长相在别处转了一圈回到原样,版本同样已变,也被拒。只按长相比较做不到最后一种。投影仍只按 rank 收敛,`version` 不参与;比较只防同一入口上的过期请求,两台 Node 同时接收的写入照样按 rank 决出。 @@ -76,7 +86,8 @@ BotAvatarSet { | 投影 | 规则 | |---|---| -| Bot 名称、说明、模型、启用的 skill | 每个字段按事件 rank 后写者胜。`BotCreated` 给出初值,`Profile` 的修改 rank 更大时覆盖 | +| Bot 名称、说明、模型、推理档位、启用的 skill | 每个字段按事件 rank 后写者胜。`BotCreated` 给出初值,`Profile` 的修改 rank 更大时覆盖 | +| Bot 工作文件夹 | `BotCreated` 给出初值,`BotProjectSet` 的 rank 更大时覆盖 | | Bot 长相 | `Profile` 的 `avatar` 和 `BotAvatarSet` 写同一个字段,按 rank 后写者胜;没有任何一条时由 ID 派生 | | skill 库 | 全网一张表,按 `skill_id` 后写者胜,删除保留墓碑 | | 例行任务 | 按 `schedule_id` 后写者胜,删除保留墓碑,归属写入它的会话 | diff --git a/packages/docs/design/desktop-platforms.md b/packages/docs/design/desktop-platforms.md index e671c762d..829b47d64 100644 --- a/packages/docs/design/desktop-platforms.md +++ b/packages/docs/design/desktop-platforms.md @@ -6,8 +6,8 @@ Windows、macOS 和 Linux 使用 Electron 桌面宿主,复用 React 业务界 ```text macOS / Windows / Linux - Electron 主进程 → 启动器与本机节点管理 → 捆绑的 Rust CLI / Core - Electron 业务窗口 → 内置 React 客户端 → 加密连接本机或远端 Node + Electron 主进程 → 本机节点管理 → 捆绑的 Rust CLI / Core + Electron 客户端窗口 → 内置 React 客户端 → 加密连接本机或远端 Node iOS / Android React Native App → 共享客户端与密码学模块 → 加密连接远端 Node @@ -16,9 +16,9 @@ Node Core → 持久记录、同步、调度 → Provider / SDK → 所在电脑 CLI → 本机控制、服务注册、安装与更新 ``` -桌面负责窗口、单实例、菜单/托盘、系统交互以及启动、离线和设置状态。Core 继续负责持久化、同步、调度与 Provider。业务窗口开启 sandbox、contextIsolation,关闭 nodeIntegration,不向页面暴露任意进程、文件或管理者能力。 +桌面负责窗口、单实例、菜单/托盘、系统交互以及启动、离线和设置状态。Core 继续负责持久化、同步、调度与 Provider。客户端窗口开启 sandbox、contextIsolation,关闭 nodeIntegration,不向页面暴露任意进程、文件或管理者能力。 -启动器与业务窗口分开。启动器只能通过校验过的窄 IPC 操作本机运行。业务页面来自安装包内经过清单校验的 Web 文件,固定使用 `vibeface-app://app/` 来源;即使没有本机 Node,也能打开客户端并使用邀请链接。原有非导出设备私钥保存在这个固定来源的 IndexedDB 内,不复制既有浏览器私钥。 +桌面只有一个客户端窗口。本机节点管理在客户端的设置页,只能通过校验过的窄 IPC 操作本机运行。业务页面来自安装包内经过清单校验的 Web 文件,固定使用 `vibeface-app://app/` 来源;即使没有本机 Node,也能打开客户端并使用邀请链接。原有非导出设备私钥保存在这个固定来源的 IndexedDB 内,不复制既有浏览器私钥。 业务页通过专用 preload 使用本机接入和 LAN 传输,不获得通用命令、文件或 HTTP 能力。本机接入由主进程重新检查所选节点的目录、设备身份和私有 loopback 来源;长期启动能力和 HttpOnly cookie 保留在主进程。首次注册继续使用已有身份确认、恢复文件下载和保存确认流程。普通远端入口继续使用现有 WebSocket 与 Noise;LAN 使用捆绑 Core 的客户端桥接模式和原有 Iroh QUIC,客户端模式不初始化节点。 diff --git a/packages/docs/design/questions-in-chat.md b/packages/docs/design/questions-in-chat.md index 64a4909b3..8902ba53c 100644 --- a/packages/docs/design/questions-in-chat.md +++ b/packages/docs/design/questions-in-chat.md @@ -56,7 +56,7 @@ PrimaryBotSet { // 写在 BOTS_SCOPE,须本人签名 Subject { // 问题所涉的设备、项目和 session node: DeviceId, // 运行该 session 的设备 - agent: String, // "codex" | "claude" + agent: Option, // codex | cursor | claude | pi | opencode;问的是该设备自身设置时为空 session_id: String, // Codex thread ID 或 Claude session ID cwd: String, // "workspace-N/…":该设备第 N 个可用文件夹(roots,从 1 数)下的相对路径,不在任何文件夹下时为 "workspace";网页和手机按该设备公开的 roots 还原成文件夹名 summary: String, // 一行,session 最近在说什么 @@ -90,7 +90,7 @@ MessagePosted { // 现有事件,新增一个字段 SessionAttributed { // 写在接手 Bot 的会话 scope;rank 最大者为准 node: DeviceId, - agent: String, + agent: Provider, session_id: String, cwd: String, summary: String, @@ -100,6 +100,11 @@ SessionMuted { // 写在当前接手 Bot 的会话 scope node: DeviceId, session_id: String, } + +QuestionClosed { // 提问设备写在问题所在会话:挂起的请求已消失、答案无处可送;已有回答仍以回答为准 + question_id: String, + reason: CloseReason, // request_lost +} ``` 签名规则:网页回答须本人设备签名。Grok 经已验证的 decision token 回答,由入口 Node 保存同一答案及私有授权绑定。普通无签名消息不能进入本人控制通路。普通问题后续轮的触发类型为 `answer`,保持原目标且不提供改设置工具;live request 的答案不用 Answer job。 @@ -108,11 +113,11 @@ SessionMuted { // 写在当前接手 Bot 的会话 scope | 表 | 主键 | 规则 | |---|---|---| -| `questions` | `(network_id, question_id)` | 先到者胜;存会话 ID、事件体、作者、时间 | +| `questions` | `(network_id, question_id)` | rank 最小者胜;存会话 ID、事件体、作者、时间和 `closed` | | `messages.answers` | 新列,索引 `(network_id, answers)` | 回答即消息;同 ID 先到者胜 | | `session_owners` | `(network_id, node, session_id)` | 来自 `WorkProgress.thread_id`(rank 最小者胜)与 `SessionAttributed`(rank 最大者胜,覆盖工作记录);`muted` 由同一 Bot 会话里 rank 更大的 `SessionMuted` 置位,新的 `SessionAttributed` 清除 | -未回答 = `questions` 左连接 `messages.answers` 为空。不另设“已回答”状态。 +未回答 = `questions` 左连接 `messages.answers` 为空且 `closed` 为空。不另设“已回答”状态;提问设备可用 `QuestionClosed` 关闭已无法送达的问题。 主 Bot 不建表,也不改数据纪元。读取时取 `BOTS_SCOPE` 里 rank 最大的 `PrimaryBotSet`,所指 Bot 仍在则用它,否则用最早创建的 Bot。旧版本 Node 不认识这个事件,升级前会拒收。 diff --git a/packages/docs/design/web-ux.md b/packages/docs/design/web-ux.md index 2fed63178..0f998bb58 100644 --- a/packages/docs/design/web-ux.md +++ b/packages/docs/design/web-ux.md @@ -107,7 +107,7 @@ | 再试 | 重试 | | 复制 | 复制 | -**排版。** 中文与英文、数字之间加一个空格,如“运行 Codex”“3 个文件”。后端拼好的中文文案(如 `chat_controls.rs` 的“原生 Agent请求”)不直接显示。标点用全角,省略号用“…”。 +**排版。** 中文与英文、数字之间加一个空格,如“运行 Codex”“3 个文件”。后端拼好的中文文案不直接显示。标点用全角,省略号用“…”。 **禁用词。** 下列词只能出现在 `Details` 里,或出现在 CLI 和文档中。 diff --git a/packages/docs/e2e.md b/packages/docs/e2e.md index 3243a32f9..49657fe17 100644 --- a/packages/docs/e2e.md +++ b/packages/docs/e2e.md @@ -26,15 +26,15 @@ PLAYWRIGHT_BROWSERS_PATH="$PWD/.artifacts/e2e/browsers" pnpm exec e2e-web instal 所有 Web fixture 显式选择受控 Cursor CLI,避免 AI 设置的自动探针启动 PATH 中的个人 CLI。`onboarding.e2e.ts` 的 Cursor 场景从旧 SDK 程序选择开始,在受控 PATH 中发现并保存官方入口,核对未登录提示、无密钥输入、受控 CLI 登录后返回页面的认证与模型状态,以及 Bot 和执行用途仍关闭。全过程不发送模型提示。 -示例检查建网页面。核心测试依次建网、下载恢复文件、跳过 AI 设置、创建 Bot,再刷新确认它仍存在。传输测试启动发送 Node、接收 Node 和运行 relay 的公共节点,经真实界面创建两个独立个人网络,从“设置 → 实验室”开启文件传输,再到 `/settings/lab/transfers` 确认零费用订单,接受订单并重启接收 Node。它还关闭实验并刷新,检查记录仍在、已收到文件仍可保存、重开不新增订单且不改变原传输方式。浏览器下载的原文件必须通过 SHA-256 核对,免费过程不创建钱包或调用链上 RPC。这些测试不需要模型或登录。CI 使用本次提交打包出的 Linux 程序运行。 +核心测试依次建网、下载恢复文件、跳过 AI 设置、创建 Bot,再刷新确认它仍存在。传输测试启动发送 Node、接收 Node 和运行 relay 的公共节点,经真实界面创建两个独立个人网络,从“设置 → 实验室”开启文件传输,再到 `/settings/lab/transfers` 确认零费用订单,接受订单并重启接收 Node。它还关闭实验并刷新,检查记录仍在、已收到文件仍可保存、重开不新增订单且不改变原传输方式。浏览器下载的原文件必须通过 SHA-256 核对,免费过程不创建钱包或调用链上 RPC。这些测试不需要模型或登录。CI 使用本次提交打包出的 Linux 程序运行。 headless 传输测试仅阻止临时文件输入打开原生系统选择框,再用真实 `setInputFiles` 选择任务内文件。文件输入的 change 事件、原文件内容、产品加密和 Node 请求均保留真实路径。下载结果仍需独立核对 SHA-256。 -测试使用 `tests/e2e/fixtures.ts` 导出的 `test`、`deliveryTest` 或 `workspaceTest`,每项测试均重建 Node。保持 `workers: 1` 和 `retries: 0`,避免重复执行有外部副作用的验收。 +测试使用 `tests/e2e/fixtures.ts` 导出的 `test`、`cursorTest`、`deliveryTest`、`workspaceTest` 或 `meshTest`,每项测试均重建 Node。保持 `workers: 1` 和 `retries: 0`,避免重复执行有外部副作用的验收。 `workspace.e2e.ts` 从真实表单创建 Bot、独立 Task 和频道,检查连续补充、稍后队列控制、Context 来源、scope 隔离及窄屏输入和停止。控制器只释放固定的受控 Provider 门,并读取实际原生输入和回合记录,不直接写业务表。390px 网页通过不能替代原生手机制品验收。 -公共入网使用同一文件导出的 `meshTest`。测试页面由一台公共节点提供,它在随机网络名的全网里当 bootstrap 节点,提供开放 relay 和面向任何设备的浏览器转发;成员 Node 只把这台公共节点配成 bootstrap 节点,不配置 relay 或运营者令牌。浏览器粘贴加入链接,经公共节点按设备编号连到成员 Node,完成真实安全码配对后读取助手列表,刷新后仍能连上。普通夹具的 Node 不入全网(`--no-mesh`),本机页面不连接官方服务。 +公共入网使用同一文件导出的 `meshTest`。测试页面由一台公共节点提供,它在随机网络名的全网里当 bootstrap 节点,提供开放 relay 和面向任何设备的浏览器转发;成员 Node 只把这台公共节点配成 bootstrap 节点,不配置 relay 或运营者令牌。浏览器粘贴加入链接,经公共节点按设备编号连到成员 Node,完成真实安全码配对后读取 Bot 列表,刷新后仍能连上。普通夹具的 Node 不入全网(`--no-mesh`),本机页面不连接官方服务。 ```sh pnpm exec e2e run --config tests/e2e/e2e.config.ts mesh.e2e.ts @@ -220,7 +220,7 @@ pnpm exec e2e run --config tests/e2e/e2e.workspace.native.config.ts workspace.na 宿主构建前还要求 HEAD 等于本次提交,且 `git status --porcelain --untracked-files=normal` 为空。DerivedData 和 Simulator zip 位于已忽略的 `.artifacts/native/`,不会干扰这个检查。Expo prebuild 改变源码时必须先解决,不能继续把脏源码产物记为当前提交。 -本地运行使用上节的四个明确产物与 simulator 环境变量,并补充当前源码身份。仅选择 Provider 用例,不运行公益文件用例。Node 端的 `native_provider_clipboard` 总是核对 CI 身份:要设置 `GITHUB_RUN_ID` 和 `GITHUB_RUN_ATTEMPT`,模拟器名为 `vibeface-provider--`,并把它的 UUID 写入 `.artifacts/native/simulator.txt`,否则本地运行在这一步失败。 +本地运行使用[验证原生接收和本地文件](#验证原生接收和本地文件)一节的四个明确产物与 simulator 环境变量,并补充当前源码身份。仅选择 Provider 用例,不运行公益文件用例。Node 端的 `native_provider_clipboard` 总是核对 CI 身份:要设置 `GITHUB_RUN_ID` 和 `GITHUB_RUN_ATTEMPT`,模拟器名为 `vibeface-provider--`,并把它的 UUID 写入 `.artifacts/native/simulator.txt`,否则本地运行在这一步失败。 ```sh umask 077 @@ -230,7 +230,7 @@ pnpm exec e2e run --config tests/e2e/e2e.native.config.ts --grep '^provider ' \ --trace off --video off --retries 0 > .artifacts/native/private/ui.log 2>&1 ``` -该用例重新安装当前 App,逐项核对已安装 bundle 与构建 bundle 的文件摘要,包括实际可执行文件、打包 JavaScript 和原生库。它用 e2e Secret 从任务私有文件读取邀请,填写原生“加入链接”表单,再核对双方安全码并授予管理权限。邀请不会作为普通深链接参数传入 UI driver。iOS 的 TextInput 可把 placeholder 或值附在可访问名称后面,因此输入定位使用 textbox 角色和以字段名称开头、带分隔边界的正则,仍要求唯一匹配。已填写值、保存回读和私有命令剪贴板均作精确核对。 +该用例重新安装当前 App,逐项核对已安装 bundle 与构建 bundle 的文件摘要,包括实际可执行文件、打包 JavaScript 和原生库。fixture 把邀请经 `simctl pbcopy` 的标准输入写入专属模拟器剪贴板,用例点系统粘贴按钮填入原生“加入链接”表单,再核对双方安全码并授予管理权限。邀请不会作为普通深链接参数传入 UI driver。iOS 的 TextInput 可把 placeholder 或值附在可访问名称后面,因此输入定位使用 textbox 角色和以字段名称开头、带分隔边界的正则,仍要求唯一匹配。已填写值、保存回读和私有命令剪贴板均作精确核对。 原生设备页的“Bot 与任务”进入真实 AI 设置页。fixture 只配置受控程序与连接模式,并关闭 Bot 和执行角色,真实返回 `manager=null`。用例先确认未启用的 Codex 尚未主动检查,再开启执行用途;依照 Node 的首次设置默认,这也开启 Bot,用例随后由原生界面关闭 Bot。启用和已有 manager 的 Node 启动都会主动检查,不能把这些结果称为未检查。用例在 execution-only 状态实际检查未登录提示,精确核对从界面复制的登录命令,由受限 fake CLI 完成一次合成登录,再主动检查并选择、手填和清空执行模型。之后开启 Bot,验证双角色草稿、独立保存、默认模型和 high。它还确认 Provider 控制强度时清除旧覆盖,包括带空白的手填已知模型,以及目录不可用时保留旧模型和强度。所有启用与保存均经已授权手机的正常接口执行。 @@ -238,7 +238,7 @@ pnpm exec e2e run --config tests/e2e/e2e.native.config.ts --grep '^provider ' \ native config 默认关闭 trace 和整段 video。原始日志、自动失败截图、e2e report、邀请、恢复文件、Node 数据与 driver 状态都属于私有材料,不能递归上传 `.artifacts/native/`。CI 只上传固定的 `provider.json`、`provider-probe.json`、`provider-initial.png`、`provider-selectable.png`、`provider-controlled.png`、`provider-typed.png` 和 `terminology-device-kinds.png`。`provider-probe.json` 只记录首轮检查的 `link`、`readiness`、`authentication`、`catalog` 和 `checked` 五个固定状态字段。 -`provider-initial.png` 是唯一的配对前诊断图。它只在本次 CI 新建的专属 simulator 上,重新安装、清除钥匙串并启动 App 后主动拍摄,且早于首次 `secrets.get` 和邀请输入。用例核对 simulator 文件、实际 UUID、Booted 状态以及包含当前 run ID 和 attempt 的专属名称。此时 App 尚未接收邀请、登录命令或凭证,也没有旧应用数据;初始图只用于查看路由、系统弹窗和空表单。`terminology-device-kinds.png` 在配对后的“添加设备”面板记录节点与客户端分类,其他三张图在配对后的设置页保存。诊断图不代表配对或表单验收通过。导航诊断仅记录固定阶段和已知界面的布尔状态,不输出界面文本、加入链接、命令或剪贴板内容。CI 按固定键与布尔类型校验后,将该诊断并入公开的 `provider.json`,不上传原始页面树或测试日志。最终收据只有在一个目标测试真实通过、fixture 退出、专属 simulator 删除和私有状态清理后才标为 `passed`。 +`provider-initial.png` 是唯一的配对前诊断图。它只在本次 CI 新建的专属 simulator 上,重新安装、清除钥匙串并启动 App 后主动拍摄,且早于剪贴板写入和邀请输入。用例核对 simulator 文件、实际 UUID、Booted 状态以及包含当前 run ID 和 attempt 的专属名称。此时 App 尚未接收邀请、登录命令或凭证,也没有旧应用数据;初始图只用于查看路由、系统弹窗和空表单。`terminology-device-kinds.png` 在配对后的“添加设备”面板记录节点与客户端分类,其他三张图在配对后的设置页保存。诊断图不代表配对或表单验收通过。导航诊断仅记录固定阶段和已知界面的布尔状态,不输出界面文本、加入链接、命令或剪贴板内容。CI 按固定键与布尔类型校验后,将该诊断并入公开的 `provider.json`,不上传原始页面树或测试日志。最终收据只有在一个目标测试真实通过、fixture 退出、专属 simulator 删除和私有状态清理后才标为 `passed`。 失败收据与 stdout 保留固定阶段、报告是否可读,以及从实际 e2e report 提取的受限错误码、固定 `engine_reason` 和 `engine_timeout_kind`、已知 API 名和两个验收文件的行号。`completed_poll_samples` 只来自唯一合法的既有 expect 采样事件;零表示没有记录完成的采样,字段缺失不补零。错误 message、stack、locator label、值和原始报告不会导出。 diff --git a/packages/docs/history-sync.md b/packages/docs/history-sync.md index 90bb084e8..b0b0ee1e7 100644 --- a/packages/docs/history-sync.md +++ b/packages/docs/history-sync.md @@ -36,7 +36,7 @@ DAG 是有向无环图。每个事件带作者签名,并记录它承接的事 从另一台电脑查看历史,与让那台电脑负责 Bot,是两个动作。 -另一台 Node 先加入同一个人网络并同步所需记录。你再在原聊天选择 **交给这台设备处理**,由该 Node 用共享历史建立自己的协调 Agent 上下文。原生 SDK 进程、缓存、工程和登录不会跟着负责人切换搬过去。 +另一台 Node 先加入同一个人网络并同步所需记录。你再在原聊天选择 **换到 某某**(某某是当前设备的名称),由该 Node 用共享历史建立自己的协调 Agent 上下文。原生 SDK 进程、缓存、工程和登录不会跟着负责人切换搬过去。 如果旧设备已把任务派到其他电脑,切换负责人后仍要核对那项原工作的状态。缺失历史、执行设备不可达与结果未知有不同原因,不能用新建同名任务替代恢复。操作说明见 [创建机器人并处理结果](node.md#创建机器人并处理结果),异常情况见 [待核对](node.md#待核对)。 diff --git a/packages/docs/install.md b/packages/docs/install.md index 0b7ebb48b..6c9659946 100644 --- a/packages/docs/install.md +++ b/packages/docs/install.md @@ -210,7 +210,7 @@ Stable 不存在时不会切换 Nightly,更新器也不自动降级。每次 ` 从同一个产品 Release 下载适合本机的 `vibeface-desktop--`。macOS Apple Silicon 使用 `.dmg`,Windows x64 使用 `.exe` 安装器,Linux x64 和 ARM64 使用对应架构的 `.AppImage`。两端也提供 `.zip`,以及校验摘要和来源收据。 -桌面应用内含同版本、同源码的 CLI、Core 和 Web 资源。关闭窗口后继续在托盘运行。选择退出时,应用停止自己启动的 Core;连接既有服务时,退出保留该服务。首次点击“在这台电脑开始使用”后,应用在自己的配置目录下保存数据。选择已有数据时,所选目录决定这台电脑的数据位置。 +桌面应用内含同版本、同源码的 CLI、Core 和 Web 资源。关闭窗口后继续在托盘运行。选择退出时,应用停止自己启动的 Core;连接既有服务时,退出保留该服务。首次点击“在此电脑启用节点”后,应用在自己的配置目录下保存数据。选择已有数据时,所选目录决定这台电脑的数据位置。 Windows 安装器只安装到当前账户,不需要管理员、WSL、Git Bash 或开发者模式。未配置签名证书的 Nightly 明确标记为未签名开发预览。正式版必须通过签名验证。已有独立 CLI 服务可以继续运行;桌面应用只连接它,不接管启停。 diff --git a/packages/docs/ios.md b/packages/docs/ios.md index 8b8442dd5..34f7aba0b 100644 --- a/packages/docs/ios.md +++ b/packages/docs/ios.md @@ -27,7 +27,7 @@ iOS 先通过 TestFlight 内测,验证后再上 App Store。当前工作流只 请求的分发方式,再签名归档并导出 `vibeface--ios.ipa`。 输出包含经签名与描述文件校验的 SHA256 和来源收据。只配置部分 secrets 时构建失败。 -每日 Nightly 的版本准备会将 iOS `buildNumber` 递增一次,同日恢复沿用已经准备的值。 +每个四小时 Nightly 批次的版本准备会将 iOS `buildNumber` 递增一次,同批次恢复沿用已经准备的值。 构建号按 Apple 的 CFBundleVersion 分段规则验证;末段超出上限时停止,不重置或自动进位。 Mobile 的 marketing version 仍保持 `0.0.1`。 diff --git a/packages/docs/node-protocol.md b/packages/docs/node-protocol.md index cf3b0b990..2d5bd7b6a 100644 --- a/packages/docs/node-protocol.md +++ b/packages/docs/node-protocol.md @@ -104,8 +104,6 @@ Opencode Bot 和执行器使用 2.2.0 的 `/api` 接口。每轮发送提示前 | `delivery-wallet.json` | 独立加密 EVM 钱包,0600,不包含接收密钥 | | `delivery/service.sqlite3` | 订单、接收密钥、证明任务、续传偏移、nonce 和签名交易账本;`user_version=1`,只初始化空库,不进入共享 DAG | | `delivery/objects/`、`delivery/private/` | 交付对象与本机私密材料,目录 0700、文件 0600;完整恢复需保留整个 `delivery/` | - -这张表说明各文件的用途和私密程度,不是备份白名单:`node.sqlite3` 以 WAL 模式运行,去重、待补依赖和投影状态都在数据库文件里,备份须在停止 Node 后复制整个目录。 | `join.json` | `vibeface join` 或本机网页进行中的加入请求,重试时沿用同一请求 | | `codex-app-server.pid` | 托管 App Server 的进程组号 | | `cursor-agent.pid` | 受管 Cursor Agent CLI 的进程组号和程序路径,Node 启动时结束上次遗留且命令相符的进程组 | @@ -119,6 +117,8 @@ Opencode Bot 和执行器使用 2.2.0 的 `/api` 接口。每轮发送提示前 | `node.log`、`node.log.1`…`node.log.4` | Node 日志,JSON lines,0600,8 MiB 轮转,共保留 5 个 | | `service.*.log`、`update.*.log` | macOS 服务和更新器的标准输出与错误 | +这张表说明各文件的用途和私密程度,不是备份白名单:`node.sqlite3` 以 WAL 模式运行,去重、待补依赖和投影状态都在数据库文件里,备份须在停止 Node 后复制整个目录。 + 运行中的 Node 用目录锁独占数据目录,并在私有维护 socket 上回答 `vibeface status`。`vibeface join` 遇到运行中的 Node 时,经同一 socket 发 `join { link, name }`,由 Node 自己完成加入,回复 `join` 为 `waiting`、`confirming`(带 `code`)、`joined`、`failed`(带 `reason`)或 `cancelled`。同一链接再发只读取进度,不新建请求;命令每秒发一次,直到结束。失败时 Node 保留 `join.json`,用同一链接和名称重跑会沿用原随机数,入口按原请求回答;本机网页的 `node_join` 同样如此。换一条链接时,旧承诺作废。网页正在加入时,命令被拒绝。 ## HTTP 与客户端通道 @@ -328,7 +328,7 @@ Provider 初始只收到 `tool_search`、`tool_describe`、`tool_call`、`contex 修改 bot 的工具为 `update_profile { call_ref, name?, instructions?, avatar?, default_avatar? }`、`save_skill { call_ref, skill_id?, name, description, body }`、`remove_skill { call_ref, skill_id }`、`save_schedule { call_ref, schedule_id?, name, prompt, first_run_at_ms, every_minutes?, enabled? }`、`remove_schedule { call_ref, schedule_id }`、`remember { call_ref, memory_id?, text }`、`forget { call_ref, memory_id }`、`create_bot { call_ref, name, instructions?, project_node?, project_cwd? }`、`configure_bot { call_ref, bot, name?, instructions?, model?, skills?, all_skills?, avatar?, default_avatar? }` 和 `delete_bot { bot }`,只提供给本人消息触发的轮次。Node 再核对 trigger 是 `message:` 且该消息是本会话的本人消息,`cause` 取自 trigger,`change_id` 由 `(会话, trigger, call_ref)` 派生,同一 `call_ref` 同内容返回原记录,换内容拒绝,`call_lookup` 也能查到修改。改前值取自投影,没有变化的修改被拒绝。参数不接受其他字段,AI 服务和文件夹只能在设置里改。`model` 为空表示跟随设备默认;`skills` 是启用的 skill ID 集合,必须都在库里,删除的 skill 从各 bot 的集合里去掉,`all_skills: true` 恢复全部,两者不能同时给。`avatar` 为 `{ outline?, eyes?, hue? }`,至少给一项,没给的项取这个 bot 当前显示的长相补全;`hue` 只能取 20、45、100、130、155、180、205、230、255、285、315、345;补全后与当前显示的长相相同时被拒绝。`default_avatar: true` 恢复由 bot ID 派生的长相(写 `null`),与 `avatar` 不能同时给。同一 `call_ref` 重试时,给出的长相各项与原记录的 `after` 相同即视为同内容。修改名称和说明需要会话有机器人;`create_bot` 和改名都不能与现有 Bot 重名(忽略大小写和首尾空格);schedule 只能由创建它的会话修改。每个 bot 最多 20 个活动 schedule;本机新增或恢复记忆时以 50 条有效记忆为接纳上限,回合完成事务逐条重检容量。不同离线 Node 的合法新增合并后可能超过该数量,不为容量删除已签名事实。笔记每条最多 500 字符,像密钥的内容被拒绝。一条本人消息最多建 3 个 bot。`create_bot` 的 `bot_id` 和会话 ID 由 `(会话, trigger, call_ref)` 派生,Agent 只给名字。各协调工具的 `call_ref` 只作本次调用的重试键,须为 1-128 个 ASCII 字母、数字、`-`、`.` 或 `_`,不合规时错误点名 `call_ref`。`delete_bot` 在被删 bot 的会话写 `BotDeleted { cause }`,不能删除发起轮次的 bot 自己,重复删除不写新事件;网页由本人签名写 `BotDeleted { attestation }`,RPC 为 `delete_bot { conversation_id, attestation }`,返回 `{ written, primary }`。 -Node 接纳工作时核对派发方是成员 Node 且处于进行中的调度轮次,并核对 `cwd` 位于自己的 `roots` 内。本机工作的 `kind` 是执行它的产品,由该产品的执行器开始、复查和中断。Codex 工作(`kind=codex`):`track_work` 写 `WorkDispatched` 并返回 `{work_id, call_ref, state, may_send, send_by_ms, cwd, thread_id?}`,只有第一次登记且由 CLI 发送时 `may_send=true`;CLI 用 `thread/start`(`approvalPolicy=never`、`danger-full-access`)开线程,`bind_work {work_id, report: {status: "thread", thread_id}}` 绑定后才发 `turn/start`,`clientUserMessageId` 为 `work_id`,再 `bind_work {work_id, report}` 回报 `{status: "turn", turn_id}`、`{status: "rejected", kind, detail}` 或 `{status: "unknown", reason}`;`unknown` 时 Node 先对账,不重发。`send_by_ms` 为登记后 60 秒,之后不再发送;再过 30 秒仍没有回合时 Node 按 `clientId` 复查线程,找不到就记为 `rejected`。`target_node` 是其他设备时,任务(`kind=task`)作为那台设备协调 Agent 的一轮执行,由它在本机直连派发。`continues` 在原工作的 thread 上开新 turn,原目标不可达时报错,不改派。`thread` 是本机已有的 App Server 线程(`vibeface codex send`):CLI 先 `thread/read` 取 `cwd`;线程是 Codex 子 Agent(`source.subAgent`)时 Codex 不接受直接输入,CLI 在登记前拒绝并给出 `parentThreadId`,什么都不写;Node 登记时即为 `starting`,与 `continues` 互斥。发送前 Node 读取并规范化线程的真实目录,核对它位于本机 `roots` 内,并与显式 `cwd` 一致;回合进行中则 `turn/steer`,否则 `turn/start`。几项工作可共用一个回合,各自结束并各自回报。 +Node 接纳工作时核对派发方是成员 Node 且处于进行中的调度轮次,并核对 `cwd` 位于自己的 `roots` 内。本机工作的 `kind` 是执行它的产品,由该产品的执行器开始、复查和中断。Codex 工作(`kind=codex`):`track_work` 写 `WorkDispatched` 并返回 `{work_id, call_ref, state, may_send, send_by_ms, cwd, thread_id?}`,只有第一次登记且由 CLI 发送时 `may_send=true`;CLI 用 `thread/start`(`approvalPolicy=never`、`danger-full-access`)开线程,`bind_work {work_id, report: {status: "thread", thread_id}}` 绑定后才发 `turn/start`,`clientUserMessageId` 为 `work_id`,再 `bind_work {work_id, report}` 回报 `{status: "turn", turn_id}`、`{status: "rejected", kind, detail}` 或 `{status: "unknown", reason}`;`unknown` 时 Node 先对账,不重发。`send_by_ms` 为登记后 60 秒,之后不再发送;再过 30 秒仍没有回合时,还没绑定线程的记为 `rejected`;已绑定线程的由 Node 按 `clientId` 复查,找不到就记为 `unverified`,之后回合出现仍照常跟进。`target_node` 是其他设备时,任务(`kind=task`)作为那台设备协调 Agent 的一轮执行,由它在本机直连派发。`continues` 在原工作的 thread 上开新 turn,原目标不可达时报错,不改派。`thread` 是本机已有的 App Server 线程(`vibeface codex send`):CLI 先 `thread/read` 取 `cwd`;线程是 Codex 子 Agent(`source.subAgent`)时 Codex 不接受直接输入,CLI 在登记前拒绝并给出 `parentThreadId`,什么都不写;Node 登记时即为 `starting`,与 `continues` 互斥。发送前 Node 读取并规范化线程的真实目录,核对它位于本机 `roots` 内,并与显式 `cwd` 一致;回合进行中则 `turn/steer`,否则 `turn/start`。几项工作可共用一个回合,各自结束并各自回报。 Codex 默认 bypass。Node 订阅的线程上的服务端请求和不属于线程的请求由 Node 挂起并交给协调 Agent:Agent 用 `vibeface requests` 查看、`vibeface respond ''` 回答,需要本人时用 `vibeface triage raise --request-id … --question … --choice <标签>` 在负责该会话的 Bot 聊天里提问,提问挂住请求直到有回答。本人答案先持久化,再经私有 `HeldAnswerControl` 绑定原问题、请求、session、turn、transport generation 和响应 schema,回到原执行设备递交。基础审批按原请求动作递交,文字题由捕获配置的新协调会话整理。普通 Bot 在提问后不能代答。不属于任何 Bot 的会话先归给主 Bot 再按归属处理;没有 Bot、不属于线程或后台线程(`codex exec`、子代理)上的请求立即兜底。没有协调 Agent 或 120 秒内无人处理时按方法拒绝并记录(见 `packages/docs/codex-app-server.md`)。其他客户端的请求留给原客户端。hook 也能挂起请求:事件带 `hold`(`permission`、`question` 或 `continue`)时 Node 同样挂起它并唤醒协调 Agent,`/api/hooks` 的响应给出 `request_id`,hook 随后经本机 `POST /api/hooks/wait {request_id}` 等待回答;hook 的请求不因提问延长,30 秒内没有回答时返回 `{"decision":null}`,交回会话自己处理,不当作拒绝。Node 不自动重试写请求。请求 ID 由方法、线程、回合、`itemId` 或 `callId` 及 `approvalId` 的哈希确定,缺少这些字段时随机生成。重连后同一请求再次到达时沿用原有提问或 Agent 事件,只改用新连接的 JSON-RPC ID,不会再提问一次。连接后 App Server 读完 Node 订阅的线程,本设备提过问、仍未回答但请求未再到达的提问由本设备写 `question_closed` 关闭;之后同一请求再到达时按方法兜底。 @@ -420,7 +420,7 @@ Node 的写入状态为 `aligning`、`read_only`、`writable` 或 `forked`。只 ### iroh Endpoint -每台 Node 运行一个 iroh 1.3 `Endpoint`,`SecretKey` 就是设备密钥。Endpoint 用 Minimal 预设、`MemoryLookup` 和 `RelayMode::Custom`:relay 来自 `network.relays`、本 Node 自己的 relay、成员签名地址记录里成员运行的 relay,以及从全网表选出的开放 relay,不使用 n0 公共 relay。同一个 relay URL 出现多次时合并为一条配置,带凭证的配置不会被无凭证的副本覆盖,地址簿和全网表里学到的裸 URL 也不会替换已配置的同一 relay 及其令牌。不向 n0 DNS 或 pkarr 发布地址;ticket 只有设备编号,不含地址。成员地址来自个人网络内部交换的签名地址记录,其他设备的地址来自全网表,和已有 relay 路径合并后由 iroh 自动选择连接路径。连接优先直连,失败时经 relay 转发 QUIC 密文。 +每台 Node 运行一个 iroh 1.3 `Endpoint`,`SecretKey` 就是设备密钥。Endpoint 用 Minimal 预设、`MemoryLookup` 和 `RelayMode::Custom`:relay 来自 `network.relays`、本 Node 自己的 relay、成员签名地址记录里成员运行的 relay,以及从全网表选出的开放 relay,不使用 n0 公共 relay。同一个 relay URL 出现多次时合并为一条配置,带凭证的配置不会被无凭证的副本覆盖,地址簿和全网表里学到的裸 URL 也不会替换已配置的同一 relay 及其令牌。不向 n0 DNS 或 pkarr 发布地址;ticket 带入口 Node 的节点链接(设备编号、最多 4 个直连地址和 home relay)。成员地址来自个人网络内部交换的签名地址记录,其他设备的地址来自全网表,和已有 relay 路径合并后由 iroh 自动选择连接路径。连接优先直连,失败时经 relay 转发 QUIC 密文。 成员 Node 另在局域网用 mDNS 广播 `_vibeface._udp.local.`。实例名和 TXT 记录 `t` 都是标签 `hex(HMAC-SHA256(network_id, "vibeface:lan:v1\0" ‖ device_id ‖ hour)[..16])`,`hour` 是 Unix 毫秒除以 3600000 的 u64 大端字节;主机名为 `<标签>.local.`,SRV 端口是 iroh 实际监听的 UDP 端口,A 和 AAAA 是本机非回环网卡地址,网卡变化时自动更新;iroh 在该端口没有监听的地址族不广播。每到整点,同步循环在几秒内改用新标签重新登记,旧实例发出 mDNS 告别。收到的广播在拨号时才比对,用前一、当前和后一小时的标签匹配要拨的成员 Node,过了时间窗的标签自然失效。比对上的地址在 `connect` 中与地址簿和全网表提示合并;新出现或变化的广播只要属于当前成员 Node(不含自己),就立即唤醒与它的同步,同一 Node 每 10 秒最多唤醒一次;是否属于成员在收到时判定并记下,网络或成员变化时重新判定。只收私网 IPv4 和 ULA IPv6 地址,IPv4 在前,每条最多 4 个;拨号只用比对上的最新一条广播。最多保留 64 条广播,满时先删不属于成员 Node 的,再删最早收到的;收到告别或 SRV 记录过期后删除。Node 关闭网络时撤回自己的广播,最多等 1 秒让告别发出。`bind` 为具体地址的 Node 不启用 mDNS,尚未加入或已被移出网络的 Node(包括公共节点)不广播;mDNS 失败只记录日志,不影响 Node 运行。知道 `network_id` 和 `device_id` 的任何人(包括前成员和持有过邀请或恢复材料的人)都能算出并关联标签;标签只提示拨号地址,不是授权,小时轮换也不是撤销手段,成员资格仍由 QUIC TLS 证明的设备身份另行检查。 @@ -495,7 +495,7 @@ Node 的写入状态为 `aligning`、`read_only`、`writable` 或 `forked`。只 角色只说明一台设备愿意提供什么:`relay {url, access, rate, max_clients, offer?}`、`gateway {url}`、`service {service, offer?}`。采用方先验证:relay 用 `/generate_204` 和真实握手,网关请求 `/api/info` 并核对设备编号;私网和回环地址只在 `mesh.allow_private` 时采用。运行 relay 的 Node 经 `configure_relay`(网页**公共转发**、`vibeface relay volunteer on|off`)开放 relay,请邻居从外部探测通过后才宣告 `relay` 角色。 -`vibeface join` 和本机网页的 `node_join` 只凭票据里的设备编号:加入方在全网表里查发出邀请的 Node,表里没有时问邻居,用查到的直连地址和 home relay 连接,只给这台 home relay 带邀请令牌;查不到时用配置的 relay。`vibeface status` 的 `Mesh` 和 `vibeface mesh status` 显示全网是否开启、网络名、记录数和邻居数。入网失败按退避重试,不影响个人网络内的功能。 +`vibeface join` 和本机网页的 `node_join` 先用票据里的直连地址和 home relay,同时在全网表里查发出邀请的 Node,表里没有时问邻居,再加上配置的 relay;入口的 home relay 不开放时带邀请令牌,全网表里查不到入口时,没有配置令牌的 relay 也带邀请令牌。`vibeface status` 的 `Mesh` 和 `vibeface mesh status` 显示全网是否开启、网络名、记录数和邻居数。入网失败按退避重试,不影响个人网络内的功能。 ## 可选文件交付 diff --git a/packages/docs/node.md b/packages/docs/node.md index e0291649e..93457592d 100644 --- a/packages/docs/node.md +++ b/packages/docs/node.md @@ -129,7 +129,7 @@ Bot 通过本机 `vibeface tool` 命令调用限定到当前网络和聊天的 程序先使用保存的路径和 PATH,再查 Node 的 PATH、常见用户目录、Homebrew、npm/Volta/Bun/NVM 安装。npm wrapper 的启动环境会补齐所需 Node;必要时只向登记登录 shell 查询 PATH。自定义安装仍无法发现时,在设置里填程序绝对路径和所需 PATH。 -模型留空时用各自的默认模型;opencode 写成 `provider/model`。Codex 和 pi 可在检查状态后提供模型列表,网页和手机保留手填模型。目录未取得或不完整时,不会清空已有配置。登录未确认时显示提醒并允许尝试,只有程序缺失、明确需要登录等已确认的问题才阻止发送。Claude Code 的进度按整条消息更新,Bot 回复中收到的新消息等这轮结束再处理。 +模型留空时用各自的默认模型;opencode 写成 `provider/model`。Codex 和 pi 可在检查状态后提供模型列表,网页和手机保留手填模型。目录未取得或不完整时,不会清空已有配置。登录未确认时显示提醒并允许尝试,只有程序缺失、明确需要登录等已确认的问题才阻止发送。Claude Code 的进度按整条消息更新。 `dispatch_work` 的 `thread` 只接受本机任务跑过的 Claude Code、pi 或 opencode 会话;本人自己开的会话不接任务。opencode 会话里还有未结束的工作(在跑、发送结果未知或待确认)时,新工作以 `writer_busy` 被拒,不发送;能确定是哪项工作占用时,错误里点名它。不给 `agent` 时沿用该会话里工作用过的产品。 @@ -551,7 +551,7 @@ Node 从整张表里抽取开放 relay 并行验证,先按历史通过次数 普通查询可以直接回答,本机工作使用 SDK 的宿主工具,远端工作通过 Agent 任务消息委派。日常操作不需要创建任务单、打开执行会话或选择调度器。进展、补充输入和结果都回到原机器人的聊天。 -会话的调度设备由本人在建会话时签名指定,每次更换都写一条带本人签名、epoch 加一的负责人记录(`set_owner`)。调度设备离线而当前连接的设备能运行管理 Agent 时,聊天里出现“X 离线了,这个对话在等它”,点**交给这台设备处理**即可换过来,排队的消息在新设备上继续回复。新调度设备只按共享记录和上下文检查点重建上下文,不重放已经执行的工作。旧调度设备看到更换后会停下正在进行的回复,并拒绝它之后的工具调用。每个定时时刻由当时的调度设备在共享记录里领取,本机已有有效领取记录的时刻不再排队;错过太久而跳过的时刻也会领取。每个定时任务只看最新到期的时刻:同一时刻只领一次;上一次运行还在排队时不领新时刻,错过的中间时刻并入最新到期的那个;晚于 10 分钟的时刻只记领取并跳过;会话队列满 256 项时也不领。上一次运行已经开始则不等待,所以 Parallel 的 Provider 在 `machine_slots` 允许时,同一定时任务的不同时刻可以重叠运行;Serial 的 Provider 仍串行。新设备不领取早于或等于换负责人记录时间的时刻,并等待 5 分钟接管宽限期,让旧设备同步领取记录。schedule 定义、启停和接管时间使用事件首次在本机落库的 `seen_at_ms`,不受写入方时钟偏差影响。旧设备断网超过宽限期且尚未得知负责人变更时,新旧设备仍可能执行同一时刻。详见 [Schedule](design/agent-capabilities.md#1-schedule)。 +会话的调度设备由本人在建会话时签名指定,每次更换都写一条带本人签名、epoch 加一的负责人记录(`set_owner`)。调度设备离线而当前连接的设备能运行管理 Agent 时,聊天里出现“X 离线,对话在等它”,点**换到 Y**(Y 是当前设备的名称)即可换过来,排队的消息在新设备上继续回复。新调度设备只按共享记录和上下文检查点重建上下文,不重放已经执行的工作。旧调度设备看到更换后会停下正在进行的回复,并拒绝它之后的工具调用。每个定时时刻由当时的调度设备在共享记录里领取,本机已有有效领取记录的时刻不再排队;错过太久而跳过的时刻也会领取。每个定时任务只看最新到期的时刻:同一时刻只领一次;上一次运行还在排队时不领新时刻,错过的中间时刻并入最新到期的那个;晚于 10 分钟的时刻只记领取并跳过;会话队列满 256 项时也不领。上一次运行已经开始则不等待,所以 Parallel 的 Provider 在 `machine_slots` 允许时,同一定时任务的不同时刻可以重叠运行;Serial 的 Provider 仍串行。新设备不领取早于或等于换负责人记录时间的时刻,并等待 5 分钟接管宽限期,让旧设备同步领取记录。schedule 定义、启停和接管时间使用事件首次在本机落库的 `seen_at_ms`,不受写入方时钟偏差影响。旧设备断网超过宽限期且尚未得知负责人变更时,新旧设备仍可能执行同一时刻。详见 [Schedule](design/agent-capabilities.md#1-schedule)。 发送后先看状态。`pending_delivery` 表示入口已保存消息,正在投递给原调度设备;只有目标持久入队后才是 `queued`。排队不表示模型已开始,`running` 才表示已跨过 SDK 启动边界。目标离线、能力不满足或回执丢失时,保留原目标与消息身份核对,不自动改派另一台设备。 @@ -572,7 +572,7 @@ Agent 通过 Node 的 `dispatch_work` 工具派发工作,例如 `vibeface tool 协调 Agent 的 Shell 完全访问本机,可以改文件、跑 git 和 gh。它用 `vibeface codex call [json]` 调用 App Server 的读取和线程管理方法,开始、引导或停止回合的方法(`turn/start`、`turn/steer`、`turn/interrupt`、`thread/start`、`thread/fork`、`thread/compact/start`、`thread/shellCommand`、`thread/revert`、`thread/inject_items`、`review/start`)一律拒绝,改用 `dispatch_work`、`codex send` 和 `interrupt_work`,让每个回合都是 Node 登记过的工作;`vibeface codex send --id ` 给已有会话插话(回合进行中时 steer,否则开新回合)。这条消息是本轮的一项工作,与 `dispatch_work` 相同:发送前向 Node 登记,`--id` 即 `call_ref`,Node 观察它所在的回合,结束后结果作为 `work_result` 轮回到 Bot;同一轮同一 `--id` 再次执行只回读、绝不重发,换了内容或会话则拒绝。Node 发送前读取并规范化线程的真实目录,核对它位于本机 `roots` 内。给出 `cwd` 时还须与真实目录一致。它只能在 Bot 的一轮里运行,因为它要用这一轮的工具令牌;Cursor 的 Shell 没有这个令牌,Cursor 回合用带 `thread` 的 `dispatch_work` 工具做同样的事。`vibeface codex watch ` 查看事件,`vibeface log --conversation ` 把它遇到的问题写进 Node 日志(经本机监听器的 `/api/log`,边界与 `/api/hooks`、`/api/triage` 相同:回环来源、无 `Origin`、无转发头,并带数据目录 `local-access.json` 里的所有者 bearer,命令按该文件记录的 origin 发请求;同一 OS 账户的完整 Shell 本就能读这个文件,所以这不是进程沙箱隔离)。Socket 路径在 `VIBEFACE_CODEX_SOCKET`。 -Codex 默认 bypass,正常不会发起请求。仍发起的请求(审批、提问、登录等)由 Node 挂起并立即唤醒协调 Agent:它用 `vibeface requests` 查看,`vibeface respond ''` 回答,同一请求只回答一次。需要本人拍板时,它用 `vibeface triage raise --event-id --request-id <请求> --question <问题> --choice 批准 --choice 拒绝` 在拥有该会话的 Bot 聊天里提问,按项目设置也经 webhook 转发 Grok Bot。提问挂住请求直到有回答。本人答案沿独立私有控制队列回到原执行设备,不等待被挂起 Task 的 scheduler 槽位。基础审批只按原请求动作递交,文字题由捕获配置的新协调会话按原题型整理。普通问题仍在原 Task 或 Main 排后续轮,未知结果只查询。没有协调 Agent,或它 120 秒内既没回答也没提问时,Node 按方法拒绝并记录。等待回答的 hook 挂起的请求同样经 `vibeface requests` 和 `vibeface respond` 处理,30 秒内没有回答时交回会话自己决定。没有协调 Agent 时分诊事件直接丢弃。协调 Agent 每次启动分诊都预占一次额度,上限同为 `daily_decision_limit`,但与 Bot 的自动轮次分开记账,不占它们的额度。额度用完时保留未审阅事件,挂起请求仍按原期限兜底;额度恢复后只重新审阅事件,不重放原工具或已执行的工作。只有当前进程确认模型未启动时才退还原日额度;启动后失败、结果未知或 Node 重启时不退款,也不自动重跑该批事件。设置和诊断包显示已用额度、上限、下次尝试时间,以及待审阅、处理中和结果未知的事件数。协调 Agent 能看到拥有该会话的 Bot 的说明开头和最新记忆,各有长度上限。hook 挂起的 `continue` 只在执行本人已要求的事时代发;下一步需要本人决定、难以撤销或需要本人未给的授权时,改为提问。不是 Bot 发起的交互会话由运行它的设备归给主 Bot;Bot 每轮能看到名下的会话,自己判断后用 `hand_over_session` 转给其他 Bot 或不再关注;`codex exec`、子代理等后台会话不处理,见 [聊天里的提问与回答](design/questions-in-chat.md)。 +Codex 默认 bypass,正常不会发起请求。仍发起的请求(审批、提问、登录等)由 Node 挂起并立即唤醒协调 Agent:它用 `vibeface requests` 查看,`vibeface respond ''` 回答,同一请求只回答一次。需要本人拍板时,它用 `vibeface triage raise --event-id --request-id <请求> --question <问题>` 在拥有该会话的 Bot 聊天里提问,按项目设置也经 webhook 转发 Grok Bot。挂起的审批只用 Node 给出的“允许本次”(原请求支持时)和“拒绝”,`--choice` 只用于普通提问。提问挂住请求直到有回答。本人答案沿独立私有控制队列回到原执行设备,不等待被挂起 Task 的 scheduler 槽位。基础审批只按原请求动作递交,文字题由捕获配置的新协调会话按原题型整理。普通问题仍在原 Task 或 Main 排后续轮,未知结果只查询。没有协调 Agent,或它 120 秒内既没回答也没提问时,Node 按方法拒绝并记录。等待回答的 hook 挂起的请求同样经 `vibeface requests` 和 `vibeface respond` 处理,30 秒内没有回答时交回会话自己决定。没有协调 Agent 时分诊事件直接丢弃。协调 Agent 每次启动分诊都预占一次额度,上限同为 `daily_decision_limit`,但与 Bot 的自动轮次分开记账,不占它们的额度。额度用完时保留未审阅事件,挂起请求仍按原期限兜底;额度恢复后只重新审阅事件,不重放原工具或已执行的工作。只有当前进程确认模型未启动时才退还原日额度;启动后失败、结果未知或 Node 重启时不退款,也不自动重跑该批事件。设置和诊断包显示已用额度、上限、下次尝试时间,以及待审阅、处理中和结果未知的事件数。协调 Agent 能看到拥有该会话的 Bot 的说明开头和最新记忆,各有长度上限。hook 挂起的 `continue` 只在执行本人已要求的事时代发;下一步需要本人决定、难以撤销或需要本人未给的授权时,改为提问。不是 Bot 发起的交互会话由运行它的设备归给主 Bot;Bot 每轮能看到名下的会话,自己判断后用 `hand_over_session` 转给其他 Bot 或不再关注;`codex exec`、子代理等后台会话不处理,见 [聊天里的提问与回答](design/questions-in-chat.md)。 Node 默认不启用 Codex。启用 Codex Bot 或任务执行时,缺少的程序路径由 Node 从本机找出并写进配置,设备设置里显示并可修改;Bot 也能用 `propose_provider_config` 提议显式 App Server socket、会话扫描目录或添加可用文件夹(`roots`),经聊天里的「允许 / 不允许」卡片同意后由 Node 写入。首次设置时打开 Codex 运行 Bot 会同时打开执行任务,并可一键添加家目录下常见的项目文件夹(`node_settings.suggested_roots`)。整个 `providers.codex_app_server` 对象省略时默认 `spawn`,提供对象时 `mode` 必填。spawn 时 Node 托管自己的 `codex app-server`,使用 `/providers/codex` 和私有的 `/tmp/vibeface-/` socket;不会扫描用户 control socket、sessions 或 hooks。`system` 只连接明确配置的 socket,不启动或结束外部服务。App Server 运行在独立进程组,进程组号写入数据目录的 `codex-app-server.pid`。Node 启动时先结束上次遗留的进程组,正常退出时一并停止它,异常退出则退避重启。连接系统 App Server 时,同时设置 `providers.codex_app_server.mode` 为 `system` 和显式的绝对 `socket`;`init --codex-socket` 会同时保存两者。启动网页成功不等于程序已安装、已登录或模型可用,应查看聊天中工作的实际状态。 @@ -614,7 +614,7 @@ vibeface status vibeface service status ``` -服务管理命令需要完整的受管安装,启动路径始终为安装根目录下的 `current/vibeface`。通过 `$VIBEFACE_BIN_DIR/vibeface` 链接调用也保留该路径,升级后不会固定在旧 release。直接运行 `cargo build` 的程序不安装服务。先使用 `update configure --install-root "$VIBEFACE_INSTALL_ROOT"` 保存部署时选择的安装根。 +GitHub 受管安装通过安装根目录下固定的 `current/vibeface` 启动,npm 安装通过 npm 包中固定的原生程序路径启动。通过 `$VIBEFACE_BIN_DIR/vibeface` 链接调用也保留该路径,升级后不会固定在旧 release。直接运行 `cargo build` 的程序不安装服务。先使用 `update configure --install-root "$VIBEFACE_INSTALL_ROOT"` 保存部署时选择的安装根。 每个系统用户管理一个 Node 服务。各服务命令核对 `--data-dir` 与已安装服务一致,再操作该服务。省略参数时使用 `VIBEFACE_DATA_DIR`,未设置时使用 `~/.vibeface`。管理其他数据目录时显式传入绝对路径。 @@ -627,7 +627,7 @@ vibeface service start vibeface service restart ``` -macOS 使用当前登录用户的 launchd agent,Linux 使用 `systemd --user`。Node 无论前台还是后台都把 info 级日志写到数据目录的 `node.log`(JSON lines,用 `vibeface logs` 查看);后台运行时 macOS 的 `service.stderr.log` 和 Linux 的用户 journal 只剩崩溃输出。退出登录后仍需运行的 Linux 主机,由管理员按主机策略启用该用户的 lingering。 +macOS 使用当前登录用户的 launchd agent,Linux 使用 `systemd --user`,Windows 使用当前用户的计划任务。Node 无论前台还是后台都把 info 级日志写到数据目录的 `node.log`(JSON lines,用 `vibeface logs` 查看);后台运行时 macOS 的 `service.stderr.log` 和 Linux 的用户 journal 只剩崩溃输出。退出登录后仍需运行的 Linux 主机,由管理员按主机策略启用该用户的 lingering。 后台服务不保证继承终端的 PATH 或临时环境变量。在 `config.json` 使用 Provider 的绝对路径,并通过对应服务管理器配置模型凭证。安装脚本不保存或复制密钥。 diff --git a/packages/docs/overview.md b/packages/docs/overview.md index 5c01eed0e..37fc12bee 100644 --- a/packages/docs/overview.md +++ b/packages/docs/overview.md @@ -64,7 +64,7 @@ Bot 的协调角色与任务执行角色可以选择不同产品,各自的原 | `apps/core` | Rust 后台 `vibeface-core`,负责身份、存储、同步、调度和执行。 | | `apps/cli` | `vibeface` 命令行,负责启动、服务管理、更新与命令交互。 | | `apps/mobile` | 原生 iOS、Android 客户端,通过共享协议连接 Node。 | -| `apps/desktop` | macOS、Windows 桌面客户端,复用操作界面,并管理本机 Node 的连接与生命周期。 | +| `apps/desktop` | macOS、Windows、Linux 桌面客户端,复用操作界面,并管理本机 Node 的连接与生命周期。 | 安装包把 CLI、Core 和静态网页放在同一个发行目录,便于一起安装与更新,但三者职责独立。网页独立部署并不提供一台执行电脑,也不会自动获得你的设备权限。`app.vibeface.dev` 的可用性以实际部署为准,本地上手使用 `http://localhost:4790`。 diff --git a/packages/docs/paid-delivery.md b/packages/docs/paid-delivery.md index abef400ed..2cf317a36 100644 --- a/packages/docs/paid-delivery.md +++ b/packages/docs/paid-delivery.md @@ -8,7 +8,7 @@ 预算固定 payer、payee、Provider PeerID、asset 和一次存款金额。多 Provider 使用不同预算。Node 固定当前构建的 DeliveryEscrow、官方 adapter/verifier、产品 profile 和 TestToken runtime,不接受自定义 verifier、公开 RPC、主网或真实资产。 -在 S、P 的本机维护命令中创建并解锁独立钱包,备份保管方式沿用钱包命令。密码只通过受保护 FD 传递。R 先用现有 `register-key` 操作完成真实接收密钥注册,再准备订单;历史接收密钥仍保留给已分配订单。 +在 S、R、P 的本机维护命令中创建并解锁独立钱包,备份保管方式沿用钱包命令。口令通过关闭回显的终端或受保护 FD 输入。R 先用现有 `register-key` 操作完成真实接收密钥注册,再准备订单;历史接收密钥仍保留给已分配订单。 S 和 R 各自管理个人网络,可以属于不同网络。P 是普通公共 Node,可以不加入二者的个人网络。服务通道认证 PeerID,个人网络通道另外验证成员资格;服务 PeerID 不授予个人网络成员权限。付款、报价或发现记录不能访问私人事件、附件、Agent 或模型密钥。 diff --git a/packages/docs/releasing.md b/packages/docs/releasing.md index 5d5f63842..3a6c9e4e8 100644 --- a/packages/docs/releasing.md +++ b/packages/docs/releasing.md @@ -28,7 +28,7 @@ Core、CLI、Web App、Desktop 和 Mobile 共享一个版本、一个 `v- `crypto-web` 在固定版本的 wasm-bindgen 工具链生成一份浏览器密码学资源,运行 native Rust 与 WASM 的实际 Noise 互通和篡改、重放、身份错配负例。`web` 下载这份资源及其真实 TypeScript 声明,以锁定的 pnpm 依赖生成 TanStack Start 静态 SPA。被选中的检查和打包任务下载同一份密码学资源和 SPA。Core 从 `VIBEFACE_APP_DIR` 或发行包同级 `web/` 读取完整静态目录,不在编译时内嵌网页或 WASM。Core 可独立构建和运行,未提供 App 时网页返回 404;App 构建和完整发行包缺少资源时失败。 -质量检查按计划选择受影响的 crate,包含 Rust fmt、快慢测试、Clippy、声明的最低 Rust 版本编译检查、工作流和 shell 静态检查、JavaScript 语法、Web TypeScript 检查和静态构建,以及 Atlas 迁移文件校验。Atlas 不打开用户数据库。README 和项目指引不触发构建,`packages/docs/` 触发门户构建;`main` 的纯 App 改动只构建 Linux x64 包并验收网页资源,不运行 Core 库业务测试。`main` 保留相关快速测试、Clippy 和 Linux x64 制品。慢测试、最低 Rust 版本和三平台制品在扩展检查执行。`ci-gate` 要求本次计划中的任务全部成功。 +质量检查按计划选择受影响的 crate,包含 Rust fmt、快慢测试、Clippy、声明的最低 Rust 版本编译检查、工作流和 shell 静态检查、JavaScript 语法、Web TypeScript 检查和静态构建,以及 Atlas 迁移文件校验。Atlas 不打开用户数据库。README 和项目指引不触发构建,`packages/docs/` 触发门户构建;`main` 的纯 App 改动只构建 Linux x64 包并验收网页资源,不运行 Core 库业务测试。`main` 保留相关快速测试、Clippy 和 Linux x64 制品。慢测试、最低 Rust 版本和四平台制品在扩展检查执行。`ci-gate` 要求本次计划中的任务全部成功。 打包任务校验 SHA256、源码提交、版本、target、密码学资源和存储 epoch。扩展检查在 Linux x64 启动解包后的程序运行无账号网络验收;每个选中的平台独立启动网页进程,检查 SPA 路由、JavaScript、CSS、字体、每段内联脚本的 CSP hash、HEAD、缓存策略和未知资源的 404。安装包不含 Provider SDK,验收不安装或导入 Provider SDK,也不开启模型会话。 @@ -151,7 +151,7 @@ Rust 更新器从 `leaperone/vibeface` 的公开 GitHub Releases 发现版本, 每小时的独立用户服务调用 `update apply --automatic`,不调用模型,不消耗模型 token。更新器先下载并校验,再请求 Node 进入维护状态。正在执行的操作、管理 Agent 调用或 `unknown` 结果会推迟升级。更新器不会为升级强行结束任务。更新只更换程序,不覆盖身份、历史、配置和凭证,也不更新 Codex、Cursor 或其他 Provider 程序。 -`BUILD-INFO.json` 声明 `update_protocol=1` 和 `data_epoch=1`,两者取自共享控制 crate `crates/control/src/lib.rs` 的 `UPDATE_PROTOCOL` 和 `DATA_EPOCH`。包协议 1 的 BUILD-INFO 只接受 `version`、`target`、`source_commit`、`update_protocol`、`data_epoch`、`core_version`、`core_source_commit`、`app_version` 和 `app_source_commit` 这 9 个字段。校验涵盖同目录 CLI、Core 和完整 `web/` 的版本、源码及文件摘要。设备授权和业务记录使用单一 `node.sqlite3`,数据库 `user_version=1`,Atlas HCL 为 `apps/core/schema.hcl`。不同 epoch 的数据目录和节点不能混用。更新器只安装与本机存储 epoch 一致的包,不隐式转换或清空数据目录。安装后会重启用户服务并核验本机健康状态,Node 不提供网页(`--no-web` 或 `web_enabled` 为 false;`inspect` 的 `http_enabled` 恒等于 `web_enabled`)时只经维护 socket 以维护身份核验;失败时恢复上一份程序入口。每次激活先把 `current` 目标快照到安装根目录私有的 `backups//`,并在数据目录写 `update-pending.json`;确认成功并删除该 journal 后,只保留同一 Node 最近两份有旁记录 `.updater-.json` 的成功快照。失败、中断、没有旁记录或归属其他 Node 的快照一律保留,总占用不承诺两份封顶。更新器不自动恢复业务数据库,不能以程序回退代替数据恢复。网络、校验或安装错误通过命令退出状态和私有更新日志报告,不当作“没有更新”。 +`BUILD-INFO.json` 声明 `update_protocol=1` 和 `data_epoch=1`,两者取自共享控制 crate `crates/control/src/lib.rs` 的 `UPDATE_PROTOCOL` 和 `DATA_EPOCH`。包协议 1 的 BUILD-INFO 只接受 `version`、`target`、`source_commit`、`update_protocol`、`data_epoch`、`core_version`、`core_source_commit`、`app_version` 和 `app_source_commit` 这 9 个字段。校验涵盖同目录 CLI、Core 和完整 `web/` 的版本、源码及文件摘要。设备授权和业务记录使用单一 `node.sqlite3`,数据库 `user_version=1`,Atlas HCL 为 `apps/core/schema.hcl`。不同 epoch 的数据目录和节点不能混用。更新器只安装与本机存储 epoch 一致的包,不隐式转换或清空数据目录。安装后会重启用户服务并核验本机健康状态,Node 不提供网页(`--no-web` 或 `web_enabled` 为 false;`inspect` 的 `http_enabled` 恒等于 `web_enabled`)时只经维护 socket 以维护身份核验;失败时恢复上一份程序入口。每次激活先把 Node 数据目录整体复制到安装根目录私有的 `backups//`,并在数据目录写 `update-pending.json`;确认成功并删除该 journal 后,只保留同一 Node 最近两份有旁记录 `.updater-.json` 的成功快照。失败、中断、没有旁记录或归属其他 Node 的快照一律保留,总占用不承诺两份封顶。更新器不自动恢复业务数据库,不能以程序回退代替数据恢复。网络、校验或安装错误通过命令退出状态和私有更新日志报告,不当作“没有更新”。 ## 首次安装 diff --git a/packages/docs/service-deployments.md b/packages/docs/service-deployments.md index f84f423b8..0f1d9d78e 100644 --- a/packages/docs/service-deployments.md +++ b/packages/docs/service-deployments.md @@ -38,7 +38,7 @@ gh workflow run deploy-services.yml --ref '' -f service=node -f tag='' -f service=node -f tag=' [--conversation ID] [--work ID] [--thread ID]` 写一条;`vibeface codex call` 自动记下结果,`vibeface codex send` 与 `dispatch_work` 一样由 Node 记下工作事件; -- Codex App Server 和 Codex SDK 的标准错误逐行记录,能看出 thread 时带上 `thread_id`。Cursor ACP 不记录原始标准错误,只返回受控的失败类别。 +- Codex App Server 的标准错误逐行记录,能看出 thread 时带上 `thread_id`。Cursor ACP 不记录原始标准错误,只返回受控的失败类别。 每条外来记录不超过 8 KiB,一次最多 20 条,每个发送方每分钟最多 120 条,超出整批拒绝。浏览器按设备身份分别计数,本机 Agent 和 CLI 各自共享额度。 @@ -86,7 +86,6 @@ Node 没在运行时只输出前四行并以非零码退出,`Detail` 给出原 | `sync.forked`(`another copy of this device wrote different events; writes stopped`) | 发现这台设备的数据被复制过,已停止写入 | | `sync.write_confirmed`(`write confirmed without a backup check`) | 有人在网页上确认了“不是从备份恢复的” | | `refused a connection from a non-member` | 非成员设备试图连接,debug 级别 | -| `work changed a file outside its directory` | 工作改动了它目录之外的文件,只记录,不拦截 | | `relay.started`(`relay started`) | 本机 relay 已启动,`listen` 字段是它的地址 | | `app_server.start_failed`、`app_server.exited` | Node 启动的 Codex App Server 没能启动或已退出,`error`、`status` 是原因 | | `work.dispatched`、`work.dispatch_rejected` | 工作被接纳或派发被拒绝,带 `work_id` 和原因 | @@ -94,8 +93,8 @@ Node 没在运行时只输出前四行并以非零码退出,`Detail` 给出原 | `work.state` | 工作状态变化,结束时带 `outcome` | | `agent.turn.started`、`agent.turn.finished` | 协调 Agent 一轮开始和结束 | | `agent.tool`、`agent.tool_failed` | 协调 Agent 调用的工具 | -| `codex.send`、`codex.call`、`codex.call_failed` | Agent 经命令行给 Codex 发的消息和请求 | -| `codex.app_server.stderr`、`codex.sdk.stderr`、`cursor.stderr` | 子进程的标准错误 | +| `codex.call`、`codex.call_failed` | Agent 经命令行向 Codex App Server 发的请求 | +| `codex.app_server.stderr` | Codex App Server 的标准错误 | 写入前每条记录统一脱敏:邀请链接片段替换为 `[invite]`,`Bearer` 后的令牌、relay 令牌、Cursor 回调令牌和环境变量中名字以 `_KEY`、`_TOKEN`、`_SECRET`、`_PASSWORD` 结尾的值,以及设置页填写的 Provider 变量值替换为 `[redacted]`。日志不记录加入 secret、本机启动 token 或模型密钥。 @@ -116,9 +115,9 @@ Node 没在运行时只输出前四行并以非零码退出,`Detail` 给出原 | `Writes` | 网页显示 | 意思 | 怎么办 | |---|---|---|---| | `writable` | 无提示 | 正常 | 无 | -| `aligning` | “这台设备正在和你的其他设备对齐” | 数据像是复制或从备份恢复的,正在确认自己没有落后于其他设备记下的内容 | 等它连上每一台其他 Node,通常几秒;某个 `Peer` 行一直 `unreachable` 时检查网络和 relay,那台 Node 不再使用就移除它 | +| `aligning` | 连接状态显示“同步中” | 数据像是复制或从备份恢复的,正在确认自己没有落后于其他设备记下的内容 | 等它连上每一台其他 Node,通常几秒;某个 `Peer` 行一直 `unreachable` 时检查网络和 relay,那台 Node 不再使用就移除它 | | `read_only` | 待处理里出现“这个节点暂时只读” | 数据像是复制或从备份恢复的,还没确认过它的其他 Node 都连不上,无法确认这份数据是不是旧备份 | 见下文 | -| `forked` | “这台设备的数据有两份副本” | 另一份同样身份的数据写了不同内容 | 见下文 | +| `forked` | “某某 的数据被复制过” | 另一份同样身份的数据写了不同内容 | 见下文 | 正常重启直接可写,其他设备离线也一样。只有数据库文件和上次写入时的不同(复制了数据目录或从备份恢复)才进入对齐。对齐和只读期间可以照常阅读,发消息会提示稍后再试,已排队的消息在可写后继续处理。 @@ -139,7 +138,7 @@ Node 没在运行时只输出前四行并以非零码退出,`Detail` 给出原 3. 停掉这台设备两份副本上的 Node,用 `vibeface init --data-dir <新目录>` 初始化一个新的数据目录,再用新的加入链接执行 `vibeface join --data-dir <新目录> <链接>`。旧数据目录不要再启动。 4. 把需要保留的内容重新发一次。 -其他设备上出现“某某 的数据有两份副本”时,说明是那台设备分叉了,按同样步骤处理那台设备。 +其他设备上出现“某某 的数据被复制过”时,说明是那台设备分叉了,按同样步骤处理那台设备。 ## 常见问题 diff --git a/packages/docs/user-guide.md b/packages/docs/user-guide.md index 477a0bedb..6f662bf5f 100644 --- a/packages/docs/user-guide.md +++ b/packages/docs/user-guide.md @@ -31,7 +31,7 @@ Bot 的协调 Agent 负责理解需求、派发工作和汇报结果,项目任 ## 补充、取消与停止 -给正在回复的 Bot 追加信息时,是否立即并入取决于 Provider。Codex、pi 和 OpenCode 支持把补充并入当前回复,Claude Code 和 Cursor 会排队。以页面显示的送达状态为准。 +给正在回复的 Bot 追加信息时,是否立即并入取决于 Provider。Codex、Claude Code、pi 和 OpenCode 支持把补充并入当前回复,Cursor 会排队。以页面显示的送达状态为准。 停止前先区分对象: @@ -53,7 +53,7 @@ Bot 详情中的 **持久记忆** 与聊天记录分开,用于之后的工作 先把新电脑[加入同一网络](onboarding.md#加入已有网络),等待历史同步。准备该电脑上的项目、依赖和 Provider 登录,再打开原 Bot 聊天。 -需要转移协调职责时,选择 **交给这台设备处理**。这会用已同步的共享记录建立本机 Agent 上下文,不会搬走另一台机器的原生 SDK 会话,也不会自动复制项目文件。 +需要转移协调职责时,选择 **换到 某某**(某某是当前设备的名称)。这会用已同步的共享记录建立本机 Agent 上下文,不会搬走另一台机器的原生 SDK 会话,也不会自动复制项目文件。 原设备的工作仍可能在运行。接续之前先核对未完成任务,尤其是结果未知的写操作。历史回放本身不会重跑旧工作。 diff --git a/packages/theme/theme.css b/packages/theme/theme.css index 059d8549b..7f3882944 100644 --- a/packages/theme/theme.css +++ b/packages/theme/theme.css @@ -25,15 +25,8 @@ --brand: oklch(0.53 0.2 280); --brand-foreground: oklch(0.99 0.005 280); --brand-soft: oklch(0.96 0.025 280); - --chart-1: oklch(0.87 0 0); - --chart-2: oklch(0.556 0 0); - --chart-3: oklch(0.439 0 0); - --chart-4: oklch(0.371 0 0); - --chart-5: oklch(0.269 0 0); --sidebar: oklch(0.982 0.003 270); --sidebar-foreground: oklch(0.27 0.014 270); - --sidebar-primary: oklch(0.24 0.016 270); - --sidebar-primary-foreground: oklch(0.985 0.002 270); --sidebar-accent: oklch(0.94 0.008 270); --sidebar-accent-foreground: oklch(0.21 0.012 270); --sidebar-border: oklch(0.925 0.006 270); @@ -80,15 +73,8 @@ --brand: oklch(0.72 0.15 280); --brand-foreground: oklch(0.18 0.02 280); --brand-soft: oklch(0.72 0.15 280 / 14%); - --chart-1: oklch(0.87 0 0); - --chart-2: oklch(0.556 0 0); - --chart-3: oklch(0.439 0 0); - --chart-4: oklch(0.371 0 0); - --chart-5: oklch(0.269 0 0); --sidebar: oklch(0.155 0.006 270); --sidebar-foreground: oklch(0.88 0.006 270); - --sidebar-primary: oklch(0.72 0.15 280); - --sidebar-primary-foreground: oklch(0.18 0.02 280); --sidebar-accent: oklch(0.235 0.009 270); --sidebar-accent-foreground: oklch(0.97 0.003 270); --sidebar-border: oklch(1 0 0 / 7%); @@ -121,15 +107,8 @@ --color-sidebar-border: var(--sidebar-border); --color-sidebar-accent-foreground: var(--sidebar-accent-foreground); --color-sidebar-accent: var(--sidebar-accent); - --color-sidebar-primary-foreground: var(--sidebar-primary-foreground); - --color-sidebar-primary: var(--sidebar-primary); --color-sidebar-foreground: var(--sidebar-foreground); --color-sidebar: var(--sidebar); - --color-chart-5: var(--chart-5); - --color-chart-4: var(--chart-4); - --color-chart-3: var(--chart-3); - --color-chart-2: var(--chart-2); - --color-chart-1: var(--chart-1); --color-ring: var(--ring); --color-input: var(--input); --color-border: var(--border); @@ -180,6 +159,4 @@ --radius-lg: var(--radius); --radius-xl: calc(var(--radius) * 1.4); --radius-2xl: calc(var(--radius) * 1.8); - --radius-3xl: calc(var(--radius) * 2.2); - --radius-4xl: calc(var(--radius) * 2.6); } diff --git a/scripts/build-ios.sh b/scripts/build-ios.sh index 825307a00..c9192ea50 100755 --- a/scripts/build-ios.sh +++ b/scripts/build-ios.sh @@ -149,7 +149,7 @@ PY export IOS_SIGNING_TEAM="$team" IOS_SIGNING_PROFILE_UUID="$profile_uuid" IOS_SIGNING_IDENTITY="$identity" fi -scripts/build-mobile-secure.sh ios +"$root/scripts/build-mobile-secure.sh" ios cd "$root/apps/mobile" npx expo prebuild --platform ios --no-install (cd ios && pod install) diff --git a/scripts/check-delivery.py b/scripts/check-delivery.py index f9315998b..3385f75e9 100755 --- a/scripts/check-delivery.py +++ b/scripts/check-delivery.py @@ -570,7 +570,9 @@ def checked_transaction(value): integer(value["status"], 0, 1) for field in ("gasUsed", "effectiveGasPrice", "nativeCostWei"): decimal(value[field]) - event_types = {"KeyUpdated": ("hash", "amount", "hash", "bool"), "Funded": ("hash", "address", "amount"), "WindowUpdated": ("hash", "amount", "amount"), "DecryptionProven": ("hash", "amount"), "Withdrawn": ("hash", "address", "amount"), "Refunded": ("hash", "address", "amount")} + event_types = {"KeyUpdated": ("hash", "amount", "hash", "bool"), "Funded": ("hash", "address", "amount"), "WindowUpdated": ("hash", "amount", "amount"), "DecryptionProven": ("hash", "amount"), "Refunded": ("hash", "address", "amount"), + "BudgetOpened": ("hash", "address", "address", "amount"), "BudgetReserved": ("hash", "hash", "amount"), "BudgetEarned": ("hash", "hash", "amount", "amount"), + "BudgetWithdrawn": ("hash", "address", "amount"), "BudgetClosed": ("hash",), "BudgetRefunded": ("hash", "address", "amount")} if not isinstance(value["events"], list) or len(value["events"]) > 8: raise ValueError("Unexpected public event list") for event in value["events"]: @@ -645,10 +647,11 @@ def checked_node_summary(value, item, context, commit): checked_transaction(record) if value["deployment"] is not None: deployment = value["deployment"] - object_keys(deployment, ("chainId", "escrow", "asset", "payer", "provider", "profileId", "adapter", "verifier", "tokenDecimals", "orderId", "fundTransaction", "runtimeCodeHashes")) + object_keys(deployment, ("chainId", "escrow", "asset", "payer", "provider", "profileId", "adapter", "verifier", "tokenDecimals", "orderId", "budgetId", "allocationTransaction", "runtimeCodeHashes")) if context is None or any(deployment[field] != context["deployment"][field] for field in ("chainId", "escrow", "asset", "payer", "provider", "adapter", "verifier", "tokenDecimals", "runtimeCodeHashes")) or deployment["profileId"] != "0x" + context["profileId"] or deployment["orderId"] != "0x" + context["orderId"]: raise ValueError("Final deployment differs from reconstructed context") - prefixed(deployment["fundTransaction"], 32) + for field in ("budgetId", "allocationTransaction"): + prefixed(deployment[field], 32) if value["failure"] is not None: object_keys(value["failure"], ("stage", "kind", "code")) for field in ("stage", "kind", "code"): @@ -1460,6 +1463,23 @@ def must_reject(call): must_reject(lambda: checked_counters({"cpu.stat": "usage_usec 1\ncore_sched.force_idle_usec -1"})) checked_transaction({"label": "fund", "hash": "0x" + "1" * 64, "blockHash": "0x" + "2" * 64, "blockNumber": 5, "status": 1, "gasUsed": "1", "effectiveGasPrice": "2", "nativeCostWei": "2", "events": [{"name": "Funded", "args": ["0x" + "4" * 64, "0x" + "Ab" * 20, "17"]}]}) + budget, order = "0x" + "5" * 64, "0x" + context["orderId"] + accepted_events = (("open-budget", [("BudgetOpened", [budget, addresses[0], addresses[1], "17"])]), + ("reserve-batch", [("Funded", [order, addresses[0], "17"]), ("BudgetReserved", [budget, order, "17"])]), + ("publish", [("WindowUpdated", [order, "0", "3"]), ("BudgetEarned", [budget, order, "0", "17"])]), + ("withdraw", [("BudgetWithdrawn", [budget, addresses[1], "17"])]), + ("close", [("BudgetClosed", [budget])]), + ("refund", [("Refunded", [order, addresses[0], "17"]), ("BudgetRefunded", [budget, addresses[0], "17"])])) + accepted = {**node_summary, "workItem": "accept", "status": "PASS-accept-candidate", + "transactions": [{"label": label, "hash": "0x" + "1" * 64, "blockHash": "0x" + "2" * 64, "blockNumber": 5, "status": 1, "gasUsed": "1", "effectiveGasPrice": "2", "nativeCostWei": "2", + "events": [{"name": name, "args": arguments} for name, arguments in events]} for label, events in accepted_events], + "deployment": {**{field: context["deployment"][field] for field in ("chainId", "escrow", "asset", "payer", "provider", "adapter", "verifier", "tokenDecimals", "runtimeCodeHashes")}, + "profileId": "0x" + context["profileId"], "orderId": order, "budgetId": budget, "allocationTransaction": "0x" + "6" * 64}} + checked_node_summary(accepted, "accept", context, commit) + must_reject(lambda: checked_node_summary({**accepted, "deployment": {**{field: value for field, value in accepted["deployment"].items() if field not in ("budgetId", "allocationTransaction")}, "fundTransaction": "0x" + "6" * 64}}, "accept", context, commit)) + must_reject(lambda: checked_node_summary({**accepted, "deployment": {**accepted["deployment"], "budgetId": "5" * 64}}, "accept", context, commit)) + must_reject(lambda: checked_transaction({**accepted["transactions"][0], "events": [{"name": "Withdrawn", "args": [order, addresses[1], "17"]}]})) + must_reject(lambda: checked_transaction({**accepted["transactions"][0], "events": [{"name": "BudgetClosed", "args": [budget, "17"]}]})) for field, value in (("sourceCommit", "b" * 40), ("profileId", "f" * 64), ("profileSha256", "f" * 64), ("orderId", "0x" + "4" * 64), ("secret", "private")): changed = {**context, field: value} must_reject(lambda: checked_context(json_bytes(changed), compiled, vectors["profileId"], commit)) diff --git a/scripts/ci.py b/scripts/ci.py index c10a90d65..656b41a04 100644 --- a/scripts/ci.py +++ b/scripts/ci.py @@ -22,11 +22,11 @@ DEPENDENTS = { "protocol": ("bridge", "control"), "bridge": ("control",), - "secure": ("node", "secure-ffi"), + "secure": ("control", "node", "secure-ffi"), "node": (), "control": ("node", "cli"), "cli": (), - "secure-ffi": (), + "secure-ffi": ("node",), "delivery": ("node",), } CRATES = { @@ -571,7 +571,7 @@ def self_test(): assert not mobile["rust_packages"] and not mobile["docs_only"] for path in ("packages/client/src/lib/transport.ts", "packages/client/src/avatar/face.ts", "packages/client/src/avatar/derived-faces.json", "packages/theme/theme.css", "package.json", "pnpm-workspace.yaml", "pnpm-lock.yaml"): assert make_plan([path])["mobile"], path - assert make_plan(["crates/secure-ffi/src/lib.rs"])["rust_packages"] == ["vibeface-secure-ffi"] + assert make_plan(["crates/secure-ffi/src/lib.rs"])["rust_packages"] == ["vibeface-core", "vibeface-secure-ffi"] docs = make_plan(["README.md", "packages/docs/node.md"]) assert docs["docs_only"] and docs["www"] and docs["required_jobs"] == ["quick-check", "www"] for path in ("README.md", "README.zh-CN.md"): @@ -608,7 +608,7 @@ def self_test(): "node": ["vibeface-core"], "bridge": ["vibeface-bridge", "vibeface-core", "vibeface-control", "vibeface"], "protocol": ["vibeface-protocol", "vibeface-bridge", "vibeface-core", "vibeface-control", "vibeface"], - "secure": ["vibeface-secure", "vibeface-core", "vibeface-secure-ffi"], + "secure": ["vibeface-secure", "vibeface-core", "vibeface-control", "vibeface", "vibeface-secure-ffi"], "control": ["vibeface-core", "vibeface-control", "vibeface"], "cli": ["vibeface"], "delivery": ["vibeface-core", "vibeface-delivery"], diff --git a/scripts/deploy-activate.py b/scripts/deploy-activate.py index e768376e7..cf91b6b15 100644 --- a/scripts/deploy-activate.py +++ b/scripts/deploy-activate.py @@ -628,7 +628,7 @@ def self_test(): with patch(__name__ + '.docker', return_value=result): with TestCase().assertRaises(ValueError, msg='accepted an ambiguous imported image'): import_image(str(archive), digest) - settings = Path(temporary) / 'config.json' + settings = Path(temporary).resolve() / 'config.json' settings.write_text(json.dumps({'project': 'official-app', 'role': 'app', 'deploy_dir': '/srv/service-control/app', 'listen': '127.0.0.1:8088', 'nginx_config': '/etc/nginx/conf.d/app.conf', diff --git a/scripts/e2e-desktop.mjs b/scripts/e2e-desktop.mjs index 53091f754..6e43b4698 100644 --- a/scripts/e2e-desktop.mjs +++ b/scripts/e2e-desktop.mjs @@ -564,12 +564,15 @@ async function cleanup() { await ensurePrivateDirectory(controlRoot, { root }); await prepareProfileParent(); +function authorized(value, token) { + if (typeof value !== 'string') return false; + const received = Buffer.from(value); + const expected = Buffer.from(`Bearer ${token}`); + return received.length === expected.length && timingSafeEqual(received, expected); +} const token = randomBytes(32).toString('hex'); const control = createServer(async (request, response) => { - const authorization = request.headers.authorization; - const expected = `Bearer ${token}`; - if (request.method !== 'POST' || request.url !== '/' || typeof authorization !== 'string' - || authorization.length !== expected.length || !timingSafeEqual(Buffer.from(authorization), Buffer.from(expected))) { + if (request.method !== 'POST' || request.url !== '/' || !authorized(request.headers.authorization, token)) { response.writeHead(403).end(); return; } if (changing || stopping) { response.writeHead(409).end(); return; } diff --git a/scripts/e2e-node.mjs b/scripts/e2e-node.mjs index c4f90ba5d..9d28d3347 100644 --- a/scripts/e2e-node.mjs +++ b/scripts/e2e-node.mjs @@ -110,7 +110,7 @@ const control = createServer(async (request, response) => { let result; if (value.op === 'reset') result = await startFixture(value.kind); else if (value.op === 'stop') { await stopFixture(); result = { stopped: true }; } - else if (['restart', 'inspect', 'cursor_login', 'cursor_inspect', 'workspace_release', 'workspace_inspect', 'workspace_native_setup', 'mesh_info', 'mesh_pairing', 'mesh_approve'].includes(value.op)) result = await command(value); + else if (['restart', 'inspect', 'cursor_login', 'cursor_inspect', 'workspace_release', 'workspace_inspect', 'mesh_info', 'mesh_pairing', 'mesh_approve'].includes(value.op)) result = await command(value); else throw new Error('Unknown fixture operation'); response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(result)); } catch (error) { diff --git a/scripts/install-node-service.ps1 b/scripts/install-node-service.ps1 index 730704a28..210ccfb86 100644 --- a/scripts/install-node-service.ps1 +++ b/scripts/install-node-service.ps1 @@ -17,7 +17,7 @@ Usage: install-node-service.ps1 install --binary C:\absolute\vibeface.exe --data install-node-service.ps1 install-updater --binary C:\install-root\current\vibeface.exe --data-dir C:\absolute\data install-node-service.ps1 start|stop|restart [--data-dir C:\absolute\data] install-node-service.ps1 status - install-node-service.ps1 uninstall-updater|uninstall --data-dir C:\absolute\data + install-node-service.ps1 uninstall-updater|uninstall-node|uninstall --data-dir C:\absolute\data Installs scheduled tasks for the account that runs this script. Initialize the node first. '@ diff --git a/scripts/run-delivery-live.py b/scripts/run-delivery-live.py index 37fe73a2e..5670b60c4 100644 --- a/scripts/run-delivery-live.py +++ b/scripts/run-delivery-live.py @@ -2888,7 +2888,14 @@ def protected_package_dispatch(package_input, expected, run_directory): container = protected_container(original, package, expected, run, common, git_directory, name) process = None returncode = 1 + previous_term = signal.getsignal(signal.SIGTERM) + + def interrupted(*_): + raise InterruptedError("Protected native acceptance interrupted") + try: + # The docker client runs in its own session, so only this handler lets a terminated host reach the cleanup below. + signal.signal(signal.SIGTERM, interrupted) process = subprocess.Popen(container, cwd=ROOT, start_new_session=True) returncode = process.wait() finally: @@ -2905,6 +2912,7 @@ def protected_package_dispatch(package_input, expected, run_directory): terminate_owned(process) except Exception: returncode = returncode or 1 + signal.signal(signal.SIGTERM, previous_term) try: public, passed = protected_public(run, expected, returncode) except Exception: @@ -3039,7 +3047,16 @@ def forbidden(*_args, **_kwargs): raise AssertionError("stage-bound selfcheck op patch("socket.socket", forbidden), patch("time.time", side_effect=[0, LIVE_TIMEOUT_SECONDS + 1]), \ patch.dict(os.environ, {"GITHUB_OUTPUT": ""}), patch("builtins.print"): protected_package_dispatch(package, expected, run) - process.wait.assert_called_once_with() + process.wait.assert_called_once_with() + previous_term = signal.getsignal(signal.SIGTERM) + terminated = Mock(wait=Mock(side_effect=lambda: os.kill(os.getpid(), signal.SIGTERM) or time.sleep(5)), poll=Mock(side_effect=[None, 0])) + with patch("subprocess.Popen", return_value=terminated), patch("subprocess.run", return_value=subprocess.CompletedProcess([], 0, b"", b"")) as cleanup, \ + patch("subprocess.check_output", side_effect=[str(common) + "\n", str(common / "worktrees/task") + "\n"]): + try: protected_package_dispatch(package, expected, Path(temporary) / "terminated") + except InterruptedError: pass + else: raise AssertionError("a terminated protected host must not report success") + assert [call.args[0][:2] for call in cleanup.call_args_list] == [["docker", "stop"], ["docker", "rm"]], "a terminated host must stop its container" + assert signal.getsignal(signal.SIGTERM) is previous_term assert "timeout" not in build.call_args.kwargs, "the native stages must not inherit the old UI total timeout" with tempfile.TemporaryDirectory(prefix="protected-npm-cache-selftest-", dir=ARTIFACTS) as temporary: run = Path(temporary); package = run / "package"; package.mkdir() diff --git a/scripts/verify-delivery-protected.py b/scripts/verify-delivery-protected.py index 9de4fb07b..254842f07 100644 --- a/scripts/verify-delivery-protected.py +++ b/scripts/verify-delivery-protected.py @@ -768,7 +768,7 @@ def process_fact(pid): try: fields = Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split() return {"pid": pid, "birth": fields[19], "group": int(fields[2]), "state": fields[0]} - except FileNotFoundError: + except (FileNotFoundError, ProcessLookupError): return None @@ -791,7 +791,7 @@ def capture(self): for task in Path(f"/proc/{pid}/task").glob("*"): try: pending.extend(map(int, (task / "children").read_text().split())) - except FileNotFoundError: + except (FileNotFoundError, ProcessLookupError): pass def alive(self): @@ -1798,12 +1798,13 @@ def summarize(records, node="S", index=0, facts=()): and all(job["resources"]["cgroup"] == synthetic_target for job in collected["jobs"]), "four_synthetic_streams_bound_to_the_pinned_directory_fixture") for node in experiment.nodes: need(experiment.proof_channels[node.name] is None, "collector_closes_pinned_descriptors") need(experiment.collect_proof_diagnostics() == collected, "collector_never_upgrades_first_attempt") - for kind in ("missing", "fifo", "directory", "symlink", "hardlink", "mode", "owner", "changed", "replaced-directory", "overflow", "half-line", "extra"): + for kind in ("valid", "missing", "fifo", "directory", "symlink", "hardlink", "mode", "owner", "changed", "replaced-directory", "overflow", "half-line", "extra"): with tempfile.TemporaryDirectory(prefix="proof-collector-negative-", dir=ARTIFACTS) as temporary: run = Path(temporary); node = SimpleNamespace(name="S", device_id=principals["S"]["peer"], directory=run / "S"); node.directory.mkdir(mode=0o700) - experiment = object.__new__(Experiment); experiment.nodes = [node]; experiment.proof_channels = {}; experiment.proof_diagnostic_result = None + experiment = object.__new__(Experiment); experiment.nodes = [node, SimpleNamespace(name="R", device_id=principals["R"]["peer"])]; experiment.proof_channels = {}; experiment.proof_diagnostic_result = None experiment.config = {"source_commit": source, "sha256": artifacts}; experiment.profile_id = profile - experiment.orders = {orders[0]["order_id"]: orders[0]}; experiment.summary = {"genuine_receipts": []}; experiment.rows = Mock(return_value=[]) + experiment.orders = {orders[0]["order_id"]: orders[0]}; experiment.summary = {"genuine_receipts": []} + experiment.rows = Mock(return_value=[(records[0]["job"], str(node.directory / "delivery/private" / ("proof-" + records[0]["job"] + ".receipt")))]) experiment.prepare_proof_diagnostics(node); channel = experiment.proof_channels["S"]; path = channel["path"] / (records[0]["job"] + ".jsonl") if kind == "fifo": os.mkfifo(path, 0o600) elif kind == "directory": path.mkdir(mode=0o700) @@ -1831,6 +1832,9 @@ def checked_fstat(descriptor): return info with patch.dict(globals(), resources=lambda: (_ for _ in ()).throw(OSError())), patch.object(os, "fstat", side_effect=checked_fstat): unavailable = experiment.collect_proof_diagnostics() + if kind == "valid": + need(unavailable["availability"] != "unavailable", "safe_stream_with_reservation_is_collected") + continue need(unavailable["availability"] == "unavailable" and all(job == unavailable_proof_job(job["node"], job["order_index"]) for job in unavailable["jobs"]), "unsafe_stream_is_nonblocking_unavailable") maximum, maximum_group = 2**63-1, [2**64-1] * 2 conservative_records = copy.deepcopy(records) diff --git a/scripts/verify-desktop.mjs b/scripts/verify-desktop.mjs index 71a3123d1..ed8ef2179 100644 --- a/scripts/verify-desktop.mjs +++ b/scripts/verify-desktop.mjs @@ -43,7 +43,6 @@ function readReceipt(input, target, version) { assert(SIGNING_STATES.includes(receipt.signing) && typeof receipt.signed === 'boolean', 'invalid desktop signing status'); assert.equal(receipt.signed, ['developer-id-notarized', 'authenticode'].includes(receipt.signing), 'desktop signing status and signed flag disagree'); assert(!receipt.signed || receipt.signing === platform.signing, 'desktop signing kind does not match its platform'); - assert(receipt.signing !== 'platform-checksums' || target.endsWith('-unknown-linux-gnu'), 'platform checksums are Linux-only'); assert(target.endsWith('-unknown-linux-gnu') ? receipt.signing === 'platform-checksums' : receipt.signing !== 'platform-checksums', 'desktop signing status does not match its platform'); assert.equal(receipt.runtime.archive, `vibeface-${version}-${target}.tar.gz`, 'the runtime must be this platform CLI bundle'); diff --git a/tests/e2e/paid-native-transfers.paid.ts b/tests/e2e/paid-native-transfers.paid.ts index 027f265ff..1c2a140fb 100644 --- a/tests/e2e/paid-native-transfers.paid.ts +++ b/tests/e2e/paid-native-transfers.paid.ts @@ -33,7 +33,7 @@ test('accepts a paid file in the release Android app, disconnects, resumes and s await device.installApp(undefined, { reinstall: true }); await app.open(); await screen.getByRole('textbox', /^加入链接/).fill(secrets.get('paidAndroidInvitation'), { timeout: 30000 }); - await screen.getByRole('textbox', /^这台手机叫什么/).fill('VDP paid native receiver'); + await screen.getByRole('textbox', /^这台设备的名字(?:$|[\s,,])/).fill('VDP paid native receiver'); await device.dismissKeyboard(); await screen.getByRole('button', '加入', { exact: true }).click(); await expect.poll(async () => (await pairing('android')) !== null, { timeout: 45000, message: 'The real Android member reveals its pairing nonce' }).toBe(true); diff --git a/tests/fixtures/delivery-probe/Cargo.lock b/tests/fixtures/delivery-probe/Cargo.lock index 234fbf8a7..a72d84a8f 100644 --- a/tests/fixtures/delivery-probe/Cargo.lock +++ b/tests/fixtures/delivery-probe/Cargo.lock @@ -438,9 +438,9 @@ dependencies = [ [[package]] name = "ctutils" -version = "0.4.3" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03bb0e1cc970d482d121d9a1744999169b69a07470b3d644a7894e53fcaf4574" +checksum = "12218662ccac37d9714f2191252553d67585b97df8c839cbe49e0bde278dc865" dependencies = [ "cmov", ] @@ -656,7 +656,6 @@ checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" dependencies = [ "curve25519-dalek 4.1.3", "ed25519 2.2.3", - "rand_core 0.6.4", "serde", "sha2 0.10.9", "subtle",