diff --git a/docs/superpowers/specs/2026-09-07-terminal-agent-lifecycle-gold-standard.md b/docs/superpowers/specs/2026-09-07-terminal-agent-lifecycle-gold-standard.md index 7ef9ef512..e90cf232a 100644 --- a/docs/superpowers/specs/2026-09-07-terminal-agent-lifecycle-gold-standard.md +++ b/docs/superpowers/specs/2026-09-07-terminal-agent-lifecycle-gold-standard.md @@ -33,7 +33,7 @@ - **输入策略**沿用 `shared/agent-catalog.ts`,能力字段定义于 `shared/agent-surfaces/initial-prompts.ts`,解析及验证在 `services/agents/initial-prompt.ts`。最终执行核验过的绝对路径;任务文本在解析基础命令之后按单个字面参数附加。逻辑恢复命令不携带首条任务。 - **草稿**唯一写入方是 `main/state/terminal-drafts/`,文件为 userData 下的 `terminal-unsent-drafts.json`。按窗口记录 UUID 与面板 ID 索引,原子写入、0600 权限、修订号 CAS。保存文本、编辑器快照和附件引用/必要元数据,不保存模型输出或对话台账。 - **renderer**镜像 main 草稿。内容比较使用 `terminalDraftCompositionKey`,避免 IPC 字段顺序变化引发重复保存。附件操作在打开选择器/开始粘贴时登记完整 Promise;包括多图片和末尾文本。转移/退出的 flush 即使命中正在保存的请求,也重新越过附件等待屏障。 -- **转移**使用现有 `panel-transfer` 服务:原生终端、进程记录、任务回调和输出所有权在第一个异步边界前同步迁移,随后原子迁移会话与草稿;回滚使用对应补偿。没有增加转移数据库。 +- **转移**使用现有 `panel-transfer` 服务:原生终端、进程记录、任务回调和输出所有权在第一个异步边界前同步迁移,随后原子迁移会话与草稿;回滚使用对应补偿。没有增加转移数据库。会话生命周期身份由 `state/terminal-session-identity.ts` 单一提供(任务 `runId`,智能体 `restore.spawnGeneration`,shell 空串),与 `resolveAgentSpawnLifecycle`、原生进程注册表同一映射;`tests/unit/main/terminal/lifecycle/transfer-identity-governance.test.ts` 锁定三者。租约要求实时身份与会话已记录身份一致;没有原生 surface(未创建的恢复卡片)时不比对,但存在原生进程而实时身份为空时拒绝(不能把存活 PTY 当静态卡片)。提交开始前再校验一次租约身份:目标暂存可能跨过重启,身份已变化时不做任何子步骤直接失败,避免补偿把被取代的代际写回源窗口。提交 CAS 始终执行,身份取租约捕获的会话值(物化条目为空串)。智能体退出补丁只丢弃「会话与补丁都已声明且不一致」的代际;未记录代际的历史行接受退出——新创建在原生回调前写入代际,缺失代际不属于存活 surface。 ## 35 个智能体覆盖矩阵 diff --git a/docs/superpowers/specs/2026-11-20-agent-status-config-diagnostic-gold-standard.md b/docs/superpowers/specs/2026-11-20-agent-status-config-diagnostic-gold-standard.md new file mode 100644 index 000000000..8dc671bbc --- /dev/null +++ b/docs/superpowers/specs/2026-11-20-agent-status-config-diagnostic-gold-standard.md @@ -0,0 +1,74 @@ +# 智能体状态配置诊断 — 金标准 + +## 01 触发条件 + +某些智能体允许用户在自己的配置里关掉 Pier 写入的状态集成。以 pi 为例: +`settings.json` 的 `extensions` 覆盖可以用 `-extensions/pier-agent-status.ts` +强制排除托管扩展,排除后 pi 不加载扩展,Pier 收不到状态事件,智能体列表和 +侧栏一直显示为 idle。这个配置决定不经过 Pier,宿主无法自动纠正,只能在设置页 +把事实告诉用户并给出恢复动作。 + +只有同时满足以下条件才提示: + +- 扩展文件存在,且内容是 Pier 托管写入的(`isPierManagedPluginContent`); +- 用户配置可解析,且确实排除了该扩展; +- 只看全局 `settings.json`。项目级覆盖需要项目上下文,设置页没有,宁可少提示, + 也不误报(fail-open)。 + +## 02 展示 + +宿主设置 → 智能体 → 展开某个智能体详情,在版本检查失败提示之后显示一条 +`Alert`(`variant="warning"`,`AlertDescription`)。诊断是当前事实而不是历史, +用户改完智能体配置后应立刻消失。 + +- 只在 `probe.statusHooksDisabledByConfig === true` 时显示。 +- 不新增弹窗、通知中心消息或入口;不提供「帮用户改配置」按钮。 +- 配置诊断只说明状态为什么缺失,不改变安装 / 更新 / 卸载动作。 + +## 03 文案 + +文案说用户看到的现象和下一步,不说「状态集成」这类实现概念: + +- zh-CN:`Pi 现在的设置让 Pier 看不到它的运行状态。运行 pi config 重新开启即可恢复。` +- en:`Pi’s current settings hide its status from Pier. Run pi config to turn it back on.` +- ja:`Pi の現在の設定では Pier に実行状態が表示されません。pi config で再び有効にすると復元されます。` +- ko:`현재 Pi 설정에서는 Pier에 Pi의 실행 상태가 표시되지 않습니다. pi config에서 다시 켜면 복구됩니다.` + +i18n key 是 `settings.agents.row.statusHooksDisabledByConfig`。不得在业务代码里 +内联用户串。 + +**偏离记录**:方案讨论时拟定的文案是「状态集成已在 pi 设置中关闭……」,审阅指出 +「状态集成」是实现词。上文改为用户可见结果(看不到运行状态)+ 恢复动作,满足 +`docs/superpowers/specs/2026-09-09-user-copy-gold-standard.md`。 + +## 04 数据路径 + +- 共享契约:`src/shared/contracts/agent/lifecycle.ts` 的 + `agentLifecycleProbeSchema.statusHooksDisabledByConfig`(可选布尔),随既有 + catalog `details` 下发;不新增 IPC。 +- 读取:`src/main/services/agents/integrations/pi.ts` + `readStatusHooksDisabledByConfig` 负责文件与覆盖语序;分派在 + `src/main/services/agents/integrations/registry.ts` + `readDisabledStatusHooks`,宿主 catalog provider 保持与具体 agent 无关。 +- 覆盖语序与 pi 一致:默认启用 → `!glob` 排除 → `+path` 强制启用 → `-path` + 强制排除;匹配前归一化 `file://`、`~`、`./` 和反斜杠。`+` / `-` 只做精确路径 + 匹配,`!` 才走 glob。 +- 读取失败:文件缺失静默按「已开启」处理;其它读取 / 解析错误写日志后同样 + fail-open,不把坏文件伪装成诊断结论。 + +## 05 新鲜度 + +- local / derived / remote 三类 probe 都在同一批里读取一次配置诊断,挂到既有 + probe 详情上。 +- 读取持久化快照时先剥掉旧 `statusHooksDisabledByConfig`,由本次探测结果重新 + 决定是否挂回;智能体缺失时也不携带该字段。旧警告不得在重启或重新开启后复活。 +- 设置页挂载时,如果当前快照里已有该诊断,强制一次 local probe 复核;用户运行 + `pi config` 重新开启后,提示立即消失。 + +## 06 检查点 + +- `tests/unit/agent-integrations/pi-status-settings.test.ts`:覆盖语序、路径归一化、 + 托管扩展识别、缺失 / 损坏配置 fail-open。 +- `tests/unit/main/host-catalog/agent-cli-provider.test.ts`:生产 remote probe 下发、 + local probe 清除旧标记、智能体缺失时丢弃标记。 +- `tests/unit/renderer/settings/agent-row-details.test.tsx`:诊断行显示 / 隐藏。 diff --git a/src/main/app-core/host-catalog-boot.ts b/src/main/app-core/host-catalog-boot.ts index be04d6f28..a88e018fe 100644 --- a/src/main/app-core/host-catalog-boot.ts +++ b/src/main/app-core/host-catalog-boot.ts @@ -2,6 +2,7 @@ import type { AgentLifecycleProbe } from "@shared/contracts/agent/lifecycle.ts"; import type { AgentKind } from "@shared/contracts/agent.ts"; import type { AppUpdateSnapshot } from "@shared/contracts/app-update.ts"; import type { ManagedPluginCatalogSnapshot } from "@shared/contracts/plugin/managed.ts"; +import { readDisabledStatusHooks } from "../services/agents/integrations/registry.ts"; import type { AppUpdateRuntimeMode, AppUpdateService, @@ -46,6 +47,7 @@ export function createBootedHostCatalogRuntime(options: { "agent-cli" ), probe: options.probe, + readStatusHooksDisabledAgents: (env) => readDisabledStatusHooks(env), }) ); if (options.listPlugins && options.refreshPluginIndex) { diff --git a/src/main/services/agents/integrations/pi.ts b/src/main/services/agents/integrations/pi.ts index eddd336d1..a79f5023b 100644 --- a/src/main/services/agents/integrations/pi.ts +++ b/src/main/services/agents/integrations/pi.ts @@ -1,8 +1,9 @@ import { existsSync } from "node:fs"; import { readFile, rm } from "node:fs/promises"; import { homedir } from "node:os"; -import { join } from "node:path"; +import { basename, join, relative } from "node:path"; import type { AgentKind } from "@shared/contracts/agent.ts"; +import { Minimatch } from "minimatch"; import { isPierManagedPluginContent, pierManagedPluginMarker, @@ -68,6 +69,122 @@ export function piExtensionPath(): string { return join(piHome(), "extensions", EXTENSION_FILE_NAME); } +function toPosixPath(value: string): string { + return value.replaceAll("\\", "/"); +} + +/** + * pi 的 `extensions` 覆盖语序(dist/core/package-manager.js + * `isEnabledByOverrides`):默认启用 → `!glob` 排除 → `+path` 强制启用 → + * `-path` 强制排除。`+` / `-` 只做精确路径匹配,`!` 才走 glob; + * 匹配前与 pi 一样做路径归一化(`file://`、`~`、`./`、反斜杠)。 + * + * 只看全局 `settings.json`:项目级覆盖需要项目上下文,设置页没有, + * 宁可少提示也不误报(fail-open)。 + */ +export function isStatusExtensionEnabled( + patterns: readonly string[] | undefined, + extensionPath: string, + agentDir: string, + home: string = homedir() +): boolean { + if (!patterns || patterns.length === 0) { + return true; + } + const overrides = patterns.filter( + (pattern) => + pattern.startsWith("!") || + pattern.startsWith("+") || + pattern.startsWith("-") + ); + const excludes = overrides + .filter((pattern) => pattern.startsWith("!")) + .map((pattern) => pattern.slice(1)); + const forceIncludes = overrides + .filter((pattern) => pattern.startsWith("+")) + .map((pattern) => pattern.slice(1)); + const forceExcludes = overrides + .filter((pattern) => pattern.startsWith("-")) + .map((pattern) => pattern.slice(1)); + + const rel = toPosixPath(relative(agentDir, extensionPath)); + const name = basename(extensionPath); + const absolute = toPosixPath(extensionPath); + const normalizePattern = (pattern: string): string => { + let value = pattern; + if (value.startsWith("file://")) { + value = value.slice("file://".length); + } + if (value === "~") { + value = home; + } else if (value.startsWith("~/")) { + value = join(home, value.slice(2)); + } + return toPosixPath(value); + }; + const matchesGlob = (pattern: string): boolean => { + const matcher = new Minimatch(normalizePattern(pattern)); + return matcher.match(rel) || matcher.match(name) || matcher.match(absolute); + }; + const matchesExact = (pattern: string): boolean => { + const normalized = normalizePattern(pattern); + const stripped = normalized.startsWith("./") + ? normalized.slice(2) + : normalized; + return stripped === rel || stripped === absolute; + }; + + let enabled = true; + if (excludes.some((pattern) => matchesGlob(pattern))) { + enabled = false; + } + if (forceIncludes.some((pattern) => matchesExact(pattern))) { + enabled = true; + } + if (forceExcludes.some((pattern) => matchesExact(pattern))) { + enabled = false; + } + return enabled; +} + +/** + * Pier 写入的 pi 状态扩展是否被用户自己的 pi 设置禁用。设置文件缺失或 + * 损坏时不报警(安装流程负责重建扩展),只在可解析且确实排除时返回 true; + * 读取失败留给日志,避免把「文件坏了」伪装成「配置已开启」。 + */ +export async function readStatusHooksDisabledByConfig( + env: NodeJS.ProcessEnv = process.env +): Promise { + const agentDir = resolvePiHome(env); + const extensionPath = join(agentDir, "extensions", EXTENSION_FILE_NAME); + const home = env.HOME ?? homedir(); + try { + const source = await readFile(extensionPath, "utf8"); + // Only claim a missing status feed for an extension Pier actually wrote. + if (!isPierManagedPluginContent(source)) { + return false; + } + const text = await readFile(join(agentDir, "settings.json"), "utf8"); + const parsed: unknown = JSON.parse(text); + const raw = + typeof parsed === "object" && parsed !== null && "extensions" in parsed + ? (parsed as { extensions?: unknown }).extensions + : undefined; + const patterns = Array.isArray(raw) + ? raw.filter((value): value is string => typeof value === "string") + : []; + return !isStatusExtensionEnabled(patterns, extensionPath, agentDir, home); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") { + console.warn( + "[agent-hooks:pi] failed to read status extension settings:", + error + ); + } + return false; + } +} + export function piDetect(): boolean { return existsSync(piHome()) || commandExistsOnPath("pi"); } diff --git a/src/main/services/agents/integrations/registry.ts b/src/main/services/agents/integrations/registry.ts index 2c3618ab9..b1df7ea49 100644 --- a/src/main/services/agents/integrations/registry.ts +++ b/src/main/services/agents/integrations/registry.ts @@ -38,7 +38,7 @@ import { mistralVibeIntegration } from "./mistral-vibe.ts"; import { ompIntegration } from "./omp.ts"; import { openclaudeIntegration } from "./openclaude.ts"; import { opencodeIntegration } from "./opencode.ts"; -import { piIntegration } from "./pi.ts"; +import { piIntegration, readStatusHooksDisabledByConfig } from "./pi.ts"; import { qodercliIntegration } from "./qodercli.ts"; import { qwenCodeIntegration } from "./qwen-code.ts"; import type { @@ -203,3 +203,18 @@ export async function applyAgentStatusHooksPreference( setAgentStatusHooksIngestEnabled(enabled); await (enabled ? installAgentHooksStack() : uninstallAllAgentHooks()); } + +/** + * 智能体自己的配置是否关掉了 Pier 的状态集成,供设置页做诊断。 + * 目前只有 pi 的 `extensions` 覆盖会排除托管扩展;分派留在这里, + * host-catalog provider 保持与具体 agent 无关。 + */ +export async function readDisabledStatusHooks( + env: NodeJS.ProcessEnv = process.env +): Promise> { + const disabled = new Set(); + if (await readStatusHooksDisabledByConfig(env)) { + disabled.add("pi"); + } + return disabled; +} diff --git a/src/main/services/host-catalog/providers/agent-cli.ts b/src/main/services/host-catalog/providers/agent-cli.ts index 0ce5eea38..f8b405f19 100644 --- a/src/main/services/host-catalog/providers/agent-cli.ts +++ b/src/main/services/host-catalog/providers/agent-cli.ts @@ -21,6 +21,14 @@ export interface AgentCliCatalogProviderOptions { checkLatest: boolean; force?: boolean; }) => Promise; + /** + * Agent ids whose own config disables Pier's status integration + * (e.g. pi `extensions` overrides). Optional so tests and non-desktop + * hosts never read user config. + */ + readStatusHooksDisabledAgents?: ( + env: NodeJS.ProcessEnv + ) => Promise>; } function presenceOf(probe: AgentLifecycleProbe): CatalogItem["presence"] { @@ -30,12 +38,41 @@ function presenceOf(probe: AgentLifecycleProbe): CatalogItem["presence"] { return probe.detected ? "present" : "missing"; } -function itemFromProbe(probe: AgentLifecycleProbe): CatalogItem { +function withoutStatusHooksFlag(details: unknown): unknown { + if (!(details && typeof details === "object")) { + return details; + } + const { statusHooksDisabledByConfig: _stale, ...rest } = details as Record< + string, + unknown + >; + return rest; +} + +/** + * 配置诊断是当前事实,不是历史:持久化快照里的旧值必须先剥掉, + * 再按本次读取结果决定是否重新挂上,否则用户改完 pi 设置后仍显示旧警告。 + */ +function withStatusHooksFlag(details: unknown, disabled: boolean): unknown { + const clean = withoutStatusHooksFlag(details); + if (!(disabled && clean && typeof clean === "object")) { + return clean; + } + return { + ...(clean as Record), + statusHooksDisabledByConfig: true, + }; +} + +function itemFromProbe( + probe: AgentLifecycleProbe, + statusHooksDisabled: boolean +): CatalogItem { const entry = AGENT_CATALOG.find( (candidate) => candidate.id === probe.agentId ); return { - details: probe, + details: withStatusHooksFlag(probe, statusHooksDisabled), domain: "agent-cli", id: probe.agentId, label: entry?.label ?? probe.agentId, @@ -46,6 +83,33 @@ function itemFromProbe(probe: AgentLifecycleProbe): CatalogItem { }; } +async function readDisabledStatusHooks( + options: AgentCliCatalogProviderOptions, + env: NodeJS.ProcessEnv +): Promise> { + const reader = options.readStatusHooksDisabledAgents; + if (!reader) { + return new Set(); + } + try { + return await reader(env); + } catch (error) { + console.warn("[host-catalog] status-hook diagnostics failed:", error); + return new Set(); + } +} + +function snapshotFromProbes( + probes: readonly AgentLifecycleProbe[], + disabled: ReadonlySet, + fingerprint: string | null +): CatalogDomainSnapshot { + return snapshotFromItems( + probes.map((probe) => itemFromProbe(probe, disabled.has(probe.agentId))), + fingerprint + ); +} + function detailsForMissing( previous: CatalogItem | undefined ): AgentLifecycleProbe | null { @@ -53,8 +117,9 @@ function detailsForMissing( if (!parsed.success) { return null; } + const { statusHooksDisabledByConfig: _stale, ...details } = parsed.data; return { - ...parsed.data, + ...details, canUninstall: false, detected: false, installedButBroken: false, @@ -73,7 +138,8 @@ function detailsForMissing( function itemFromDetection( agentId: AgentKind, detected: ReadonlySet, - previous: CatalogItem | undefined + previous: CatalogItem | undefined, + statusHooksDisabled: boolean ): CatalogItem { const entry = AGENT_CATALOG.find((candidate) => candidate.id === agentId); const present = detected.has(agentId); @@ -83,12 +149,12 @@ function itemFromDetection( return detailsForMissing(previous); } if (parsed.success) { - return { - ...parsed.data, - updateOffered: isAgentUpdateOffered(parsed.data), - }; + return withStatusHooksFlag( + { ...parsed.data, updateOffered: isAgentUpdateOffered(parsed.data) }, + statusHooksDisabled + ); } - return previous?.details ?? null; + return withoutStatusHooksFlag(previous?.details ?? null); })(); return { details, @@ -128,15 +194,22 @@ export function createAgentCliCatalogProvider( ); const { detectedIds } = await options.detect(); const detected = new Set(detectedIds); + const disabled = await readDisabledStatusHooks(options, env.env); const items = AGENT_CATALOG.map((entry) => - itemFromDetection(entry.id, detected, previousById.get(entry.id)) + itemFromDetection( + entry.id, + detected, + previousById.get(entry.id), + disabled.has(entry.id) + ) ); return snapshotFromItems(items, fingerprintPath(env.env.PATH)); }, - async probeDerived() { + async probeDerived(env) { const previous = await options.persist.read(); const probes = await options.probe({ checkLatest: false }); - return snapshotFromItems(probes.map(itemFromProbe), previous.fingerprint); + const disabled = await readDisabledStatusHooks(options, env.env); + return snapshotFromProbes(probes, disabled, previous.fingerprint); }, async probeRemote(env) { const previous = await options.persist.read(); @@ -144,7 +217,8 @@ export function createAgentCliCatalogProvider( checkLatest: true, ...(env.force === true ? { force: true } : {}), }); - return snapshotFromItems(probes.map(itemFromProbe), previous.fingerprint); + const disabled = await readDisabledStatusHooks(options, env.env); + return snapshotFromProbes(probes, disabled, previous.fingerprint); }, readPersisted: () => options.persist.read(), }; diff --git a/src/main/services/panel-transfer/terminal-compensation.ts b/src/main/services/panel-transfer/terminal-compensation.ts index 091897a2d..e951a164e 100644 --- a/src/main/services/panel-transfer/terminal-compensation.ts +++ b/src/main/services/panel-transfer/terminal-compensation.ts @@ -39,6 +39,12 @@ export interface StagedTransfer { lifecycleId: string; panelId: string; phase: TerminalPanelTransferPhase; + /** + * Session-side identity captured at lease for the commit CAS. Always a + * string: "" for legacy rows or entries materialized during the lease, so + * the CAS still checks that the panel is present at commit time. + */ + sessionIdentity: string; sessionToken: TerminalPanelOwnershipRollbackToken | null; sourceElectronWindowId: string; sourcePresentationId: number | null; diff --git a/src/main/services/panel-transfer/terminal-identity.ts b/src/main/services/panel-transfer/terminal-identity.ts new file mode 100644 index 000000000..97deba66f --- /dev/null +++ b/src/main/services/panel-transfer/terminal-identity.ts @@ -0,0 +1,25 @@ +import { sessionIdentityForLiveLifecycle } from "../../state/terminal-session-identity.ts"; + +/** + * Lease-time rule: a live surface must agree with the session record. Restored + * exited-agent cards have no native process, so nothing can contradict their + * session; a present process does have authority — an empty live identity then + * means the lifecycle entry is missing, not that the panel is static. Shells + * normalize `shell:` to "", so stale task metadata on a shell still vetoes. + */ +export function assertLeaseSessionIdentity(input: { + hasLiveSurface: boolean; + lifecycleId: string; + sessionIdentity: string | undefined; +}): void { + const expected = sessionIdentityForLiveLifecycle(input.lifecycleId); + if ( + input.hasLiveSurface && + input.sessionIdentity && + input.sessionIdentity !== expected + ) { + throw new Error( + `session lifecycle mismatch: expected ${input.lifecycleId}, got ${input.sessionIdentity}` + ); + } +} diff --git a/src/main/services/panel-transfer/terminal.ts b/src/main/services/panel-transfer/terminal.ts index 7aa51c475..5b46a92f0 100644 --- a/src/main/services/panel-transfer/terminal.ts +++ b/src/main/services/panel-transfer/terminal.ts @@ -8,6 +8,7 @@ import { terminalDraftStore } from "../../state/terminal-drafts/index.ts"; import { toNativePanelKey } from "../../ipc/terminal/panel-id.ts"; import { nativeTerminalProcesses } from "../../ipc/terminal/process/registry.ts"; +import { sessionIdentityForLiveLifecycle } from "../../state/terminal-session-identity.ts"; import { ensureTerminalPanelSession } from "../../state/terminal-session-state.ts"; import { getTransferSession, @@ -22,6 +23,7 @@ import { type StagedTransfer, } from "./terminal-compensation.ts"; import { activateAlias } from "./terminal-hook-owner-routing.ts"; +import { assertLeaseSessionIdentity } from "./terminal-identity.ts"; export type { TerminalPanelTransfer, @@ -137,15 +139,16 @@ export function createTerminalPanelTransfer( source.recordId, input.panelId ); - if ( - sourceSession && - sourceSession.lifecycleId !== - (input.lifecycleId.startsWith("shell:") ? "" : input.lifecycleId) - ) { - throw new Error( - `session lifecycle mismatch: expected ${input.lifecycleId}, got ${sourceSession.lifecycleId}` - ); - } + const hasLiveSurface = + sessionIdentityForLiveLifecycle(input.lifecycleId) !== "" || + nativeTerminalProcesses.get( + toNativePanelKey(source.win, input.panelId) + ) !== undefined; + assertLeaseSessionIdentity({ + hasLiveSurface, + lifecycleId: input.lifecycleId, + sessionIdentity: sourceSession?.lifecycleId, + }); if (!sourceSession) { // Metadata-less legacy terminal (created before the ensure-on-create // invariant). Materialize the entry so commit CAS has something to @@ -158,6 +161,7 @@ export function createTerminalPanelTransfer( lifecycleId: input.lifecycleId, panelId: input.panelId, phase: "leased", + sessionIdentity: sourceSession?.lifecycleId ?? "", sessionToken: null, sourceElectronWindowId: String(source.win.id), sourcePresentationId: null, @@ -188,6 +192,21 @@ export function createTerminalPanelTransfer( if (staged.phase === "moved") { return; } + // Re-validate before the first substep: target staging can outlive the + // lease, and moving a respawned surface would let compensation write the + // superseded identity back over the live one. + const liveIdentity = api.resolveTransferIdentity({ + expectedLifecycleId: staged.lifecycleId, + panelId: staged.panelId, + recordId: staged.sourceRecordId, + runtimeWindowId: staged.sourceRuntimeWindowId, + }); + if (!liveIdentity.ok) { + staged.phase = "rolled-back"; + clearLeaseIndexes(staged); + transfers.delete(input.transferId); + throw new Error(liveIdentity.reason ?? "transfer identity mismatch"); + } staged.phase = "moving"; const source = deps.resolveWindow(staged.sourceRuntimeWindowId); @@ -256,9 +275,10 @@ export function createTerminalPanelTransfer( }); staged.sessionToken = await transferSessionPanelOwnership({ - expectedLifecycleId: staged.lifecycleId.startsWith("shell:") - ? "" - : staged.lifecycleId, + // CAS against the identity captured at lease time. The captured value + // is always a string ("" for legacy rows or entries materialized + // during the lease), so the existence check always runs. + expectedLifecycleId: staged.sessionIdentity, panelId: staged.panelId, sourceRecordId: staged.sourceRecordId, targetRecordId: staged.targetRecordId, @@ -446,12 +466,14 @@ export function createTerminalPanelTransfer( }, resolveTransferIdentity(input) { - const current = + const current = sessionIdentityForLiveLifecycle( deps .getTaskLifecycle() - ?.getCurrentLifecycleId(input.panelId, input.runtimeWindowId) ?? ""; - const expected = input.expectedLifecycleId; - // Shells may carry empty lifecycleId on both sides. + ?.getCurrentLifecycleId(input.panelId, input.runtimeWindowId) ?? "" + ); + const expected = sessionIdentityForLiveLifecycle( + input.expectedLifecycleId + ); if (expected !== current) { return { lifecycleId: current, diff --git a/src/main/services/panel-transfer/types.ts b/src/main/services/panel-transfer/types.ts index dd471fe16..6537aa9e0 100644 --- a/src/main/services/panel-transfer/types.ts +++ b/src/main/services/panel-transfer/types.ts @@ -122,9 +122,10 @@ export interface PanelTransferTerminalPort { transferId: string; }): Promise; /** - * Canonical current lifecycle for a terminal panel (task run id; shells - * return ""). Main fills the transfer snapshot from here — renderers never - * forge lifecycle identity. + * Canonical current lifecycle for a live terminal panel: task run id, agent + * spawn generation, or `shell:` for shells. Empty when main has no live + * surface for the panel (e.g. a restored exited-agent card). Main fills the + * transfer snapshot from here — renderers never forge lifecycle identity. */ getCurrentLifecycleId(input: { panelId: string; diff --git a/src/main/state/terminal-session-identity.ts b/src/main/state/terminal-session-identity.ts new file mode 100644 index 000000000..48d79909c --- /dev/null +++ b/src/main/state/terminal-session-identity.ts @@ -0,0 +1,29 @@ +/** Session-side lifecycle identity shared by transfer and exit bookkeeping. */ + +import type { TerminalPanelSession } from "./terminal-session-state-schemas.ts"; + +/** + * Session counterpart of the live panel lifecycle: task run id, else agent + * spawn generation, else "" (shells and agent rows without a recorded + * generation). Must stay in lockstep with `resolveAgentSpawnLifecycle` + * (create-launch.ts) and `nativeTerminalProcesses.begin` (process/registry.ts) + * — tests/unit/main/terminal/lifecycle/transfer-identity-governance.test.ts + * pins the three mappings together. + */ +export function terminalSessionLifecycleId( + session: TerminalPanelSession +): string { + if (session.task?.runId) { + return session.task.runId; + } + const generation = session.agent?.restore?.spawnGeneration; + return generation === undefined ? "" : String(generation); +} + +/** + * Live registry lifecycle → session-side identity. Shells are the only surface + * whose live id (`shell:`) never appears in session metadata. + */ +export function sessionIdentityForLiveLifecycle(lifecycleId: string): string { + return lifecycleId.startsWith("shell:") ? "" : lifecycleId; +} diff --git a/src/main/state/terminal-session-state.ts b/src/main/state/terminal-session-state.ts index 9888d5009..e77ad5ff2 100644 --- a/src/main/state/terminal-session-state.ts +++ b/src/main/state/terminal-session-state.ts @@ -267,9 +267,15 @@ export async function patchTerminalPanelAgentStatus( if (!(windowState && current?.agent)) { return state; } + // Legacy rows from builds that predate spawn generations have no identity + // to compare against. Dropping their exit would leave `running` forever, so + // accept it: creation records the new generation before native callbacks + // run, so an absent generation cannot belong to a live surface. A declared, + // different generation is a stale exit event and must be dropped. if ( patch.spawnGeneration !== undefined && - current.agent.restore?.spawnGeneration !== patch.spawnGeneration + current.agent.restore?.spawnGeneration !== undefined && + current.agent.restore.spawnGeneration !== patch.spawnGeneration ) return state; const canPatchExited = diff --git a/src/main/state/terminal-session-transfer.ts b/src/main/state/terminal-session-transfer.ts index 0c0bcffb0..0bb8f9040 100644 --- a/src/main/state/terminal-session-transfer.ts +++ b/src/main/state/terminal-session-transfer.ts @@ -5,6 +5,7 @@ import { rekeyPendingAgentResume, updateTerminalPanelAgentResume, } from "./terminal-session-agent-resume.ts"; +import { terminalSessionLifecycleId } from "./terminal-session-identity.ts"; import { readTerminalPanelSession } from "./terminal-session-state.ts"; import type { TerminalPanelSession } from "./terminal-session-state-schemas.ts"; import { @@ -14,7 +15,11 @@ import { /** Narrow view for transfer identity checks — never invents ownerWindowId. */ export interface TerminalTransferSessionView { - /** Task run id when present; shells/agents without a task use empty string. */ + /** + * Session-side lifecycle identity, mirroring the live panel lifecycle: + * task run id, else agent spawn generation, else "" (shell / legacy agent + * metadata without a recorded generation). + */ lifecycleId: string; panelId: string; recordId: string; @@ -30,7 +35,7 @@ export async function getTransferSession( return null; } return { - lifecycleId: session.task?.runId ?? "", + lifecycleId: terminalSessionLifecycleId(session), panelId, recordId, session, @@ -59,7 +64,8 @@ export class TerminalPanelOwnershipConflictError extends Error { /** * CAS-move `windows[sourceRecordId].panels[panelId]` → `windows[targetRecordId]` - * and flush. Optional expectedLifecycleId must match task.runId (shells: ""). + * and flush. Optional expectedLifecycleId must match the panel's transfer + * lifecycle identity (task run id / agent spawn generation; shells: ""). */ export async function transferPanelOwnership(input: { expectedLifecycleId?: string | undefined; @@ -94,7 +100,7 @@ export async function transferPanelOwnership(input: { ); } if (input.expectedLifecycleId !== undefined) { - const actual = panel.task?.runId ?? ""; + const actual = terminalSessionLifecycleId(panel); if (actual !== input.expectedLifecycleId) { throw new TerminalPanelOwnershipConflictError( `lifecycle mismatch: expected ${input.expectedLifecycleId}, got ${actual}`, diff --git a/src/renderer/i18n/locales/en/settings-agents.ts b/src/renderer/i18n/locales/en/settings-agents.ts index 0b7f152ce..f04c118cd 100644 --- a/src/renderer/i18n/locales/en/settings-agents.ts +++ b/src/renderer/i18n/locales/en/settings-agents.ts @@ -156,6 +156,8 @@ export const settingsAgents = { envDesc: "Variables added when launching this agent", latestCheckFailed: "Couldn’t check for a newer version. Refresh the list and try again.", + statusHooksDisabledByConfig: + "Pi’s current settings hide its status from Pier. Run pi config to turn it back on.", }, sessionTitleRefine: { label: "Name sessions automatically", diff --git a/src/renderer/i18n/locales/ja/settings-agents.ts b/src/renderer/i18n/locales/ja/settings-agents.ts index 60f46c6a8..6c1876a7e 100644 --- a/src/renderer/i18n/locales/ja/settings-agents.ts +++ b/src/renderer/i18n/locales/ja/settings-agents.ts @@ -156,6 +156,8 @@ export const settingsAgents = { envDesc: "このエージェント起動時に足す変数", latestCheckFailed: "新しいバージョンを確認できませんでした。一覧右上の更新を押して再試行してください。", + statusHooksDisabledByConfig: + "Pi の現在の設定では Pier に実行状態が表示されません。pi config で再び有効にすると復元されます。", }, sessionTitleRefine: { label: "セッション名を自動で付ける", diff --git a/src/renderer/i18n/locales/ko/settings-agents.ts b/src/renderer/i18n/locales/ko/settings-agents.ts index 3518a773d..19f7c65f4 100644 --- a/src/renderer/i18n/locales/ko/settings-agents.ts +++ b/src/renderer/i18n/locales/ko/settings-agents.ts @@ -150,6 +150,8 @@ export const settingsAgents = { envDesc: "이 에이전트를 시작할 때 더하는 변수", latestCheckFailed: "최신 버전을 확인하지 못했습니다. 목록 오른쪽 위 새로고침 후 다시 시도하세요.", + statusHooksDisabledByConfig: + "현재 Pi 설정에서는 Pier에 Pi의 실행 상태가 표시되지 않습니다. pi config에서 다시 켜면 복구됩니다.", }, sessionTitleRefine: { label: "세션 이름을 자동으로 지정", diff --git a/src/renderer/i18n/locales/zh-CN/settings-agents.ts b/src/renderer/i18n/locales/zh-CN/settings-agents.ts index f2c87e9a0..74a1151ed 100644 --- a/src/renderer/i18n/locales/zh-CN/settings-agents.ts +++ b/src/renderer/i18n/locales/zh-CN/settings-agents.ts @@ -146,6 +146,8 @@ export const settingsAgents = { env: "附加环境变量", envDesc: "启动此智能体时一并注入", latestCheckFailed: "最新版本检查失败。可点列表右上角刷新后重试。", + statusHooksDisabledByConfig: + "Pi 现在的设置让 Pier 看不到它的运行状态。运行 pi config 重新开启即可恢复。", }, sessionTitleRefine: { label: "自动命名会话", diff --git a/src/renderer/pages/settings/components/agent-row-details.tsx b/src/renderer/pages/settings/components/agent-row-details.tsx index 7bb9e935d..b7ad9c455 100644 --- a/src/renderer/pages/settings/components/agent-row-details.tsx +++ b/src/renderer/pages/settings/components/agent-row-details.tsx @@ -1,3 +1,4 @@ +import { Alert, AlertDescription } from "@pier/ui/alert.tsx"; import { Separator } from "@pier/ui/separator.tsx"; import { getAgentCatalogEntry } from "@shared/agent-catalog.ts"; import { @@ -102,6 +103,13 @@ export function AgentExpandedDetails({ agentId }: { agentId: AgentKind }) { {t("settings.agents.row.latestCheckFailed")} ) : null} + {probe?.statusHooksDisabledByConfig === true ? ( + + + {t("settings.agents.row.statusHooksDisabledByConfig")} + + + ) : null}
diff --git a/src/renderer/pages/settings/components/agents-section.tsx b/src/renderer/pages/settings/components/agents-section.tsx index fcbbde253..c510ccade 100644 --- a/src/renderer/pages/settings/components/agents-section.tsx +++ b/src/renderer/pages/settings/components/agents-section.tsx @@ -36,6 +36,7 @@ import { } from "@/stores/agent-lifecycle.store.ts"; import { useAgentPreferencesStore } from "@/stores/agent-preferences.store.ts"; import { showAppAlert } from "@/stores/app-dialog.store.ts"; +import { useHostCatalogStore } from "@/stores/host-catalog/store.ts"; const PERMISSION_MODE_OPTIONS: Array<{ value: "yolo" | "manual"; @@ -336,6 +337,20 @@ export function AgentsSection() { useEffect(() => { const openTask = (async () => { try { + // 只在已经亮出「配置关掉了状态」时复核:警告是当前事实, + // 用户刚改完 pi 设置就应立刻消失;没有警告时保持轻量刷新。 + const probes = useAgentLifecycleStore.getState().probesById; + const needsConfigCheck = Object.values(probes).some( + (probe) => probe?.statusHooksDisabledByConfig === true + ); + if (needsConfigCheck) { + await useHostCatalogStore.getState().ensureFresh({ + class: "local", + domain: "agent-cli", + force: true, + }); + return; + } await softRevalidate(); } catch { // Best-effort: catalog + last probes still render. diff --git a/src/shared/contracts/agent/lifecycle.ts b/src/shared/contracts/agent/lifecycle.ts index 5d545012c..b19aab513 100644 --- a/src/shared/contracts/agent/lifecycle.ts +++ b/src/shared/contracts/agent/lifecycle.ts @@ -90,6 +90,12 @@ export const agentLifecycleProbeSchema = z.object({ installedButBroken: z.boolean(), installs: z.array(agentInstallInfoSchema), isConflict: z.boolean(), + /** + * True when the agent's own settings disable Pier's status integration + * (currently the pi `extensions` overrides). Diagnostic only: the agent row + * details explain how to turn it back on. + */ + statusHooksDisabledByConfig: z.boolean().optional(), /** * True when checkLatest ran for a versioned agent but remote latest could * not be resolved (distinct from “already up to date”). diff --git a/tests/unit/agent-integrations/pi-status-settings.test.ts b/tests/unit/agent-integrations/pi-status-settings.test.ts new file mode 100644 index 000000000..5ea4534cf --- /dev/null +++ b/tests/unit/agent-integrations/pi-status-settings.test.ts @@ -0,0 +1,170 @@ +import { mkdir, mkdtemp, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { pierManagedPluginMarker } from "../../../src/main/services/agents/integrations/managed-plugin-file.ts"; +import { + isStatusExtensionEnabled, + readStatusHooksDisabledByConfig, +} from "../../../src/main/services/agents/integrations/pi.ts"; + +const AGENT_DIR = "/home/tester/.pi/agent"; +const EXTENSION_PATH = join(AGENT_DIR, "extensions", "pier-agent-status.ts"); + +describe("isStatusExtensionEnabled", () => { + it("enables the extension when pi has no overrides", () => { + expect(isStatusExtensionEnabled(undefined, EXTENSION_PATH, AGENT_DIR)).toBe( + true + ); + expect(isStatusExtensionEnabled([], EXTENSION_PATH, AGENT_DIR)).toBe(true); + }); + + it("honors a relative force-exclude override", () => { + expect( + isStatusExtensionEnabled( + ["extensions/other.ts", "-extensions/pier-agent-status.ts"], + EXTENSION_PATH, + AGENT_DIR + ) + ).toBe(false); + }); + + it("honors absolute and ./ force-exclude overrides", () => { + expect( + isStatusExtensionEnabled([EXTENSION_PATH], EXTENSION_PATH, AGENT_DIR) + ).toBe(true); + expect( + isStatusExtensionEnabled( + [`-${EXTENSION_PATH}`], + EXTENSION_PATH, + AGENT_DIR + ) + ).toBe(false); + expect( + isStatusExtensionEnabled( + ["-./extensions/pier-agent-status.ts"], + EXTENSION_PATH, + AGENT_DIR + ) + ).toBe(false); + }); + + it("applies excludes, force-includes, then force-excludes", () => { + const relative = "extensions/pier-agent-status.ts"; + expect( + isStatusExtensionEnabled(["!extensions/*.ts"], EXTENSION_PATH, AGENT_DIR) + ).toBe(false); + expect( + isStatusExtensionEnabled( + ["!extensions/*.ts", `+${relative}`], + EXTENSION_PATH, + AGENT_DIR + ) + ).toBe(true); + expect( + isStatusExtensionEnabled( + ["!extensions/*.ts", `+${relative}`, `-${relative}`], + EXTENSION_PATH, + AGENT_DIR + ) + ).toBe(false); + }); + + it("normalizes ~, file:// and ./ before matching", () => { + expect( + isStatusExtensionEnabled( + ["-~/.pi/agent/extensions/pier-agent-status.ts"], + EXTENSION_PATH, + AGENT_DIR, + "/home/tester" + ) + ).toBe(false); + expect( + isStatusExtensionEnabled( + [`-file://${EXTENSION_PATH}`], + EXTENSION_PATH, + AGENT_DIR + ) + ).toBe(false); + }); + + it("leaves the extension enabled for unrelated patterns", () => { + expect( + isStatusExtensionEnabled( + ["!extensions/orca-*.ts", "-extensions/superset-hooks.ts"], + EXTENSION_PATH, + AGENT_DIR + ) + ).toBe(true); + }); +}); + +describe("readStatusHooksDisabledByConfig", () => { + it("reports an excluded managed extension", async () => { + const home = await mkdtemp(join(tmpdir(), "pier-pi-settings-")); + await mkdir(join(home, "extensions"), { recursive: true }); + await writeFile( + join(home, "extensions", "pier-agent-status.ts"), + `// ${pierManagedPluginMarker()}\nexport default function () {}` + ); + await writeFile( + join(home, "settings.json"), + JSON.stringify({ + extensions: [ + "-extensions/superset-hooks.ts", + "-extensions/pier-agent-status.ts", + ], + }) + ); + + await expect( + readStatusHooksDisabledByConfig({ + HOME: home, + PI_CODING_AGENT_DIR: home, + }) + ).resolves.toBe(true); + }); + + it("ignores an unmanaged file at the extension path", async () => { + const home = await mkdtemp(join(tmpdir(), "pier-pi-settings-")); + await mkdir(join(home, "extensions"), { recursive: true }); + await writeFile( + join(home, "extensions", "pier-agent-status.ts"), + "export default function () {}" + ); + await writeFile( + join(home, "settings.json"), + JSON.stringify({ extensions: ["-extensions/pier-agent-status.ts"] }) + ); + + await expect( + readStatusHooksDisabledByConfig({ + HOME: home, + PI_CODING_AGENT_DIR: home, + }) + ).resolves.toBe(false); + }); + + it("treats missing or malformed settings as enabled", async () => { + const home = await mkdtemp(join(tmpdir(), "pier-pi-settings-")); + await expect( + readStatusHooksDisabledByConfig({ + HOME: home, + PI_CODING_AGENT_DIR: home, + }) + ).resolves.toBe(false); + + await mkdir(join(home, "extensions"), { recursive: true }); + await writeFile( + join(home, "extensions", "pier-agent-status.ts"), + `// ${pierManagedPluginMarker()}\nexport default function () {}` + ); + await writeFile(join(home, "settings.json"), "{oops"); + await expect( + readStatusHooksDisabledByConfig({ + HOME: home, + PI_CODING_AGENT_DIR: home, + }) + ).resolves.toBe(false); + }); +}); diff --git a/tests/unit/main/host-catalog/agent-cli-provider.test.ts b/tests/unit/main/host-catalog/agent-cli-provider.test.ts index f77b997cf..d62b1c808 100644 --- a/tests/unit/main/host-catalog/agent-cli-provider.test.ts +++ b/tests/unit/main/host-catalog/agent-cli-provider.test.ts @@ -1,4 +1,8 @@ -import type { AgentLifecycleProbe } from "@shared/contracts/agent/lifecycle.ts"; +import { + type AgentLifecycleProbe, + agentLifecycleProbeSchema, +} from "@shared/contracts/agent/lifecycle.ts"; +import type { AgentKind } from "@shared/contracts/agent.ts"; import { emptyDomainSnapshot } from "@shared/contracts/host-catalog/runtime.ts"; import { describe, expect, it } from "vitest"; import { createAgentCliCatalogProvider } from "../../../../src/main/services/host-catalog/providers/agent-cli.ts"; @@ -199,4 +203,131 @@ describe("createAgentCliCatalogProvider", () => { await provider.probeRemote({ env: {}, force: true, now: 30 }); expect(seen).toEqual([{ checkLatest: true, force: true }]); }); + + it("surfaces status-hook config diagnostics from the production remote probe", async () => { + const seenEnv: NodeJS.ProcessEnv[] = []; + const provider = createAgentCliCatalogProvider({ + detect: async () => ({ detectedIds: ["pi", "claude"] }), + persist: { + flush: async () => undefined, + read: async () => emptyDomainSnapshot("agent-cli"), + write: async () => undefined, + }, + probe: async () => [ + probe({ agentId: "pi" }), + probe({ agentId: "claude" }), + ], + readStatusHooksDisabledAgents: async (env) => { + seenEnv.push(env); + return new Set(["pi"]); + }, + }); + if (!provider.probeRemote) { + throw new Error("expected probeRemote"); + } + + const snapshot = await provider.probeRemote({ + env: { HOME: "/tmp/pier-home" }, + now: 31, + }); + const piDetails = snapshot.items.find((item) => item.id === "pi")?.details; + expect(piDetails).toMatchObject({ statusHooksDisabledByConfig: true }); + // The renderer mirrors probes through the shared schema; the diagnostic + // must survive parsing or the detail line never renders. + expect( + agentLifecycleProbeSchema.parse(piDetails).statusHooksDisabledByConfig + ).toBe(true); + expect( + snapshot.items.find((item) => item.id === "claude")?.details + ).not.toHaveProperty("statusHooksDisabledByConfig"); + expect(seenEnv).toEqual([{ HOME: "/tmp/pier-home" }]); + }); + + it("re-reads the config diagnostic on local probes and clears stale flags", async () => { + let disabled = new Set(); + const createProvider = () => + createAgentCliCatalogProvider({ + detect: async () => ({ detectedIds: ["pi"] }), + persist: { + flush: async () => undefined, + read: async () => ({ + ...emptyDomainSnapshot("agent-cli"), + items: [ + { + details: probe({ + agentId: "pi", + statusHooksDisabledByConfig: true, + }), + domain: "agent-cli", + id: "pi", + label: "Pi", + localVersion: "1.2.3", + presence: "present", + remoteVersion: null, + updateOffered: false, + }, + ], + }), + write: async () => undefined, + }, + probe: async () => [], + readStatusHooksDisabledAgents: async () => disabled, + }); + + // 用户已重新开启:旧的 true 必须被清掉,而不是跟着快照复活。 + const cleared = await createProvider().probeLocal({ + env: { PATH: "/opt/bin" }, + now: 32, + }); + expect( + cleared.items.find((item) => item.id === "pi")?.details + ).not.toHaveProperty("statusHooksDisabledByConfig"); + + disabled = new Set(["pi"]); + const flagged = await createProvider().probeLocal({ + env: { PATH: "/opt/bin" }, + now: 33, + }); + expect( + flagged.items.find((item) => item.id === "pi")?.details + ).toMatchObject({ statusHooksDisabledByConfig: true }); + }); + + it("drops the config diagnostic when the agent is missing", async () => { + const provider = createAgentCliCatalogProvider({ + detect: async () => ({ detectedIds: [] }), + persist: { + flush: async () => undefined, + read: async () => ({ + ...emptyDomainSnapshot("agent-cli"), + items: [ + { + details: probe({ + agentId: "pi", + statusHooksDisabledByConfig: true, + }), + domain: "agent-cli", + id: "pi", + label: "Pi", + localVersion: "1.2.3", + presence: "present", + remoteVersion: null, + updateOffered: false, + }, + ], + }), + write: async () => undefined, + }, + probe: async () => [], + readStatusHooksDisabledAgents: async () => new Set(["pi"]), + }); + + const snapshot = await provider.probeLocal({ + env: { PATH: "/opt/bin" }, + now: 34, + }); + expect( + snapshot.items.find((item) => item.id === "pi")?.details + ).not.toHaveProperty("statusHooksDisabledByConfig"); + }); }); diff --git a/tests/unit/main/terminal/lifecycle/transfer-identity-governance.test.ts b/tests/unit/main/terminal/lifecycle/transfer-identity-governance.test.ts new file mode 100644 index 000000000..87c9438ce --- /dev/null +++ b/tests/unit/main/terminal/lifecycle/transfer-identity-governance.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it } from "vitest"; +import { resolveAgentSpawnLifecycle } from "../../../../../src/main/ipc/terminal/create-launch.ts"; +import { createNativeProcessRegistry } from "../../../../../src/main/ipc/terminal/process/registry.ts"; +import { + sessionIdentityForLiveLifecycle, + terminalSessionLifecycleId, +} from "../../../../../src/main/state/terminal-session-identity.ts"; +import { terminalPanelSessionSchema } from "../../../../../src/main/state/terminal-session-state-schemas.ts"; + +/** + * Locks the three identity sources together: the spawn helper, the native + * process registry, and session metadata. They are deliberately different + * shapes (shells are `shell:` live and `""` in session metadata), so a + * change to any mapping must update this table. + */ +describe("terminal transfer identity mapping", () => { + it("keeps spawn helper, registry and agent session metadata aligned", () => { + const registry = createNativeProcessRegistry(); + + const shell = registry.begin("101::shell", { + lifecycleId: "", + savedGeneration: 4, + }); + const shellLaunch = resolveAgentSpawnLifecycle({ spawnGeneration: 5 }); + expect(shellLaunch).toEqual({ lifecycleId: "", surface: "shell" }); + expect(shell.lifecycleId).toBe("shell:5"); + expect(sessionIdentityForLiveLifecycle(shell.lifecycleId)).toBe( + shellLaunch.lifecycleId + ); + + const agent = registry.begin("101::agent", { savedGeneration: 2 }); + const agentLaunch = resolveAgentSpawnLifecycle({ + launchAgentId: "claude", + spawnGeneration: 3, + }); + expect(agentLaunch).toEqual({ lifecycleId: "3", surface: "agent" }); + expect(agent.lifecycleId).toBe(agentLaunch.lifecycleId); + expect( + terminalSessionLifecycleId( + terminalPanelSessionSchema.parse({ + agent: { + agentId: "claude", + launch: { agentId: "claude", command: "claude", cwd: "/repo" }, + restore: { spawnGeneration: 3 }, + startedAt: 1, + status: "running", + }, + updatedAt: "2026-01-01T00:00:00.000Z", + }) + ) + ).toBe(agentLaunch.lifecycleId); + + const task = registry.begin("101::task", { lifecycleId: "run-7" }); + const taskLaunch = resolveAgentSpawnLifecycle({ + launchAgentId: "codex", + spawnGeneration: 1, + taskRunId: "run-7", + }); + expect(taskLaunch).toEqual({ lifecycleId: "run-7", surface: "task" }); + expect(task.lifecycleId).toBe(taskLaunch.lifecycleId); + }); + + it("treats shells as the only live identity that maps to empty", () => { + expect(sessionIdentityForLiveLifecycle("shell:5")).toBe(""); + expect(sessionIdentityForLiveLifecycle("")).toBe(""); + expect(sessionIdentityForLiveLifecycle("3")).toBe("3"); + expect(sessionIdentityForLiveLifecycle("run-7")).toBe("run-7"); + }); +}); diff --git a/tests/unit/main/terminal/lifecycle/transfer.test.ts b/tests/unit/main/terminal/lifecycle/transfer.test.ts index 60308ff99..92665a96b 100644 --- a/tests/unit/main/terminal/lifecycle/transfer.test.ts +++ b/tests/unit/main/terminal/lifecycle/transfer.test.ts @@ -71,6 +71,7 @@ describe("terminal transfer compensation", () => { panelId: "xfer-panel", phase: "moving", sessionToken: null, + sessionIdentity: "life-1", sourceElectronWindowId: "11", sourcePresentationId: 1, sourceRecordId: "source-record", diff --git a/tests/unit/main/terminal/panel-transfer.test.ts b/tests/unit/main/terminal/panel-transfer.test.ts index 40b992aba..14f9fad6d 100644 --- a/tests/unit/main/terminal/panel-transfer.test.ts +++ b/tests/unit/main/terminal/panel-transfer.test.ts @@ -1,5 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { resolveTerminalTransferCreateAction } from "../../../../src/main/ipc/terminal/create-transfer-guard.ts"; +import { toNativePanelKey } from "../../../../src/main/ipc/terminal/panel-id.ts"; import type { AppWindow } from "../../../../src/main/windows/app-window.ts"; function fakeWin(id: number): AppWindow { @@ -87,7 +88,7 @@ describe("TerminalPanelTransfer", () => { moveTerminal?: ReturnType; sourceWin: AppWindow; targetWin: AppWindow; - lifecycleId?: string; + lifecycleId?: string | (() => string); }) { const moveTerminal = args.moveTerminal ?? vi.fn((..._args: unknown[]) => true); @@ -99,7 +100,7 @@ describe("TerminalPanelTransfer", () => { const surfaceWillClose = vi.fn(); const surfaceCreated = vi.fn(); const replayMovedSession = vi.fn(); - const lifecycleId = args.lifecycleId ?? ""; + const readLifecycleId = args.lifecycleId ?? ""; const transfer = args.createTerminalPanelTransfer({ focusCoordinator: { surfaceCreated, surfaceWillClose } as never, foreground: { @@ -109,7 +110,10 @@ describe("TerminalPanelTransfer", () => { getAddon: () => ({ moveTerminal, requestTerminalPresentation }) as never, getTaskLifecycle: () => ({ - getCurrentLifecycleId: () => lifecycleId, + getCurrentLifecycleId: () => + typeof readLifecycleId === "function" + ? readLifecycleId() + : readLifecycleId, moveOwner, }) as never, getTaskOutputBindings: () => ({ moveNativeKey }) as never, @@ -144,6 +148,19 @@ describe("TerminalPanelTransfer", () => { const { createTerminalPanelTransfer, resolveOwner } = await load(); const sourceWin = fakeWin(11); const targetWin = fakeWin(22); + getTransferSession.mockImplementation(async (recordId: unknown) => + recordId === "source-record" + ? { + lifecycleId: "run-1", + panelId: "panel-1", + recordId, + session: { + task: { runId: "run-1", status: "running" }, + updatedAt: "2026-01-01T00:00:00.000Z", + }, + } + : null + ); const { moveOwner, moveTaskOwner, @@ -214,6 +231,321 @@ describe("TerminalPanelTransfer", () => { expect(surfaceCreated).toHaveBeenCalledWith(targetWin, "panel-1"); }); + it("leases and commits agent panels by spawn generation, not task run id", async () => { + const { createTerminalPanelTransfer } = await load(); + const { moveOwner, transfer } = baseDeps({ + createTerminalPanelTransfer, + lifecycleId: "2", + sourceWin: fakeWin(3), + targetWin: fakeWin(4), + }); + getTransferSession.mockImplementation(async (recordId: unknown) => + recordId === "source-record" + ? { + lifecycleId: "2", + panelId: "panel-1", + recordId, + session: { + agent: { + agentId: "claude", + restore: { spawnGeneration: 2 }, + status: "running", + }, + updatedAt: "2026-01-01T00:00:00.000Z", + }, + } + : null + ); + + await transfer.stageLease({ + lifecycleId: "2", + panelId: "panel-1", + sourceWindowId: "source", + targetWindowId: "target", + transferId: "t-agent", + }); + await transfer.commitMove({ + lifecycleId: "2", + panelId: "panel-1", + sourceWindowId: "source", + targetWindowId: "target", + transferId: "t-agent", + }); + + expect(moveOwner).toHaveBeenCalledWith({ + lifecycleId: "2", + panelId: "panel-1", + sourceWindowId: "source", + targetWindowId: "target", + }); + expect(transferSession).toHaveBeenCalledWith({ + expectedLifecycleId: "2", + panelId: "panel-1", + sourceRecordId: "source-record", + targetRecordId: "target-record", + }); + }); + + it("passes the empty identity for agent panels whose session has no generation yet", async () => { + const { createTerminalPanelTransfer } = await load(); + const { transfer } = baseDeps({ + createTerminalPanelTransfer, + lifecycleId: "3", + sourceWin: fakeWin(5), + targetWin: fakeWin(6), + }); + getTransferSession.mockImplementation(async (recordId: unknown) => + recordId === "source-record" + ? { + lifecycleId: "", + panelId: "panel-1", + recordId, + session: { + agent: { agentId: "claude", status: "running" }, + updatedAt: "2026-01-01T00:00:00.000Z", + }, + } + : null + ); + + await transfer.stageLease({ + lifecycleId: "3", + panelId: "panel-1", + sourceWindowId: "source", + targetWindowId: "target", + transferId: "t-agent-legacy", + }); + await transfer.commitMove({ + lifecycleId: "3", + panelId: "panel-1", + sourceWindowId: "source", + targetWindowId: "target", + transferId: "t-agent-legacy", + }); + + expect(transferSession).toHaveBeenCalledWith({ + expectedLifecycleId: "", + panelId: "panel-1", + sourceRecordId: "source-record", + targetRecordId: "target-record", + }); + }); + + it("rejects a lease when session identity no longer matches the live generation", async () => { + const { createTerminalPanelTransfer } = await load(); + const { transfer } = baseDeps({ + createTerminalPanelTransfer, + lifecycleId: "2", + sourceWin: fakeWin(7), + targetWin: fakeWin(8), + }); + getTransferSession.mockImplementation(async (recordId: unknown) => + recordId === "source-record" + ? { + lifecycleId: "1", + panelId: "panel-1", + recordId, + session: { + agent: { + agentId: "claude", + restore: { spawnGeneration: 1 }, + status: "running", + }, + updatedAt: "2026-01-01T00:00:00.000Z", + }, + } + : null + ); + + await expect( + transfer.stageLease({ + lifecycleId: "2", + panelId: "panel-1", + sourceWindowId: "source", + targetWindowId: "target", + transferId: "t-agent-stale", + }) + ).rejects.toThrow("session lifecycle mismatch: expected 2, got 1"); + }); + + it("rejects a lease when a live PTY has lost its lifecycle identity", async () => { + const { createTerminalPanelTransfer } = await load(); + const { nativeTerminalProcesses: registry } = await import( + "../../../../src/main/ipc/terminal/process/registry.ts" + ); + const sourceWin = fakeWin(97); + const targetWin = fakeWin(98); + registry.begin(toNativePanelKey(sourceWin, "panel-1"), { + lifecycleId: "shell:1", + savedGeneration: 0, + }); + const { transfer } = baseDeps({ + createTerminalPanelTransfer, + sourceWin, + targetWin, + }); + getTransferSession.mockImplementation(async (recordId: unknown) => + recordId === "source-record" + ? { + lifecycleId: "2", + panelId: "panel-1", + recordId, + session: { + agent: { + agentId: "claude", + restore: { spawnGeneration: 2 }, + status: "running", + }, + updatedAt: "2026-01-01T00:00:00.000Z", + }, + } + : null + ); + + await expect( + transfer.stageLease({ + lifecycleId: "", + panelId: "panel-1", + sourceWindowId: "source", + targetWindowId: "target", + transferId: "t-live-identity-missing", + }) + ).rejects.toThrow("session lifecycle mismatch: expected , got 2"); + registry.closeWindow(97); + }); + + it("rejects a commit whose live lifecycle changed after the lease", async () => { + const { createTerminalPanelTransfer } = await load(); + let liveLifecycleId = "2"; + const { moveTerminal, transfer } = baseDeps({ + createTerminalPanelTransfer, + lifecycleId: () => liveLifecycleId, + sourceWin: fakeWin(12), + targetWin: fakeWin(13), + }); + getTransferSession.mockImplementation(async (recordId: unknown) => + recordId === "source-record" + ? { + lifecycleId: "2", + panelId: "panel-1", + recordId, + session: { + agent: { + agentId: "claude", + restore: { spawnGeneration: 2 }, + status: "running", + }, + updatedAt: "2026-01-01T00:00:00.000Z", + }, + } + : null + ); + + await transfer.stageLease({ + lifecycleId: "2", + panelId: "panel-1", + sourceWindowId: "source", + targetWindowId: "target", + transferId: "t-respawned", + }); + liveLifecycleId = "3"; + + await expect( + transfer.commitMove({ + lifecycleId: "2", + panelId: "panel-1", + sourceWindowId: "source", + targetWindowId: "target", + transferId: "t-respawned", + }) + ).rejects.toThrow("lifecycle mismatch: expected 2, got 3"); + + expect(moveTerminal).not.toHaveBeenCalled(); + expect(transferSession).not.toHaveBeenCalled(); + }); + + it("runs the session CAS for an entry materialized during the lease", async () => { + const { createTerminalPanelTransfer } = await load(); + const { transfer } = baseDeps({ + createTerminalPanelTransfer, + lifecycleId: "2", + sourceWin: fakeWin(31), + targetWin: fakeWin(32), + }); + + await transfer.stageLease({ + lifecycleId: "2", + panelId: "panel-1", + sourceWindowId: "source", + targetWindowId: "target", + transferId: "t-materialized", + }); + expect(ensureSession).toHaveBeenCalledWith("source-record", "panel-1"); + + await transfer.commitMove({ + lifecycleId: "2", + panelId: "panel-1", + sourceWindowId: "source", + targetWindowId: "target", + transferId: "t-materialized", + }); + + expect(transferSession).toHaveBeenCalledWith({ + expectedLifecycleId: "", + panelId: "panel-1", + sourceRecordId: "source-record", + targetRecordId: "target-record", + }); + }); + + it("moves a restored exited-agent card that has no live surface", async () => { + const { createTerminalPanelTransfer } = await load(); + const { transfer } = baseDeps({ + createTerminalPanelTransfer, + sourceWin: fakeWin(9), + targetWin: fakeWin(10), + }); + getTransferSession.mockImplementation(async (recordId: unknown) => + recordId === "source-record" + ? { + lifecycleId: "3", + panelId: "panel-1", + recordId, + session: { + agent: { + agentId: "claude", + restore: { spawnGeneration: 3 }, + status: "exited", + }, + updatedAt: "2026-01-01T00:00:00.000Z", + }, + } + : null + ); + + await transfer.stageLease({ + lifecycleId: "", + panelId: "panel-1", + sourceWindowId: "source", + targetWindowId: "target", + transferId: "t-agent-exited", + }); + await transfer.commitMove({ + lifecycleId: "", + panelId: "panel-1", + sourceWindowId: "source", + targetWindowId: "target", + transferId: "t-agent-exited", + }); + + expect(transferSession).toHaveBeenCalledWith({ + expectedLifecycleId: "3", + panelId: "panel-1", + sourceRecordId: "source-record", + targetRecordId: "target-record", + }); + }); + it("source close lease is idempotent and target adopts without recreate", async () => { const { createTerminalPanelTransfer } = await load(); const { transfer } = baseDeps({ diff --git a/tests/unit/main/terminal/session-state.test.ts b/tests/unit/main/terminal/session-state.test.ts index d5cf56084..cd42765dc 100644 --- a/tests/unit/main/terminal/session-state.test.ts +++ b/tests/unit/main/terminal/session-state.test.ts @@ -1,6 +1,7 @@ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import type * as TerminalSessionIdentityModule from "@main/state/terminal-session-identity.ts"; import type * as TerminalSessionStateModule from "@main/state/terminal-session-state.ts"; import type * as TerminalSessionTitleModule from "@main/state/terminal-session-title.ts"; import type * as TerminalSessionTransferModule from "@main/state/terminal-session-transfer.ts"; @@ -40,13 +41,15 @@ function context(root: string, updatedAt = 1_772_000_000_000): PanelContext { async function loadTerminalSessionState(): Promise< typeof TerminalSessionStateModule & typeof TerminalSessionTitleModule & - typeof TerminalSessionTransferModule + typeof TerminalSessionTransferModule & + typeof TerminalSessionIdentityModule > { // Dynamic import is required because each test resets modules and mocks electron app.getPath before this state module resolves userData. const state = await import("@main/state/terminal-session-state.ts"); const title = await import("@main/state/terminal-session-title.ts"); const transfer = await import("@main/state/terminal-session-transfer.ts"); - return { ...state, ...title, ...transfer }; + const identity = await import("@main/state/terminal-session-identity.ts"); + return { ...state, ...title, ...transfer, ...identity }; } describe("terminal session state", () => { @@ -915,6 +918,73 @@ describe("terminal session state", () => { }); }); + it("records an exit for a legacy agent row without a recorded generation", async () => { + const { + patchTerminalPanelAgentStatus, + readTerminalPanelSession, + updateTerminalPanelAgent, + } = await loadTerminalSessionState(); + await updateTerminalPanelAgent("main", "terminal-legacy", { + agentId: "claude", + launch: { + agentId: "claude", + command: "claude", + cwd: "/repo", + }, + startedAt: 1_772_000_000_000, + status: "running", + }); + + await expect( + patchTerminalPanelAgentStatus("main", "terminal-legacy", { + exitCode: 0, + finishedAt: 1_772_000_001_000, + spawnGeneration: 3, + status: "exited", + }) + ).resolves.toBe(true); + await expect( + readTerminalPanelSession("main", "terminal-legacy") + ).resolves.toMatchObject({ + agent: { + exitCode: 0, + finishedAt: 1_772_000_001_000, + status: "exited", + }, + }); + }); + + it("drops an exit event from a superseded generation", async () => { + const { + patchTerminalPanelAgentStatus, + readTerminalPanelSession, + updateTerminalPanelAgent, + } = await loadTerminalSessionState(); + await updateTerminalPanelAgent("main", "terminal-1", { + agentId: "claude", + launch: { + agentId: "claude", + command: "claude", + cwd: "/repo", + }, + restore: { spawnGeneration: 2 }, + startedAt: 1_772_000_000_000, + status: "running", + }); + + await expect( + patchTerminalPanelAgentStatus("main", "terminal-1", { + exitCode: 1, + finishedAt: 1_772_000_001_000, + spawnGeneration: 1, + status: "exited", + }) + ).resolves.toBe(false); + await expect( + readTerminalPanelSession("main", "terminal-1") + ).resolves.toMatchObject({ agent: { status: "running" } }); + }); + it("migrates legacy agent success tabs on disk", async () => { const { migrateLegacyAgentSuccessTabs, @@ -1551,6 +1621,81 @@ describe("terminal session state", () => { ).resolves.toMatchObject({ context: pier }); }); + it("keys ownership transfer identity on agent spawn generation", async () => { + const { + getTransferSession, + readTerminalPanelSession, + rollbackTransferPanelOwnership, + terminalSessionLifecycleId, + transferPanelOwnership, + updateTerminalPanelAgent, + updateTerminalPanelContext, + } = await loadTerminalSessionState(); + + const pier = context("/Users/dev/ABC/pier"); + await updateTerminalPanelContext("source-record", "agent-1", pier); + await updateTerminalPanelAgent("source-record", "agent-1", { + agentId: "claude", + launch: { agentId: "claude", command: "claude", cwd: "/repo" }, + restore: { spawnGeneration: 2 }, + startedAt: 1_772_000_000_000, + status: "running", + }); + + const view = await getTransferSession("source-record", "agent-1"); + expect(view).toMatchObject({ lifecycleId: "2" }); + expect(view && terminalSessionLifecycleId(view.session)).toBe("2"); + + await expect( + transferPanelOwnership({ + expectedLifecycleId: "1", + panelId: "agent-1", + sourceRecordId: "source-record", + targetRecordId: "target-record", + }) + ).rejects.toMatchObject({ code: "lifecycle_mismatch" }); + + const token = await transferPanelOwnership({ + expectedLifecycleId: "2", + panelId: "agent-1", + sourceRecordId: "source-record", + targetRecordId: "target-record", + }); + await expect( + readTerminalPanelSession("target-record", "agent-1") + ).resolves.toMatchObject({ agent: { restore: { spawnGeneration: 2 } } }); + + await rollbackTransferPanelOwnership(token); + await expect( + readTerminalPanelSession("source-record", "agent-1") + ).resolves.toMatchObject({ agent: { restore: { spawnGeneration: 2 } } }); + }); + + it("keeps legacy agent sessions without a generation transferable", async () => { + const { + getTransferSession, + terminalSessionLifecycleId, + updateTerminalPanelAgent, + updateTerminalPanelContext, + } = await loadTerminalSessionState(); + + await updateTerminalPanelContext( + "source-record", + "agent-legacy", + context("/Users/dev/ABC/pier") + ); + await updateTerminalPanelAgent("source-record", "agent-legacy", { + agentId: "grok", + launch: { agentId: "grok", command: "grok", cwd: "/repo" }, + startedAt: 1_772_000_000_000, + status: "running", + }); + + const view = await getTransferSession("source-record", "agent-legacy"); + expect(view?.lifecycleId).toBe(""); + expect(view && terminalSessionLifecycleId(view.session)).toBe(""); + }); + it("ensureTerminalPanelSession materializes an entry without clobbering metadata", async () => { const { ensureTerminalPanelSession, diff --git a/tests/unit/renderer/settings/agent-row-details.test.tsx b/tests/unit/renderer/settings/agent-row-details.test.tsx new file mode 100644 index 000000000..806c34e43 --- /dev/null +++ b/tests/unit/renderer/settings/agent-row-details.test.tsx @@ -0,0 +1,66 @@ +import type { AgentLifecycleProbe } from "@shared/contracts/agent/lifecycle.ts"; +import { cleanup, render, screen } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { initI18n } from "@/i18n/index.ts"; +import { AgentExpandedDetails } from "@/pages/settings/components/agent-row-details.tsx"; +import { useAgentLifecycleStore } from "@/stores/agent-lifecycle.store.ts"; +import { useAgentPreferencesStore } from "@/stores/agent-preferences.store.ts"; + +const HINT = + "Pi’s current settings hide its status from Pier. Run pi config to turn it back on."; + +function probe(patch: Partial = {}): AgentLifecycleProbe { + return { + agentId: "pi", + canInstall: true, + canUninstall: false, + detected: true, + installedButBroken: false, + installs: [], + isConflict: false, + latestVersion: null, + support: "full", + uninstallMode: "none", + updateAvailable: false, + updateMode: "versioned", + updateOffered: false, + version: "1.2.3", + ...patch, + }; +} + +describe("AgentExpandedDetails status-hook diagnostic", () => { + beforeEach(async () => { + await initI18n(); + useAgentPreferencesStore.setState({ + agentCommandOverrides: {}, + agentDefaultArgs: {}, + agentDefaultEnv: {}, + agentPermissionMode: "manual", + agentStatusHooks: true, + defaultAgentId: null, + disabledAgentIds: [], + }); + useAgentLifecycleStore.setState({ probesById: {} }); + }); + + afterEach(cleanup); + + it("shows the hint when the agent config hides the status feed", () => { + useAgentLifecycleStore.setState({ + probesById: { pi: probe({ statusHooksDisabledByConfig: true }) }, + }); + + render(); + + expect(screen.getByText(HINT)).toBeInTheDocument(); + }); + + it("stays quiet when the status feed is enabled", () => { + useAgentLifecycleStore.setState({ probesById: { pi: probe() } }); + + render(); + + expect(screen.queryByText(HINT)).not.toBeInTheDocument(); + }); +});