gentle-pi 4.7.0 → 4.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +55 -44
- package/assets/agents/gentle-ai-explore.md +3 -3
- package/assets/agents/gentle-ai-verify.md +20 -6
- package/assets/agents/gentle-ai-worker.md +6 -6
- package/assets/agents/jd-judge-a.md +1 -3
- package/assets/agents/jd-judge-b.md +1 -3
- package/assets/agents/review-readability.md +1 -5
- package/assets/agents/review-reliability.md +1 -5
- package/assets/agents/review-resilience.md +1 -5
- package/assets/agents/review-risk.md +1 -5
- package/assets/design-canvas/canvas-api.js +45 -0
- package/assets/design-canvas/canvas-boards.js +456 -0
- package/assets/design-canvas/canvas-boot.js +217 -0
- package/assets/design-canvas/canvas-checks.js +491 -0
- package/assets/design-canvas/canvas-comments.js +315 -0
- package/assets/design-canvas/canvas-compare.js +159 -0
- package/assets/design-canvas/canvas-events.js +75 -0
- package/assets/design-canvas/canvas-export.js +393 -0
- package/assets/design-canvas/canvas-focus.js +203 -0
- package/assets/design-canvas/canvas-handoffs.js +150 -0
- package/assets/design-canvas/canvas-i18n-es.js +392 -0
- package/assets/design-canvas/canvas-i18n.js +108 -0
- package/assets/design-canvas/canvas-layout.js +526 -0
- package/assets/design-canvas/canvas-menu.js +213 -0
- package/assets/design-canvas/canvas-messages.js +86 -0
- package/assets/design-canvas/canvas-minimap.js +163 -0
- package/assets/design-canvas/canvas-parts.js +401 -0
- package/assets/design-canvas/canvas-popover.js +234 -0
- package/assets/design-canvas/canvas-rail.js +348 -0
- package/assets/design-canvas/canvas-sizes.js +524 -0
- package/assets/design-canvas/canvas-store.js +164 -0
- package/assets/design-canvas/canvas-tokens.js +674 -0
- package/assets/design-canvas/canvas-ui.js +24 -0
- package/assets/design-canvas/canvas-view.js +184 -0
- package/assets/design-canvas/canvas.css +746 -15
- package/assets/design-canvas/canvas.js +2 -1506
- package/assets/design-canvas/index.html +117 -36
- package/assets/design-canvas/inspector.js +546 -16
- package/assets/install-wizard/wizard.js +5 -1
- package/assets/migrations/agent-body-history.json +24 -0
- package/assets/orchestrator-delegation-reference.md +8 -14
- package/assets/orchestrator-delegation.md +4 -4
- package/assets/orchestrator-full-delegation-card.md +4 -5
- package/assets/orchestrator-full-delegation.md +8 -8
- package/assets/orchestrator-memory.md +2 -2
- package/assets/orchestrator-prompts.md +1 -1
- package/assets/orchestrator-quota-recovery.md +5 -0
- package/assets/orchestrator-skills.md +13 -12
- package/assets/orchestrator-tracking.md +10 -14
- package/assets/orchestrator-verification.md +10 -8
- package/assets/orchestrator-writer.md +4 -4
- package/assets/orchestrator.md +18 -22
- package/bin/gentle-shell.mjs +128 -9
- package/contracts/review-provider-contract-mirror/provider-contract.lock.json +8 -9
- package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/manifest.json +3 -3
- package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/orchestration/pi.md +1 -0
- package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/routing/pi.md +6 -6
- package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/generated/provider-capabilities.baseline.json +3 -3
- package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/generated/provider-roles.baseline.json +1 -1
- package/docs/assets/brand/sponsor-banner.svg +60 -0
- package/docs/bundled-install.md +14 -6
- package/docs/delegated-verification.md +18 -2
- package/docs/desktop-rpc.md +1253 -0
- package/docs/gentle-agents-activity.md +26 -0
- package/docs/gentle-shell.md +39 -16
- package/docs/install-wizard.md +30 -21
- package/docs/odd-preparation-continuity.md +24 -0
- package/docs/permission-modes.md +9 -1
- package/docs/prompt-budget.md +12 -0
- package/docs/rdd-odd-friction-triage-2026-11-07.md +57 -0
- package/docs/readme-reference.md +76 -24
- package/docs/review-coordinator.md +29 -9
- package/docs/review-delivery-preflight.md +22 -0
- package/docs/work-continuity.md +11 -1
- package/extensions/ask-user-question.ts +2 -2
- package/extensions/child-context.ts +21 -7
- package/extensions/gentle-agents.ts +234 -33
- package/extensions/gentle-ai.ts +576 -135
- package/extensions/gentle-design.ts +69 -3
- package/extensions/gentle-desktop-rpc.ts +143 -0
- package/extensions/gentle-guide.ts +3 -0
- package/extensions/gentle-shell.ts +105 -52
- package/extensions/gentle-todo.ts +48 -25
- package/extensions/skill-registry.ts +248 -223
- package/lib/agent-assets.ts +30 -6
- package/lib/agent-tool-overlay.ts +117 -0
- package/lib/agents-config.ts +47 -6
- package/lib/agents-message-delivery.ts +17 -0
- package/lib/agents-messaging.ts +8 -2
- package/lib/agents-protocol.ts +15 -0
- package/lib/agents-report-cap.ts +115 -0
- package/lib/agents-runner.ts +91 -6
- package/lib/agents-session-transport.ts +17 -1
- package/lib/background-jobs-tools.ts +9 -4
- package/lib/bounded-writer-admission.ts +184 -31
- package/lib/child-context-files.ts +21 -6
- package/lib/codemode-renderer.ts +1 -0
- package/lib/delivery-conflict-markers.ts +349 -0
- package/lib/design-canvas-assets.ts +36 -0
- package/lib/design-canvas-server.ts +241 -23
- package/lib/design-comments.ts +94 -4
- package/lib/design-handoffs.ts +2 -1
- package/lib/design-layout.ts +125 -0
- package/lib/design-parts.ts +281 -0
- package/lib/design-system-tokens.ts +111 -0
- package/lib/desktop-agents-service.ts +294 -0
- package/lib/desktop-design-service.ts +233 -0
- package/lib/desktop-jobs-service.ts +263 -0
- package/lib/desktop-rpc-agents.ts +294 -0
- package/lib/desktop-rpc-config.ts +731 -0
- package/lib/desktop-rpc-design.ts +138 -0
- package/lib/desktop-rpc-jobs.ts +181 -0
- package/lib/desktop-rpc-permissions.ts +177 -0
- package/lib/desktop-rpc-profiles.ts +196 -0
- package/lib/desktop-rpc-usage.ts +229 -0
- package/lib/desktop-rpc.ts +225 -0
- package/lib/desktop-usage-service.ts +310 -0
- package/lib/destructive-command-guard.ts +188 -13
- package/lib/gentle-ai-renderer.ts +13 -1
- package/lib/gentle-design.ts +201 -14
- package/lib/gentle-shell-bundled.ts +100 -9
- package/lib/hidden-tools.ts +35 -0
- package/lib/inprocess-reviewer.ts +96 -12
- package/lib/model-fallback-policy.ts +9 -0
- package/lib/model-routing-authority.ts +9 -0
- package/lib/nan-provider.ts +42 -28
- package/lib/native-review-cli.ts +79 -4
- package/lib/orchestrator-discovery.ts +39 -2
- package/lib/reply-language-anchor.ts +27 -2
- package/lib/request-context-placement.ts +53 -0
- package/lib/review-candidate-view.ts +11 -1
- package/lib/review-continuation-registry.ts +17 -0
- package/lib/review-coordinator.ts +252 -8
- package/lib/review-delivery-preflight.ts +85 -0
- package/lib/review-host-relay.ts +5 -1
- package/lib/review-integration-v2.ts +56 -3
- package/lib/reviewer-stream.ts +87 -0
- package/lib/shell-prompt.ts +16 -3
- package/lib/shell-usage.ts +10 -0
- package/lib/vim-editor-adapter.ts +9 -2
- package/lib/writer-batch-admission.ts +55 -0
- package/lib/yolo-session-policy.ts +6 -1
- package/package.json +2 -2
- package/prompts/skill-creation.md +1 -10
- package/runtime/design-canvas-assets.mjs +37 -0
- package/runtime/gentle-shell-bundled.mjs +100 -9
- package/runtime/native-review-cli.mjs +79 -4
- package/runtime/review-integration-v2.mjs +56 -3
- package/scripts/bootstrap.cmd +2 -2
- package/scripts/bootstrap.sh +41 -4
- package/scripts/build-full-delegation-card.mjs +4 -0
- package/scripts/build-runtime-modules.mjs +1 -0
- package/scripts/gentle-ai-installer.mjs +10 -10
- package/scripts/gentle-ai-proxy.mjs +1 -1
- package/scripts/installer-downloads.mjs +34 -8
- package/scripts/installer-preflight.mjs +28 -17
- package/scripts/installer-probes.mjs +25 -5
- package/scripts/installer-server.mjs +38 -9
- package/scripts/installer-windows.mjs +2 -2
- package/scripts/pi-update.mjs +166 -27
- package/scripts/prepare-verifier.mjs +107 -0
- package/scripts/update-agent-body-history.mjs +55 -8
- package/scripts/verify-package-files.mjs +40 -19
- package/skills/branch-pr/SKILL.md +16 -16
- package/skills/comment-writer/SKILL.md +1 -1
- package/skills/design/SKILL.md +6 -6
- package/skills/gentle-ai/SKILL.md +5 -5
- package/skills/judgment-day/SKILL.md +2 -2
- package/skills/judgment-day/references/prompts-and-formats.md +1 -1
- package/skills/rdd-defect-workflow/SKILL.md +6 -6
- package/skills/skill-improver/SKILL.md +2 -2
- package/skills/skill-registry/SKILL.md +11 -13
- package/skills/tui-design/SKILL.md +1 -1
- package/skills/work-unit-commits/SKILL.md +5 -5
- package/tests/agent-prompt-diet-contract.test.ts +101 -0
- package/tests/agent-tool-overlay-acceptance.test.ts +158 -0
- package/tests/agent-tool-overlay.test.ts +89 -0
- package/tests/agents-config.test.ts +10 -1
- package/tests/agents-message-delivery.test.ts +36 -0
- package/tests/agents-queries.test.ts +144 -4
- package/tests/agents-report-cap.test.ts +126 -0
- package/tests/agents-runner.test.ts +37 -1
- package/tests/agents-session-transport.test.ts +34 -0
- package/tests/always-on-prompt-verdicts-contract.test.ts +188 -0
- package/tests/append-system-prompt-route.test.ts +10 -2
- package/tests/approved-text-leftovers-contract.test.ts +136 -0
- package/tests/artifact-language.test.ts +1 -1
- package/tests/ask-user-question.test.ts +2 -1
- package/tests/audit-leftovers-contract.test.ts +51 -0
- package/tests/bounded-stop-contract.test.ts +9 -1
- package/tests/branch-pr-skill.test.ts +10 -1
- package/tests/bundled-install.test.ts +1 -1
- package/tests/child-context-files.test.ts +64 -8
- package/tests/child-skills-catalog.test.ts +56 -0
- package/tests/codemode-rendering.test.ts +4 -1
- package/tests/delegate-for-reason-contract.test.ts +30 -8
- package/tests/delivery-conflict-markers.test.ts +348 -0
- package/tests/design-canvas-all-sizes.test.ts +631 -0
- package/tests/design-canvas-allowlist.test.ts +32 -0
- package/tests/design-canvas-assets.test.ts +11 -878
- package/tests/design-canvas-boards.test.ts +77 -0
- package/tests/design-canvas-checks.test.ts +655 -0
- package/tests/design-canvas-compare.test.ts +79 -0
- package/tests/design-canvas-events.test.ts +59 -0
- package/tests/design-canvas-export.test.ts +1168 -0
- package/tests/design-canvas-focus.test.ts +113 -0
- package/tests/design-canvas-handoffs.test.ts +59 -0
- package/tests/design-canvas-i18n-review.test.ts +513 -0
- package/tests/design-canvas-i18n-views.test.ts +259 -0
- package/tests/design-canvas-i18n.test.ts +526 -0
- package/tests/design-canvas-inspector.test.ts +937 -0
- package/tests/design-canvas-layout.test.ts +1222 -0
- package/tests/design-canvas-minimap.test.ts +413 -0
- package/tests/design-canvas-modules.test.ts +90 -0
- package/tests/design-canvas-parts.test.ts +721 -0
- package/tests/design-canvas-rail.test.ts +799 -0
- package/tests/design-canvas-server.test.ts +855 -17
- package/tests/design-canvas-sizes.test.ts +548 -0
- package/tests/design-canvas-store.test.ts +180 -0
- package/tests/design-canvas-tokens.test.ts +965 -0
- package/tests/design-canvas-view.test.ts +299 -0
- package/tests/design-comments.test.ts +201 -1
- package/tests/design-handoffs.test.ts +20 -0
- package/tests/design-layout.test.ts +100 -0
- package/tests/design-parts.test.ts +260 -0
- package/tests/design-system-tokens.test.ts +215 -0
- package/tests/desktop-rpc-agents.test.ts +893 -0
- package/tests/desktop-rpc-config.test.ts +1452 -0
- package/tests/desktop-rpc-design.test.ts +662 -0
- package/tests/desktop-rpc-jobs.test.ts +796 -0
- package/tests/desktop-rpc-permissions.test.ts +311 -0
- package/tests/desktop-rpc-profiles.test.ts +140 -0
- package/tests/desktop-rpc-safety.test.ts +119 -0
- package/tests/desktop-rpc-usage.test.ts +697 -0
- package/tests/desktop-rpc.test.ts +252 -0
- package/tests/devbinary/pi-host-relay.devtest.ts +149 -80
- package/tests/devbinary/review-session-consent.devtest.ts +84 -0
- package/tests/engram-safety.test.ts +111 -0
- package/tests/fixtures/devbinary/status-v9-escalated-non-blocking.captured.json +92 -0
- package/tests/fixtures/devbinary/status-v9-escalated-non-blocking.provenance.md +3 -0
- package/tests/fixtures/primary-session-prompt/gentleman.golden.md +20 -29
- package/tests/fixtures/refusal-identity.probe.mjs +139 -0
- package/tests/full-delegation-closure.test.ts +29 -0
- package/tests/gentle-agents.test.ts +329 -4
- package/tests/gentle-ai-binary.test.ts +1 -1
- package/tests/gentle-ai-child-guards.test.ts +1 -0
- package/tests/gentle-ai-installer.test.ts +52 -51
- package/tests/gentle-ai-renderer.test.ts +36 -2
- package/tests/gentle-ai.test.ts +121 -6
- package/tests/gentle-design.test.ts +365 -1
- package/tests/gentle-shell-bundled.test.ts +91 -5
- package/tests/gentle-shell-launcher.test.ts +1 -1
- package/tests/gentle-shell.test.ts +118 -87
- package/tests/gentle-todo.test.ts +32 -9
- package/tests/hidden-tools.test.ts +188 -0
- package/tests/independent-recovery-delivery.test.ts +19 -5
- package/tests/inprocess-reviewer.test.ts +73 -0
- package/tests/install-wizard.test.ts +27 -1
- package/tests/installer-downloads.test.ts +30 -1
- package/tests/installer-posix-bootstrap.test.ts +114 -13
- package/tests/installer-preflight.test.ts +49 -1
- package/tests/installer-probes.test.ts +146 -0
- package/tests/installer-server.test.ts +203 -4
- package/tests/installer-windows-bootstrap.test.ts +19 -1
- package/tests/judgment-day-severity-admission.test.ts +46 -0
- package/tests/lazy-module-contradictions-contract.test.ts +158 -0
- package/tests/maintainer/desktop-rpc.maintest.ts +632 -0
- package/tests/maintainer/pi-update-source.maintest.ts +48 -18
- package/tests/model-fallback-policy.test.ts +26 -7
- package/tests/nan-provider-runtime.test.ts +17 -3
- package/tests/nan-provider.test.ts +111 -56
- package/tests/native-review-capability-contract.test.ts +11 -1
- package/tests/native-review-cli-nonblocking-findings.test.ts +165 -0
- package/tests/native-review-parity.test.ts +24 -5
- package/tests/native-review-refusal-identity.test.ts +25 -0
- package/tests/no-self-pause-contract.test.ts +11 -3
- package/tests/odd-integration.test.ts +11 -3
- package/tests/odd-routing-contract.test.ts +80 -28
- package/tests/orchestrator-budget.test.ts +30 -5
- package/tests/orchestrator-consultation-sdk.test.ts +32 -6
- package/tests/orchestrator-delegation-mode.test.ts +2 -1
- package/tests/orchestrator-discovery.test.ts +28 -0
- package/tests/orchestrator-prompt-budget.test.ts +11 -2
- package/tests/orchestrator-prompt-diet-contract.test.ts +221 -0
- package/tests/orchestrator-rdd-ownership.test.ts +2 -1
- package/tests/orchestrator-work-search.test.ts +4 -2
- package/tests/package-files.test.ts +25 -1
- package/tests/package-manifest.test.ts +11 -10
- package/tests/parallel-reason-contract.test.ts +6 -3
- package/tests/permission-allowlist.test.ts +200 -30
- package/tests/persona-neutral-voseo.test.ts +4 -4
- package/tests/persona-reply-language.test.ts +1 -1
- package/tests/persona-single-channel.test.ts +13 -5
- package/tests/pi-update-launcher.test.ts +17 -7
- package/tests/pi-update-source.test.ts +113 -6
- package/tests/pi-update.test.ts +294 -19
- package/tests/pnpm-workspace-policy.test.ts +47 -0
- package/tests/primary-context-files.test.ts +233 -0
- package/tests/primary-context-three-files.test.ts +174 -0
- package/tests/provider-defect-handoff.test.ts +9 -2
- package/tests/rdd-aware-verification-contract.test.ts +1 -1
- package/tests/rdd-status-line.test.ts +94 -1
- package/tests/reply-language-anchor-placement.test.ts +184 -0
- package/tests/reply-language-anchor.test.ts +17 -1
- package/tests/request-context-append-only.test.ts +218 -0
- package/tests/request-context-placement.test.ts +148 -0
- package/tests/review-agent-end-preflight.test.ts +79 -1
- package/tests/review-candidate-view.test.ts +65 -0
- package/tests/review-continuation-registry.test.ts +31 -0
- package/tests/review-contract-prompt.test.ts +1 -1
- package/tests/review-controller.test.ts +2 -1
- package/tests/review-coordinator-correction-gate.test.ts +105 -0
- package/tests/review-coordinator-findings.test.ts +206 -0
- package/tests/review-coordinator-nonblocking-scope.test.ts +169 -0
- package/tests/review-coordinator.test.ts +271 -4
- package/tests/review-delivery-preflight.test.ts +462 -0
- package/tests/review-due-compaction.test.ts +31 -0
- package/tests/review-due-public-boundary.test.ts +26 -0
- package/tests/review-integration-nonblocking-findings.test.ts +108 -0
- package/tests/review-json-arguments.test.ts +41 -2
- package/tests/review-ledger-contract.test.ts +19 -40
- package/tests/review-loadout-rdd-off-sdk.test.ts +30 -1
- package/tests/review-one-call-findings.test.ts +131 -0
- package/tests/review-one-call-followups.test.ts +308 -0
- package/tests/review-one-call-reviewer-requests.test.ts +207 -0
- package/tests/review-one-call.test.ts +452 -0
- package/tests/review-relay-transport-agent.test.ts +28 -1
- package/tests/review-reviewer-evidence.test.ts +41 -1
- package/tests/review-risk-assessment.test.ts +52 -5
- package/tests/review-run-statement-guidance-independent.test.ts +54 -0
- package/tests/review-session-standing-permission-controller.test.ts +32 -2
- package/tests/review-tool-prose-budget.test.ts +1 -0
- package/tests/reviewer-stream.test.ts +149 -0
- package/tests/session-profile-extension.test.ts +2 -2
- package/tests/shell-prompt.test.ts +17 -0
- package/tests/shell-usage.test.ts +59 -10
- package/tests/skill-contradictions-contract.test.ts +122 -0
- package/tests/skill-registry-watcher.test.ts +216 -2
- package/tests/skill-registry.test.ts +929 -306
- package/tests/support/design-canvas-dom.ts +369 -0
- package/tests/support/review-coordinator-runtime.ts +212 -17
- package/tests/task-size-routing-contract.test.ts +42 -11
- package/tests/test-strength-contract.test.ts +2 -1
- package/tests/todo-request-append-only.test.ts +214 -0
- package/tests/tool-batching-contract.test.ts +3 -1
- package/tests/update-agent-body-history.test.ts +138 -0
- package/tests/verification-tiers-contract.test.ts +229 -0
- package/tests/verifier-preparation.test.ts +229 -0
- package/tests/verify-agent-contract.test.ts +20 -2
- package/tests/verify-first-launch-contract.test.ts +87 -11
- package/tests/vim-editor-adapter.test.ts +2 -2
- package/tests/work-continuity-contract.test.ts +54 -11
- package/tests/writer-admission-messages.test.ts +232 -0
- package/tests/writer-batch-admission.test.ts +66 -0
- package/tests/writer-edit-surface-scope.test.ts +52 -20
- package/tests/writer-feature-document-admission.test.ts +184 -0
- package/tests/yolo-mode.test.ts +39 -0
- package/skills/_shared/review-ledger-contract.md +0 -106
- /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/README.md +0 -0
- /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/lens.schema.json +0 -0
- /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/refuter.schema.json +0 -0
- /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/targeted-validator.schema.json +0 -0
- /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/lens.json +0 -0
- /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/refuter.json +0 -0
- /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/targeted-validator.json +0 -0
|
@@ -0,0 +1,893 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join, resolve } from "node:path";
|
|
5
|
+
import { test } from "node:test";
|
|
6
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
7
|
+
import desktopRpc from "../extensions/gentle-desktop-rpc.ts";
|
|
8
|
+
import gentleAgents, { type SessionTransportFactory } from "../extensions/gentle-agents.ts";
|
|
9
|
+
import { isFinished, TASK_STATUS, TaskStore, type ChildResponseObservation, type ChildTokenMeasurement, type TaskRecord } from "../lib/agents-protocol.ts";
|
|
10
|
+
import { historyDir, loadStoredTask, saveTask } from "../lib/agents-history.ts";
|
|
11
|
+
import { AgentRunner } from "../lib/agents-runner.ts";
|
|
12
|
+
import { fakeChild } from "./agents-fake-child.ts";
|
|
13
|
+
import {
|
|
14
|
+
AGENT_NOT_FOUND,
|
|
15
|
+
AGENTS_UNAVAILABLE,
|
|
16
|
+
DESKTOP_AGENTS_EVENT,
|
|
17
|
+
DESKTOP_AGENTS_EVENTS,
|
|
18
|
+
DESKTOP_AGENTS_LIST_LIMIT,
|
|
19
|
+
DESKTOP_AGENTS_METHODS,
|
|
20
|
+
DESKTOP_AGENTS_SERVICE_CHANNEL,
|
|
21
|
+
DESKTOP_AGENTS_SERVICE_SCHEMA,
|
|
22
|
+
INVALID_AGENTS_PARAMS,
|
|
23
|
+
accumulateTaskUsage,
|
|
24
|
+
isDesktopAgentsServiceShape,
|
|
25
|
+
parseCancelSubagentParams,
|
|
26
|
+
parseDesktopAgentEntry,
|
|
27
|
+
parseListSubagentsParams,
|
|
28
|
+
projectDesktopAgent,
|
|
29
|
+
selectDesktopAgents,
|
|
30
|
+
type DesktopAgentEntry,
|
|
31
|
+
type DesktopAgentsCancelOutcome,
|
|
32
|
+
type DesktopAgentsOwnerRead,
|
|
33
|
+
type DesktopAgentsService,
|
|
34
|
+
} from "../lib/desktop-rpc-agents.ts";
|
|
35
|
+
import { DesktopAgentsBridge, discoverDesktopAgentsService } from "../lib/desktop-agents-service.ts";
|
|
36
|
+
import { DESKTOP_RPC_SCHEMA, DesktopRpcRouter, type DesktopRpcDomain } from "../lib/desktop-rpc.ts";
|
|
37
|
+
import { INTERACTIVE_HOST_ENV } from "../lib/rpc-host.ts";
|
|
38
|
+
|
|
39
|
+
// ---- Fixtures: real TaskStore + a fake runner ----
|
|
40
|
+
|
|
41
|
+
function task(id: string, parentSessionId: string, overrides: Partial<TaskRecord> = {}): TaskRecord {
|
|
42
|
+
return {
|
|
43
|
+
id,
|
|
44
|
+
agent: "worker",
|
|
45
|
+
mode: "task",
|
|
46
|
+
prompt: "the full user prompt must never leak",
|
|
47
|
+
label: "worker",
|
|
48
|
+
cwd: "/secret/repo",
|
|
49
|
+
parentSessionId,
|
|
50
|
+
status: TASK_STATUS.RUNNING,
|
|
51
|
+
createdAt: 1000,
|
|
52
|
+
startedAt: 1000,
|
|
53
|
+
endedAt: null,
|
|
54
|
+
model: "anthropic/claude-probe",
|
|
55
|
+
thinking: "high",
|
|
56
|
+
sessionPath: "/sessions/child.jsonl",
|
|
57
|
+
error: null,
|
|
58
|
+
result: null,
|
|
59
|
+
lastStep: "working",
|
|
60
|
+
lastActivityAt: 1000,
|
|
61
|
+
turns: 1,
|
|
62
|
+
toolCalls: 2,
|
|
63
|
+
tokens: 1234,
|
|
64
|
+
cost: 0.005,
|
|
65
|
+
...overrides,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function reported(value: number): ChildTokenMeasurement {
|
|
70
|
+
return Object.freeze({ state: "reported", value });
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const unavailable = Object.freeze({ state: "unavailable" });
|
|
74
|
+
|
|
75
|
+
function observation(tokens: Partial<Record<"input" | "output" | "cacheRead" | "cacheWrite" | "reasoning", number>> = {}): ChildResponseObservation {
|
|
76
|
+
return Object.freeze({
|
|
77
|
+
provider: Object.freeze({ state: "observed", value: "anthropic" }),
|
|
78
|
+
model: Object.freeze({ state: "observed", value: "claude" }),
|
|
79
|
+
responseModel: Object.freeze({ state: "observed", value: "claude" }),
|
|
80
|
+
providerThinkingLevel: unavailable,
|
|
81
|
+
selected: Object.freeze({ provider: unavailable, model: unavailable, effort: unavailable }),
|
|
82
|
+
stopReason: "stop",
|
|
83
|
+
tokens: Object.freeze({
|
|
84
|
+
input: reported(tokens.input ?? 0),
|
|
85
|
+
output: reported(tokens.output ?? 0),
|
|
86
|
+
cacheRead: reported(tokens.cacheRead ?? 0),
|
|
87
|
+
cacheWrite: reported(tokens.cacheWrite ?? 0),
|
|
88
|
+
totalTokens: reported(0),
|
|
89
|
+
reasoning: reported(tokens.reasoning ?? 0),
|
|
90
|
+
}),
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
interface FakeRunner {
|
|
95
|
+
calls: Array<{ id: string; reason: string; result: boolean }>;
|
|
96
|
+
cancel(id: string, reason: string): boolean;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** A fake `AgentRunner`-shaped stop path that mirrors the real runner's cancel
|
|
100
|
+
* result: a queued task finishes synchronously, a live task is accepted with no
|
|
101
|
+
* synchronous store mutation, and a terminal task is refused. */
|
|
102
|
+
function makeRunner(store: TaskStore): FakeRunner {
|
|
103
|
+
const calls: Array<{ id: string; reason: string; result: boolean }> = [];
|
|
104
|
+
return {
|
|
105
|
+
calls,
|
|
106
|
+
cancel(id, reason) {
|
|
107
|
+
const current = store.get(id);
|
|
108
|
+
const result = current !== undefined && !isFinished(current.status);
|
|
109
|
+
calls.push({ id, reason, result });
|
|
110
|
+
if (result && current!.status === TASK_STATUS.QUEUED) {
|
|
111
|
+
store.update(id, { status: TASK_STATUS.CANCELLED, endedAt: 1000, lastStep: "cancelled: stopped from desktop before start" });
|
|
112
|
+
}
|
|
113
|
+
return result;
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function makeAgentsOwnerService(store: TaskStore, runner: FakeRunner, sessionId = "session-a") {
|
|
119
|
+
const observers = new Set<(sessionId: string) => void>();
|
|
120
|
+
let disposed = false;
|
|
121
|
+
const service: DesktopAgentsService = {
|
|
122
|
+
schema: DESKTOP_AGENTS_SERVICE_SCHEMA,
|
|
123
|
+
read: (): DesktopAgentsOwnerRead => ({ sessionId, agents: disposed ? [] : selectDesktopAgents(store.list(sessionId)) }),
|
|
124
|
+
cancel: (id: string): DesktopAgentsCancelOutcome => {
|
|
125
|
+
if (disposed) return { kind: "not_found" };
|
|
126
|
+
const before = store.get(id);
|
|
127
|
+
if (!before || before.parentSessionId !== sessionId) return { kind: "not_found" };
|
|
128
|
+
const requested = runner.cancel(id, "cancelled: stopped from desktop");
|
|
129
|
+
const after = store.get(id) ?? before;
|
|
130
|
+
const changed = requested && after.status !== before.status;
|
|
131
|
+
return { kind: "ok", agent: projectDesktopAgent(after), requested, changed };
|
|
132
|
+
},
|
|
133
|
+
observe: (onChange) => { observers.add(onChange); return () => observers.delete(onChange); },
|
|
134
|
+
dispose: () => { disposed = true; observers.clear(); },
|
|
135
|
+
};
|
|
136
|
+
return { service, observers, notify: (id: string) => { for (const observer of [...observers]) observer(id); } };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function recordedScheduler() {
|
|
140
|
+
const entries: Array<{ fn: () => void; ms: number; cancelled: boolean }> = [];
|
|
141
|
+
return {
|
|
142
|
+
entries,
|
|
143
|
+
schedule: (fn: () => void, ms: number) => {
|
|
144
|
+
const entry = { fn, ms, cancelled: false };
|
|
145
|
+
entries.push(entry);
|
|
146
|
+
return () => { entry.cancelled = true; };
|
|
147
|
+
},
|
|
148
|
+
pendingCount: () => entries.filter((entry) => !entry.cancelled).length,
|
|
149
|
+
flushAll: () => {
|
|
150
|
+
for (const entry of [...entries]) {
|
|
151
|
+
if (entry.cancelled) continue;
|
|
152
|
+
entry.cancelled = true;
|
|
153
|
+
entry.fn();
|
|
154
|
+
}
|
|
155
|
+
},
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function makeBridge(service: DesktopAgentsService, sessionId = "session-a", scheduler = recordedScheduler()) {
|
|
160
|
+
const bridge = new DesktopAgentsBridge({} as ExtensionAPI, { discover: async () => service, schedule: scheduler.schedule, coalesceMs: 10 });
|
|
161
|
+
const host = { sessionManager: { getSessionId: () => sessionId } } as unknown as ExtensionContext;
|
|
162
|
+
bridge.attach(host);
|
|
163
|
+
const events: Array<{ event: string; data: Record<string, unknown> }> = [];
|
|
164
|
+
bridge.wire((event, data) => events.push({ event, data }));
|
|
165
|
+
return { bridge, events, scheduler };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// ---- Pure contract: usage accumulation ----
|
|
169
|
+
|
|
170
|
+
test("accumulateTaskUsage sums only reported token breakdowns and ignores unavailable", () => {
|
|
171
|
+
const usage = accumulateTaskUsage([
|
|
172
|
+
observation({ input: 100, output: 40, cacheRead: 30, cacheWrite: 10, reasoning: 5 }),
|
|
173
|
+
observation({ input: 20, output: 10 }),
|
|
174
|
+
]);
|
|
175
|
+
assert.deepEqual(usage, { input: 120, output: 50, cacheRead: 30, cacheWrite: 10, reasoning: 5 });
|
|
176
|
+
|
|
177
|
+
// Unavailable measurements contribute nothing.
|
|
178
|
+
const empty = accumulateTaskUsage([]);
|
|
179
|
+
assert.deepEqual(empty, { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoning: 0 });
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
// ---- Pure contract: projection ----
|
|
183
|
+
|
|
184
|
+
test("projectDesktopAgent keeps only the whitelist and never prompt/cwd/path/result", () => {
|
|
185
|
+
const record = task("t1", "session-a", {
|
|
186
|
+
modelSource: "binding",
|
|
187
|
+
fallbackFrom: "anthropic/claude-old",
|
|
188
|
+
usage: { input: 100, output: 40, cacheRead: 30, cacheWrite: 10, reasoning: 5 },
|
|
189
|
+
});
|
|
190
|
+
assert.deepEqual(projectDesktopAgent(record), {
|
|
191
|
+
id: "t1",
|
|
192
|
+
agent: "worker",
|
|
193
|
+
status: TASK_STATUS.RUNNING,
|
|
194
|
+
model: "anthropic/claude-probe",
|
|
195
|
+
modelSource: "binding",
|
|
196
|
+
fallbackFrom: "anthropic/claude-old",
|
|
197
|
+
thinking: "high",
|
|
198
|
+
lastStep: "running",
|
|
199
|
+
usage: { total: 1234, cost: 0.005, input: 100, output: 40, cache: 40, reasoning: 5 },
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
const projected = JSON.stringify(projectDesktopAgent(record));
|
|
203
|
+
assert.equal(projected.includes("the full user prompt"), false, "prompt never leaks");
|
|
204
|
+
assert.equal(projected.includes("/secret/repo"), false, "cwd never leaks");
|
|
205
|
+
assert.equal(projected.includes("/sessions/child.jsonl"), false, "session path never leaks");
|
|
206
|
+
assert.equal(projected.includes("result"), false, "result field never leaks");
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
test("projectDesktopAgent omits optional fields and the breakdown when absent", () => {
|
|
210
|
+
const record = task("t1", "session-a");
|
|
211
|
+
assert.deepEqual(projectDesktopAgent(record), {
|
|
212
|
+
id: "t1",
|
|
213
|
+
agent: "worker",
|
|
214
|
+
status: TASK_STATUS.RUNNING,
|
|
215
|
+
model: "anthropic/claude-probe",
|
|
216
|
+
thinking: "high",
|
|
217
|
+
lastStep: "running",
|
|
218
|
+
usage: { total: 1234, cost: 0.005 },
|
|
219
|
+
});
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
test("projectDesktopAgent projects a closed step and never forwards raw error/path/secret/provider text", () => {
|
|
223
|
+
const record = task("t1", "session-a", {
|
|
224
|
+
status: TASK_STATUS.FAILED,
|
|
225
|
+
endedAt: 2000,
|
|
226
|
+
lastStep: "error: ENOENT /home/secret/.env api_key=sk-live-1234 provider said 'quota exceeded'",
|
|
227
|
+
error: "pi exited with 1 before agent_settled: /tmp/secret.log stderr tail",
|
|
228
|
+
prompt: "original user prompt /etc/passwd",
|
|
229
|
+
});
|
|
230
|
+
const projected = projectDesktopAgent(record);
|
|
231
|
+
assert.equal(projected.status, TASK_STATUS.FAILED);
|
|
232
|
+
assert.equal(projected.lastStep, "failed", "a failed task gets the closed generic reason");
|
|
233
|
+
const json = JSON.stringify(projected);
|
|
234
|
+
for (const secret of ["/home/secret", "/etc/passwd", "sk-live-1234", "quota exceeded", "stderr", "ENOENT", ".env", "/tmp/secret.log", "original user prompt", "api_key"]) {
|
|
235
|
+
assert.equal(json.includes(secret), false, `leaked: ${secret}`);
|
|
236
|
+
}
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
test("projectDesktopAgent keeps only safe active steps and maps everything else to running", () => {
|
|
240
|
+
assert.equal(projectDesktopAgent(task("t1", "s", { status: TASK_STATUS.RUNNING, lastStep: "writing" })).lastStep, "writing");
|
|
241
|
+
assert.equal(projectDesktopAgent(task("t1", "s", { status: TASK_STATUS.RUNNING, lastStep: "generating tool arguments" })).lastStep, "generating tool arguments");
|
|
242
|
+
assert.equal(projectDesktopAgent(task("t1", "s", { status: TASK_STATUS.RUNNING, lastStep: "error: /etc/passwd api_key=sk-live" })).lastStep, "running");
|
|
243
|
+
assert.equal(projectDesktopAgent(task("t1", "s", { status: TASK_STATUS.RUNNING, lastStep: "bash" })).lastStep, "running", "a raw tool name is not a safe step label");
|
|
244
|
+
assert.equal(projectDesktopAgent(task("t1", "s", { status: TASK_STATUS.COMPLETED, endedAt: 2, lastStep: "some raw text" })).lastStep, "completed");
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
test("projectDesktopAgent bounds the freeform name and model fields", () => {
|
|
248
|
+
const record = task("t1", "session-a", { agent: "a".repeat(300), model: "m".repeat(200) });
|
|
249
|
+
const projected = projectDesktopAgent(record);
|
|
250
|
+
assert.ok(projected.agent.length <= 200 && projected.agent.endsWith("…"));
|
|
251
|
+
assert.ok(projected.model.length <= 128 && projected.model.endsWith("…"));
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
// ---- Pure contract: selection ----
|
|
255
|
+
|
|
256
|
+
test("selectDesktopAgents keeps active first then recent finished, bounded", () => {
|
|
257
|
+
const make = (id: string, status: TaskRecord["status"], endedAt: number | null, lastActivityAt: number): TaskRecord =>
|
|
258
|
+
task(id, "s", { status, endedAt, lastActivityAt });
|
|
259
|
+
const records = [
|
|
260
|
+
make("running-1", TASK_STATUS.RUNNING, null, 5),
|
|
261
|
+
make("waiting-1", TASK_STATUS.WAITING, null, 6),
|
|
262
|
+
make("queued-1", TASK_STATUS.QUEUED, null, 3),
|
|
263
|
+
make("finished-new", TASK_STATUS.COMPLETED, 200, 200),
|
|
264
|
+
make("finished-old", TASK_STATUS.FAILED, 100, 100),
|
|
265
|
+
];
|
|
266
|
+
const selected = selectDesktopAgents(records);
|
|
267
|
+
assert.deepEqual(selected.map((entry) => entry.id), ["running-1", "waiting-1", "queued-1", "finished-new", "finished-old"]);
|
|
268
|
+
|
|
269
|
+
const many = Array.from({ length: DESKTOP_AGENTS_LIST_LIMIT + 20 }, (_, i) => make(`t-${i}`, TASK_STATUS.COMPLETED, i + 1, i + 1));
|
|
270
|
+
assert.equal(selectDesktopAgents(many).length, DESKTOP_AGENTS_LIST_LIMIT, "the list is bounded");
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
// ---- Pure contract: params and shape ----
|
|
274
|
+
|
|
275
|
+
test("params parsers accept only the documented shapes", () => {
|
|
276
|
+
assert.deepEqual(parseListSubagentsParams({}), { ok: true });
|
|
277
|
+
assert.deepEqual(parseListSubagentsParams({ unexpected: true }), { error: INVALID_AGENTS_PARAMS });
|
|
278
|
+
assert.deepEqual(parseCancelSubagentParams({ id: "task-1" }), { id: "task-1" });
|
|
279
|
+
for (const params of [{}, { id: "" }, { id: 1 }, { id: "task-1", extra: true }, { task_id: "task-1" }]) {
|
|
280
|
+
assert.deepEqual(parseCancelSubagentParams(params), { error: INVALID_AGENTS_PARAMS }, JSON.stringify(params));
|
|
281
|
+
}
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
test("isDesktopAgentsServiceShape accepts only the versioned adapter", () => {
|
|
285
|
+
const good = { schema: DESKTOP_AGENTS_SERVICE_SCHEMA, read: () => ({ sessionId: "s", agents: [] }), cancel: () => ({ kind: "not_found" }), observe: () => () => {}, dispose: () => {} };
|
|
286
|
+
assert.equal(isDesktopAgentsServiceShape(good), true);
|
|
287
|
+
assert.equal(isDesktopAgentsServiceShape({ ...good, schema: "gentle-pi.desktop-agents-service/v0" }), false);
|
|
288
|
+
assert.equal(isDesktopAgentsServiceShape({ ...good, cancel: undefined }), false);
|
|
289
|
+
assert.equal(isDesktopAgentsServiceShape(null), false);
|
|
290
|
+
assert.equal(isDesktopAgentsServiceShape("nope"), false);
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
test("parseDesktopAgentEntry re-validates owner entries and drops foreign fields", () => {
|
|
294
|
+
const valid = { id: "t1", agent: "worker", status: "running", model: "anthropic/claude", lastStep: "running", usage: { total: 1, cost: 0 } };
|
|
295
|
+
assert.deepEqual(parseDesktopAgentEntry(valid), { id: "t1", agent: "worker", status: "running", model: "anthropic/claude", lastStep: "running", usage: { total: 1, cost: 0 } });
|
|
296
|
+
assert.deepEqual(
|
|
297
|
+
parseDesktopAgentEntry({ ...valid, modelSource: "binding", fallbackFrom: "m", thinking: "high", usage: { total: 2, cost: 0.1, input: 1, output: 1, cache: 1, reasoning: 1 }, prompt: "secret", cwd: "/etc", sessionPath: "/s" }),
|
|
298
|
+
{ id: "t1", agent: "worker", status: "running", model: "anthropic/claude", modelSource: "binding", fallbackFrom: "m", thinking: "high", lastStep: "running", usage: { total: 2, cost: 0.1, input: 1, output: 1, cache: 1, reasoning: 1 } },
|
|
299
|
+
);
|
|
300
|
+
for (const bad of [
|
|
301
|
+
null,
|
|
302
|
+
{ id: "", agent: "a", status: "running", model: "m", lastStep: "running", usage: { total: 0, cost: 0 } },
|
|
303
|
+
{ id: "t", agent: 1, status: "running", model: "m", lastStep: "running", usage: { total: 0, cost: 0 } },
|
|
304
|
+
{ id: "t", agent: "a", status: "exploded", model: "m", lastStep: "running", usage: { total: 0, cost: 0 } },
|
|
305
|
+
{ id: "t", agent: "a", status: "running", model: "m", lastStep: "error: /etc/passwd", usage: { total: 0, cost: 0 } },
|
|
306
|
+
{ id: "t", agent: "a", status: "running", model: "m", lastStep: "working", usage: { total: 0, cost: 0 } },
|
|
307
|
+
{ id: "t", agent: "a", status: "running", model: "m", lastStep: "running", usage: { total: -1, cost: 0 } },
|
|
308
|
+
{ id: "t", agent: "a", status: "running", model: "m", lastStep: "running", usage: { total: 0, cost: "free" } },
|
|
309
|
+
]) {
|
|
310
|
+
assert.equal(parseDesktopAgentEntry(bad), undefined, JSON.stringify(bad));
|
|
311
|
+
}
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
// ---- Bridge reads ----
|
|
315
|
+
|
|
316
|
+
test("list_subagents answers the projected active-session list and emits nothing", async () => {
|
|
317
|
+
const store = new TaskStore();
|
|
318
|
+
store.add(task("t1", "session-a"));
|
|
319
|
+
const { service } = makeAgentsOwnerService(store, makeRunner(store));
|
|
320
|
+
const { bridge, events } = makeBridge(service);
|
|
321
|
+
const outcome = await bridge.handle("list_subagents", {});
|
|
322
|
+
assert.equal(outcome.ok, true);
|
|
323
|
+
assert.deepEqual((outcome as { ok: true; data: Record<string, unknown> }).data, {
|
|
324
|
+
agents: [projectDesktopAgent(task("t1", "session-a"))],
|
|
325
|
+
});
|
|
326
|
+
assert.equal(events.length, 0, "a read emits nothing");
|
|
327
|
+
});
|
|
328
|
+
|
|
329
|
+
test("list_subagents filters out foreign sessions", async () => {
|
|
330
|
+
const store = new TaskStore();
|
|
331
|
+
store.add(task("mine", "session-a"));
|
|
332
|
+
store.add(task("theirs", "session-b"));
|
|
333
|
+
const { service } = makeAgentsOwnerService(store, makeRunner(store), "session-a");
|
|
334
|
+
const { bridge } = makeBridge(service, "session-a");
|
|
335
|
+
const outcome = await bridge.handle("list_subagents", {});
|
|
336
|
+
assert.equal(outcome.ok, true);
|
|
337
|
+
const data = (outcome as { ok: true; data: Record<string, unknown> }).data as { agents: DesktopAgentEntry[] };
|
|
338
|
+
assert.deepEqual(data.agents.map((entry) => entry.id), ["mine"]);
|
|
339
|
+
});
|
|
340
|
+
|
|
341
|
+
test("invalid params are rejected before any owner discovery", async () => {
|
|
342
|
+
const store = new TaskStore();
|
|
343
|
+
const { service } = makeAgentsOwnerService(store, makeRunner(store));
|
|
344
|
+
let discoveries = 0;
|
|
345
|
+
const bridge = new DesktopAgentsBridge({} as ExtensionAPI, { discover: async () => { discoveries += 1; return service; } });
|
|
346
|
+
bridge.attach({ sessionManager: { getSessionId: () => "session-a" } } as unknown as ExtensionContext);
|
|
347
|
+
for (const params of [{ unexpected: true }]) {
|
|
348
|
+
const bad = await bridge.handle("list_subagents", params);
|
|
349
|
+
assert.equal(bad.ok, false);
|
|
350
|
+
assert.deepEqual(bad.error, INVALID_AGENTS_PARAMS);
|
|
351
|
+
}
|
|
352
|
+
for (const params of [{}, { id: "" }, { id: 1 }, { id: "task-1", extra: true }]) {
|
|
353
|
+
const bad = await bridge.handle("cancel_subagent", params);
|
|
354
|
+
assert.equal(bad.ok, false);
|
|
355
|
+
assert.deepEqual(bad.error, INVALID_AGENTS_PARAMS);
|
|
356
|
+
}
|
|
357
|
+
assert.equal(discoveries, 0, "invalid params never reach discovery");
|
|
358
|
+
});
|
|
359
|
+
|
|
360
|
+
test("no owner answers agents_unavailable rather than inventing an empty list", async () => {
|
|
361
|
+
const bridge = new DesktopAgentsBridge({} as ExtensionAPI, { discover: async () => undefined });
|
|
362
|
+
bridge.attach({ sessionManager: { getSessionId: () => "session-a" } } as unknown as ExtensionContext);
|
|
363
|
+
const outcome = await bridge.handle("list_subagents", {});
|
|
364
|
+
assert.equal(outcome.ok, false);
|
|
365
|
+
assert.deepEqual(outcome.error, AGENTS_UNAVAILABLE);
|
|
366
|
+
});
|
|
367
|
+
|
|
368
|
+
test("a throwing or malformed owner never leaks raw prompt text or paths", async () => {
|
|
369
|
+
const throwing: DesktopAgentsService = {
|
|
370
|
+
schema: DESKTOP_AGENTS_SERVICE_SCHEMA,
|
|
371
|
+
read: () => { throw new Error("secret prompt /etc/passwd"); },
|
|
372
|
+
cancel: () => { throw new Error("secret prompt /etc/passwd"); },
|
|
373
|
+
observe: () => () => {},
|
|
374
|
+
dispose: () => {},
|
|
375
|
+
};
|
|
376
|
+
const { bridge } = makeBridge(throwing);
|
|
377
|
+
const read = await bridge.handle("list_subagents", {});
|
|
378
|
+
assert.equal(read.ok, false);
|
|
379
|
+
assert.equal(JSON.stringify(read).includes("secret prompt"), false);
|
|
380
|
+
assert.deepEqual(read.error, AGENTS_UNAVAILABLE);
|
|
381
|
+
const cancelled = await bridge.handle("cancel_subagent", { id: "t1" });
|
|
382
|
+
assert.equal(cancelled.ok, false);
|
|
383
|
+
assert.equal(JSON.stringify(cancelled).includes("secret prompt"), false);
|
|
384
|
+
|
|
385
|
+
// A foreign prompt field on an owner entry is dropped, never echoed.
|
|
386
|
+
const malformed: DesktopAgentsService = {
|
|
387
|
+
schema: DESKTOP_AGENTS_SERVICE_SCHEMA,
|
|
388
|
+
read: () => ({ sessionId: "session-a", agents: [{ id: "t", agent: "a", status: "running", model: "m", lastStep: "running", usage: { total: 0, cost: 0 }, prompt: "rm -rf /" }] as unknown as DesktopAgentEntry[] }),
|
|
389
|
+
cancel: () => ({ kind: "not_found" }),
|
|
390
|
+
observe: () => () => {},
|
|
391
|
+
dispose: () => {},
|
|
392
|
+
};
|
|
393
|
+
const badBridge = makeBridge(malformed);
|
|
394
|
+
const bad = await badBridge.bridge.handle("list_subagents", {});
|
|
395
|
+
assert.equal(bad.ok, true);
|
|
396
|
+
assert.deepEqual((bad as { ok: true; data: Record<string, unknown> }).data, { agents: [{ id: "t", agent: "a", status: "running", model: "m", lastStep: "running", usage: { total: 0, cost: 0 } }] });
|
|
397
|
+
assert.equal(JSON.stringify(bad).includes("rm -rf"), false);
|
|
398
|
+
});
|
|
399
|
+
|
|
400
|
+
// ---- Cancel: the runner.cancel owner path ----
|
|
401
|
+
|
|
402
|
+
test("cancel_subagent honors the runner result and the actual store transition (queued)", async () => {
|
|
403
|
+
const store = new TaskStore();
|
|
404
|
+
store.add(task("t1", "session-a", { status: TASK_STATUS.QUEUED, startedAt: null }));
|
|
405
|
+
const runner = makeRunner(store);
|
|
406
|
+
const { service } = makeAgentsOwnerService(store, runner);
|
|
407
|
+
const { bridge, events } = makeBridge(service);
|
|
408
|
+
const outcome = await bridge.handle("cancel_subagent", { id: "t1" });
|
|
409
|
+
assert.equal(outcome.ok, true);
|
|
410
|
+
assert.deepEqual(runner.calls, [{ id: "t1", reason: "cancelled: stopped from desktop", result: true }], "the same runner.cancel owner path runs");
|
|
411
|
+
const data = (outcome as { ok: true; data: Record<string, unknown> }).data as { agent: DesktopAgentEntry };
|
|
412
|
+
assert.equal(data.agent.status, TASK_STATUS.CANCELLED, "a queued task transitioned synchronously");
|
|
413
|
+
assert.equal(data.agent.lastStep, "cancelled", "the post-action state is the closed label");
|
|
414
|
+
// A synchronous transition is a real state change: the response carries one event.
|
|
415
|
+
assert.equal((outcome as { ok: true; event?: unknown }).event !== undefined, true, "a synchronous transition emits an agents_update");
|
|
416
|
+
assert.equal(events.length, 0, "the immediate event rides the outcome, not the observer");
|
|
417
|
+
});
|
|
418
|
+
|
|
419
|
+
test("cancel_subagent of an already-terminal task answers terminal state without an error or event", async () => {
|
|
420
|
+
const store = new TaskStore();
|
|
421
|
+
store.add(task("t1", "session-a", { status: TASK_STATUS.COMPLETED, endedAt: 2000 }));
|
|
422
|
+
const runner = makeRunner(store);
|
|
423
|
+
const { service } = makeAgentsOwnerService(store, runner);
|
|
424
|
+
const { bridge, events } = makeBridge(service);
|
|
425
|
+
const outcome = await bridge.handle("cancel_subagent", { id: "t1" });
|
|
426
|
+
assert.equal(outcome.ok, true);
|
|
427
|
+
const data = (outcome as { ok: true; data: Record<string, unknown> }).data as { agent: DesktopAgentEntry };
|
|
428
|
+
assert.equal(data.agent.status, TASK_STATUS.COMPLETED);
|
|
429
|
+
assert.equal(data.agent.lastStep, "completed");
|
|
430
|
+
assert.equal((outcome as { ok: true; event?: unknown }).event, undefined, "a no-op cancel emits nothing");
|
|
431
|
+
assert.equal(events.length, 0, "an already-terminal cancel emits nothing");
|
|
432
|
+
assert.deepEqual(runner.calls, [{ id: "t1", reason: "cancelled: stopped from desktop", result: false }], "the owner path is still the runner's, and its result is honored");
|
|
433
|
+
});
|
|
434
|
+
|
|
435
|
+
test("a running-task cancel is requested but not changed and emits no immediate event (even when repeated)", async () => {
|
|
436
|
+
const store = new TaskStore();
|
|
437
|
+
store.add(task("t1", "session-a", { status: TASK_STATUS.RUNNING }));
|
|
438
|
+
const runner = makeRunner(store);
|
|
439
|
+
const { service } = makeAgentsOwnerService(store, runner);
|
|
440
|
+
const { bridge, events } = makeBridge(service);
|
|
441
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
442
|
+
const outcome = await bridge.handle("cancel_subagent", { id: "t1" });
|
|
443
|
+
assert.equal(outcome.ok, true);
|
|
444
|
+
const data = (outcome as { ok: true; data: Record<string, unknown> }).data as { agent: DesktopAgentEntry };
|
|
445
|
+
assert.equal(data.agent.status, TASK_STATUS.RUNNING, "a running task's cancellation is asynchronous; the post-action state is still running");
|
|
446
|
+
assert.equal((outcome as { ok: true; event?: unknown }).event, undefined, "no immediate byte-identical agents_update for an in-flight cancel");
|
|
447
|
+
}
|
|
448
|
+
assert.equal(events.length, 0, "the eventual transition emits through the observer, not here");
|
|
449
|
+
assert.deepEqual(runner.calls.map((call) => call.result), [true, true]);
|
|
450
|
+
});
|
|
451
|
+
|
|
452
|
+
test("cancel_subagent unknown and foreign-session ids are typed not_found", async () => {
|
|
453
|
+
const store = new TaskStore();
|
|
454
|
+
store.add(task("t1", "session-b"));
|
|
455
|
+
const runner = makeRunner(store);
|
|
456
|
+
const { service } = makeAgentsOwnerService(store, runner, "session-a");
|
|
457
|
+
const { bridge } = makeBridge(service, "session-a");
|
|
458
|
+
|
|
459
|
+
const foreign = await bridge.handle("cancel_subagent", { id: "t1" });
|
|
460
|
+
assert.equal(foreign.ok, false);
|
|
461
|
+
assert.deepEqual(foreign.error, AGENT_NOT_FOUND);
|
|
462
|
+
|
|
463
|
+
const unknown = await bridge.handle("cancel_subagent", { id: "t-99" });
|
|
464
|
+
assert.equal(unknown.ok, false);
|
|
465
|
+
assert.deepEqual(unknown.error, AGENT_NOT_FOUND);
|
|
466
|
+
assert.deepEqual(runner.calls, [], "a foreign or unknown id never reaches the runner");
|
|
467
|
+
});
|
|
468
|
+
|
|
469
|
+
// ---- Events: observer-driven transitions, dedupe and coalescing ----
|
|
470
|
+
|
|
471
|
+
test("agent-driven transitions become one coalesced agents_update filtered by active session", async () => {
|
|
472
|
+
const store = new TaskStore();
|
|
473
|
+
const { service, notify } = makeAgentsOwnerService(store, makeRunner(store), "session-a");
|
|
474
|
+
const { bridge, events, scheduler } = makeBridge(service, "session-a");
|
|
475
|
+
await bridge.handle("list_subagents", {});
|
|
476
|
+
|
|
477
|
+
store.add(task("t1", "session-a", { status: TASK_STATUS.QUEUED, startedAt: null }));
|
|
478
|
+
notify("session-a");
|
|
479
|
+
assert.equal(scheduler.pendingCount(), 1, "a change schedules one coalesced flush");
|
|
480
|
+
store.update("t1", { status: TASK_STATUS.RUNNING, startedAt: 1000 });
|
|
481
|
+
notify("session-a");
|
|
482
|
+
assert.equal(scheduler.pendingCount(), 1, "a burst inside the window does not add timers");
|
|
483
|
+
assert.equal(events.length, 0, "nothing is emitted before the flush");
|
|
484
|
+
|
|
485
|
+
scheduler.flushAll();
|
|
486
|
+
assert.equal(events.length, 1);
|
|
487
|
+
assert.equal(events[0]!.event, DESKTOP_AGENTS_EVENT);
|
|
488
|
+
assert.deepEqual(events[0]!.data, { agents: [projectDesktopAgent(task("t1", "session-a"))] });
|
|
489
|
+
|
|
490
|
+
// A foreign-session change does not reach this bridge.
|
|
491
|
+
store.add(task("t2", "session-b"));
|
|
492
|
+
notify("session-b");
|
|
493
|
+
scheduler.flushAll();
|
|
494
|
+
assert.equal(events.length, 1, "a foreign session change is filtered out");
|
|
495
|
+
});
|
|
496
|
+
|
|
497
|
+
test("byte-identical projected content is deduped across flushes", async () => {
|
|
498
|
+
const store = new TaskStore();
|
|
499
|
+
store.add(task("t1", "session-a"));
|
|
500
|
+
const { service, notify } = makeAgentsOwnerService(store, makeRunner(store), "session-a");
|
|
501
|
+
const { bridge, events, scheduler } = makeBridge(service, "session-a");
|
|
502
|
+
await bridge.handle("list_subagents", {});
|
|
503
|
+
|
|
504
|
+
notify("session-a");
|
|
505
|
+
scheduler.flushAll();
|
|
506
|
+
assert.equal(events.length, 1);
|
|
507
|
+
|
|
508
|
+
notify("session-a");
|
|
509
|
+
scheduler.flushAll();
|
|
510
|
+
assert.equal(events.length, 1, "identical content emits once");
|
|
511
|
+
});
|
|
512
|
+
|
|
513
|
+
test("session reset disconnects observers and drops stale async outcomes", async () => {
|
|
514
|
+
const observers = new Set<(sessionId: string) => void>();
|
|
515
|
+
const service: DesktopAgentsService = {
|
|
516
|
+
schema: DESKTOP_AGENTS_SERVICE_SCHEMA,
|
|
517
|
+
read: () => ({ sessionId: "session-a", agents: [] }),
|
|
518
|
+
cancel: () => ({ kind: "not_found" }),
|
|
519
|
+
observe: (onChange) => { observers.add(onChange); return () => observers.delete(onChange); },
|
|
520
|
+
dispose: () => { observers.clear(); },
|
|
521
|
+
};
|
|
522
|
+
let releaseService: (value: DesktopAgentsService) => void = () => {};
|
|
523
|
+
const serviceGate = new Promise<DesktopAgentsService>((resolve) => { releaseService = resolve; });
|
|
524
|
+
const scheduler = recordedScheduler();
|
|
525
|
+
const bridge = new DesktopAgentsBridge({} as ExtensionAPI, { discover: () => serviceGate, schedule: scheduler.schedule, coalesceMs: 10 });
|
|
526
|
+
bridge.attach({ sessionManager: { getSessionId: () => "session-a" } } as unknown as ExtensionContext);
|
|
527
|
+
const events: Array<{ event: string; data: Record<string, unknown> }> = [];
|
|
528
|
+
bridge.wire((event, data) => events.push({ event, data }));
|
|
529
|
+
|
|
530
|
+
const pending = bridge.handle("list_subagents", {});
|
|
531
|
+
bridge.reset();
|
|
532
|
+
for (const observer of [...observers]) observer("session-a");
|
|
533
|
+
scheduler.flushAll();
|
|
534
|
+
assert.equal(events.length, 0, "a disposed session never delivers a change");
|
|
535
|
+
releaseService(service);
|
|
536
|
+
const outcome = await pending;
|
|
537
|
+
assert.equal(outcome.ok, false);
|
|
538
|
+
assert.deepEqual(outcome.error, AGENTS_UNAVAILABLE);
|
|
539
|
+
});
|
|
540
|
+
|
|
541
|
+
test("a late discovery after reset is disposed and never cached for the next session", async () => {
|
|
542
|
+
const disposed: string[] = [];
|
|
543
|
+
const service: DesktopAgentsService = {
|
|
544
|
+
schema: DESKTOP_AGENTS_SERVICE_SCHEMA,
|
|
545
|
+
read: () => ({ sessionId: "session-a", agents: [] }),
|
|
546
|
+
cancel: () => ({ kind: "not_found" }),
|
|
547
|
+
observe: () => () => {},
|
|
548
|
+
dispose: () => { disposed.push("old"); },
|
|
549
|
+
};
|
|
550
|
+
let releaseOld: (value: DesktopAgentsService) => void = () => {};
|
|
551
|
+
const oldGate = new Promise<DesktopAgentsService>((resolve) => { releaseOld = resolve; });
|
|
552
|
+
let discoverCount = 0;
|
|
553
|
+
const bridge = new DesktopAgentsBridge({} as ExtensionAPI, {
|
|
554
|
+
discover: () => { discoverCount += 1; return discoverCount === 1 ? oldGate : Promise.resolve(service); },
|
|
555
|
+
});
|
|
556
|
+
bridge.attach({ sessionManager: { getSessionId: () => "session-a" } } as unknown as ExtensionContext);
|
|
557
|
+
const first = bridge.handle("list_subagents", {});
|
|
558
|
+
bridge.reset();
|
|
559
|
+
releaseOld(service);
|
|
560
|
+
const firstOutcome = await first;
|
|
561
|
+
assert.equal(firstOutcome.ok, false);
|
|
562
|
+
assert.deepEqual(disposed, ["old"], "the late adapter is disposed, never cached");
|
|
563
|
+
});
|
|
564
|
+
|
|
565
|
+
// ---- Discovery ----
|
|
566
|
+
|
|
567
|
+
test("discoverDesktopAgentsService accepts the versioned adapter and ignores malformed responders", async () => {
|
|
568
|
+
const listeners = new Map<string, (value: unknown) => void>();
|
|
569
|
+
const pi = {
|
|
570
|
+
events: {
|
|
571
|
+
on(name: string, handler: (value: unknown) => void) { listeners.set(name, handler); return () => listeners.delete(name); },
|
|
572
|
+
emit(name: string, value: unknown) { listeners.get(name)?.(value); },
|
|
573
|
+
},
|
|
574
|
+
} as unknown as ExtensionAPI;
|
|
575
|
+
const ctx = {} as ExtensionContext;
|
|
576
|
+
|
|
577
|
+
listeners.set(DESKTOP_AGENTS_SERVICE_CHANNEL, (payload) => {
|
|
578
|
+
(payload as { respond(service: unknown): void }).respond({
|
|
579
|
+
schema: DESKTOP_AGENTS_SERVICE_SCHEMA,
|
|
580
|
+
read: () => ({ sessionId: "s", agents: [] }),
|
|
581
|
+
cancel: () => ({ kind: "not_found" }),
|
|
582
|
+
observe: () => () => {},
|
|
583
|
+
dispose: () => {},
|
|
584
|
+
});
|
|
585
|
+
});
|
|
586
|
+
const service = await discoverDesktopAgentsService(pi, ctx);
|
|
587
|
+
assert.equal(service?.schema, DESKTOP_AGENTS_SERVICE_SCHEMA);
|
|
588
|
+
|
|
589
|
+
listeners.set(DESKTOP_AGENTS_SERVICE_CHANNEL, (payload) => {
|
|
590
|
+
(payload as { respond(service: unknown): void }).respond({ schema: "gentle-pi.desktop-agents-service/v0", read: () => ({ sessionId: "s", agents: [] }) });
|
|
591
|
+
});
|
|
592
|
+
assert.equal(await discoverDesktopAgentsService(pi, ctx), undefined);
|
|
593
|
+
});
|
|
594
|
+
|
|
595
|
+
// ---- Router sequencing: response before event ----
|
|
596
|
+
|
|
597
|
+
test("the router publishes a changed cancel response before its agents_update event", async () => {
|
|
598
|
+
const store = new TaskStore();
|
|
599
|
+
store.add(task("t1", "session-a", { status: TASK_STATUS.QUEUED, startedAt: null }));
|
|
600
|
+
const { service } = makeAgentsOwnerService(store, makeRunner(store));
|
|
601
|
+
const bridge = new DesktopAgentsBridge({} as ExtensionAPI, { discover: async () => service, schedule: () => () => {}, coalesceMs: 10 });
|
|
602
|
+
bridge.attach({ sessionManager: { getSessionId: () => "session-a" } } as unknown as ExtensionContext);
|
|
603
|
+
const domain: DesktopRpcDomain = (method, params) => bridge.handle(method, params as Record<string, unknown>);
|
|
604
|
+
const lines: string[] = [];
|
|
605
|
+
const router = new DesktopRpcRouter(
|
|
606
|
+
["capabilities", "get_snapshot", ...DESKTOP_AGENTS_METHODS],
|
|
607
|
+
[...DESKTOP_AGENTS_EVENTS],
|
|
608
|
+
undefined,
|
|
609
|
+
domain,
|
|
610
|
+
);
|
|
611
|
+
router.start((line) => lines.push(line));
|
|
612
|
+
await router.handle(JSON.stringify({ schema: DESKTOP_RPC_SCHEMA, requestId: "cancel-1", method: "cancel_subagent", params: { id: "t1" } }));
|
|
613
|
+
assert.deepEqual(lines.map((line) => JSON.parse(line).kind), ["response", "event"]);
|
|
614
|
+
assert.equal(JSON.parse(lines[0]!).requestId, "cancel-1");
|
|
615
|
+
assert.equal(JSON.parse(lines[1]!).event, DESKTOP_AGENTS_EVENT);
|
|
616
|
+
});
|
|
617
|
+
|
|
618
|
+
// ---- Transport: capabilities and owner absence ----
|
|
619
|
+
|
|
620
|
+
function desktopHarness(t: test.TestContext) {
|
|
621
|
+
const previous = process.env[INTERACTIVE_HOST_ENV];
|
|
622
|
+
process.env[INTERACTIVE_HOST_ENV] = "1";
|
|
623
|
+
t.after(() => {
|
|
624
|
+
if (previous === undefined) delete process.env[INTERACTIVE_HOST_ENV];
|
|
625
|
+
else process.env[INTERACTIVE_HOST_ENV] = previous;
|
|
626
|
+
});
|
|
627
|
+
const commands = new Map<string, { handler: (args: string, ctx: any) => Promise<void> }>();
|
|
628
|
+
const events = new Map<string, (event: unknown, ctx: any) => void>();
|
|
629
|
+
const pi = {
|
|
630
|
+
registerCommand(name: string, command: any) { commands.set(name, command); },
|
|
631
|
+
on(name: string, handler: any) { events.set(name, handler); },
|
|
632
|
+
} as unknown as ExtensionAPI;
|
|
633
|
+
desktopRpc(pi);
|
|
634
|
+
const widgets: Array<{ key: string; lines: string[] }> = [];
|
|
635
|
+
const ctx = { mode: "rpc", ui: { setWidget(key: string, lines: string[]) { widgets.push({ key, lines }); } } };
|
|
636
|
+
events.get("session_start")?.({}, ctx);
|
|
637
|
+
return { commands, events, ctx, widgets };
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
test("the Desktop transport advertises the agents methods and event", (t) => {
|
|
641
|
+
const app = desktopHarness(t);
|
|
642
|
+
app.commands.get("gentle:desktop")!.handler(
|
|
643
|
+
JSON.stringify({ schema: DESKTOP_RPC_SCHEMA, requestId: "cap-1", method: "capabilities", params: {} }),
|
|
644
|
+
app.ctx,
|
|
645
|
+
);
|
|
646
|
+
const response = JSON.parse(app.widgets[0]!.lines[0]!);
|
|
647
|
+
assert.deepEqual(response.data.methods, [
|
|
648
|
+
"capabilities",
|
|
649
|
+
"get_snapshot",
|
|
650
|
+
"get_config",
|
|
651
|
+
"set_config",
|
|
652
|
+
"get_permission_mode",
|
|
653
|
+
"set_permission_mode",
|
|
654
|
+
"get_subscription_usage",
|
|
655
|
+
"refresh_subscription_usage",
|
|
656
|
+
"get_design_canvas",
|
|
657
|
+
"list_jobs",
|
|
658
|
+
"cancel_job",
|
|
659
|
+
"apply_profile",
|
|
660
|
+
"list_subagents",
|
|
661
|
+
"cancel_subagent",
|
|
662
|
+
]);
|
|
663
|
+
assert.deepEqual(response.data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update"]);
|
|
664
|
+
});
|
|
665
|
+
|
|
666
|
+
test("list_subagents answers agents_unavailable through the transport without an owner extension", async (t) => {
|
|
667
|
+
const app = desktopHarness(t);
|
|
668
|
+
await app.commands.get("gentle:desktop")!.handler(
|
|
669
|
+
JSON.stringify({ schema: DESKTOP_RPC_SCHEMA, requestId: "agents-1", method: "list_subagents", params: {} }),
|
|
670
|
+
app.ctx,
|
|
671
|
+
);
|
|
672
|
+
const response = JSON.parse(app.widgets[0]!.lines[0]!);
|
|
673
|
+
assert.equal(response.ok, false);
|
|
674
|
+
assert.deepEqual(response.error, AGENTS_UNAVAILABLE);
|
|
675
|
+
});
|
|
676
|
+
|
|
677
|
+
// ---- Real owner: the gentle-agents agents seam ----
|
|
678
|
+
|
|
679
|
+
const tick = () => new Promise((resolve) => setImmediate(resolve));
|
|
680
|
+
const settle = () => new Promise((resolve) => setTimeout(resolve, 30));
|
|
681
|
+
|
|
682
|
+
interface RealOwnerHarness {
|
|
683
|
+
handlers: Map<string, Array<(event: unknown, ctx: ExtensionContext) => unknown>>;
|
|
684
|
+
listeners: Map<string, Set<(data: unknown) => void>>;
|
|
685
|
+
pi: ExtensionAPI;
|
|
686
|
+
ctx: ExtensionContext;
|
|
687
|
+
service: DesktopAgentsService;
|
|
688
|
+
tools: Map<string, any>;
|
|
689
|
+
children: ReturnType<typeof fakeChild>[];
|
|
690
|
+
tasksDir: string;
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
/**
|
|
694
|
+
* Instantiates the real `gentleAgents` extension (the actual owner seam, real
|
|
695
|
+
* `TaskStore`, and real `AgentRunner`) with a fake host and a fake child spawn
|
|
696
|
+
* (never a real process), then discovers the real owner service. A minimal
|
|
697
|
+
* `worker` agent definition is written into the agent home so `subagent_run`
|
|
698
|
+
* can launch a real background task.
|
|
699
|
+
*/
|
|
700
|
+
async function realOwnerHarness(t: test.TestContext): Promise<RealOwnerHarness> {
|
|
701
|
+
const root = mkdtempSync(join(tmpdir(), "desktop-rpc-agents-real-"));
|
|
702
|
+
t.after(() => rmSync(root, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 }));
|
|
703
|
+
const home = join(root, "home");
|
|
704
|
+
const agentHome = join(root, "agent");
|
|
705
|
+
const cwd = join(root, "workspace");
|
|
706
|
+
const configHome = join(root, "config");
|
|
707
|
+
const jobOutputDir = join(root, "job-output");
|
|
708
|
+
for (const directory of [home, agentHome, cwd, configHome, jobOutputDir]) mkdirSync(directory, { recursive: true });
|
|
709
|
+
mkdirSync(join(agentHome, "agents"), { recursive: true });
|
|
710
|
+
writeFileSync(join(agentHome, "agents", "explore.md"), "---\ndescription: explore\ntools: [read]\n---\nExplore.");
|
|
711
|
+
|
|
712
|
+
const handlers = new Map<string, Array<(event: unknown, ctx: ExtensionContext) => unknown>>();
|
|
713
|
+
const listeners = new Map<string, Set<(data: unknown) => void>>();
|
|
714
|
+
const tools = new Map<string, any>();
|
|
715
|
+
const children: ReturnType<typeof fakeChild>[] = [];
|
|
716
|
+
const pi = {
|
|
717
|
+
appendEntry: () => {},
|
|
718
|
+
registerMarkdownTransformer: () => {},
|
|
719
|
+
events: {
|
|
720
|
+
emit: (name: string, data: unknown) => { for (const listener of [...(listeners.get(name) ?? [])]) listener(data); },
|
|
721
|
+
on: (name: string, listener: (data: unknown) => void) => {
|
|
722
|
+
const set = listeners.get(name) ?? new Set();
|
|
723
|
+
listeners.set(name, set);
|
|
724
|
+
set.add(listener);
|
|
725
|
+
return () => { set.delete(listener); };
|
|
726
|
+
},
|
|
727
|
+
},
|
|
728
|
+
sendMessage: () => {},
|
|
729
|
+
sendUserMessage: () => {},
|
|
730
|
+
registerMessageRenderer: () => {},
|
|
731
|
+
registerEntryRenderer: () => {},
|
|
732
|
+
on: (event: string, handler: (event: unknown, ctx: ExtensionContext) => unknown) => {
|
|
733
|
+
handlers.set(event, [...(handlers.get(event) ?? []), handler]);
|
|
734
|
+
},
|
|
735
|
+
registerTool: (tool: any) => tools.set(tool.name, tool),
|
|
736
|
+
registerShortcut: () => {},
|
|
737
|
+
registerCommand: () => {},
|
|
738
|
+
} as unknown as ExtensionAPI;
|
|
739
|
+
|
|
740
|
+
const ctx = {
|
|
741
|
+
cwd,
|
|
742
|
+
hasUI: true,
|
|
743
|
+
mode: "tui",
|
|
744
|
+
model: { provider: "claude-bridge", id: "claude-probe" },
|
|
745
|
+
sessionManager: {
|
|
746
|
+
getSessionId: () => "session-a",
|
|
747
|
+
getCwd: () => cwd,
|
|
748
|
+
getEntries: () => [],
|
|
749
|
+
getBranch: () => [],
|
|
750
|
+
getSessionFile: () => undefined,
|
|
751
|
+
getSessionName: () => "test",
|
|
752
|
+
},
|
|
753
|
+
ui: {
|
|
754
|
+
notify: () => {},
|
|
755
|
+
setStatus: () => {},
|
|
756
|
+
custom: async () => {},
|
|
757
|
+
setWidget: () => {},
|
|
758
|
+
select: async () => undefined,
|
|
759
|
+
confirm: async () => true,
|
|
760
|
+
input: async () => undefined,
|
|
761
|
+
editor: async () => "edited",
|
|
762
|
+
},
|
|
763
|
+
isIdle: () => true,
|
|
764
|
+
} as unknown as ExtensionContext;
|
|
765
|
+
|
|
766
|
+
const inertSessionTransport: SessionTransportFactory = {
|
|
767
|
+
createRegistry: async () => ({ list: async () => [], listActivations: async () => [] }),
|
|
768
|
+
createListener: (registry) => ({ registry, start: async () => {}, close: async () => {} }),
|
|
769
|
+
createClient: () => ({ close() {}, sendNotification: async () => { throw new Error("inert transport must not send"); } }),
|
|
770
|
+
};
|
|
771
|
+
|
|
772
|
+
gentleAgents(pi, { GENTLE_PI_CONFIG_HOME: configHome, PATH: process.env.PATH ?? "" }, {
|
|
773
|
+
home,
|
|
774
|
+
agentHome,
|
|
775
|
+
env: { GENTLE_PI_CONFIG_HOME: configHome, PATH: process.env.PATH ?? "" },
|
|
776
|
+
schedule: () => () => {},
|
|
777
|
+
now: () => 1000,
|
|
778
|
+
jobShell: () => { throw new Error("real-owner agents harness must not run jobs"); },
|
|
779
|
+
jobOutputDir: () => jobOutputDir,
|
|
780
|
+
sessionTransport: inertSessionTransport,
|
|
781
|
+
resolveWorktree: (path: string, base: string) => ({ root: resolve(base, path), commonDir: "/fixture/common" }),
|
|
782
|
+
spawn: () => {
|
|
783
|
+
const child = fakeChild();
|
|
784
|
+
children.push(child);
|
|
785
|
+
return child.child;
|
|
786
|
+
},
|
|
787
|
+
pi: { command: "pi", args: [] },
|
|
788
|
+
});
|
|
789
|
+
|
|
790
|
+
for (const handler of handlers.get("session_start") ?? []) await handler({ reason: "new" }, ctx);
|
|
791
|
+
|
|
792
|
+
const service = await discoverDesktopAgentsService(pi, ctx);
|
|
793
|
+
assert.ok(service, "the real owner seam must answer in-process");
|
|
794
|
+
return { pi, ctx, service, tools, children, tasksDir: historyDir(home, agentHome), handlers, listeners };
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
async function launchBackgroundTask(h: RealOwnerHarness): Promise<string> {
|
|
798
|
+
const run = h.tools.get("subagent_run")!;
|
|
799
|
+
const result = await run.execute("run", { agent: "explore", task: "Map the repo", mode: "background" }, undefined, undefined, h.ctx);
|
|
800
|
+
await tick();
|
|
801
|
+
const taskId = (result.details.gentleAgents as { taskId: string }).taskId;
|
|
802
|
+
assert.equal(h.children.length, 1, "the background task spawned exactly one child");
|
|
803
|
+
return taskId;
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
test("the real owner serves a truthful empty subagent list and a typed not_found cancel", async (t) => {
|
|
807
|
+
const { service } = await realOwnerHarness(t);
|
|
808
|
+
assert.deepEqual(service.read(), { sessionId: "session-a", agents: [] }, "no subagents exist, so the list is empty rather than fabricated");
|
|
809
|
+
assert.deepEqual(service.cancel("unknown-id"), { kind: "not_found" }, "an unknown id is a typed not_found, never a spawn");
|
|
810
|
+
assert.deepEqual(service.cancel(""), { kind: "not_found" });
|
|
811
|
+
});
|
|
812
|
+
|
|
813
|
+
test("saveTask/loadStoredTask retain the final usage breakdown across restore", async (t) => {
|
|
814
|
+
const dir = mkdtempSync(join(tmpdir(), "desktop-rpc-agents-history-"));
|
|
815
|
+
t.after(() => rmSync(dir, { recursive: true, force: true }));
|
|
816
|
+
const record = task("t1", "session-a", {
|
|
817
|
+
status: TASK_STATUS.COMPLETED,
|
|
818
|
+
endedAt: 2000,
|
|
819
|
+
usage: { input: 100, output: 40, cacheRead: 30, cacheWrite: 10, reasoning: 5 },
|
|
820
|
+
});
|
|
821
|
+
await saveTask(dir, record, { items: [], dropped: 0, version: 0, limits: { maxItems: 400, maxOutputChars: 16000 } });
|
|
822
|
+
const stored = await loadStoredTask(dir, "t1");
|
|
823
|
+
assert.ok(stored);
|
|
824
|
+
assert.deepEqual(stored.task.usage, { input: 100, output: 40, cacheRead: 30, cacheWrite: 10, reasoning: 5 });
|
|
825
|
+
assert.deepEqual(projectDesktopAgent(stored.task).usage, { total: 1234, cost: 0.005, input: 100, output: 40, cache: 40, reasoning: 5 });
|
|
826
|
+
});
|
|
827
|
+
|
|
828
|
+
test("the real owner cancels a live task through runner.cancel and emits one eventual agents_update", async (t) => {
|
|
829
|
+
const h = await realOwnerHarness(t);
|
|
830
|
+
const originalCancel = AgentRunner.prototype.cancel;
|
|
831
|
+
const cancelCalls: Array<{ id: string; reason: string; result: boolean }> = [];
|
|
832
|
+
t.mock.method(AgentRunner.prototype, "cancel", function (this: AgentRunner, id: string, reason: string) {
|
|
833
|
+
const result = originalCancel.call(this, id, reason);
|
|
834
|
+
cancelCalls.push({ id, reason, result });
|
|
835
|
+
return result;
|
|
836
|
+
});
|
|
837
|
+
|
|
838
|
+
const taskId = await launchBackgroundTask(h);
|
|
839
|
+
const scheduler = recordedScheduler();
|
|
840
|
+
const bridge = new DesktopAgentsBridge(h.pi, { discover: async () => h.service, schedule: scheduler.schedule, coalesceMs: 10 });
|
|
841
|
+
bridge.attach(h.ctx);
|
|
842
|
+
const events: Array<{ event: string; data: Record<string, unknown> }> = [];
|
|
843
|
+
bridge.wire((event, data) => events.push({ event, data }));
|
|
844
|
+
await bridge.start();
|
|
845
|
+
|
|
846
|
+
const list = await bridge.handle("list_subagents", {});
|
|
847
|
+
assert.equal(list.ok, true);
|
|
848
|
+
assert.deepEqual(((list as { ok: true; data: Record<string, unknown> }).data as { agents: DesktopAgentEntry[] }).agents.map((entry) => entry.status), [TASK_STATUS.RUNNING]);
|
|
849
|
+
|
|
850
|
+
const cancel = await bridge.handle("cancel_subagent", { id: taskId });
|
|
851
|
+
assert.equal(cancel.ok, true);
|
|
852
|
+
const data = (cancel as { ok: true; data: Record<string, unknown> }).data as { agent: DesktopAgentEntry };
|
|
853
|
+
assert.equal(data.agent.status, TASK_STATUS.RUNNING, "the post-action state is still running: cancellation is asynchronous");
|
|
854
|
+
assert.equal((cancel as { ok: true; event?: unknown }).event, undefined, "no immediate byte-identical agents_update for an in-flight cancel");
|
|
855
|
+
assert.deepEqual(cancelCalls, [{ id: taskId, reason: "cancelled: stopped from desktop", result: true }], "the real runner.cancel path ran and its result is honored");
|
|
856
|
+
assert.equal(events.length, 0);
|
|
857
|
+
|
|
858
|
+
// The cancel's SIGTERM already propagated the child exit into a real
|
|
859
|
+
// store transition; the observer scheduled exactly one coalesced flush.
|
|
860
|
+
scheduler.flushAll();
|
|
861
|
+
assert.equal(events.length, 1, "exactly one eventual agents_update for the real transition");
|
|
862
|
+
assert.equal(events[0]!.event, DESKTOP_AGENTS_EVENT);
|
|
863
|
+
assert.deepEqual((events[0]!.data as { agents: DesktopAgentEntry[] }).agents.map((entry) => entry.status), [TASK_STATUS.CANCELLED]);
|
|
864
|
+
assert.deepEqual((events[0]!.data as { agents: DesktopAgentEntry[] }).agents.map((entry) => entry.lastStep), ["cancelled"]);
|
|
865
|
+
});
|
|
866
|
+
|
|
867
|
+
test("the real owner persists the final usage breakdown so restored finished tasks retain it", async (t) => {
|
|
868
|
+
const h = await realOwnerHarness(t);
|
|
869
|
+
const taskId = await launchBackgroundTask(h);
|
|
870
|
+
|
|
871
|
+
// Record a final-assistant observation with a token breakdown, then settle.
|
|
872
|
+
h.children[0]!.emit({ type: "message_end", message: { role: "assistant", model: "gpt-4o", provider: "openai", providerThinkingLevel: "low", stopReason: "stop", usage: { input: 100, output: 40, cacheRead: 30, cacheWrite: 10, totalTokens: 180, reasoning: 5 } } });
|
|
873
|
+
h.children[0]!.emit({ type: "agent_end", messages: [{ role: "assistant", content: [{ type: "text", text: "done" }] }] });
|
|
874
|
+
h.children[0]!.emit({ type: "agent_settled" });
|
|
875
|
+
await tick();
|
|
876
|
+
await tick();
|
|
877
|
+
await settle();
|
|
878
|
+
|
|
879
|
+
const stored = await loadStoredTask(h.tasksDir, taskId);
|
|
880
|
+
assert.ok(stored, "the finished task was persisted");
|
|
881
|
+
assert.equal(stored.task.status, TASK_STATUS.COMPLETED);
|
|
882
|
+
assert.deepEqual(stored.task.usage, { input: 100, output: 40, cacheRead: 30, cacheWrite: 10, reasoning: 5 });
|
|
883
|
+
});
|
|
884
|
+
|
|
885
|
+
test("a shut-down owner leaves the agents service channel and never answers discovery", async (t) => {
|
|
886
|
+
const harness = await realOwnerHarness(t);
|
|
887
|
+
assert.equal(harness.listeners.get(DESKTOP_AGENTS_SERVICE_CHANNEL)?.size, 1, "one owner answers while the session is live");
|
|
888
|
+
for (const handler of harness.handlers.get("session_shutdown") ?? []) await handler({}, harness.ctx);
|
|
889
|
+
assert.equal(harness.listeners.get(DESKTOP_AGENTS_SERVICE_CHANNEL)?.size ?? 0, 0, "the owner subscription is removed on shutdown");
|
|
890
|
+
let answered = 0;
|
|
891
|
+
harness.pi.events.emit(DESKTOP_AGENTS_SERVICE_CHANNEL, { context: harness.ctx, respond: () => { answered += 1; } });
|
|
892
|
+
assert.equal(answered, 0, "a replaced runtime is never discovered through the old owner");
|
|
893
|
+
});
|