Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): carry final reply in done.result + gate Pi against SSH remotes
Chris0a5dca30a079
diff --git a/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts b/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.tsindex b4acee2918..aa19e0ad00 100644--- a/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts+++ b/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts@@ -263,6 +263,19 @@ describe('Shared create project picker', () => {expect(newMakerDraftRouteSource).not.toContain('buildDeviceLinkCreateArgs({');});+ // codex review P1:Pi 是本地专属 agent(startSession 拒绝任何 remoteHostId),SSH 目标+ // 会建出永远起不来的会话。两道防线:dialog 按 agentVendor 过滤掉 SSH 主机(proactive),+ // handleRemoteProjectAdded 的 SSH 分支再 fail-closed 兜底(防非 UI 路径漏进 Pi+SSH)。+ it('hides SSH targets for Pi and fail-closed guards Pi+SSH session creation', () => {+ // dialog:选中 Pi 时把 SSH 主机从可选目标里剔除。+ expect(addRemoteProjectDialogSource).toContain("agentVendor === 'pi'");+ expect(addRemoteProjectDialogSource).toMatch(/excludeSsh\s*\?\s*\[\]/);+ // 父层把当前 draft.vendor 传进 dialog 驱动过滤。+ expect(newMakerDraftRouteSource).toContain('agentVendor={draft.vendor}');+ // 兜底:SSH 建会话前拦住 Pi,抛清晰的本地化错误而非建出注定失败的会话。+ expect(newMakerDraftRouteSource).toContain("t('ccAgent.draft.piRemoteUnsupported')");+ });+// #807:设备切换 pill。三条产品裁决写进源码断言,防后续重构悄悄改掉。it('wires the device switcher pill and keeps it invisible without paired devices', () => {expect(newMakerDraftRouteSource).toContain(diff --git a/apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx b/apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsxindex 5aaaf92a86..9ce8c801fd 100644--- a/apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx+++ b/apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx@@ -22,6 +22,7 @@ import * as Dialog from '@radix-ui/react-dialog';import { X, Folder, FolderSymlink, ChevronLeft, RotateCw } from 'lucide-react';import { cn } from '@/lib/utils';+import type { MakerVendor } from '@/lib/ccAgent.types';import { Spinner } from '@/components/ui/spinner';import { toast } from '@/lib/toast';import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';@@ -59,6 +60,14 @@ interface Props {* 未指名(从通用入口打开)时才由用户自己在下拉里选。*/initialDeviceId?: string | null;+ /**+ * 当前 draft 选中的 agent(由父层的 VendorSegmentedSwitcher 决定,dialog 不选 vendor)。+ * Pi 是本地专属 agent:startSession 拒绝任何 remoteHostId(见 agents/pi/index.ts),+ * 所以选中 Pi 时把 SSH 主机从可选目标里过滤掉 —— 用户根本选不到会建出「起不来的 SSH+ * 会话」的目标(codex review P1)。device-link 不受影响:被控端跑自己的本地 Pi 进程,+ * 不经 SSH remoteHostId。+ */+ agentVendor?: MakerVendor;/** vendor 不在 dialog 里选 —— 由父层根据当前 draft / segmented switcher 决定。 */onProjectAdded: (target: RemoteProjectTarget) => void | Promise<void>;}@@ -67,6 +76,7 @@ export function AddRemoteProjectDialog({open,onOpenChange,initialDeviceId,+ agentVendor,onProjectAdded,}: Props) {const { t } = useTranslation();@@ -80,13 +90,17 @@ export function AddRemoteProjectDialog({// SSH「已有项目」数据源:本地 active 会话(按 host 过滤,见 sshExistingProjects)。const { sessions } = useCCSessions();+ // 选中 Pi 时排除 SSH 主机:Pi 不支持 remoteHostId,选中即建出起不来的会话。+ const excludeSsh = agentVendor === 'pi';const targets = useMemo<RemoteTarget[]>(() => {- const ssh: RemoteTarget[] = sshHosts.map((h) => ({- key: `ssh:${h.config.id}`,- kind: 'ssh',- hostId: h.config.id,- label: `${h.config.id} (${h.config.user}@${h.config.hostname})`,- }));+ const ssh: RemoteTarget[] = excludeSsh+ ? []+ : sshHosts.map((h) => ({+ key: `ssh:${h.config.id}`,+ kind: 'ssh',+ hostId: h.config.id,+ label: `${h.config.id} (${h.config.user}@${h.config.hostname})`,+ }));const dev: RemoteTarget[] = devices.map((d) => ({key: `device:${d.deviceId}`,kind: 'device',@@ -95,7 +109,7 @@ export function AddRemoteProjectDialog({label: d.name,}));return [...ssh, ...dev];- }, [sshHosts, devices]);+ }, [excludeSsh, sshHosts, devices]);const sshTargets = useMemo(() => targets.filter((tg) => tg.kind === 'ssh'), [targets]);const deviceTargets = useMemo(() => targets.filter((tg) => tg.kind === 'device'), [targets]);@@ -313,6 +327,8 @@ export function AddRemoteProjectDialog({}, [selectedTarget, adapter, path, confirm, onProjectAdded, onOpenChange, t]);const noTargets = targets.length === 0;+ // Pi 过滤掉 SSH 后无任何可用目标时,通用空态提示「加个 SSH 主机」是误导(Pi 用不了 SSH)。+ const emptyIsPiSshFiltered = noTargets && excludeSsh && sshHosts.length > 0;return (<Dialog.Root open={open} onOpenChange={busy ? undefined : onOpenChange}>@@ -372,7 +388,9 @@ export function AddRemoteProjectDialog({<div className="flex flex-col gap-3 px-5 py-4">{noTargets ? (<div className="text-13 py-8 text-center" style={{ color: 'var(--text-secondary)' }}>- {t('newChat.addRemoteProject.empty')}+ {t(emptyIsPiSshFiltered+ ? 'newChat.addRemoteProject.emptyPiSshFiltered'+ : 'newChat.addRemoteProject.empty')}</div>) : (<>diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsxindex 0aec6fc90c..5fa3111db7 100644--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx@@ -1596,6 +1596,14 @@ export function NewMakerDraftRoute() {return;}+ // fail-closed:Pi 是本地专属 agent,PiAgent.startSession 拒绝任何 remoteHostId+ // (agents/pi/index.ts)。SSH 目标会带 remoteHostId 建会话 → 首消息必然起不来。+ // dialog 侧已按 agentVendor 过滤掉 SSH 主机,这里是防非 UI 路径(编程调用 / 未来回归)+ // 漏进 Pi+SSH 的兜底,抛清晰错误由 dialog 呈现,而不是建出一条注定失败的会话(codex review P1)。+ if (draftVendor === 'pi') {+ throw new Error(t('ccAgent.draft.piRemoteUnsupported'));+ }+// SSH:lazy-create(workspaceKind='project',第一条消息发出时 agent 进程才真正起),// 立即建会话记录并 navigate 过去。建会话约定与本文件其它 createSession 路径一致// (createSession + makerChatStore.setSessionRuntime + navigate)。@@ -3719,6 +3727,9 @@ export function NewMakerDraftRoute() {open={addRemoteProjectOpen}onOpenChange={setAddRemoteProjectOpen}initialDeviceId={addRemoteProjectDeviceId}+ // 选中 Pi 时 dialog 过滤掉 SSH 主机(Pi 不支持 remoteHostId);handleRemoteProjectAdded+ // 里还有一道 fail-closed 兜底,防非 UI 路径漏进 Pi+SSH。+ agentVendor={draft.vendor}onProjectAdded={handleRemoteProjectAdded}/></div>diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex cf16d3d390..0e9397db10 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -4668,6 +4668,7 @@"add": "Add project","cancel": "Cancel","empty": "Connect a controllable device under Settings → Remote connection, or add an SSH host under Settings → Remote machines first.",+ "emptyPiSshFiltered": "Pi runs locally only, so SSH hosts aren't shown here. Connect a controllable device under Settings → Remote connection, or switch to Claude or Codex to use an SSH host.","loading": "Loading…","noSubdirs": "No subfolders here","doubleClickHint": "Double-click to enter",@@ -5954,6 +5955,7 @@},"draft": {"createSessionFailed": "Failed to create session, please retry",+ "piRemoteUnsupported": "Pi runs locally only and can't use SSH remote hosts. Switch to Claude or Codex to use this host.","remoteWorktreeCleanupPending": "The previous remote worktree is still awaiting cleanup. Reconnect the device and try again.","remoteProviderUpdating": "Provider credentials are being updated — retry in a moment","remoteProviderUnsupported": "This provider is not supported in SSH remote sessions — pick another source",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex bb396cf8ea..18e2fa93e3 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -4666,6 +4666,7 @@"add": "プロジェクトを追加","cancel": "キャンセル","empty": "「設定 → リモート接続」で被制御デバイスに接続するか、「設定 → リモートマシン」で SSH ホストを追加してください。",+ "emptyPiSshFiltered": "Pi はローカルでのみ動作するため、ここに SSH ホストは表示されません。「設定 → リモート接続」で被制御デバイスに接続するか、SSH ホストを使う場合は Claude または Codex に切り替えてください。","loading": "読み込み中…","noSubdirs": "サブフォルダはありません","doubleClickHint": "ダブルクリックで入る",@@ -5943,6 +5944,7 @@},"draft": {"createSessionFailed": "セッションの作成に失敗しました。再試行してください",+ "piRemoteUnsupported": "Pi はローカルでのみ動作し、SSH リモートホストは利用できません。このホストを使うには Claude または Codex に切り替えてください。","remoteWorktreeCleanupPending": "前回のリモート worktree はまだクリーンアップ待ちです。デバイスを再接続してから再試行してください。","remoteProviderUpdating": "プロバイダーの認証情報を更新中です。しばらくしてから再試行してください","remoteProviderUnsupported": "このプロバイダーは SSH リモートセッションに対応していません。別のソースを選択してください",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex ddd469a74a..e62554c2be 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -4666,6 +4666,7 @@"add": "프로젝트 추가","cancel": "취소","empty": "먼저 「설정 → 원격 연결」에서 제어 가능한 기기에 연결하거나 「설정 → 원격 머신」에서 SSH 호스트를 추가하세요.",+ "emptyPiSshFiltered": "Pi는 로컬에서만 실행되어 여기에 SSH 호스트가 표시되지 않습니다. 「설정 → 원격 연결」에서 제어 가능한 기기에 연결하거나, SSH 호스트를 사용하려면 Claude 또는 Codex로 전환하세요.","loading": "로드 중…","noSubdirs": "하위 폴더가 없습니다","doubleClickHint": "더블 클릭으로 진입",@@ -5943,6 +5944,7 @@},"draft": {"createSessionFailed": "세션 생성에 실패했습니다. 다시 시도하세요",+ "piRemoteUnsupported": "Pi는 로컬에서만 실행되어 SSH 원격 호스트를 사용할 수 없습니다. 이 호스트를 사용하려면 Claude 또는 Codex로 전환하세요.","remoteWorktreeCleanupPending": "이전 원격 worktree가 아직 정리 대기 중입니다. 기기를 다시 연결한 후 재시도하세요.","remoteProviderUpdating": "제공자 자격 증명을 업데이트하는 중입니다. 잠시 후 다시 시도하세요","remoteProviderUnsupported": "이 제공자는 SSH 원격 세션을 지원하지 않습니다. 다른 소스를 선택하세요",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex dd28ece3d6..1f21fffdae 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -4666,6 +4666,7 @@"add": "添加项目","cancel": "取消","empty": "请先在「设置 → 远程连接」连接一台被控设备,或在「设置 → 远端机器」添加 SSH 主机。",+ "emptyPiSshFiltered": "Pi 仅在本地运行,这里不显示 SSH 主机。请在「设置 → 远程连接」连接一台被控设备,或切换到 Claude / Codex 以使用 SSH 主机。","loading": "加载中…","noSubdirs": "此目录下没有子文件夹","doubleClickHint": "双击进入此文件夹",@@ -5943,6 +5944,7 @@},"draft": {"createSessionFailed": "创建任务失败,请重试",+ "piRemoteUnsupported": "Pi 仅在本地运行,无法使用 SSH 远程主机。请切换到 Claude 或 Codex 来使用该主机。","remoteWorktreeCleanupPending": "上一次远程 worktree 仍待回收,请重新连接设备后再试。","remoteProviderUpdating": "供应商凭证正在更新,请稍后重试","remoteProviderUnsupported": "该供应商不支持 SSH 远程会话,请更换来源",diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.tsindex a3809b2f67..7eceb598fd 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts@@ -83,12 +83,48 @@ describe('pi translator', () => {expect(usage.cacheCreationTokens).toBe(3);// 快照累计 input+output。expect(usageSnapshotOf(ctx).tokenUsage).toBe(120);+ // done.data.result 带上最终回复文本 —— register.ts 的 will-assistant-message 出口钩子+ // 与 Orca worker 终态 finalText 都读它,不带上就对 Pi 静默跳过(codex review P1)。+ expect((done!.data as { result?: unknown }).result).toBe('hi');expect(events).toContainEqual(expect.objectContaining({type: 'status',data: expect.objectContaining({ status: 'Done', isRunning: false }),}));});+ it('done.result carries the last assistant message text (multi-message turn) and resets per turn', () => {+ const ctx = createPiTranslateContext(noopLogger);+ const { queue, events } = makeQueue();+ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);+ // 文本 → 纯 tool_call(无文本)→ 最终文本:result 应取最后一条有文本的回复。+ translatePiEvent(+ ev({ type: 'message_end', message: { role: 'assistant', content: [{ type: 'text', text: 'thinking…' }], usage: { input: 10, output: 2 } } }),+ queue,+ ctx,+ );+ translatePiEvent(+ ev({ type: 'message_end', message: { role: 'assistant', content: [{ type: 'tool_use', id: 't1', name: 'x', input: {} }], usage: { input: 5, output: 1 } } }),+ queue,+ ctx,+ );+ translatePiEvent(+ ev({ type: 'message_end', message: { role: 'assistant', content: [{ type: 'text', text: 'final answer' }], usage: { input: 5, output: 3 } } }),+ queue,+ ctx,+ );+ translatePiEvent(ev({ type: 'agent_settled' }), queue, ctx);+ const done = events.find((e) => e.type === 'done');+ expect((done!.data as { result?: unknown }).result).toBe('final answer');++ // 新 turn:result 归零,不带上一 turn 的回复。+ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);+ expect(ctx.finalAssistantText).toBe('');+ const events2 = makeQueue();+ translatePiEvent(ev({ type: 'agent_settled' }), events2.queue, ctx);+ const done2 = events2.events.find((e) => e.type === 'done');+ expect((done2!.data as { result?: unknown }).result).toBe('');+ });+it('resets turn usage counters on the next agent_start', () => {const ctx = createPiTranslateContext(noopLogger);const { queue } = makeQueue();diff --git a/packages/maker-core/src/agents/pi/translator.ts b/packages/maker-core/src/agents/pi/translator.tsindex cc6ae80ecf..8af504a5e5 100644--- a/packages/maker-core/src/agents/pi/translator.ts+++ b/packages/maker-core/src/agents/pi/translator.ts@@ -63,6 +63,13 @@ export interface PiTranslateContext {thinkingSeq: number;/** contentIndex → 当前消息内的 thinking block 状态。 */thinkingBlocks: Map<number, PiThinkingBlock>;+ /**+ * 本 turn 最后一条 assistant 消息的全文(每次非空 message_end 覆盖;agent_start 重置)。+ * 用于 agent_settled 的 done.data.result —— 与 CC/Codex 对齐:register.ts 的+ * will-assistant-message 出口钩子与 Orca worker 终态 finalText 都读 done.data.result,+ * 不带上就会对 Pi 静默跳过这些钩子(codex review P1)。+ */+ finalAssistantText: string;}export function createPiTranslateContext(logger: Logger): PiTranslateContext {@@ -79,6 +86,7 @@ export function createPiTranslateContext(logger: Logger): PiTranslateContext {isStreaming: false,thinkingSeq: 0,thinkingBlocks: new Map(),+ finalAssistantText: '',};}@@ -181,6 +189,7 @@ export function translatePiEvent(ctx.turnOutput = 0;ctx.turnCacheRead = 0;ctx.turnCacheWrite = 0;+ ctx.finalAssistantText = '';pushStatus(queue, ctx, 'Working…', true);return;}@@ -206,6 +215,8 @@ export function translatePiEvent(applyUsage(ctx, message.usage);const fullText = assistantTextOf(message);if (fullText.length > 0) {+ // 覆盖为本 turn 最新一条有文本的 assistant 回复,agent_settled 作 done.result 上报。+ ctx.finalAssistantText = fullText;queue.push({type: 'text',data: { text: fullText, isFinal: true },@@ -270,6 +281,10 @@ export function translatePiEvent(type: 'done',data: {type: 'pi/agent_settled',+ // 本 turn 最终 assistant 回复文本。与 CC/Codex 的 done.data.result 对齐:+ // register.ts 的 will-assistant-message 出口钩子与 Orca worker 终态 finalText+ // 都读 done.data.result,不带上就会对 Pi 静默跳过这些钩子(codex review P1)。+ result: ctx.finalAssistantText,// ghost 订阅 did-turn-end 的 usage 上报(subscriptionGateway.normalizeTurnUsage// 认 camelCase);与 CC/Codex 的 done.usage 对齐,让插件能显示 pi turn 的用量。usage: {