diff --git a/AGENTS.md b/AGENTS.md index 5948b2603b..0c4b85fe0f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,7 +19,7 @@ Agent 团队的长程效果和长程效率:在可比预算下取得更好的 - **Governed continuation:** heartbeat, scheduling, quota and explicit stop/wait conditions decide when authorized work can continue. - **Peer collaboration:** claims, leases, scoped handoffs, dependent artifacts, - receiver adoption and result return; a coordinator gains no implicit authority. + receiver adoption and result return. - **Personal Workspace:** App/frontend, Lark and CLI expose conversations, settings, work, decisions, artifacts and readback over the same typed owners. - **Capabilities and extensions:** reusable engineering, research, knowledge, @@ -40,7 +40,7 @@ prompt. Keep the root within both the 24,000-byte (24 KB) Antigravity per-file rule cap and the default 32 KiB Codex discovery budget, and do not eagerly import linked detail documents. See [loading](docs/development/README.md#agent-instruction-loading-and-maintenance) -for host-specific checks; delivery does not prove model compliance. +for host-specific checks. Prefer [context](docs/development/README.md#progressive-context-for-development): current goals, constraints and acceptance criteria first; supporting evidence and @@ -65,16 +65,14 @@ acceptance is proven; reconcile the existing checkpoint as evidence changes. Carry one compact delivery brief from task to PR (goal/source, current gap, observable result, owning boundary and decisive acceptance evidence), keeping private Goal state out of public artifacts. Choose a complete, independently -reviewable and reversible outcome slice; small diffs, fields, receipts, test -counts and merged PR counts do not establish progress. Characterization, +reviewable and reversible outcome slice. Characterization, prerequisites, research, docs and maintenance are valid when they remove an evidenced gap or enable a named next step. For long-horizon improvements, trace the accepted goal and structured state through feedback, the replan decision, subsequent work and validated outcomes. Check whether new evidence changed the action or justified continuing it, and -preserve negative results and uncertainty (`state survival`, graph edges, read -receipts or replan records alone do not prove adoption or benefit). Compare +preserve negative results and uncertainty. Compare outcomes and complete costs under comparable conditions using the [measurement contract](docs/architecture/rfcs/long-horizon-harness-benchmark-research-program-v0.md#6-measurement-model); do not force a direction change merely to increase replan counts. @@ -93,8 +91,7 @@ a registered vocabulary, remains local or creates a shared contract, and follow the [diff advisory](CONTRIBUTING.md#check-new-semantic-vocabulary-while-developing) before the full-tree check (including intentional untracked sources). For multi-Agent changes, qualify dependency artifacts, receiver adoption, claim/lease -handling, independent acceptance and result return; sending a message or -registering workers does not prove collaboration, and missing frontend/Lark/CLI +handling, independent acceptance and result return; missing frontend/Lark/CLI companion work makes a product journey partial. Before delivery, reconcile the result with the original/current goal, update its @@ -102,7 +99,7 @@ task and RFC checkpoint when the boundary changes, and preserve passed, failed and untested distinctions. If user feedback exposes the same missing outcome, repair the owning rule, active task or projection through self-repair rather than appending stronger prose. PR review must execute the capability-owned -`problem_context` delivery judgment; author declarations do not certify it. +`problem_context` delivery judgment. ## Commit And PR Hygiene @@ -171,9 +168,7 @@ Before staging non-trivial changes: Before approval or merge, read the repository-kept [merge workflow](skills/loopx-pr-merge/SKILL.md) and its -[self-merge rules](skills/loopx-pr-merge/SKILL.md#self-merge-eligibility-and-benchmark-exceptions); -installing it is optional and does not replace repository policy or the current -capability-owned review. +[self-merge rules](skills/loopx-pr-merge/SKILL.md#self-merge-eligibility-and-benchmark-exceptions). Control-plane, runtime and product surfaces (`loopx/**`, `apps/**`, `packages/**`, permissions/authority, persisted state/receipts, quota/scheduler/todo rules, and diff --git a/README.ja.md b/README.ja.md index 16fd08cfba..c207e24b2c 100644 --- a/README.ja.md +++ b/README.ja.md @@ -105,8 +105,7 @@ LoopX は、永続的な作業状態を 1 つのコンパクトなレイヤー 作業を実行するのは Agent ランタイムです。LoopX は、エンジニアリング、研究、探索、 -運用のループが実行をまたいで継続できるようにするための状態を保持します。これは -新たなエージェントフレームワークでも、特定プロバイダー向けのオーケストレーションランタイムでもありません。 +運用のループが実行をまたいで継続できるようにするための状態を保持します。
詳細:コントロールレイヤーの仕組みと位置付け @@ -136,7 +135,7 @@ LoopX は、次のようなものを実行するときに役立ちます: - 進捗がエンジニアではないオペレーターにも理解できる状態でなければならない、 クリエイター、研究、運用のワークフロー -LoopX は自律的な本番コントローラーではありません。危険な権限、 +危険な権限、 公開、本番環境への書き込み、最終的なオーナーシップは人間に残ります。
@@ -867,8 +866,7 @@ LoopX は、長時間稼働するエージェントのエコシステムを築 ## 現在のステータス LoopX は、長時間にわたるエージェントの作業のための実用的なローカルコントロールプレーンであり、 -より広い導入の段階に入りつつあります。完全なエージェントプラットフォーム、エージェントランタイム、 -自律的な本番コントローラーではありません。 +より広い導入の段階に入りつつあります。 現在の LoopX は、ゴール、型付きの todo と意思決定の スコープ、対等な claim とリース、エビデンスと writeback、クォータを考慮したスケジューリング、 diff --git a/README.md b/README.md index 7c74e0c5f7..3318276e50 100644 --- a/README.md +++ b/README.md @@ -138,7 +138,7 @@ LoopX is useful when you run: - creator, research, or operations workflows whose progress must remain legible to a non-engineering operator. -LoopX is not an autonomous production controller. Dangerous permissions, +Dangerous permissions, publishing, production writes, and final ownership stay with the human. @@ -390,14 +390,11 @@ benchmark's strict solved threshold. No score in this study equals 0.80, so these counts also match the study brief's >0.80 view. Against native Goal, task-level rewards improve on **23**, tie on **13**, and -regress on **10** tasks. Strict solves match Plain Codex, so the mean gain is -not a claim that every task improves or that more tasks are fully solved than -Plain. Mean reward also credits partial progress. +regress on **10** tasks. Strict solves match Plain Codex. Mean reward also credits partial progress. One effective trial per task and mode; designated replacement trials and unequal runtime/budgets, including longer budgets for some Heartbeat replacements. -These are observed system results, not an equal-budget efficiency result or -an isolated causal estimate of LoopX's effect. +These are observed system results. [Interactive results, task comparisons and methodology](https://loopx-project.github.io/loopx/benchmarks/lhtb/) · [Five-arm study and limits](benchmark/LHTB/studies/five-arm-gpt56sol-max/README.md) @@ -564,7 +561,7 @@ its own policy and authority checks before proposing a transition. | Session dash | Starts a live single-page panel that tracks fleet progress: sessions, their goals, and each goal's status/todo progress, with result statistics; auto-refreshes in place. | `loopx dash`, [session dash design](docs/product/surfaces/session-dash-panel-design.md) | | External projections | Projects todos and gates into collaboration surfaces while LoopX remains authoritative. | `loopx lark-kanban`, [Lark Kanban adapter](docs/integrations/lark-kanban-control-plane-adapter.md) | | Domain capabilities | Packages repeatable work lanes such as issue fixing, content operations, value connector planning, ML experiment advice, benchmark evidence, and Explore. | `loopx issue-fix`, `loopx content-ops`, `loopx value-connectors`, `loopx ml-experiment`, `loopx benchmark`, [Explore](loopx/capabilities/explore/README.md) | -| Experimental context learning | Lets named registered agents trial provider-neutral Reward Memory through ignored, default-off project configuration. OpenViking is one provider option, not a global dependency. | `loopx reward-memory experiment-status`, [Reward Memory architecture](loopx/capabilities/reward_memory/README.md) | +| Experimental context learning | Lets named registered agents trial provider-neutral Reward Memory through ignored, default-off project configuration. OpenViking is one provider option. | `loopx reward-memory experiment-status`, [Reward Memory architecture](loopx/capabilities/reward_memory/README.md) | | Governance patterns | Captures reusable routing, gate, evidence, projection, and planning shapes. | [interaction patterns](docs/concepts/interaction-pattern-catalog.md), [state model](docs/state-interaction-model.md) | The shipped primitives include lifetime goals, concrete user gates, audited safe @@ -583,8 +580,7 @@ signals, and public/private boundary checks. The execution path is `Agent -> Capability -> Provider`; the control path returns `Provider readback -> Capability transition -> Kernel`. An extension is -how an optional provider is packaged and managed, not another control-plane -owner. See [Architecture](docs/architecture.md) and +how an optional provider is packaged and managed. See [Architecture](docs/architecture.md) and [Extensions and Capabilities](docs/reference/extensions.md). @@ -599,8 +595,7 @@ owner. See [Architecture](docs/architecture.md) and [Anthropic's *Building always-on agents*](https://claude.com/resources/articles/building-always-on-agents) make persistent personal agents and sleep/wake event-driven runs a familiar product and architecture model. LoopX approaches that space as an open, provider-neutral -[24/7 control plane](#always-on-agents) for agents you already run—not as a hosted -replacement for either product. +[24/7 control plane](#always-on-agents) for agents you already run. - **Personal agent:** use the shipped Workspace and connected Lark surfaces to inspect goals, steer work and resolve decisions. The @@ -615,10 +610,9 @@ replacement for either product. [Reward Memory](loopx/capabilities/reward_memory/README.md), and evaluate candidate changes through [Explore](loopx/capabilities/explore/README.md). Both are optional. The link to **recursive self-improvement (RSI)** is the - engineering loop—propose, test, review, retain—not a claim that LoopX has - demonstrated autonomous model improvement or compounding capability gains. + engineering loop—propose, test, review, retain. -A personal steward is an interaction role, not a second source of authority. +A personal steward is an interaction role. Background execution still needs an available host and configured runtime. The [overall roadmap](docs/architecture/rfcs/loopx-overall-roadmap-v0.md) separates shipped foundations from the next end-to-end acceptance milestones. @@ -876,8 +870,7 @@ long-running agent ecosystem. Our confirmed partners include: ## Current Status LoopX is a usable local control plane for long-running agent work and is -entering broader adoption. It is not a full agent platform, an agent runtime, or -an autonomous production controller. +entering broader adoption. Today LoopX ships a durable state kernel for goals, typed todos and decision scopes, peer claims and leases, evidence and writeback, quota-aware scheduling, @@ -888,9 +881,7 @@ Workspace all build on that shared control state. Support levels remain explicit. The state and CLI contracts are the stable center; several host integrations and advanced paths are optional, default-off, -or experimental. LoopX does not grant credentials, approve destructive or -production actions, publish on a user's behalf without authorization, or turn -an unverified run into evidence of success. +or experimental. Current investment is organized through the [Technical Directions map](docs/project/technical-directions.md): long-horizon diff --git a/README.zh-CN.md b/README.zh-CN.md index 0bfad065b2..c1d4fe3445 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -94,8 +94,7 @@ LoopX 把长期控制状态留在同一层紧凑状态里: Agent runtime 负责执行,LoopX 负责治理跨运行延续的控制状态,让工程、 -研究、discovery 和运营 Loop 能持续推进。它不是又一个 agent framework,也不是 -绑定某一 Provider 的编排 runtime。 +研究、discovery 和运营 Loop 能持续推进。 @@ -123,7 +122,7 @@ LoopX 适合: - 需要 ownership、lease 和 handoff 的平级 agent team; - 需要把进展、阻塞和反馈入口清晰呈现给非技术用户的创作、研究或运营工作。 -LoopX 不是生产自动化控制器。危险权限、生产写入、公开发布和最终 ownership +危险权限、生产写入、公开发布和最终 ownership 仍由人类负责。 @@ -237,7 +236,7 @@ App 为 ad-hoc 签名,尚未 notarize。Windows 预览版目前手动更新, | DeepSeek Harness | 安装 [DSH 原生 Plugin](packages/dsh-loopx-plugin/README.md),在技能选择器中选 `loopx`,然后直接描述任务 | LoopX 会复用项目已有状态或连接项目,把工作规划成 Todo,并引导宿主激活。 -让 Agent 回报当前 Goal、下一条 Todo 和实际续跑机制;生成 setup packet 不等于循环已经启动。 +让 Agent 回报当前 Goal、下一条 Todo 和实际续跑机制; 持续工作需要宿主保持可用。`loopx status` 显示目标、等你处理的决策和下一条 Todo; `loopx doctor` 诊断安装。 @@ -340,12 +339,10 @@ loopx doctor 本组没有恰好等于 0.80 的分数,因此这里的计数与研究简报的 >0.80 一致。 相对原生 Goal,逐题 Reward **23 胜、13 平、10 负**。 -严格通过题数与 Plain Codex 相同;平均 Reward 也计入部分完成的得分, -因此均分提升不代表每题都改善,也不代表比 Plain 完整解决了更多任务。 +严格通过题数与 Plain Codex 相同;平均 Reward 也计入部分完成的得分。 每个任务、每种模式仅一条有效轨迹;包含指定替代运行,运行时与预算不完全相同, -部分 Heartbeat 替代运行使用了更长预算。这是观测到的系统结果, -不是等预算效率结论,也未单独识别 LoopX 的因果增益。 +部分 Heartbeat 替代运行使用了更长预算。这是观测到的系统结果。 [交互结果、逐题对比与方法](https://loopx-project.github.io/loopx/benchmarks/lhtb/?lang=zh) · [五臂研究与边界](benchmark/LHTB/studies/five-arm-gpt56sol-max/README.md) @@ -354,7 +351,7 @@ loopx doctor Benchmark 之外,LoopX 也有可检查的长程项目证据。 OpenViking 的公开贡献序列跨越 **200+ 小时自然时长**,保留多轮 Todo、决策和证据更新。这里衡量的是项目经过的 -wall-clock 时间,不是连续模型执行时长或无人值守的生产自治。点击原图查看 +wall-clock 时间。点击原图查看 公开安全的任务图、证据分支和跨轮决策;案例说明了来源与可复现边界。 ### 开源 Issue Fix @@ -473,7 +470,7 @@ Kernel 把控制面归结为五个用户可以直接行动的问题。每个问 架构、控制面能力与运行责任 LoopX 显式保留架构边界,使同一个受治理结果在更换 Agent harness 或外部 Provider -后仍然成立。以下术语描述的是不同边界,而不是几种可以互换的插件: +后仍然成立。以下术语描述的是不同边界: | 边界 | 含义 | 深入阅读 | | --- | --- | --- | @@ -483,7 +480,7 @@ LoopX 显式保留架构边界,使同一个受治理结果在更换 Agent harn | **Extension** | 通过显式安装、readiness、启用、升级、停用和回滚生命周期交付可选 Provider。 | [Extension 生命周期](docs/reference/extensions.md#runtime-lifecycle) | `--available-capability shell` 等 host 声明描述的是已观测到的执行支持;在这张 -产品图里属于 runtime capacity,不是产品 Capability,也不授予权限。真正执行前, +产品图里属于 runtime capacity。真正执行前, Capability 仍须应用自己的 policy 和 authority check,再提出 typed transition。 ### 控制面能力 @@ -496,7 +493,7 @@ Capability 仍须应用自己的 policy 和 authority check,再提出 typed tr | Operator surface | 呈现紧凑状态,但不让浏览器成为状态事实源。 | `loopx serve-status`、[Dashboard](apps/presentation/dashboard/README.md) | | External projection | 把 todo / gate 投影到协作表面,同时保持 LoopX 权威。 | `loopx lark-kanban`、[Lark Kanban adapter](docs/integrations/lark-kanban-control-plane-adapter.md) | | Domain capability | 打包 Issue Fix、内容运营、value connector、ML 实验、benchmark 与 Explore 等可重复泳道。 | `loopx issue-fix`、`loopx content-ops`、`loopx value-connectors`、`loopx ml-experiment`、`loopx benchmark`、[Explore](loopx/capabilities/explore/README.md) | -| 实验性上下文学习 | 通过 ignored、默认关闭的项目配置,为明确注册的 agent 试用 provider-neutral Reward Memory;OpenViking 是 provider 之一,不是全局依赖。 | `loopx reward-memory experiment-status`、[Reward Memory 中文架构](loopx/capabilities/reward_memory/README.zh-CN.md) | +| 实验性上下文学习 | 通过 ignored、默认关闭的项目配置,为明确注册的 agent 试用 provider-neutral Reward Memory;OpenViking 是 provider 之一。 | `loopx reward-memory experiment-status`、[Reward Memory 中文架构](loopx/capabilities/reward_memory/README.zh-CN.md) | | Governance pattern | 沉淀可复用的 routing、gate、evidence、projection 和 planning 形状。 | [Interaction Pattern Catalog](docs/concepts/interaction-pattern-catalog.md)、[State Model](docs/state-interaction-model.md) | 这些能力共同提供 lifetime goal、具体 user gate、经过审计的安全侧路、平级 todo @@ -514,7 +511,7 @@ ownership、quota 与 steering、紧凑 run history、证据化 handoff、read-f 执行路径是 `Agent -> Capability -> Provider`,控制结果沿 `Provider readback -> Capability transition -> Kernel` 返回。Extension 负责可选 -provider 的打包和生命周期,不是另一个控制面 owner。详见 +provider 的打包和生命周期。详见 [核心架构](docs/architecture.md)与 [Extension / Capability 参考](docs/reference/extensions.md)。 @@ -529,8 +526,7 @@ provider 的打包和生命周期,不是另一个控制面 owner。详见 [Grok Bot](https://x.ai/news/introducing-grok-bot) 以及 [Anthropic《Building always-on agents》](https://claude.com/resources/articles/building-always-on-agents) 正在让“把工作交给 7×24 常驻个人 Agent”与“休眠—事件唤醒”成为越来越清晰的产品与架构共识。LoopX -选择的是开放、Provider-neutral 的[7×24 控制面](#always-on-agents)路线,连接你已经在用的 Agent, -而不是提供这两款托管产品的等价替代。 +选择的是开放、Provider-neutral 的[7×24 控制面](#always-on-agents)路线,连接你已经在用的 Agent。 - **个人 Agent:**通过已发布的工作区与关联飞书入口查看目标、调整方向、处理决策。 [常驻管家与语义交接 RFC](docs/architecture/rfcs/capable-manager-semantic-handoff-v0.zh-CN.md) @@ -541,9 +537,9 @@ provider 的打包和生命周期,不是另一个控制面 owner。详见 - **自我改进:**用 [Reward Memory](loopx/capabilities/reward_memory/README.md) 将反馈带入下一次尝试,用 [Explore](loopx/capabilities/explore/README.md) 评估候选改动, 两者均按需启用。与 **RSI(递归自我改进)** 的交集在于“提出改动—验证—审阅—保留”的 - 工程闭环,而不是宣称 LoopX 已实现模型自主升级或能力递归增长。 + 工程闭环。 -个人管家是一种交互角色,不是另一套状态权威。后台执行仍需要可用的主机和已配置的运行时。 +个人管家是一种交互角色。后台执行仍需要可用的主机和已配置的运行时。 [整体路线图](docs/architecture/rfcs/loopx-overall-roadmap-v0.zh-CN.md) 区分了已交付的基础与下一步需要验收的端到端能力。 @@ -665,8 +661,7 @@ loopx check \ ## 当前技术方向 -LoopX 当前有三个活跃战略计划和一个架构与研究孵化器。这些内容用于表达方向, -不是交付承诺;`main`、已发布 artifact 和 stable reference contract 仍然定义真实 +LoopX 当前有三个活跃战略计划和一个架构与研究孵化器。这些内容用于表达方向;`main`、已发布 artifact 和 stable reference contract 仍然定义真实 已交付行为。 - **长程 Benchmark 与证据:**在互补 benchmark 环境中建立可复现的能力证据, @@ -677,8 +672,7 @@ LoopX 当前有三个活跃战略计划和一个架构与研究孵化器。这 旅程仍在验收,由 `@maxliux5` 作为 implementation lead。 [方向 Tracker](https://github.com/loopx-project/loopx/issues/3244) - **Shared Goal Authority 与跨 Host 协作:**为显式共享 goal 提供 - provider-neutral 协调;NoKV 是尚未晋级的 provider candidate,而不是新的控制面 - 权威。 + provider-neutral 协调;NoKV 是尚未晋级的 provider candidate。 [方向 Tracker](https://github.com/loopx-project/loopx/issues/3245) - **架构与研究孵化器:**以明确不同的成熟度推进 Effect Program hardening、 TypeScript parity migration、hierarchical stride、research exploration、human @@ -775,7 +769,6 @@ LoopX 欢迎与其他开源项目协作,共建长程 Agent 生态。已确认 ## 当前状态 LoopX 已经是一套可用的长程 Agent 本地控制面,正在进入更广泛的采用阶段。 -LoopX 不是完整 agent platform,不是 agent runtime,也不是自治生产控制器。 目前 LoopX 已交付围绕 goal、typed todo / decision scope、平级 claim / lease、 evidence / writeback、quota-aware scheduling 和跨轮 continuation 的 durable state diff --git a/apps/desktop/loopx-control-plane/src-tauri/src/bundled_runtime.rs b/apps/desktop/loopx-control-plane/src-tauri/src/bundled_runtime.rs index 858eb610e7..0d9b551942 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/bundled_runtime.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/bundled_runtime.rs @@ -21,9 +21,11 @@ pub fn identity(app: &AppHandle) -> Result { fn identity_at(resources: &Path) -> Result { let path = resources.join("runtime/identity.json"); - let value: Value = - serde_json::from_slice(&fs::read(path).map_err(|_| "runtime_bundle_missing")?) - .map_err(|_| "runtime_bundle_invalid")?; + parse_identity(&fs::read(path).map_err(|_| "runtime_bundle_missing")?) +} + +pub(crate) fn parse_identity(bytes: &[u8]) -> Result { + let value: Value = serde_json::from_slice(bytes).map_err(|_| "runtime_bundle_invalid")?; if value["schema_version"] != "desktop_runtime_bundle_v1" || !value["source_revision"] .as_str() diff --git a/apps/desktop/loopx-control-plane/src-tauri/src/macos_update.rs b/apps/desktop/loopx-control-plane/src-tauri/src/macos_update.rs index 4a876cbb2b..16c07501b0 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/macos_update.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/macos_update.rs @@ -3,13 +3,57 @@ //! the existing updater. This is only its macOS filesystem effect adapter. use std::{ fs, - io::{self, Cursor}, + io::{self, Cursor, Read}, path::{Component, Path}, }; use flate2::read::GzDecoder; +use serde_json::Value; use tauri_plugin_updater::Update; +const PUBLIC_DEFAULT_CONTRACT: &str = + include_str!("../../../../../loopx/cli_commands/public_default_contract.json"); + +/// Read the publisher's observed contract inside the signature-verified bytes +/// before an update can be cached, close the workspace, or replace its App. +pub(crate) fn qualify_candidate( + channel: &str, + version: &str, + verified_bytes: &[u8], +) -> Result<(), String> { + // Historical stable bundles predate the attestation and remain usable. + // A preview stays subject to the check even if cache metadata changes channel. + if channel != "main" + && !semver::Version::parse(version) + .is_ok_and(|value| value.pre.as_str().starts_with("main.")) + { + return Ok(()); + } + let invalid = "runtime_bundle_invalid"; + let unavailable = "update_platform_unavailable"; + let supported: Value = serde_json::from_str(PUBLIC_DEFAULT_CONTRACT).map_err(|_| invalid)?; + let identity_path = Path::new("LoopX.app/Contents/Resources/runtime/identity.json"); + let mut archive = tar::Archive::new(GzDecoder::new(Cursor::new(verified_bytes))); + let mut qualified = false; + for entry in archive.entries().map_err(|_| invalid)? { + let mut entry = entry.map_err(|_| invalid)?; + if entry.path().map_err(|_| invalid)? != identity_path { + continue; + } + if qualified || !entry.header().entry_type().is_file() || entry.size() > 16 * 1024 { + return Err(invalid.into()); + } + let mut raw = Vec::new(); + entry.read_to_end(&mut raw).map_err(|_| invalid)?; + let identity = crate::bundled_runtime::parse_identity(&raw)?; + if identity["default_contract"] != supported { + return Err(unavailable.into()); + } + qualified = true; + } + qualified.then_some(()).ok_or_else(|| unavailable.into()) +} + // Provider-local errors, never a new persisted or caller-facing vocabulary. #[derive(Debug, PartialEq)] enum InstallError { @@ -132,6 +176,55 @@ mod tests { builder.into_inner().unwrap().finish().unwrap() } + #[test] + fn only_qualified_preview_can_replace_the_prepared_candidate() { + let root = tempfile::tempdir().unwrap(); + let candidate = root.path().join("candidate"); + let resources = candidate.join("Contents/Resources/runtime"); + fs::create_dir_all(&resources).unwrap(); + let cache = root.path().join("prepared"); + let version = "0.0.0-main.2.1"; + let identity_path = resources.join("identity.json"); + let mut identity = serde_json::json!({ + "schema_version": "desktop_runtime_bundle_v1", + "source_revision": "1111111111111111111111111111111111111111" + }); + let rejected = [ + None, + Some(serde_json::json!({"surface": "unknown"})), + Some(serde_json::json!({ + "surface": "complete_turn", + "schema_version": "loopx_turn_envelope_v1", + "interaction_schema_version": "loopx_interaction_contract_v0" + })), + ]; + for contract in rejected { + if let Some(contract) = contract { + identity["default_contract"] = contract; + } + fs::write(&identity_path, identity.to_string()).unwrap(); + let bytes = archive(&candidate); + assert_eq!( + crate::prepared_update::save(&cache, "main", version, "unused", &bytes), + Err("update_platform_unavailable".into()) + ); + assert!(!cache.exists()); + assert_eq!( + qualify_candidate("stable", version, &bytes), + Err("update_platform_unavailable".into()) + ); + assert!(qualify_candidate("stable", "2.3.0", &bytes).is_ok()); + } + + identity["default_contract"] = serde_json::from_str(PUBLIC_DEFAULT_CONTRACT).unwrap(); + fs::write(identity_path, identity.to_string()).unwrap(); + let bytes = archive(&candidate); + crate::prepared_update::save(&cache, "main", version, "unused", &bytes).unwrap(); + let pointer = fs::read(cache.join("prepared.json")).unwrap(); + assert!(crate::prepared_update::save(&cache, "main", version, "unused", b"bad").is_err()); + assert_eq!(fs::read(cache.join("prepared.json")).unwrap(), pointer); + } + #[test] fn verified_candidate_replaces_app_and_retains_intact_previous_bundle() { let root = tempfile::tempdir().unwrap(); diff --git a/apps/desktop/loopx-control-plane/src-tauri/src/maintenance.rs b/apps/desktop/loopx-control-plane/src-tauri/src/maintenance.rs index 09b438f266..e94f056365 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/maintenance.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/maintenance.rs @@ -896,14 +896,27 @@ async fn perform( let bytes = if let Some(cached) = cached { cached.bytes } else { - download_update(&update, |chunk, total| { + let bytes = download_update(&update, |chunk, total| { received += chunk as u64; state.publish( "downloading", json!({"received":received,"total":total,"version":update.version}), ); }) - .await? + .await?; + #[cfg(target_os = "macos")] + { + let version = update.version.clone(); + let channel = channel.to_owned(); + tauri::async_runtime::spawn_blocking(move || { + crate::macos_update::qualify_candidate(&channel, &version, &bytes)?; + Ok::<_, String>(bytes) + }) + .await + .map_err(|_| "runtime_bundle_invalid".to_string())?? + } + #[cfg(not(target_os = "macos"))] + bytes }; let target = update.version.clone(); install_verified_app(app, target, move || { diff --git a/apps/desktop/loopx-control-plane/src-tauri/src/prepared_update.rs b/apps/desktop/loopx-control-plane/src-tauri/src/prepared_update.rs index 2085a3ba7a..07e596e2a1 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/prepared_update.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/prepared_update.rs @@ -75,6 +75,8 @@ pub(crate) fn save( if !matches!(channel, "main" | "stable") || semver::Version::parse(version).is_err() { return Err(INVALID.into()); } + #[cfg(target_os = "macos")] + crate::macos_update::qualify_candidate(channel, version, bytes)?; fs::create_dir_all(root).map_err(|_| INVALID)?; let old = metadata(root).ok().flatten(); let value = json!({"schema_version":"desktop_prepared_update_v1", "channel":channel, @@ -156,6 +158,8 @@ fn read( let signature = Signature::decode(std::str::from_utf8(&signature).map_err(|_| INVALID)?) .map_err(|_| INVALID)?; key.verify(&bytes, &signature, true).map_err(|_| INVALID)?; + #[cfg(target_os = "macos")] + crate::macos_update::qualify_candidate(channel, version, &bytes)?; Ok(Some(PreparedUpdate { version: version.into(), signature: value["signature"].as_str().ok_or(INVALID)?.into(), diff --git a/apps/presentation/dashboard/smoke/research-evidence-version-browser-smoke.mjs b/apps/presentation/dashboard/smoke/research-evidence-version-browser-smoke.mjs index 69d8220693..61921dc2c8 100644 --- a/apps/presentation/dashboard/smoke/research-evidence-version-browser-smoke.mjs +++ b/apps/presentation/dashboard/smoke/research-evidence-version-browser-smoke.mjs @@ -103,14 +103,19 @@ try { localizedReady = false; const child = JSON.parse(await readFile(resolve(import.meta.dirname, "../src/data/fixtures/case-study-child.json"), "utf8")); const parent = {goal_id: child.parent_goal_id, display_name: "Benchmark", events: [], analyses: []}; + const recordsOnly = structuredClone(child.analyses[0]); + recordsOnly.title = "仅保留研究记录的版本"; + delete recordsOnly.case_study; const second = structuredClone(child.analyses[0]); second.title = "另一版解读"; + second.case_study.title = "修订版:误差与留存证据"; second.case_study.sections[1].citations[0].first_line = 2; - child.analyses.push(second); + child.analyses.push(recordsOnly, second); const study = await start("study", child, parent); const studyRead = await (await fetch(new URL(analysisPath + "?" + new URLSearchParams({goal_id: child.goal_id}), study))).json(); const studyPack = studyRead.pack; - const otherPack = studyRead.catalog.packs.find(pack => pack.pack_id !== studyPack.pack_id); + const otherPack = studyRead.catalog.packs.find(pack => pack.pack_id !== studyPack.pack_id && pack.case_study_summary); + const recordsPack = studyRead.catalog.packs.find(pack => !pack.case_study_summary); assert(otherPack, "Same Goal has two saved versions"); const chapter = studyPack.case_study.sections[1]; const address = new URL("/chat/", study); @@ -229,6 +234,117 @@ try { await page.goForward(); await page.waitForURL(url => url.searchParams.get("goalId") === parent.goal_id); assertParentAddress(); + + // Pinning the default study to its chapter address rereads the same version. + // Its late response must respect the focus returned by the evidence reader. + const defaultStudy = new URL(address); + defaultStudy.searchParams.delete("research_pack"); + defaultStudy.searchParams.delete("research_analysis_goal"); + defaultStudy.hash = ""; + await page.goto(defaultStudy.href); + await page.setViewportSize({width: 390, height: 900}); + await chapterControl.locator("summary").waitFor(); + const isSelectedVersionRead = url => url.origin === defaultStudy.origin && url.pathname === analysisPath + && url.searchParams.get("pack_id") === studyPack.pack_id; + const isLocalizedRead = url => isSelectedVersionRead(url) && url.searchParams.has("output_language"); + const stagedRead = Promise.withResolvers(); + await page.route(isLocalizedRead, async route => { + await stagedRead.promise; + return route.continue(); + }, {times: 1}); + try { + const selectedVersionRequest = page.waitForRequest(request => isLocalizedRead(new URL(request.url()))); + await page.getByRole("navigation", {name: "解读目录"}).getByRole("link").nth(1).press("Enter"); + await selectedVersionRequest; + await atChapter(); + await chapterControl.locator("summary").press("Enter"); + await originalLink.press("Enter"); + await citation.locator("pre").first().waitFor(); + await citation.press("Escape"); + await page.waitForFunction(id => document.activeElement?.id === id, bookmark.hash.slice(1)); + const savedOriginalRead = page.waitForResponse(response => { + const url = new URL(response.url()); + return response.ok() && isSelectedVersionRead(url) && !url.searchParams.has("output_language"); + }); + stagedRead.resolve(); + await (await savedOriginalRead).finished(); + await page.evaluate(() => new Promise(resolvePaint => requestAnimationFrame(() => requestAnimationFrame(resolvePaint)))); + assert.equal(await originalLink.evaluate(link => document.activeElement === link), true, + "A delayed reread of the selected version must leave focus on the citation after closing it"); + assert.equal(new URL(page.url()).hash, address.hash); + } finally { + stagedRead.resolve(); + await page.unroute(isLocalizedRead); + } + await page.setViewportSize({width: 1200, height: 900}); + + // A saved case address is never rewritten to a nearby version. Recover + // explicitly with the owner's version selector or default catalogue read. + const metrics = async () => (await fetch(new URL("/fixture/readback", study))).json(); + const beforeRecovery = await metrics(); + const caseHistoryReads = []; + const observeCaseHistory = request => { + const url = new URL(request.url()); + if (url.pathname === "/api/chat/explore-results" && url.searchParams.get("goal_id") === child.goal_id + && url.searchParams.get("view") === "history") caseHistoryReads.push(url.search); + }; + page.on("request", observeCaseHistory); + const versionWithoutStudy = new URL(address); + versionWithoutStudy.searchParams.set("research_pack", recordsPack.pack_id); + const versionOnly = new URL(versionWithoutStudy); + versionOnly.hash = ""; + await page.goto(versionOnly.href); + await page.getByText("此版本没有已保存的案例解读。", {exact: true}).waitFor({timeout: 6000}); + assert.equal(new URL(page.url()).searchParams.get("research_pack"), recordsPack.pack_id); + await page.goto(versionWithoutStudy.href); + await page.getByText("此版本没有已保存的案例解读。", {exact: true}).waitFor({timeout: 6000}); + assert.equal(new URL(page.url()).searchParams.get("research_pack"), recordsPack.pack_id); + assert.equal(new URL(page.url()).hash, address.hash); + assert.equal(await page.locator(".case-opening h2").count(), 0); + await page.getByRole("combobox", {name: "选择解读版本"}).selectOption(otherPack.pack_id); + await page.locator(".case-opening h2").waitFor(); + assert.equal(new URL(page.url()).searchParams.get("research_pack"), otherPack.pack_id); + assert.equal(await page.locator(".case-opening h2").textContent(), otherPack.case_study_summary.title); + await page.goBack(); + await page.getByText("此版本没有已保存的案例解读。", {exact: true}).waitFor(); + assert.equal(new URL(page.url()).hash, address.hash); + + await page.setViewportSize({width: 390, height: 900}); + const unavailable = new URL(bookmark); + unavailable.searchParams.set("research_pack", "f".repeat(64)); + await page.goto(unavailable.href); + await page.getByText("无法读取链接指定的解读。", {exact: true}).waitFor(); + const exactRetry = page.waitForResponse(response => { + const url = new URL(response.url()); + return url.pathname === analysisPath && url.searchParams.get("pack_id") === unavailable.searchParams.get("research_pack"); + }); + await page.getByRole("button", {name: "重试读取", exact: true}).press("Enter"); + assert.equal((await exactRetry).status(), 409); + assert.equal(new URL(page.url()).hash, unavailable.hash); + const browseSaved = page.getByRole("button", {name: "查看已保存的解读", exact: true}); + await browseSaved.press("Enter"); + await page.getByRole("heading", {name: studyPack.case_study.title, exact: true}).waitFor(); + assert.equal(await page.getByRole("combobox", {name: "选择解读版本"}).evaluate(el => el === document.activeElement), true); + assert.equal(new URL(page.url()).searchParams.get("goalId"), child.goal_id); + assert.equal(new URL(page.url()).hash, ""); + await page.goBack(); + await page.getByText("无法读取链接指定的解读。", {exact: true}).waitFor(); + assert.equal(new URL(page.url()).hash, unavailable.hash); + + const absentChapter = new URL(address); + absentChapter.hash = `case-section-${studyPack.pack_id}-absent`; + await page.goto(absentChapter.href); + await page.getByText("这条链接在所选解读中找不到章节。", {exact: false}).waitFor(); + assert.equal(new URL(page.url()).hash, absentChapter.hash); + await page.getByRole("navigation", {name: "解读目录"}).getByRole("link").nth(1).press("Enter"); + await atChapter(); + assert.equal(await page.getByText("这条链接在所选解读中找不到章节。", {exact: false}).count(), 0); + const afterRecovery = await metrics(); + page.off("request", observeCaseHistory); + assert.equal(afterRecovery.citation_reads, beforeRecovery.citation_reads); + assert.deepEqual(caseHistoryReads, [], "Explicit case links do not read the case's research history"); + assert.equal(afterRecovery.mutation_attempts, beforeRecovery.mutation_attempts); + assert.equal(afterRecovery.source_unchanged, true); console.log("research evidence version: study and history navigation, saved excerpts and chapter position restored"); } finally { releaseOriginal?.(); diff --git a/apps/presentation/dashboard/src/data/capability-configuration.ts b/apps/presentation/dashboard/src/data/capability-configuration.ts index 6c61e3d091..0a0469b9ff 100644 --- a/apps/presentation/dashboard/src/data/capability-configuration.ts +++ b/apps/presentation/dashboard/src/data/capability-configuration.ts @@ -127,7 +127,7 @@ export function goalExploreWriteValue(draft: Record, modeOverri return value; } -/** A v0 storage selector did not enable creation; opening Settings must not. */ +/** opening Settings must not. */ export function goalStorageEditorValue(value: unknown): unknown { const record = configurationObject(value); return record.schema_version === "loopx_goal_storage_defaults_v0" diff --git a/apps/presentation/dashboard/src/data/chat.ts b/apps/presentation/dashboard/src/data/chat.ts index c3db5a2c22..451aaebd1e 100644 --- a/apps/presentation/dashboard/src/data/chat.ts +++ b/apps/presentation/dashboard/src/data/chat.ts @@ -470,6 +470,7 @@ export const typedActionProposalSchema = z.object({ validation_evidence: z.array(z.string().refine((value) => value.trim().length > 0, "Validation evidence must be non-blank text")), available_transitions: z.array(z.enum(["apply", "cancel", "regenerate", "reject", "defer"])), status: z.enum(["preview_ready", "applying", "gated", "failed", "rejected", "deferred", "cancelled", "stale", "applied"]), + task_execution_dispatch_pending: z.literal(true).optional(), receipt: z.record(z.string(), z.unknown()).nullable(), stale: z.record(z.string(), z.unknown()).nullable(), gate: z.record(z.string(), z.unknown()).nullable().optional(), diff --git a/apps/presentation/dashboard/src/data/status.ts b/apps/presentation/dashboard/src/data/status.ts index b79f89b55d..4c778ac672 100644 --- a/apps/presentation/dashboard/src/data/status.ts +++ b/apps/presentation/dashboard/src/data/status.ts @@ -606,8 +606,7 @@ export const runGoalSchema = z.object({ turn_started_at: z.string().optional().nullable(), last_turn_ended_at: z.string().optional().nullable(), last_event_at: z.string().optional().nullable(), - // This is cadence evidence about observed host activity, not proof that - // a scheduled prompt was delivered or an agent started. + delivery_window: z.object({ schema_version: z.string().optional(), state: z.enum(["fresh", "stale", "missing", "unknown"]).catch("unknown"), diff --git a/apps/presentation/dashboard/src/data/use-lark-apps.ts b/apps/presentation/dashboard/src/data/use-lark-apps.ts index 82d58d3bbe..55e41a3476 100644 --- a/apps/presentation/dashboard/src/data/use-lark-apps.ts +++ b/apps/presentation/dashboard/src/data/use-lark-apps.ts @@ -21,7 +21,7 @@ export function useLarkApps() { if (!active()) return; setApps(profiles); let next = 0; - // A slow profile neither holds the catalog nor other profile results. + const worker = async () => { while (active() && next < profiles.length) { const profile = profiles[next++]; diff --git a/apps/presentation/dashboard/src/data/workspace-progressive-status.ts b/apps/presentation/dashboard/src/data/workspace-progressive-status.ts index 5c771f0df4..4378a86d4e 100644 --- a/apps/presentation/dashboard/src/data/workspace-progressive-status.ts +++ b/apps/presentation/dashboard/src/data/workspace-progressive-status.ts @@ -49,10 +49,9 @@ export function scopeWorkspaceDirectory( /** * Snapshots a same-source read may keep visible while it reconciles. - * * A directory entry is the cheap authoritative signal for "this Goal's - * lifecycle did not move here". It does not establish Todo freshness: a full - * refresh still re-reads retained Goals. A partial retry or known action may + * lifecycle did not move here". + * A partial retry or known action may * skip unaffected peers. Touched Goals and entries that moved or left the * directory lose their snapshot. */ diff --git a/apps/presentation/dashboard/src/features/personal-workspace/attached-conversation-record.tsx b/apps/presentation/dashboard/src/features/personal-workspace/attached-conversation-record.tsx index 129b1d6d56..d51dbd6365 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/attached-conversation-record.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/attached-conversation-record.tsx @@ -6,7 +6,7 @@ export type ConversationRecord = { id: string; end: number; role: "user" | "assistant" | "tool" | "activity"; kind: string; label: string; text: string; truncated: boolean; timestamp?: string | null; content_ref?: string; redacted?: boolean; unavailable?: string; - /** Saved shell observations only; neither inferred failures nor task acceptance. */ + /** Saved shell observations only; */ tool_exit_codes?: number[]; }; export type ContentPage = {text: string; next_offset: number; has_more: boolean}; diff --git a/apps/presentation/dashboard/src/features/personal-workspace/capability-localization.ts b/apps/presentation/dashboard/src/features/personal-workspace/capability-localization.ts index bb4d4f76dc..3e21cefefd 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/capability-localization.ts +++ b/apps/presentation/dashboard/src/features/personal-workspace/capability-localization.ts @@ -25,6 +25,10 @@ const capabilityCopy: Record> = { displayName: "Model and executor", description: "Guides the steward executor, model, and selection boundary for this machine. A pinned route blocks substitution; a flexible pool permits only authorized fallback.", }, + steward_memory: { + displayName: "Isolated OpenViking memory", + description: "Connects owner private steward conversations to an isolated OpenViking memory namespace with per-speaker preferences and bounded recall.", + }, todo_replan_cadence: { displayName: "Goal review and stride", description: "Set review frequency and optionally choose a versioned stride strategy for work scope and route changes." }, change_quality_qualification: { displayName: "Change quality qualification", @@ -95,6 +99,10 @@ const capabilityCopy: Record> = { displayName: "模型与执行器", description: "配置本机管家的执行器、模型与选择边界;锁定路径禁止替代,灵活池只允许在已授权范围内回退。", }, + steward_memory: { + displayName: "独立 OpenViking 长期记忆", + description: "为本人私聊管家启用独立身份的 OpenViking 记忆命名空间:按已验证发言人持久化偏好、跨会话按需检索并限制超时,不向群聊或工作 Agent 泄露。", + }, todo_replan_cadence: { displayName: "Goal 复盘与步幅", description: "设置复盘周期,可选用带版本的步幅策略,调节工作大小与路线变化。" }, change_quality_qualification: { displayName: "变更质量验证", @@ -164,6 +172,9 @@ const fieldCopy: Record = { eligible_endpoints: { label: "Flexible eligible executors", description: "One authorized executor per line. Use only with flexible selection and include the primary executor." }, executor_model: { label: "Model", description: "Optional model for the selected executor. Leave blank to keep the executor's own default." }, executor_reasoning_effort: { label: "Reasoning effort", description: "Optional reasoning effort for the selected executor. Leave blank to keep the executor's own default." }, + user_space: { label: "User space", description: "OpenViking user space isolating steward memory on this machine." }, + auto_recall: { label: "Auto recall history", description: "Search past steward events automatically on substantive private messages." }, + recall_timeout_seconds: { label: "Recall timeout (seconds)", description: "Wait budget (1–15s) before continuing without recalled memory." }, count_unit: { label: "Review after", description: "Work Turns require accepted settlement; polls and retries do not count.", options: { completed_todos: "Completed Todos", effective_turns: "Settled work Turns" } }, planning_horizon_goal: { label: "Show Goal in planning horizon", description: "Default on. Keep the original Goal and acceptance visible before choosing work. Turn off for rollback or comparisons; replan, stride and execution authority are unchanged." }, yardstick_enabled: { label: "Review measurement criteria", description: "Default off. Review measurement scope and feedback using available Explore evidence. Requires Explore evidence; does not enable it or authorize execution." }, @@ -202,6 +213,9 @@ const fieldCopy: Record = { eligible_endpoints: { label: "灵活池可用执行器", description: "每行一个已授权执行器,仅用于 flexible;必须包含首选执行器。" }, executor_model: { label: "模型", description: "所选执行器使用的模型,可留空;留空表示沿用执行器自身的默认模型。" }, executor_reasoning_effort: { label: "推理档位", description: "所选执行器使用的推理档位,可留空;留空表示沿用执行器自身的默认档位。" }, + user_space: { label: "记忆用户空间", description: "本机管家在 OpenViking 中隔离使用的 user space 标识。" }, + auto_recall: { label: "跨会话自动召回", description: "收到非命令的实质私聊消息时,执行一次有界历史事件检索。" }, + recall_timeout_seconds: { label: "召回超时(秒)", description: "等待记忆读取的上限(1–15 秒);超时后跳过记忆直接恢复正常回复。" }, count_unit: { label: "复核计数依据", description: "有效工作 Turn 须完成结算;轮询和重复重试不计数。", options: { completed_todos: "已完成 Todo", effective_turns: "已结算工作 Turn" } }, planning_horizon_goal: { label: "在规划视野中显示 Goal", description: "默认开启,选择工作前可见原目标与验收要求。可为回滚或对照实验关闭;不改变复盘、步幅策略或执行权限。" }, yardstick_enabled: { label: "复核衡量标准", description: "默认关闭。使用已有 Explore 证据复核测量范围与反馈;需有可用的 Explore 证据,不会自动启用它或授予执行权限。" }, @@ -280,6 +294,11 @@ export function localizedCapabilityFieldCopy(locale: WorkspaceLocale, capability label: "Exploration mode", description: "Planning includes the evidence graph; worker and execution permissions remain separate.", options: {off: "Off", evidence: "Evidence only", planning: "Evidence and planning"}, }}; + if (capabilityId === "steward_memory") return {...fieldCopy[locale], enabled: locale === "zh-CN" ? { + label: "启用", description: "为本人私聊管家开启独立 OpenViking 长期记忆。", + } : { + label: "Enabled", description: "Enable isolated OpenViking long-term memory for owner private steward conversations.", + }}; return fieldCopy[locale]; } diff --git a/apps/presentation/dashboard/src/features/personal-workspace/context-drawer.tsx b/apps/presentation/dashboard/src/features/personal-workspace/context-drawer.tsx index 1ee6ce52e3..e4364606f6 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/context-drawer.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/context-drawer.tsx @@ -1231,7 +1231,9 @@ export function ContextDrawer({ agents, attentionHistory = [], onSelectAttention

{selection.item.title}

{selection.item.todoId && (selection.item.actionKind === "gate.resolve" || selection.item.actionKind === "todo.update") ?
: null} - {selection.item.impact ?

{selection.item.impact}

: null} + {selection.item.reviewPlan?.retryOriginal && selection.item.errorMessage + ?

{selection.item.errorMessage}

+ : selection.item.impact ?

{selection.item.impact}

: null} {selection.item.reviewPlan && !selection.item.reviewPlan.creationExecution && !selection.item.reviewPlan.retryOriginal && !taskExecution && selection.item.actionKind !== "team.plan" && !(decisionFrame && ["ready", "applied"].includes(selection.item.status)) ?

{operationUnknown ? t("actionReview.operation_reconcile_original") : selection.item.reviewPlan.operationFrame?.kind === "inactive" diff --git a/apps/presentation/dashboard/src/features/personal-workspace/goal-activity.ts b/apps/presentation/dashboard/src/features/personal-workspace/goal-activity.ts index ea1b2eabe5..3f922c18db 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/goal-activity.ts +++ b/apps/presentation/dashboard/src/features/personal-workspace/goal-activity.ts @@ -156,7 +156,7 @@ export function goalHostSurfaces(goal: Pick) { const observation = goal.hostThreadActivity; diff --git a/apps/presentation/dashboard/src/features/personal-workspace/goal-research-analysis.tsx b/apps/presentation/dashboard/src/features/personal-workspace/goal-research-analysis.tsx index 072a88d214..60c4689388 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/goal-research-analysis.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/goal-research-analysis.tsx @@ -314,7 +314,7 @@ export function useResearchAnalysis(goalId: string, active: boolean, zh: boolean requestAnimationFrame(() => {if (closedAt === citeGeneration.current) origin?.focus();}); }; return {readOnly: currentSnapshot?.execution_enabled === false || (Boolean(readSourceUrl) && currentSnapshot?.execution_enabled !== true), sourceScope, readUsageComparison, citation, citationBusy, citationError, sourcePanel, readCitation, readUsageTurn, retryCitation, closeCitation, onCitationLocationChange, goalId, zh, location, snapshot: currentSnapshot, pack: readingPack, requestPack: pack, savedOriginal, readError, error, loading, pending, cancelPending, recordedRunning, panel, trigger, read, show, execute, cancel, - studyNavigation, close: () => {invalidateCitation(); navigate(false); requestAnimationFrame(() => trigger.current?.focus());}, select: (id: string) => navigate(location.open, id, true)}; + studyNavigation, close: () => {invalidateCitation(); navigate(false); requestAnimationFrame(() => trigger.current?.focus());}, select: (id: string | null) => navigate(location.open, id, true)}; } type Controller = ReturnType; @@ -385,14 +385,18 @@ function AnalysisContinuation({pack: p, analysis: a}: {pack: Pack; analysis: Con ; } -function AnalysisReadState({analysis: a}: {analysis: Controller}) { +function AnalysisReadState({analysis: a, onBrowseStudies}: {analysis: Controller; onBrowseStudies?: () => void}) { const error = a.readError || a.snapshot?.originalReadError; if (error) return

{a.snapshot?.originalReadError && !a.readError ? {a.zh ? "已保存原文暂不可读,当前语言的分析状态仍保留。" : "The saved original could not be read. The current language’s analysis state is preserved."} : - {a.pack ? (a.zh ? "刷新失败,保留上次结果。" : "Refresh failed. Showing the last result.") + {onBrowseStudies ? (a.zh ? "无法读取链接指定的解读。" : "The linked study version could not be read.") + : a.pack ? (a.zh ? "刷新失败,保留上次结果。" : "Refresh failed. Showing the last result.") : (a.zh ? "暂时无法读取分析。" : "Analysis could not be read.")}} + {onBrowseStudies ? : null}

{error}

; if (!a.pack && a.loading && (!a.snapshot || a.snapshot.catalog.packs.length > 0)) return
@@ -419,24 +423,38 @@ export function ResearchReportSummary({analysis: a}: {analysis: Controller}) { } export function ResearchCaseReading({analysis: a, active}: {analysis: Controller; active: boolean}) { + const reader = useRef(null); + const focusAfterBrowse = useRef(false); const packs = (a.snapshot?.catalog.packs ?? []).filter(p => p.case_study_summary); const p = a.pack; const firstStudy = packs[0]?.pack_id; useEffect(() => { - const hash = window.location.hash; - if (!a.loading && !a.readError && p && !p.case_study && firstStudy - && !(hash.startsWith(caseChapterHashPrefix) && hash.includes("~"))) a.select(firstStudy); - }, [a.loading, a.readError, p?.pack_id, Boolean(p?.case_study), firstStudy]); - return
+ if (!a.loading && !a.readError && a.location.packId === null && p && !p.case_study && firstStudy + && !window.location.hash.startsWith(caseChapterHashPrefix)) a.select(firstStudy); + }, [a.loading, a.readError, a.location.packId, p?.pack_id, Boolean(p?.case_study), firstStudy]); + useLayoutEffect(() => { + if (!focusAfterBrowse.current || a.loading || (!p?.case_study && !a.readError)) return; + focusAfterBrowse.current = false; + if (document.activeElement === document.body) { + reader.current?.querySelector("select, h2, .analysis-read-error button")?.focus({preventScroll: true}); + } + }, [a.loading, a.readError, Boolean(p?.case_study)]); + const browseStudies = a.readError && !p && a.location.packId !== null ? () => { + focusAfterBrowse.current = true; + a.select(null); + } : undefined; + return
{packs.length > 1 || (packs.length === 1 && !p?.case_study) ?
: null} - + {p?.case_study ? : !a.loading && !a.readError ?

{a.zh ? "选择一份解读,阅读问题背景、策略差异、关键转折与证据。" : "Choose a study to read its background, approaches, turning points and evidence."}

: null} + onCitationLocationChange={a.onCitationLocationChange}/> : !a.loading && !a.readError && p ?

+ {a.zh ? "此版本没有已保存的案例解读。" : "This version has no saved case study."} +

: null}
; } diff --git a/apps/presentation/dashboard/src/features/personal-workspace/goal-research-history.tsx b/apps/presentation/dashboard/src/features/personal-workspace/goal-research-history.tsx index 3b2ff20e73..7bb83d289b 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/goal-research-history.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/goal-research-history.tsx @@ -68,10 +68,11 @@ export function GoalResearchHistory({goalId, originalGoalId = goalId, preferHist const requestedCase = caseMode.goalId === goalId ? caseMode.requested : null; const caseReading = requestedCase ?? !preferHistory; const hasCases = (analysis.snapshot?.catalog.packs ?? []).some(pack => pack.case_study_summary); - // Preserve the saved reading during catalogue loading or failure. A - // successful catalogue without a study falls back to the original history. + // A link to a particular version stays in the case reader even when that + // version has no study. An unpinned visit can fall back to ordinary history. const awaitingRequestedCase = requestedCase === true && (analysis.loading || Boolean(analysis.readError)); - const deferHistory = requestedCase === true && (hasCases || awaitingRequestedCase); + const caseViewAvailable = hasCases || awaitingRequestedCase || (requestedCase === true && analysis.location.packId !== null); + const deferHistory = requestedCase === true && caseViewAvailable; const historySource = JSON.stringify([goalId, originalGoalId, readSourceUrl]); const [openedHistorySource, setOpenedHistorySource] = useState(null); const readHistory = active && (!deferHistory || openedHistorySource === historySource); @@ -530,13 +531,13 @@ export function GoalResearchHistory({goalId, originalGoalId = goalId, preferHist : null; const emptyHistoryMessage = zh ? "这个 Goal 尚无研究历程" : "No research history for this Goal yet"; const selectedStrategy = hasNativeSource && !emptySourceHistory ? strategies.selection : null; - const readingCase = caseReading && (hasCases || awaitingRequestedCase) && (requestedCase === true || selectedStrategy === null); + const readingCase = caseReading && caseViewAvailable && (requestedCase === true || selectedStrategy === null); const alternateReading = readingCase ? : selectedStrategy !== null ? strategies.choose(null)}/> : null; return <> - {hasCases || awaitingRequestedCase ?
+ {caseViewAvailable ?
diff --git a/apps/presentation/dashboard/src/features/personal-workspace/goal-storage-settings.tsx b/apps/presentation/dashboard/src/features/personal-workspace/goal-storage-settings.tsx index e056f50eaf..1d59971ac7 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/goal-storage-settings.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/goal-storage-settings.tsx @@ -4,7 +4,7 @@ import {discardGoalStorage, fetchGoalStorage, previewGoalStorage, recoverGoalSto import {useWorkspaceI18n} from "./i18n"; /** Restore opaque intent from the owning server across native origin changes. - * Neither that carrier nor cached source facts replace current source checks. */ + * */ export function GoalStorageSettings({goalId, onChanged}: {goalId: string; onChanged: () => void}) { const {t} = useWorkspaceI18n(); const key = `loopx-storage-preview:${goalId}`; diff --git a/apps/presentation/dashboard/src/features/personal-workspace/machine-configuration-settings.tsx b/apps/presentation/dashboard/src/features/personal-workspace/machine-configuration-settings.tsx index 20730ae91d..0d8c7d1042 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/machine-configuration-settings.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/machine-configuration-settings.tsx @@ -135,8 +135,8 @@ export function MachineConfigurationSettings({ section, onChanged }: { (inspection?.capability_catalog.capabilities ?? []).filter((capability) => capability.available_scopes.includes("machine") && (section === "conversation" ? capability.capability_id === "codex_chat" : section === "steward" - ? capability.capability_id === "steward_executor" || capability.capability_id === "manager_runtime" - : capability.capability_id !== "steward_executor" && capability.capability_id !== "manager_runtime" && capability.capability_id !== "codex_chat")), + ? capability.capability_id === "steward_executor" || capability.capability_id === "manager_runtime" || capability.capability_id === "steward_memory" + : capability.capability_id !== "steward_executor" && capability.capability_id !== "manager_runtime" && capability.capability_id !== "steward_memory" && capability.capability_id !== "codex_chat")), locale, ), [inspection, locale, section]); const invalidNamespace = inspection?.invalid_namespaces[0]; @@ -526,6 +526,15 @@ export function MachineConfigurationSettings({ section, onChanged }: {
) : null} + {selected.capability_id === "steward_memory" ? ( +
+ +
{locale === "zh-CN" ? "仅限本人私聊与独立身份" : "Owner private chats only"}

{locale === "zh-CN" + ? "连接信息读取自本机管家私有文件,不在此表单收集;记忆按已验证发言人隔离保存,超时不阻塞正常回复,也不会进入群聊或转交给工作 Agent。" + : "Connection settings stay in the private local steward file outside this form. Memory stays isolated per verified speaker, fails open on timeout, and never enters group chats or worker handoffs."}

+
+ ) : null} + {selected.capability_id === "pull_request_review" ? (
diff --git a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-contract.test.mjs b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-contract.test.mjs index 0fdc7b1162..cf2ed749d0 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-contract.test.mjs +++ b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-contract.test.mjs @@ -502,11 +502,12 @@ for (const capabilityId of [ "pull_request_review", "reward_memory", "steward_executor", + "steward_memory", ]) { const matches = capabilityLocalization.match(new RegExp(`${capabilityId}:`, "g")) ?? []; assert.equal(matches.length, 2, `${capabilityId} has English and Simplified Chinese metadata`); } -for (const fieldKey of ["agent_orders", "allowed_domains", "coordinator_agent_id", "eligible_endpoints", "enabled", "executor_endpoint", "executor_model", "executor_reasoning_effort", "max_children", "profile", "profile_preset", "review_order", "route_ref", "safe_fix", "selection_policy", "strict_receipt", "timezone"]) { +for (const fieldKey of ["agent_orders", "allowed_domains", "auto_recall", "coordinator_agent_id", "eligible_endpoints", "enabled", "executor_endpoint", "executor_model", "executor_reasoning_effort", "max_children", "profile", "profile_preset", "recall_timeout_seconds", "review_order", "route_ref", "safe_fix", "selection_policy", "strict_receipt", "timezone", "user_space"]) { const matches = capabilityLocalization.match(new RegExp(`^\\s+${fieldKey}:`, "gm")) ?? []; assert.equal(matches.length, 2, `${fieldKey} has English and Simplified Chinese field copy`); } diff --git a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx index 94e96ece80..66f5c99f70 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx @@ -1832,10 +1832,21 @@ export function PersonalWorkspacePage({ // not have a Turn to revisit. .filter(proposal => proposal.actionKind !== "todo.create" || proposal.status !== "applied" || Boolean(proposal.reviewPlan?.taskExecution)); - const restored = Object.fromEntries(restoreable.map((proposal) => [proposal.previewId, proposal])); const previousIds = restoredProposalIdsRef.current; - restoredProposalIdsRef.current = new Set(Object.keys(restored)); - setProposals((current) => ({...Object.fromEntries(Object.entries(current).filter(([id]) => !previousIds.has(id))), ...restored})); + restoredProposalIdsRef.current = new Set(restoreable.map(proposal => proposal.previewId)); + setProposals((current) => { + const next = Object.fromEntries(Object.entries(current).filter(([id]) => !previousIds.has(id))); + for (const proposal of restoreable) { + const previous = current[proposal.previewId]; + // The stored confirmation outlives a failed dispatch attempt. + // Keep the local reason until readback observes a different confirmation. + const retryError = proposal.reviewPlan?.retryOriginal && previous?.reviewPlan?.retryOriginal + && previous.actionKind === proposal.actionKind && previous.goalId === proposal.goalId + && previous.updatedAt === proposal.updatedAt ? previous.errorMessage : undefined; + next[proposal.previewId] = retryError ? { ...proposal, errorMessage: retryError } : proposal; + } + return next; + }); // The manager conversation shows the cards this channel offered: a team // plan the steward proposed from here is confirmed here, instead of the // owner hunting for the Goal whose workspace happens to hold the card. @@ -2140,7 +2151,7 @@ export function PersonalWorkspacePage({ : null; const lifecycleChange = options.lifecycleProjection ?? inferredLifecycleChange; setActionFeedback(t("feedback.applying", { title: proposal.title })); - const applying = { ...proposal, reviewPlan: proposal.reviewPlan ? { ...proposal.reviewPlan, interaction: "pending" as const, reason: "apply_pending" as const, canApply: false as const } : undefined, status: "applying" as const }; + const applying = { ...proposal, errorMessage: undefined, reviewPlan: proposal.reviewPlan ? { ...proposal.reviewPlan, interaction: "pending" as const, reason: "apply_pending" as const, canApply: false as const } : undefined, status: "applying" as const }; setProposals((current) => ({ ...current, [proposal.previewId]: applying })); if (showDrawer) setSelection({ item: applying, kind: "proposal" }); let applyingSelection = selectionRevision.current; diff --git a/apps/presentation/dashboard/src/features/personal-workspace/research-case-study.tsx b/apps/presentation/dashboard/src/features/personal-workspace/research-case-study.tsx index 4487639894..35ab8f6e18 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/research-case-study.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/research-case-study.tsx @@ -62,11 +62,15 @@ export function ResearchCaseStudy({study, zh, historical, active, scope, navigat onCitationLocationChange: (hash: string) => void; }) { const article = useRef(null); + const currentStudy = useRef(study); + currentStudy.current = study; const openCitation = useRef(onCitation); openCitation.current = onCitation; - const [missingCitation, setMissingCitation] = useState(false); + const [missingAnchor, setMissingAnchor] = useState(""); const {url, goalId, packId, namespace, follow} = navigation; const prefix = `${caseChapterHashPrefix.slice(1)}${namespace ? namespace + '-' : ''}${packId}-`; + // A reread can replace the study object while the saved version and address + // stay the same. Only navigation should run chapter and citation restoration. useEffect(() => { if (!active) return; let frame = 0; @@ -85,23 +89,27 @@ export function ResearchCaseStudy({study, zh, historical, active, scope, navigat // into a source identifier or range for the evidence API. const match = scoped ? /^([a-zA-Z0-9_-]*)~([1-9][0-9]?)$/.exec(hash.slice(prefix.length + 1)) : null; const section = match?.[1]; - const citations = section ? study.sections.find(item => item.id === section)?.citations : study.citations; + const savedStudy = currentStudy.current; + const citations = section ? savedStudy.sections.find(item => item.id === section)?.citations : savedStudy.citations; const citation = match ? citations?.[Number(match[2]) - 1] : undefined; const origin = document.getElementById(hash.slice(1)); if (!citation || !origin || !article.current?.contains(origin)) { - setMissingCitation(true); + setMissingAnchor(hash); return; } - setMissingCitation(false); + setMissingAnchor(""); const disclosure = origin.closest('details'); if (disclosure) disclosure.open = true; openCitation.current(citation, origin, {hash, chapterHash: section ? `#${prefix}${section}` : ""}); return; } - setMissingCitation(false); - if (!scoped) return; - const chapter = document.getElementById(hash.slice(1)); - if (chapter && article.current?.contains(chapter) && chapter.getClientRects().length) focusChapter(chapter); + const chapter = scoped ? document.getElementById(hash.slice(1)) : null; + if (chapter && article.current?.contains(chapter) && chapter.getClientRects().length) { + setMissingAnchor(""); + focusChapter(chapter); + } else { + setMissingAnchor(hash.startsWith(caseChapterHashPrefix) ? hash : ""); + } }); }; restore(); @@ -112,7 +120,7 @@ export function ResearchCaseStudy({study, zh, historical, active, scope, navigat window.removeEventListener('popstate', restore); window.removeEventListener('hashchange', restore); }; - }, [active, goalId, packId, prefix, study, onCitationLocationChange]); + }, [active, goalId, packId, prefix, onCitationLocationChange]); const citationLinks = (citations: AssessmentCitation[], section = "") =>