@firstpick/pi-package-webui 0.9.1 → 0.9.3
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 +31 -9
- package/bin/pi-webui-launcher.mjs +23 -12
- package/bin/pi-webui.mjs +729 -93
- package/index.ts +266 -1
- package/lib/agent-run-adapters.mjs +500 -0
- package/lib/agent-run-protocol.mjs +262 -0
- package/lib/agent-run-registry.mjs +339 -0
- package/lib/git-workflow-preferences.mjs +18 -28
- package/lib/intercom-conversations.mjs +491 -0
- package/lib/intercom-transcript-filter.mjs +99 -0
- package/lib/resource-selection.mjs +140 -0
- package/lib/trust-boundaries.mjs +2 -0
- package/lib/ui-layout-settings.mjs +172 -28
- package/lib/update/package-layout.mjs +50 -0
- package/lib/update/plan.mjs +11 -0
- package/package.json +2 -2
- package/public/app.js +2276 -419
- package/public/index.html +142 -72
- package/public/service-worker.js +2 -1
- package/public/stream-output-controller.mjs +15 -0
- package/public/styles.css +764 -92
- package/public/syntax-highlight.mjs +622 -0
- package/tests/agent-run-adapters.test.mjs +217 -0
- package/tests/agent-run-launcher.test.mjs +41 -0
- package/tests/agent-run-protocol.test.mjs +82 -0
- package/tests/agent-run-registry.test.mjs +102 -0
- package/tests/boot-failure-diagnostics.test.mjs +3 -3
- package/tests/browser/control-deck-side-panels.spec.mjs +354 -0
- package/tests/browser/controls-layout.spec.mjs +122 -0
- package/tests/browser/file-tree-git-ignored.spec.mjs +113 -0
- package/tests/browser/interaction-continuity.spec.mjs +161 -0
- package/tests/browser/intercom-conversation-viewer.spec.mjs +355 -0
- package/tests/browser/mobile-foundation.spec.mjs +26 -0
- package/tests/browser/model-search-focus.spec.mjs +96 -0
- package/tests/browser/optimistic-prompt.spec.mjs +22 -0
- package/tests/browser/persistent-ui-layout.spec.mjs +285 -66
- package/tests/browser/resource-profiles.spec.mjs +200 -0
- package/tests/browser/subagent-observability.spec.mjs +116 -0
- package/tests/codex-fast-mode-static.test.mjs +7 -6
- package/tests/common-options-submenus-interaction-static.test.mjs +2 -0
- package/tests/common-options-submenus-markup-static.test.mjs +1 -0
- package/tests/component-update-api-static.test.mjs +2 -1
- package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
- package/tests/composer-skill-tag-layout.test.mjs +32 -2
- package/tests/control-deck-component-updates-static.test.mjs +6 -0
- package/tests/control-deck-side-panels-static.test.mjs +68 -0
- package/tests/controls-layout-static.test.mjs +22 -0
- package/tests/fast-mode-client-static.test.mjs +2 -2
- package/tests/feature-decision-output-popup-static.test.mjs +2 -2
- package/tests/feature-system-prompt-optional-feature-static.test.mjs +5 -5
- package/tests/file-tree-git-ignored-static.test.mjs +152 -0
- package/tests/file-tree-search-layout-static.test.mjs +2 -1
- package/tests/file-viewer-image-static.test.mjs +69 -0
- package/tests/fixtures/fake-pi.mjs +147 -12
- package/tests/foreground-transcript-catch-up-static.test.mjs +1 -1
- package/tests/git-panel-file-preview-static.test.mjs +5 -5
- package/tests/git-panel-live-updates-static.test.mjs +3 -3
- package/tests/git-workflow-preferences.test.mjs +55 -6
- package/tests/http-endpoints-harness.test.mjs +295 -14
- package/tests/intercom-conversation-viewer-static.test.mjs +105 -0
- package/tests/intercom-conversations-http.test.mjs +252 -0
- package/tests/intercom-conversations.test.mjs +374 -0
- package/tests/intercom-main-transcript-suppression-static.test.mjs +52 -0
- package/tests/intercom-tag-layout-static.test.mjs +46 -0
- package/tests/intercom-transcript-filter.test.mjs +98 -0
- package/tests/main-output-loading-static.test.mjs +59 -0
- package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
- package/tests/mobile-compact-layout.test.mjs +2 -3
- package/tests/mobile-continuity-tablet-static.test.mjs +6 -6
- package/tests/mobile-foundation-static.test.mjs +3 -3
- package/tests/mobile-phone-experience-static.test.mjs +1 -1
- package/tests/mobile-static.test.mjs +76 -42
- package/tests/native-parity.test.mjs +8 -7
- package/tests/open-issue-wizard-static.test.mjs +2 -2
- package/tests/optional-feature-migration-frontend.test.mjs +5 -5
- package/tests/optional-feature-resource-setup-static.test.mjs +29 -0
- package/tests/persistent-ui-layout-static.test.mjs +13 -13
- package/tests/questionnaire-dialog.test.mjs +3 -3
- package/tests/remote-auth-settings-harness.test.mjs +1 -1
- package/tests/resource-defaults-helper.test.mjs +60 -6
- package/tests/resource-selection.test.mjs +114 -0
- package/tests/resource-tui-extension.test.mjs +23 -0
- package/tests/session-sampling-ui-static.test.mjs +3 -3
- package/tests/side-panel-context-menu-static.test.mjs +1 -1
- package/tests/side-panel-resize-static.test.mjs +26 -16
- package/tests/side-panel-section-height-removal-static.test.mjs +4 -4
- package/tests/side-panel-section-reorder-static.test.mjs +16 -70
- package/tests/stream-output-controller.test.mjs +8 -0
- package/tests/stream-output-isolation-static.test.mjs +2 -2
- package/tests/streaming-ui-coupling.test.mjs +5 -0
- package/tests/subagent-gate-visibility.test.mjs +2 -1
- package/tests/subagent-launch-slots.test.mjs +1 -1
- package/tests/subagent-observability-static.test.mjs +32 -0
- package/tests/subagent-reliability-integration.test.mjs +183 -0
- package/tests/subagent-workflow-section-static.test.mjs +67 -0
- package/tests/subagents-helper.test.mjs +548 -5
- package/tests/syntax-highlight.test.mjs +235 -0
- package/tests/syntax-highlighting-static.test.mjs +84 -0
- package/tests/terminal-tabs-resize-static.test.mjs +35 -0
- package/tests/theme-customizer-static.test.mjs +5 -5
- package/tests/thinking-format-parser.test.mjs +64 -0
- package/tests/ui-layout-settings.test.mjs +104 -32
- package/tests/update-api-harness.test.mjs +24 -10
- package/tests/update-package-layout.test.mjs +38 -0
- package/tests/update-plan.test.mjs +11 -1
- package/tests/webui-settings-locking.test.mjs +33 -3
- package/webui-rpc-helper.mjs +700 -89
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
|
|
6
|
+
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
|
|
7
|
+
const [html, app, css, serviceWorker, readme, technical, development] = await Promise.all([
|
|
8
|
+
readFile(join(root, "public", "index.html"), "utf8"),
|
|
9
|
+
readFile(join(root, "public", "app.js"), "utf8"),
|
|
10
|
+
readFile(join(root, "public", "styles.css"), "utf8"),
|
|
11
|
+
readFile(join(root, "public", "service-worker.js"), "utf8"),
|
|
12
|
+
readFile(join(root, "README.md"), "utf8"),
|
|
13
|
+
readFile(join(root, "TECHNICAL.md"), "utf8"),
|
|
14
|
+
readFile(join(root, "DEVELOPMENT.md"), "utf8"),
|
|
15
|
+
]);
|
|
16
|
+
|
|
17
|
+
function count(value, pattern) {
|
|
18
|
+
return [...value.matchAll(pattern)].length;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function functionSource(name) {
|
|
22
|
+
const start = app.indexOf(`function ${name}(`);
|
|
23
|
+
assert.ok(start >= 0, `${name} should exist`);
|
|
24
|
+
const next = app.slice(start + 1).match(/\n(?:async )?function [A-Za-z0-9_$]+\(/);
|
|
25
|
+
const end = next ? start + 1 + next.index : app.length;
|
|
26
|
+
return app.slice(start, end);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
for (const id of [
|
|
30
|
+
"intercomConversationTags",
|
|
31
|
+
"intercomConversationDialog",
|
|
32
|
+
"intercomConversationTitle",
|
|
33
|
+
"intercomConversationParticipants",
|
|
34
|
+
"intercomConversationTranscript",
|
|
35
|
+
"intercomConversationStatus",
|
|
36
|
+
"intercomConversationCloseButton",
|
|
37
|
+
]) {
|
|
38
|
+
assert.equal(count(html, new RegExp(`id="${id}"`, "g")), 1, `${id} should be a singleton`);
|
|
39
|
+
assert.ok(app.includes(`${id}: $("#${id}")`), `${id} should be cached in the browser element map`);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
assert.match(
|
|
43
|
+
html,
|
|
44
|
+
/<div class="composer-context-tags">[\s\S]*<div id="intercomConversationTags" class="composer-intercom-tags" role="group" aria-label="Agent conversations" aria-live="polite" hidden><\/div>/,
|
|
45
|
+
"the dedicated conversation-tag list should live beneath the composer input in the existing context-tag surface",
|
|
46
|
+
);
|
|
47
|
+
assert.match(
|
|
48
|
+
html,
|
|
49
|
+
/<dialog id="intercomConversationDialog"[^>]*aria-labelledby="intercomConversationTitle"[^>]*aria-describedby="intercomConversationParticipants intercomConversationStatus">[\s\S]*role="log"[^>]*aria-live="polite"[\s\S]*id="intercomConversationCloseButton" type="submit" value="close"/,
|
|
50
|
+
"the viewer should be a labelled native dialog with a live transcript and explicit close control",
|
|
51
|
+
);
|
|
52
|
+
assert.match(app, /installModalPrimitives\(\)/, "the native dialog should use the shared focus-management primitive");
|
|
53
|
+
assert.match(functionSource("openIntercomConversation"), /showModal\(\)[\s\S]*intercomConversationCloseButton\?\.focus/, "opening should use the modal primitive and establish an explicit keyboard target");
|
|
54
|
+
assert.match(functionSource("setActiveTabId"), /closeIntercomConversationDialog\(\{ restoreFocus: false \}\)/, "tab switching should close the old conversation without restoring focus into the old tab");
|
|
55
|
+
|
|
56
|
+
const tagsSource = functionSource("renderIntercomConversationTags");
|
|
57
|
+
assert.match(tagsSource, /const seenConversationIds = new Set\(\)/, "tag rendering should deduplicate conversation IDs defensively");
|
|
58
|
+
assert.match(tagsSource, /seenConversationIds\.has\(conversation\.id\)[\s\S]*seenConversationIds\.add\(conversation\.id\)/, "each projected conversation should create at most one tag");
|
|
59
|
+
assert.match(tagsSource, /dataset\.intercomConversationId = conversation\.id/, "tags should retain only the opaque conversation ID");
|
|
60
|
+
assert.match(tagsSource, /aria-haspopup", "dialog"[\s\S]*aria-controls", "intercomConversationDialog"/, "each tag should advertise its dialog relationship");
|
|
61
|
+
assert.match(tagsSource, /container\.hidden = orderedTags\.length === 0/, "the tag list should disappear when there are no conversations");
|
|
62
|
+
|
|
63
|
+
const summarySource = functionSource("refreshIntercomConversationSummaries");
|
|
64
|
+
assert.match(summarySource, /api\("\/api\/intercom\/conversations", \{ tabId: tabContext\.tabId \}\)/, "summary requests should stay scoped to the selected tab");
|
|
65
|
+
assert.match(summarySource, /requestSerial !== intercomSummaryRequestSerial \|\| !isCurrentTabContext\(tabContext\)/, "summary responses should be rejected after a newer request or tab switch");
|
|
66
|
+
const detailSource = functionSource("refreshIntercomConversationDetail");
|
|
67
|
+
assert.match(detailSource, /conversation=\$\{encodeURIComponent\(state\.conversationId\)\}/, "detail selection should send only an encoded opaque ID");
|
|
68
|
+
assert.match(detailSource, /requestSerial !== intercomDetailRequestSerial[\s\S]*state !== intercomConversationDialogState[\s\S]*!isCurrentTabContext\(state\)/, "detail responses should be rejected after rapid selection or tab changes");
|
|
69
|
+
assert.match(app, /\["webui_connected", "agent_end", "message_end", "tool_execution_end"\][\s\S]*scheduleIntercomConversationRefresh\(tabContext\)/, "settlement and reconnect events should refresh conversation summaries");
|
|
70
|
+
assert.match(app, /source\.onopen = \(\) => \{[\s\S]*scheduleIntercomConversationRefresh\(tabContext, 0\)/, "event-stream reconnection should authoritatively refetch tags");
|
|
71
|
+
|
|
72
|
+
const messageRenderSource = functionSource("renderIntercomConversationMessage");
|
|
73
|
+
const renderSource = functionSource("renderIntercomConversationDetail");
|
|
74
|
+
assert.match(messageRenderSource, /message\.direction === "local"[\s\S]*conversation\.participants\.local/, "message alignment should derive the sender from the normalized direction");
|
|
75
|
+
assert.match(messageRenderSource, /text\.textContent = message\.text/, "message content should be assigned as inert text");
|
|
76
|
+
assert.doesNotMatch(`${messageRenderSource}\n${renderSource}`, /innerHTML|insertAdjacentHTML|outerHTML/, "conversation content must not reach an HTML parser sink");
|
|
77
|
+
assert.doesNotMatch(`${messageRenderSource}\n${renderSource}`, /attachment|tool|reasoning|stdout|stderr|session/i, "the renderer must not consume excluded record fields");
|
|
78
|
+
const normalizeDetailSource = functionSource("normalizeIntercomConversationDetail");
|
|
79
|
+
assert.match(normalizeDetailSource, /INTERCOM_MESSAGE_ID_PATTERN\.test\(id\)[\s\S]*seenMessageIds\.has\(id\)/, "detail normalization should require and deduplicate opaque message IDs");
|
|
80
|
+
assert.match(normalizeDetailSource, /\["local", "peer"\]\.includes\(candidate\.direction\)[\s\S]*typeof candidate\.text !== "string"/, "detail normalization should whitelist only direction and text messages");
|
|
81
|
+
assert.match(renderSource, /new Map\(\[\.\.\.transcript\.querySelectorAll\("\:scope > \.intercom-conversation-message\[data-intercom-message-id\]"\)\]/, "live refresh should reconcile existing keyed message nodes");
|
|
82
|
+
assert.match(renderSource, /existingArticles\.get\(message\.id\)[\s\S]*renderIntercomConversationMessage\(article, message, conversation\)/, "existing opaque message nodes should be reused and safely patched");
|
|
83
|
+
assert.match(renderSource, /staleArticle\.remove\(\)[\s\S]*transcript\.insertBefore\(article, cursor\)/, "only stale messages should be removed and genuinely new messages inserted");
|
|
84
|
+
assert.doesNotMatch(renderSource, /replaceChildren/, "detail polling must not rebuild the whole live log");
|
|
85
|
+
assert.match(renderSource, /const anchorOffset = anchor \? anchor\.getBoundingClientRect\(\)\.top - transcript\.getBoundingClientRect\(\)\.top[\s\S]*transcript\.scrollTop \+= currentAnchorOffset - anchorOffset/, "scrolled-up readers should retain their visual message anchor");
|
|
86
|
+
|
|
87
|
+
assert.match(functionSource("scheduleIntercomConversationDetailRefresh"), /INTERCOM_DETAIL_REFRESH_MS/, "an open dialog should use the bounded detail refresh interval");
|
|
88
|
+
assert.match(functionSource("resetIntercomConversationDialog"), /intercomDetailRequestSerial \+= 1[\s\S]*clearTimeout\(intercomDetailRefreshTimer\)[\s\S]*intercomConversationDialogState = null/, "dialog close should invalidate requests, cancel polling, and clear selection state");
|
|
89
|
+
assert.match(app, /elements\.intercomConversationDialog\?\.addEventListener\("close", resetIntercomConversationDialog\)/, "native Escape and close-button paths should share polling cleanup");
|
|
90
|
+
|
|
91
|
+
assert.match(css, /\.composer-intercom-tags \{[\s\S]*display: grid;[\s\S]*grid-auto-columns: minmax\(0, 1fr\);[\s\S]*min-width: 0;/, "all conversation tags should share the available width without a horizontal scroller");
|
|
92
|
+
assert.doesNotMatch(css, /\.composer-intercom-tags \{[^}]*overflow-x:\s*(?:auto|scroll)/, "the conversation tag group should not restore horizontal scrolling");
|
|
93
|
+
assert.match(css, /\.composer-intercom-tag:hover,[\s\S]*\.composer-intercom-tag:focus-visible/, "tags should expose pointer and keyboard focus states");
|
|
94
|
+
assert.match(css, /\.extension-dialog\.intercom-conversation-dialog \{[\s\S]*width: min\(76rem,[\s\S]*height: min\(54rem,/, "the viewer should use a large in-app modal");
|
|
95
|
+
assert.match(css, /@media \(max-width: 720px\)[\s\S]*\.composer-intercom-tag \{ min-height: 44px;[\s\S]*\.extension-dialog\.intercom-conversation-dialog[\s\S]*width: calc\(100vw - 0\.7rem\)/, "tags and the dialog should remain reachable on narrow and coarse-pointer layouts");
|
|
96
|
+
|
|
97
|
+
assert.match(html, /\/styles\.css\?v=123/, "the stylesheet URL should advance for the accepted viewer fixes");
|
|
98
|
+
assert.match(html, /data-app-src="\/app\.js\?v=146"/, "the guarded app URL should advance for incremental viewer wiring");
|
|
99
|
+
assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v108"/, "the PWA cache identity should advance with browser assets");
|
|
100
|
+
|
|
101
|
+
assert.match(readme, /one compact tag per conversation appears beneath the composer/i, "the README should explain the user-visible entry point");
|
|
102
|
+
assert.match(technical, /## Agent conversation viewer[\s\S]*Attachments, tool calls and results, thinking, stdout\/stderr, filesystem paths, raw session records/i, "the advanced guide should document privacy exclusions");
|
|
103
|
+
assert.match(development, /## Intercom conversation projection and viewer[\s\S]*GET \/api\/intercom\/conversations[\s\S]*five-second open-dialog refresh/i, "the contributor guide should document the endpoint and browser lifecycle");
|
|
104
|
+
|
|
105
|
+
console.log("intercom conversation viewer static checks passed");
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { createServer } from "node:http";
|
|
4
|
+
import { chmod, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
import { SessionManager } from "@earendil-works/pi-coding-agent";
|
|
10
|
+
import { terminateProcessTree } from "../lib/process-tree.mjs";
|
|
11
|
+
|
|
12
|
+
const packageRoot = path.join(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
13
|
+
const serverScript = path.join(packageRoot, "bin", "pi-webui.mjs");
|
|
14
|
+
const fakePi = path.join(packageRoot, "tests", "fixtures", "fake-pi.mjs");
|
|
15
|
+
const fixtureRoot = await mkdtemp(path.join(tmpdir(), "pi-webui-intercom-http-"));
|
|
16
|
+
const agentDir = path.join(fixtureRoot, "agent");
|
|
17
|
+
const sessionDir = path.join(agentDir, "sessions");
|
|
18
|
+
const cwd = path.join(fixtureRoot, "project");
|
|
19
|
+
const settingsFile = path.join(fixtureRoot, "settings.json");
|
|
20
|
+
|
|
21
|
+
await mkdir(sessionDir, { recursive: true });
|
|
22
|
+
await mkdir(cwd, { recursive: true });
|
|
23
|
+
await writeFile(path.join(agentDir, "trust.json"), `${JSON.stringify({ [cwd]: true }, null, 2)}\n`, "utf8");
|
|
24
|
+
await writeFile(settingsFile, `${JSON.stringify({ version: 3 })}\n`, "utf8");
|
|
25
|
+
await chmod(fakePi, 0o755);
|
|
26
|
+
|
|
27
|
+
const manager = SessionManager.create(cwd, sessionDir);
|
|
28
|
+
const httpPeerId = "01a00def-1234-5678-9abc-def012345678";
|
|
29
|
+
const mainTranscriptFixture = [
|
|
30
|
+
{ role: "user", content: "fake prompt", timestamp: 1000 },
|
|
31
|
+
{ role: "custom", customType: "intercom_message", content: "rendered inbound message must not be parsed", timestamp: 1500 },
|
|
32
|
+
{
|
|
33
|
+
role: "assistant",
|
|
34
|
+
content: [
|
|
35
|
+
{ type: "text", text: "ordinary assistant content must stay outside the Intercom projection" },
|
|
36
|
+
{ type: "toolCall", id: "http-intercom-call", toolName: "intercom", arguments: { action: "send", to: "01a00def", message: "HTTP_INTERCOM_ARGUMENT_SECRET" } },
|
|
37
|
+
],
|
|
38
|
+
timestamp: 2000,
|
|
39
|
+
},
|
|
40
|
+
{ role: "toolResult", toolCallId: "http-intercom-call", content: [{ type: "text", text: "HTTP_INTERCOM_RESULT_SECRET" }], timestamp: 2100 },
|
|
41
|
+
];
|
|
42
|
+
const firstMessageId = manager.appendCustomMessageEntry("intercom_message", "rendered inbound message must not be parsed", true, {
|
|
43
|
+
from: { id: httpPeerId, name: "HTTP Peer", startedAt: 1_699_999_999_000, cwd: "/private/peer/path" },
|
|
44
|
+
message: {
|
|
45
|
+
id: "http-in-1",
|
|
46
|
+
timestamp: 1_700_000_000_000,
|
|
47
|
+
content: { text: "Persisted hello", attachments: [{ name: "secret.txt", content: "HTTP_ATTACHMENT_SECRET" }] },
|
|
48
|
+
},
|
|
49
|
+
bodyText: "HTTP_BODY_TEXT_SECRET",
|
|
50
|
+
});
|
|
51
|
+
manager.appendCustomMessageEntry("intercom_message", "ABANDONED_BRANCH_SECRET", true, {
|
|
52
|
+
from: { id: httpPeerId, name: "HTTP Peer", startedAt: 1_699_999_999_000 },
|
|
53
|
+
message: { id: "http-abandoned", timestamp: 1_700_000_000_500, content: { text: "ABANDONED_BRANCH_SECRET" } },
|
|
54
|
+
});
|
|
55
|
+
manager.branch(firstMessageId);
|
|
56
|
+
manager.appendCustomEntry("intercom_sent", {
|
|
57
|
+
to: "01a00def",
|
|
58
|
+
message: { text: "Persisted reply", attachments: [{ name: "out.txt", content: "HTTP_OUTBOUND_ATTACHMENT_SECRET" }] },
|
|
59
|
+
messageId: "http-out-1",
|
|
60
|
+
timestamp: 1_700_000_001_000,
|
|
61
|
+
});
|
|
62
|
+
// SessionManager intentionally defers creating a new JSONL file until an assistant
|
|
63
|
+
// message exists. This mixed fixture also verifies that the normal transcript keeps
|
|
64
|
+
// unrelated assistant text while hiding Intercom transport records.
|
|
65
|
+
manager.appendMessage({
|
|
66
|
+
role: "assistant",
|
|
67
|
+
content: [
|
|
68
|
+
{ type: "text", text: "ordinary assistant content must stay outside the Intercom projection" },
|
|
69
|
+
{ type: "toolCall", id: "http-intercom-call", toolName: "intercom", arguments: { action: "send", to: "01a00def", message: "HTTP_INTERCOM_ARGUMENT_SECRET" } },
|
|
70
|
+
],
|
|
71
|
+
api: "openai-responses",
|
|
72
|
+
provider: "fake",
|
|
73
|
+
model: "fake-model",
|
|
74
|
+
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
|
|
75
|
+
stopReason: "toolUse",
|
|
76
|
+
timestamp: 1_700_000_001_500,
|
|
77
|
+
});
|
|
78
|
+
manager.appendMessage({
|
|
79
|
+
role: "toolResult",
|
|
80
|
+
toolCallId: "http-intercom-call",
|
|
81
|
+
toolName: "intercom",
|
|
82
|
+
content: [{ type: "text", text: "HTTP_INTERCOM_RESULT_SECRET" }],
|
|
83
|
+
isError: false,
|
|
84
|
+
timestamp: 1_700_000_001_600,
|
|
85
|
+
});
|
|
86
|
+
const sessionFile = manager.getSessionFile();
|
|
87
|
+
assert.ok(sessionFile, "fixture must create a persisted session file");
|
|
88
|
+
|
|
89
|
+
async function freePort() {
|
|
90
|
+
const server = createServer();
|
|
91
|
+
await new Promise((resolve, reject) => server.once("error", reject).listen(0, "127.0.0.1", resolve));
|
|
92
|
+
const port = server.address().port;
|
|
93
|
+
await new Promise((resolve) => server.close(resolve));
|
|
94
|
+
return port;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async function request(port, pathname) {
|
|
98
|
+
const response = await fetch(`http://127.0.0.1:${port}${pathname}`, { signal: AbortSignal.timeout(5_000) });
|
|
99
|
+
let body;
|
|
100
|
+
try { body = await response.json(); } catch { body = undefined; }
|
|
101
|
+
return { status: response.status, body, headers: response.headers };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function startServer(activeSessionFile) {
|
|
105
|
+
const port = await freePort();
|
|
106
|
+
const child = spawn(process.execPath, [serverScript, "--cwd", cwd, "--host", "127.0.0.1", "--port", String(port), "--pi", fakePi], {
|
|
107
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
108
|
+
env: {
|
|
109
|
+
...process.env,
|
|
110
|
+
PI_CODING_AGENT_DIR: agentDir,
|
|
111
|
+
PI_WEBUI_SETTINGS_FILE: settingsFile,
|
|
112
|
+
PI_WEBUI_RPC_SUPERVISOR: "0",
|
|
113
|
+
FAKE_PI_CONTINUITY_MODE: "1",
|
|
114
|
+
FAKE_PI_CONTINUITY_SESSION_FILE: activeSessionFile,
|
|
115
|
+
FAKE_PI_TRANSCRIPT_JSON: JSON.stringify(mainTranscriptFixture),
|
|
116
|
+
},
|
|
117
|
+
});
|
|
118
|
+
let output = "";
|
|
119
|
+
child.stdout.on("data", (chunk) => { output += String(chunk); });
|
|
120
|
+
child.stderr.on("data", (chunk) => { output += String(chunk); });
|
|
121
|
+
let health;
|
|
122
|
+
for (let attempt = 0; attempt < 100; attempt++) {
|
|
123
|
+
if (child.exitCode !== null) break;
|
|
124
|
+
try {
|
|
125
|
+
health = await request(port, "/api/health");
|
|
126
|
+
if (health.status === 200 && health.body?.piRunning === true) break;
|
|
127
|
+
} catch {
|
|
128
|
+
// The focused server is still starting.
|
|
129
|
+
}
|
|
130
|
+
await delay(100);
|
|
131
|
+
}
|
|
132
|
+
assert.equal(health?.status, 200, `server should become healthy\n${output}`);
|
|
133
|
+
assert.equal(health.body?.piRunning, true, `fake Pi should be running\n${output}`);
|
|
134
|
+
return { child, port, output: () => output };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function stopServer(child) {
|
|
138
|
+
if (!child || child.exitCode !== null) return;
|
|
139
|
+
await terminateProcessTree(child.pid);
|
|
140
|
+
for (let attempt = 0; attempt < 40 && child.exitCode === null; attempt++) await delay(50);
|
|
141
|
+
if (child.exitCode === null) child.kill("SIGKILL");
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async function startupTabId(server) {
|
|
145
|
+
const tabs = await request(server.port, "/api/tabs");
|
|
146
|
+
assert.equal(tabs.status, 200, tabs.body?.error);
|
|
147
|
+
const tabId = tabs.body?.data?.tabs?.[0]?.id;
|
|
148
|
+
assert.ok(tabId, `startup tab should exist\n${server.output()}`);
|
|
149
|
+
return tabId;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
let server;
|
|
153
|
+
try {
|
|
154
|
+
server = await startServer(sessionFile);
|
|
155
|
+
const tabId = await startupTabId(server);
|
|
156
|
+
const basePath = `/api/intercom/conversations?tab=${encodeURIComponent(tabId)}`;
|
|
157
|
+
|
|
158
|
+
const missingTab = await request(server.port, "/api/intercom/conversations");
|
|
159
|
+
assert.equal(missingTab.status, 400, "the endpoint must require explicit tab scope");
|
|
160
|
+
const staleTab = await request(server.port, "/api/intercom/conversations?tab=missing-tab");
|
|
161
|
+
assert.equal(staleTab.status, 404, "unknown tabs must not fall back to another session");
|
|
162
|
+
|
|
163
|
+
const mainTranscript = await request(server.port, `/api/messages?tab=${encodeURIComponent(tabId)}`);
|
|
164
|
+
assert.equal(mainTranscript.status, 200, mainTranscript.body?.error);
|
|
165
|
+
const mainMessages = mainTranscript.body?.data?.messages || [];
|
|
166
|
+
const mainSerialized = JSON.stringify(mainMessages);
|
|
167
|
+
assert.equal(mainSerialized.includes("ordinary assistant content must stay outside the Intercom projection"), true, "mixed assistant text should remain in the main transcript");
|
|
168
|
+
assert.equal(mainSerialized.includes("rendered inbound message must not be parsed"), false, "incoming Intercom custom messages should stay out of the main transcript");
|
|
169
|
+
assert.equal(mainSerialized.includes("HTTP_INTERCOM_ARGUMENT_SECRET"), false, "Intercom tool arguments should stay out of the main transcript");
|
|
170
|
+
assert.equal(mainSerialized.includes("HTTP_INTERCOM_RESULT_SECRET"), false, "paired Intercom tool results should stay out of the main transcript");
|
|
171
|
+
assert.equal(mainMessages.some((message) => message?.role === "custom" && message.customType === "intercom_message"), false);
|
|
172
|
+
assert.equal(mainMessages.some((message) => message?.role === "toolResult" && message.toolCallId === "http-intercom-call"), false);
|
|
173
|
+
|
|
174
|
+
const sessionTree = await request(server.port, `/api/session-tree?tab=${encodeURIComponent(tabId)}`);
|
|
175
|
+
assert.equal(sessionTree.status, 200, sessionTree.body?.error);
|
|
176
|
+
const treeNodes = sessionTree.body?.data?.nodes || [];
|
|
177
|
+
const intercomTreeNodes = treeNodes.filter((node) => node?.title === "intercom_message");
|
|
178
|
+
assert.ok(intercomTreeNodes.length >= 2, "the fixture should expose active and abandoned Intercom entries in the session tree");
|
|
179
|
+
assert.equal(intercomTreeNodes.every((node) => node.text === "Intercom message"), true, "session-tree Intercom entries should use only the fixed presentation label");
|
|
180
|
+
assert.equal(JSON.stringify(treeNodes).includes("rendered inbound message must not be parsed"), false, "session-tree payloads must not expose persisted Intercom prose");
|
|
181
|
+
assert.equal(JSON.stringify(treeNodes).includes("ABANDONED_BRANCH_SECRET"), false, "session-tree payloads must redact Intercom prose on inactive branches too");
|
|
182
|
+
|
|
183
|
+
const summary = await request(server.port, basePath);
|
|
184
|
+
assert.equal(summary.status, 200, summary.body?.error);
|
|
185
|
+
assert.equal(summary.headers.get("cache-control"), "private, no-store");
|
|
186
|
+
assert.equal(summary.body?.data?.conversations?.length, 1);
|
|
187
|
+
assert.equal(summary.body?.data?.conversations?.[0]?.messageCount, 2, "only the active session branch should be projected");
|
|
188
|
+
assert.equal(summary.body?.data?.conversation, null, "summary responses must not include transcript text");
|
|
189
|
+
const conversationId = summary.body?.data?.conversations?.[0]?.id;
|
|
190
|
+
assert.match(conversationId || "", /^conv_[A-Za-z0-9_-]{24}$/);
|
|
191
|
+
|
|
192
|
+
const ignoredBrowserPath = await request(server.port, `${basePath}&sessionPath=${encodeURIComponent(path.join(fixtureRoot, "outside.jsonl"))}`);
|
|
193
|
+
assert.equal(ignoredBrowserPath.status, 200, "browser-supplied session paths must not influence session resolution");
|
|
194
|
+
assert.equal(ignoredBrowserPath.body?.data?.conversations?.[0]?.id, conversationId);
|
|
195
|
+
|
|
196
|
+
const invalidConversation = await request(server.port, `${basePath}&conversation=${encodeURIComponent("../../private/session.jsonl")}`);
|
|
197
|
+
assert.equal(invalidConversation.status, 400, "detail selection accepts opaque IDs only");
|
|
198
|
+
const missingConversation = await request(server.port, `${basePath}&conversation=conv_${"a".repeat(24)}`);
|
|
199
|
+
assert.equal(missingConversation.status, 404, "unknown opaque conversation IDs must not disclose another transcript");
|
|
200
|
+
|
|
201
|
+
const detailResponse = await request(server.port, `${basePath}&conversation=${encodeURIComponent(conversationId)}`);
|
|
202
|
+
assert.equal(detailResponse.status, 200, detailResponse.body?.error);
|
|
203
|
+
assert.deepEqual(detailResponse.body?.data?.conversation?.messages?.map(({ direction, text }) => [direction, text]), [
|
|
204
|
+
["peer", "Persisted hello"],
|
|
205
|
+
["local", "Persisted reply"],
|
|
206
|
+
]);
|
|
207
|
+
const serialized = JSON.stringify(detailResponse.body);
|
|
208
|
+
for (const forbidden of [
|
|
209
|
+
sessionFile,
|
|
210
|
+
"/private/peer/path",
|
|
211
|
+
"ABANDONED_BRANCH_SECRET",
|
|
212
|
+
"HTTP_ATTACHMENT_SECRET",
|
|
213
|
+
"HTTP_OUTBOUND_ATTACHMENT_SECRET",
|
|
214
|
+
"HTTP_BODY_TEXT_SECRET",
|
|
215
|
+
"rendered inbound message must not be parsed",
|
|
216
|
+
]) assert.equal(serialized.includes(forbidden), false, `HTTP payload must not expose ${forbidden}`);
|
|
217
|
+
|
|
218
|
+
await stopServer(server.child);
|
|
219
|
+
server = undefined;
|
|
220
|
+
manager.appendCustomEntry("intercom_received", {
|
|
221
|
+
from: "HTTP Peer",
|
|
222
|
+
message: { text: "Persisted after restart" },
|
|
223
|
+
messageId: "http-in-2",
|
|
224
|
+
timestamp: 1_700_000_002_000,
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
server = await startServer(sessionFile);
|
|
228
|
+
const restartedTabId = await startupTabId(server);
|
|
229
|
+
const restartedSummary = await request(server.port, `/api/intercom/conversations?tab=${encodeURIComponent(restartedTabId)}`);
|
|
230
|
+
assert.equal(restartedSummary.status, 200, restartedSummary.body?.error);
|
|
231
|
+
const restartedConversations = restartedSummary.body?.data?.conversations || [];
|
|
232
|
+
const restartedStableConversation = restartedConversations.find((conversation) => conversation.id === conversationId);
|
|
233
|
+
assert.ok(restartedStableConversation, "the evidence-backed conversation identity should remain stable after server restart");
|
|
234
|
+
assert.equal(restartedConversations.length, 1, "all messages between the same two agents should remain one conversation after restart");
|
|
235
|
+
assert.equal(restartedStableConversation.messageCount, 3, "short-ID, full-ID, and unique display-name records should reconstruct one participant-pair conversation");
|
|
236
|
+
await stopServer(server.child);
|
|
237
|
+
server = undefined;
|
|
238
|
+
|
|
239
|
+
const outsideManager = SessionManager.create(cwd, path.join(fixtureRoot, "outside-sessions"));
|
|
240
|
+
outsideManager.appendCustomEntry("intercom_sent", { to: "Outside", message: { text: "must stay unavailable" }, messageId: "outside-message", timestamp: Date.now() });
|
|
241
|
+
const outsideSessionFile = outsideManager.getSessionFile();
|
|
242
|
+
server = await startServer(outsideSessionFile);
|
|
243
|
+
const outsideTabId = await startupTabId(server);
|
|
244
|
+
const outsideResponse = await request(server.port, `/api/intercom/conversations?tab=${encodeURIComponent(outsideTabId)}`);
|
|
245
|
+
assert.equal(outsideResponse.status, 403, "server-derived session files outside allowed Pi roots must be rejected");
|
|
246
|
+
assert.equal(JSON.stringify(outsideResponse.body).includes(outsideSessionFile), false, "confinement errors must not expose the rejected path");
|
|
247
|
+
|
|
248
|
+
console.log("intercom-conversations-http: ok");
|
|
249
|
+
} finally {
|
|
250
|
+
await stopServer(server?.child);
|
|
251
|
+
await rm(fixtureRoot, { recursive: true, force: true });
|
|
252
|
+
}
|