@firstpick/pi-package-webui 0.7.3 → 0.7.5

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.
Files changed (34) hide show
  1. package/README.md +34 -20
  2. package/bin/pi-webui.mjs +332 -39
  3. package/index.ts +10 -1
  4. package/lib/git-workflow-preferences.mjs +91 -22
  5. package/lib/subagent-launch-slots.mjs +304 -0
  6. package/lib/trust-boundaries.mjs +1 -0
  7. package/lib/webui-output-mode.mjs +97 -0
  8. package/package.json +22 -22
  9. package/public/app.js +1629 -69
  10. package/public/fast-output-live.mjs +179 -0
  11. package/public/index.html +86 -12
  12. package/public/service-worker.js +3 -1
  13. package/public/styles.css +769 -37
  14. package/public/subagent-launch-slot-state.mjs +64 -0
  15. package/tests/chat-scroll-intent-static.test.mjs +59 -0
  16. package/tests/custom-message-markdown-static.test.mjs +15 -0
  17. package/tests/fast-mode-client-static.test.mjs +169 -0
  18. package/tests/fast-mode-output-work.test.mjs +69 -0
  19. package/tests/fast-mode-sse-harness.test.mjs +204 -0
  20. package/tests/fast-output-live.test.mjs +106 -0
  21. package/tests/fixtures/fake-pi.mjs +58 -0
  22. package/tests/fixtures/fast-mode-output-events.mjs +50 -0
  23. package/tests/footer-middle-truncation.test.mjs +2 -2
  24. package/tests/git-workflow-preferences.test.mjs +8 -2
  25. package/tests/http-endpoints-harness.test.mjs +74 -0
  26. package/tests/mobile-static.test.mjs +86 -15
  27. package/tests/remote-auth-settings-harness.test.mjs +1 -1
  28. package/tests/side-panel-resize-static.test.mjs +43 -0
  29. package/tests/subagent-launch-slot-state.test.mjs +36 -0
  30. package/tests/subagent-launch-slots-static.test.mjs +34 -0
  31. package/tests/subagent-launch-slots.test.mjs +143 -0
  32. package/tests/subagents-helper.test.mjs +46 -0
  33. package/tests/webui-output-mode.test.mjs +73 -0
  34. package/webui-rpc-helper.mjs +37 -9
package/bin/pi-webui.mjs CHANGED
@@ -44,10 +44,34 @@ import {
44
44
  readGitWorkflowPreferences,
45
45
  readWebuiSettings,
46
46
  supportedGitWorkflowThinkingLevels,
47
+ updateWebuiSettings,
47
48
  webuiSettingsFile,
48
49
  writeGitWorkflowPreferences,
49
50
  writeWebuiSettings,
50
51
  } from "../lib/git-workflow-preferences.mjs";
52
+ import {
53
+ SUBAGENT_LAUNCH_SLOT_LIMITS,
54
+ SUBAGENT_LAUNCH_SLOT_ROLE_CATALOG,
55
+ SUBAGENT_LAUNCH_SLOT_THINKING_LEVELS,
56
+ normalizeSubagentLaunchSlots,
57
+ resolveSubagentLaunchSlotProjectKey,
58
+ subagentLaunchSlotModelKey,
59
+ subagentLaunchSlotProjectLabel,
60
+ subagentLaunchSlotRevision,
61
+ subagentLaunchSlotScopeEntry,
62
+ supportedSubagentLaunchSlotThinkingLevels,
63
+ validateSubagentLaunchSlotRoles,
64
+ } from "../lib/subagent-launch-slots.mjs";
65
+ import {
66
+ encodeBrowserSseEvent,
67
+ isOutputModeSemanticBarrier,
68
+ negotiateOutputMode,
69
+ normalizeOutputMode,
70
+ OUTPUT_MODE_COMPACT_V1,
71
+ OUTPUT_MODE_NORMAL,
72
+ OUTPUT_MODE_PROTOCOL_VERSION,
73
+ resolveOutputModeDefault,
74
+ } from "../lib/webui-output-mode.mjs";
51
75
  import {
52
76
  evaluateDispatchTrustGuards,
53
77
  guardsForNativeCommand,
@@ -302,7 +326,13 @@ function isTruthyEnv(value) {
302
326
 
303
327
  function isSourceCheckout(root) {
304
328
  const normalized = String(root || "").replace(/\\/g, "/");
305
- return normalized.includes("/npm-packages/") && !normalized.includes("/node_modules/");
329
+ if (normalized.includes("/node_modules/")) return false;
330
+ try {
331
+ const gitMarker = statSync(path.join(root, "..", ".git"));
332
+ return gitMarker.isDirectory() || gitMarker.isFile();
333
+ } catch {
334
+ return false;
335
+ }
306
336
  }
307
337
 
308
338
  const NATIVE_SLASH_COMMANDS = nativeSlashCommandEntries(nativeParityMatrix);
@@ -365,6 +395,7 @@ Options:
365
395
  --name <name> Initial Web UI tab display name
366
396
  --remote-auth Enable startup PIN authentication for non-local clients
367
397
  --no-remote-auth Disable startup PIN authentication
398
+ --output-mode <mode> Web UI output default: normal or compact-v1
368
399
  -h, --help Show this help
369
400
  -v, --version Print version
370
401
 
@@ -392,6 +423,14 @@ function takeValue(argv, index, flag) {
392
423
  return value;
393
424
  }
394
425
 
426
+ function requiredOutputMode(value, source) {
427
+ const mode = String(value || "").trim();
428
+ if (![OUTPUT_MODE_NORMAL, OUTPUT_MODE_COMPACT_V1].includes(mode)) {
429
+ throw new Error(`${source} must be one of: ${OUTPUT_MODE_NORMAL}, ${OUTPUT_MODE_COMPACT_V1}`);
430
+ }
431
+ return mode;
432
+ }
433
+
395
434
  function parseArgs(argv) {
396
435
  const options = {
397
436
  host: process.env.PI_WEBUI_HOST || DEFAULT_HOST,
@@ -404,6 +443,8 @@ function parseArgs(argv) {
404
443
  name: undefined,
405
444
  remoteAuth: isTruthyEnv(process.env.PI_WEBUI_REMOTE_AUTH),
406
445
  remoteAuthExplicit: process.env.PI_WEBUI_REMOTE_AUTH !== undefined,
446
+ outputMode: undefined,
447
+ envOutputMode: process.env.PI_WEBUI_OUTPUT_MODE === undefined ? undefined : requiredOutputMode(process.env.PI_WEBUI_OUTPUT_MODE, "PI_WEBUI_OUTPUT_MODE"),
407
448
  piArgs: [],
408
449
  help: false,
409
450
  version: false,
@@ -458,6 +499,11 @@ function parseArgs(argv) {
458
499
  i++;
459
500
  continue;
460
501
  }
502
+ if (arg === "--output-mode") {
503
+ options.outputMode = requiredOutputMode(takeValue(argv, i, arg), "--output-mode");
504
+ i++;
505
+ continue;
506
+ }
461
507
  if (arg === "--remote-auth") {
462
508
  options.remoteAuth = true;
463
509
  options.remoteAuthExplicit = true;
@@ -1095,8 +1141,12 @@ function sendRemoteAuthRequired(req, res, url) {
1095
1141
  sendJson(res, 401, { ok: false, error: "Remote PIN required", remoteAuthRequired: true }, { "www-authenticate": "PiRemotePin" });
1096
1142
  }
1097
1143
 
1098
- function sendSse(res, event) {
1099
- res.write(`data: ${JSON.stringify(event)}\n\n`);
1144
+ function sendSse(client, event) {
1145
+ const res = client?.res || client;
1146
+ const payload = encodeBrowserSseEvent(event, { outputMode: client?.activeMode || OUTPUT_MODE_NORMAL });
1147
+ if (payload === undefined) return false;
1148
+ res.write(`data: ${payload}\n\n`);
1149
+ return true;
1100
1150
  }
1101
1151
 
1102
1152
  function rpcSuccess(command, data = {}) {
@@ -1481,8 +1531,33 @@ function statusEventSummary(event) {
1481
1531
  return summary;
1482
1532
  }
1483
1533
 
1534
+ function deltaHistorySummary(event) {
1535
+ const update = event?.assistantMessageEvent;
1536
+ if (event?.type !== "message_update" || !update || typeof update !== "object" || !["text_delta", "thinking_delta", "toolcall_delta"].includes(update.type) || typeof update.delta !== "string") return null;
1537
+ return {
1538
+ type: "message_update",
1539
+ firstTimestamp: new Date().toISOString(),
1540
+ lastTimestamp: new Date().toISOString(),
1541
+ tabId: event.tabId,
1542
+ updateType: update.type,
1543
+ contentIndex: update.contentIndex ?? event.contentIndex ?? null,
1544
+ deltaCount: 1,
1545
+ deltaChars: update.delta.length,
1546
+ deltaUtf8Bytes: Buffer.byteLength(update.delta),
1547
+ };
1548
+ }
1549
+
1484
1550
  function recordEvent(event) {
1485
- eventHistory.push(statusEventSummary(event));
1551
+ const delta = deltaHistorySummary(event);
1552
+ const previous = eventHistory.at(-1);
1553
+ if (delta && previous?.type === delta.type && previous.tabId === delta.tabId && previous.updateType === delta.updateType && previous.contentIndex === delta.contentIndex && Number.isInteger(previous.deltaCount)) {
1554
+ previous.lastTimestamp = delta.lastTimestamp;
1555
+ previous.deltaCount += delta.deltaCount;
1556
+ previous.deltaChars += delta.deltaChars;
1557
+ previous.deltaUtf8Bytes += delta.deltaUtf8Bytes;
1558
+ } else {
1559
+ eventHistory.push(delta || statusEventSummary(event));
1560
+ }
1486
1561
  if (eventHistory.length > EVENT_HISTORY_LIMIT) eventHistory.splice(0, eventHistory.length - EVENT_HISTORY_LIMIT);
1487
1562
  }
1488
1563
 
@@ -1998,6 +2073,107 @@ async function saveSafetyGuardConfigData(body = {}) {
1998
2073
  }
1999
2074
  }
2000
2075
 
2076
+ function requireSubagentLaunchSlotScope(value) {
2077
+ const scope = String(value || "").trim();
2078
+ if (!["user", "project"].includes(scope)) throw makeHttpError(400, "scope must be user or project");
2079
+ return scope;
2080
+ }
2081
+
2082
+ async function availableSubagentLaunchSlotModels(tab) {
2083
+ const response = await safeRpcData(tab, { type: "get_available_models" });
2084
+ if (!response.ok) throw makeHttpError(400, response.error || "Failed to load available models");
2085
+ return (Array.isArray(response.data?.models) ? response.data.models : [])
2086
+ .filter((model) => subagentLaunchSlotModelKey(model))
2087
+ .sort((left, right) => subagentLaunchSlotModelKey(left).localeCompare(subagentLaunchSlotModelKey(right)));
2088
+ }
2089
+
2090
+ async function subagentLaunchSlotProjectContext(tab) {
2091
+ const projectKey = await resolveSubagentLaunchSlotProjectKey(tab.cwd);
2092
+ return { projectKey, projectLabel: subagentLaunchSlotProjectLabel(projectKey) };
2093
+ }
2094
+
2095
+ function subagentLaunchSlotConfigPayload(settings, scope, project, models, extra = {}) {
2096
+ const config = normalizeSubagentLaunchSlots(settings?.subagentLaunchSlots);
2097
+ const effective = subagentLaunchSlotScopeEntry(config, scope, project.projectKey);
2098
+ return {
2099
+ scope,
2100
+ projectKey: project.projectKey,
2101
+ projectLabel: project.projectLabel,
2102
+ inherited: effective.inherited,
2103
+ revision: subagentLaunchSlotRevision(config, scope, project.projectKey),
2104
+ roles: effective.entry.roles,
2105
+ roleMetadata: SUBAGENT_LAUNCH_SLOT_ROLE_CATALOG,
2106
+ models,
2107
+ modelThinkingLevels: Object.fromEntries(models.map((model) => [
2108
+ subagentLaunchSlotModelKey(model),
2109
+ supportedSubagentLaunchSlotThinkingLevels(model),
2110
+ ])),
2111
+ limits: SUBAGENT_LAUNCH_SLOT_LIMITS,
2112
+ thinkingLevels: SUBAGENT_LAUNCH_SLOT_THINKING_LEVELS,
2113
+ reloadRequired: false,
2114
+ ...extra,
2115
+ };
2116
+ }
2117
+
2118
+ async function subagentLaunchSlotConfigData(tab, requestedScope) {
2119
+ const scope = requireSubagentLaunchSlotScope(requestedScope);
2120
+ const [settings, models, project] = await Promise.all([
2121
+ readWebuiSettings(),
2122
+ availableSubagentLaunchSlotModels(tab),
2123
+ subagentLaunchSlotProjectContext(tab),
2124
+ ]);
2125
+ return subagentLaunchSlotConfigPayload(settings, scope, project, models);
2126
+ }
2127
+
2128
+ async function saveSubagentLaunchSlotConfigData(tab, body = {}) {
2129
+ const scope = requireSubagentLaunchSlotScope(body.scope);
2130
+ const revision = typeof body.revision === "string" ? body.revision.trim() : "";
2131
+ if (!revision || revision.length > 128) throw makeHttpError(400, "revision is required");
2132
+ const inherit = body.inherit === true;
2133
+ if (inherit && scope !== "project") throw makeHttpError(400, "inherit is only supported for project scope");
2134
+
2135
+ const [models, project] = await Promise.all([
2136
+ availableSubagentLaunchSlotModels(tab),
2137
+ subagentLaunchSlotProjectContext(tab),
2138
+ ]);
2139
+ let roles;
2140
+ if (!inherit) {
2141
+ try {
2142
+ roles = validateSubagentLaunchSlotRoles(body.roles, models);
2143
+ } catch (error) {
2144
+ throw makeHttpError(400, error instanceof Error ? error.message : String(error));
2145
+ }
2146
+ }
2147
+
2148
+ let changed = false;
2149
+ const settings = await updateWebuiSettings((currentSettings) => {
2150
+ const config = normalizeSubagentLaunchSlots(currentSettings.subagentLaunchSlots);
2151
+ const currentRevision = subagentLaunchSlotRevision(config, scope, project.projectKey);
2152
+ if (currentRevision !== revision) {
2153
+ throw makeHttpError(409, "Subagent launch-slot configuration changed; reload it before saving.");
2154
+ }
2155
+
2156
+ const nextConfig = normalizeSubagentLaunchSlots(config);
2157
+ if (scope === "user") {
2158
+ nextConfig.user = { roles };
2159
+ } else if (inherit) {
2160
+ delete nextConfig.projects[project.projectKey];
2161
+ } else {
2162
+ nextConfig.projects[project.projectKey] = { roles };
2163
+ }
2164
+ const before = scope === "user" ? config.user : config.projects[project.projectKey] || null;
2165
+ const after = scope === "user" ? nextConfig.user : nextConfig.projects[project.projectKey] || null;
2166
+ changed = JSON.stringify(before) !== JSON.stringify(after);
2167
+ return changed ? { subagentLaunchSlots: nextConfig } : undefined;
2168
+ });
2169
+
2170
+ return subagentLaunchSlotConfigPayload(settings, scope, project, models, {
2171
+ saved: true,
2172
+ changed,
2173
+ reloadRequired: changed,
2174
+ });
2175
+ }
2176
+
2001
2177
  function gitWorkflowModelKey(model) {
2002
2178
  return model?.provider && model?.id ? `${model.provider}/${model.id}` : "";
2003
2179
  }
@@ -6983,7 +7159,7 @@ async function readBundledThemes() {
6983
7159
  function normalizeStaticPath(urlPath) {
6984
7160
  if (urlPath === "/") return "index.html";
6985
7161
  const name = urlPath.startsWith("/") ? urlPath.slice(1) : urlPath;
6986
- if (!["index.html", "app.js", "voice-conversation.mjs", "aur-review-payload.mjs", "guided-git-command-state.mjs", "guided-git-review-state.mjs", "styles.css", "favicon.svg", "apple-touch-icon.png", "icon-192.png", "icon-512.png", "catppuccin-mocha-background.png", "matrix-background.webp", "manifest.webmanifest", "service-worker.js"].includes(name)) return undefined;
7162
+ if (!["index.html", "app.js", "fast-output-live.mjs", "subagent-launch-slot-state.mjs", "voice-conversation.mjs", "aur-review-payload.mjs", "guided-git-command-state.mjs", "guided-git-review-state.mjs", "styles.css", "favicon.svg", "apple-touch-icon.png", "icon-192.png", "icon-512.png", "catppuccin-mocha-background.png", "matrix-background.webp", "manifest.webmanifest", "service-worker.js"].includes(name)) return undefined;
6987
7163
  return name;
6988
7164
  }
6989
7165
 
@@ -7907,9 +8083,9 @@ function enforceNaturalConversationCommandAllowed(tab, command) {
7907
8083
  }
7908
8084
  }
7909
8085
 
7910
- function replayExtensionStatuses(tab, res) {
8086
+ function replayExtensionStatuses(tab, client) {
7911
8087
  for (const [statusKey, statusText] of extensionStatusMap(tab)) {
7912
- sendSse(res, {
8088
+ sendSseToClient(client, {
7913
8089
  type: "extension_ui_request",
7914
8090
  id: randomUUID(),
7915
8091
  method: "setStatus",
@@ -7924,10 +8100,10 @@ function replayExtensionStatuses(tab, res) {
7924
8100
  }
7925
8101
  }
7926
8102
 
7927
- function replayExtensionWidgets(tab, res) {
8103
+ function replayExtensionWidgets(tab, client) {
7928
8104
  const pendingExtensionUiRequestCount = pendingExtensionUiRequests(tab).length;
7929
8105
  for (const [widgetKey, request] of extensionWidgetMap(tab)) {
7930
- sendSse(res, {
8106
+ sendSseToClient(client, {
7931
8107
  ...request,
7932
8108
  type: "extension_ui_request",
7933
8109
  id: randomUUID(),
@@ -8214,10 +8390,10 @@ function clearPendingExtensionUiRequests(tab) {
8214
8390
  tab?.pendingExtensionUiRequests?.clear();
8215
8391
  }
8216
8392
 
8217
- function replayPendingExtensionUiRequests(tab, res) {
8393
+ function replayPendingExtensionUiRequests(tab, client) {
8218
8394
  const pending = pendingExtensionUiRequests(tab);
8219
8395
  for (const request of pending) {
8220
- sendSse(res, {
8396
+ sendSseToClient(client, {
8221
8397
  ...request,
8222
8398
  type: "extension_ui_request",
8223
8399
  replayed: true,
@@ -8416,7 +8592,7 @@ function attachRpcToTab(tab, rpc) {
8416
8592
  }
8417
8593
  scopedEvent = { ...scopedEvent, tabActivity: tabActivitySnapshot(tab), pendingExtensionUiRequestCount: pendingExtensionUiRequests(tab).length };
8418
8594
  recordEvent(scopedEvent);
8419
- for (const client of tab.sseClients) sendSse(client, scopedEvent);
8595
+ for (const client of tab.sseClients) sendSseToClient(client, scopedEvent);
8420
8596
  if (event?.type === "compaction_end") void flushCompactionQueue(tab, event);
8421
8597
  if (event?.type === "agent_settled") void restoreGitWorkflowGenerationProfile(tab);
8422
8598
  });
@@ -9223,7 +9399,7 @@ function rememberClosedRestorableTab(tab, state = null) {
9223
9399
 
9224
9400
  function broadcastTabEvent(tab, event) {
9225
9401
  recordEvent(event);
9226
- for (const client of tab.sseClients) sendSse(client, event);
9402
+ for (const client of tab.sseClients) sendSseToClient(client, event);
9227
9403
  }
9228
9404
 
9229
9405
  function broadcastServerEvent(event) {
@@ -9232,7 +9408,7 @@ function broadcastServerEvent(event) {
9232
9408
  for (const tab of tabs.values()) {
9233
9409
  for (const client of tab.sseClients) clients.add(client);
9234
9410
  }
9235
- for (const client of clients) sendSse(client, event);
9411
+ for (const client of clients) sendSseToClient(client, event);
9236
9412
  }
9237
9413
 
9238
9414
  const gitLiveWatcher = createGitLiveWatcher({
@@ -9306,10 +9482,7 @@ async function updateTabCwd(id, cwd) {
9306
9482
  const piCommand = await resolvePiCommand(piArgs);
9307
9483
  gitLiveWatcher.unsubscribe(tab.id);
9308
9484
  const restartingEvent = { type: "webui_tab_restarting", tabId: tab.id, tabTitle: tab.title, cwd: nextCwd, sessionFile };
9309
- recordEvent(restartingEvent);
9310
- for (const client of tab.sseClients) {
9311
- sendSse(client, restartingEvent);
9312
- }
9485
+ broadcastTabEvent(tab, restartingEvent);
9313
9486
 
9314
9487
  const oldRpc = tab.rpc;
9315
9488
  tab.rpcUnsubscribe?.();
@@ -9332,10 +9505,7 @@ async function updateTabCwd(id, cwd) {
9332
9505
  await primeTabRpc(tab).catch(() => {});
9333
9506
 
9334
9507
  const changedEvent = { type: "webui_cwd_changed", tabId: tab.id, tabTitle: tab.title, cwd: tab.cwd, pid: tab.rpc.child?.pid, sessionFile, tabActivity: tabActivitySnapshot(tab) };
9335
- recordEvent(changedEvent);
9336
- for (const client of tab.sseClients) {
9337
- sendSse(client, changedEvent);
9338
- }
9508
+ broadcastTabEvent(tab, changedEvent);
9339
9509
  return { tab, changed: true };
9340
9510
  }
9341
9511
 
@@ -9350,8 +9520,7 @@ async function restartTabRpc(tab, reason = "reload") {
9350
9520
  if (state.data?.sessionFile && !options.noSession) piArgs.push("--session", state.data.sessionFile);
9351
9521
  const piCommand = await resolvePiCommand(piArgs);
9352
9522
  const reloadingEvent = { type: "webui_tab_reloading", tabId: tab.id, tabTitle: tab.title, cwd: tab.cwd, reason, sessionFile: state.data?.sessionFile };
9353
- recordEvent(reloadingEvent);
9354
- for (const client of tab.sseClients) sendSse(client, reloadingEvent);
9523
+ broadcastTabEvent(tab, reloadingEvent);
9355
9524
 
9356
9525
  const oldRpc = tab.rpc;
9357
9526
  tab.rpcUnsubscribe?.();
@@ -9370,8 +9539,7 @@ async function restartTabRpc(tab, reason = "reload") {
9370
9539
  rpc.start();
9371
9540
 
9372
9541
  const reloadedEvent = { type: "webui_tab_reloaded", tabId: tab.id, tabTitle: tab.title, cwd: tab.cwd, pid: tab.rpc.child?.pid, reason, sessionFile: state.data?.sessionFile, tabActivity: tabActivitySnapshot(tab) };
9373
- recordEvent(reloadedEvent);
9374
- for (const client of tab.sseClients) sendSse(client, reloadedEvent);
9542
+ broadcastTabEvent(tab, reloadedEvent);
9375
9543
  return tab;
9376
9544
  }
9377
9545
 
@@ -11481,8 +11649,8 @@ async function closeTab(id) {
11481
11649
  const closingEvent = { type: "webui_tab_closing", tabId: tab.id, tabTitle: tab.title };
11482
11650
  recordEvent(closingEvent);
11483
11651
  for (const client of tab.sseClients) {
11484
- sendSse(client, closingEvent);
11485
- client.end();
11652
+ sendSseToClient(client, closingEvent);
11653
+ client.res.end();
11486
11654
  }
11487
11655
  tab.sseClients.clear();
11488
11656
  tab.rpcUnsubscribe?.();
@@ -11613,12 +11781,89 @@ async function createInitialTabs() {
11613
11781
  }
11614
11782
 
11615
11783
  const serverStartedAt = new Date().toISOString();
11616
- let persistedRemoteAuthEnabled = await readPersistedRemoteAuthEnabled();
11784
+ const persistedStartupSettings = await readWebuiSettings(undefined, { reportInvalidOutputMode: true });
11785
+ let persistedRemoteAuthEnabled = persistedStartupSettings.remoteAuthEnabled === true;
11786
+ let persistedOutputModeDefault = persistedStartupSettings.outputModeDefault;
11617
11787
  const initialTabs = await createInitialTabs();
11618
11788
  const initialTab = initialTabs[0];
11619
11789
  let currentHost = options.host;
11620
11790
  let networkRebindInProgress = false;
11621
11791
  let networkRebindTargetHost = null;
11792
+
11793
+ function resolvedOutputModeDefault() {
11794
+ return resolveOutputModeDefault({
11795
+ cliMode: options.outputMode,
11796
+ envMode: options.envOutputMode,
11797
+ persistedMode: persistedOutputModeDefault,
11798
+ });
11799
+ }
11800
+
11801
+ function outputModeMetadata() {
11802
+ const resolved = resolvedOutputModeDefault();
11803
+ return {
11804
+ persistedDefault: normalizeOutputMode(persistedOutputModeDefault),
11805
+ effectiveDefault: resolved.mode,
11806
+ source: resolved.source,
11807
+ overridden: resolved.source === "cli" || resolved.source === "env",
11808
+ };
11809
+ }
11810
+
11811
+ function tabHasActiveOutput(tab) {
11812
+ return tab?.activity?.isWorking === true || tab?.lastState?.isStreaming === true || tab?.lastState?.isCompacting === true;
11813
+ }
11814
+
11815
+ function activateOutputMode(client, activeMode, reason = "server-default-change") {
11816
+ const nextMode = normalizeOutputMode(activeMode);
11817
+ if (client.activeMode === nextMode) {
11818
+ client.pendingMode = undefined;
11819
+ return;
11820
+ }
11821
+ sendSse(client, {
11822
+ type: "webui_output_mode",
11823
+ protocolVersion: OUTPUT_MODE_PROTOCOL_VERSION,
11824
+ previousMode: client.activeMode,
11825
+ activeMode: nextMode,
11826
+ reason,
11827
+ });
11828
+ client.activeMode = nextMode;
11829
+ client.pendingMode = undefined;
11830
+ }
11831
+
11832
+ function sendSseToClient(client, event) {
11833
+ sendSse(client, event);
11834
+ if (client?.pendingMode && isOutputModeSemanticBarrier(event)) activateOutputMode(client, client.pendingMode);
11835
+ }
11836
+
11837
+ function refreshAutoOutputModes() {
11838
+ const resolved = resolvedOutputModeDefault();
11839
+ for (const tab of tabs.values()) {
11840
+ for (const client of tab.sseClients) {
11841
+ if (client.requestedMode !== "auto") continue;
11842
+ client.defaultSource = resolved.source;
11843
+ if (client.activeMode === resolved.mode) {
11844
+ client.pendingMode = undefined;
11845
+ } else if (tabHasActiveOutput(tab)) {
11846
+ client.pendingMode = resolved.mode;
11847
+ } else {
11848
+ activateOutputMode(client, resolved.mode);
11849
+ }
11850
+ }
11851
+ }
11852
+ }
11853
+
11854
+ async function saveOutputModeDefault(value) {
11855
+ let mode;
11856
+ try {
11857
+ mode = requiredOutputMode(value, "outputModeDefault");
11858
+ } catch (error) {
11859
+ throw makeHttpError(400, formatCliError(error));
11860
+ }
11861
+ const settings = await writeWebuiSettings({ outputModeDefault: mode });
11862
+ persistedOutputModeDefault = settings.outputModeDefault;
11863
+ refreshAutoOutputModes();
11864
+ return outputModeMetadata();
11865
+ }
11866
+
11622
11867
  const remoteAuth = {
11623
11868
  pin: undefined,
11624
11869
  token: undefined,
@@ -11751,8 +11996,8 @@ function closeSseClientsForRebind(nextHost) {
11751
11996
  };
11752
11997
  recordEvent(rebindEvent);
11753
11998
  for (const client of tab.sseClients) {
11754
- sendSse(client, rebindEvent);
11755
- client.end();
11999
+ sendSseToClient(client, rebindEvent);
12000
+ client.res.end();
11756
12001
  }
11757
12002
  tab.sseClients.clear();
11758
12003
  }
@@ -11768,8 +12013,8 @@ function closeSseClientsForRemoteAuthChange() {
11768
12013
  };
11769
12014
  recordEvent(authEvent);
11770
12015
  for (const client of tab.sseClients) {
11771
- sendSse(client, authEvent);
11772
- client.end();
12016
+ sendSseToClient(client, authEvent);
12017
+ client.res.end();
11773
12018
  }
11774
12019
  tab.sseClients.clear();
11775
12020
  }
@@ -11980,6 +12225,7 @@ async function webuiStatus({ detailed = false, eventLimit = 40, includeAuthPin =
11980
12225
  network,
11981
12226
  piPid: tab?.rpc.child?.pid,
11982
12227
  piRunning: !!tab?.rpc.child && tab.rpc.child.exitCode === null,
12228
+ outputMode: outputModeMetadata(),
11983
12229
  tabs: statusTabs,
11984
12230
  restorableTabs: mergeRestorableTabDescriptors(statusTabs),
11985
12231
  };
@@ -12046,6 +12292,17 @@ const server = createServer(async (req, res) => {
12046
12292
  return;
12047
12293
  }
12048
12294
 
12295
+ if (url.pathname === "/api/webui-output-mode" && req.method === "GET") {
12296
+ sendJson(res, 200, { ok: true, data: outputModeMetadata() });
12297
+ return;
12298
+ }
12299
+
12300
+ if (url.pathname === "/api/webui-output-mode" && req.method === "PUT") {
12301
+ const body = await readJsonBody(req);
12302
+ sendJson(res, 200, { ok: true, data: await saveOutputModeDefault(body.outputModeDefault) });
12303
+ return;
12304
+ }
12305
+
12049
12306
  if (url.pathname === "/api/tabs" && req.method === "GET") {
12050
12307
  sendJson(res, 200, { ok: true, data: { tabs: await listTabsWithReconciledActivity() } });
12051
12308
  return;
@@ -12065,6 +12322,20 @@ const server = createServer(async (req, res) => {
12065
12322
  return;
12066
12323
  }
12067
12324
 
12325
+ if (url.pathname === "/api/subagents/config" && req.method === "GET") {
12326
+ const tab = getRequestedTab(req, url);
12327
+ sendJson(res, 200, { ok: true, data: await subagentLaunchSlotConfigData(tab, url.searchParams.get("scope")) });
12328
+ return;
12329
+ }
12330
+
12331
+ if (url.pathname === "/api/subagents/config" && req.method === "POST") {
12332
+ requireLocalhostRoute(req, url.pathname);
12333
+ const body = await readJsonBody(req);
12334
+ const tab = getRequestedTab(req, url, body);
12335
+ sendJson(res, 200, { ok: true, data: await saveSubagentLaunchSlotConfigData(tab, body) });
12336
+ return;
12337
+ }
12338
+
12068
12339
  if (url.pathname === "/api/tabs" && req.method === "POST") {
12069
12340
  const body = await readJsonBody(req);
12070
12341
  const tab = await createTab({ title: body.title, cwd: body.cwd });
@@ -12096,6 +12367,20 @@ const server = createServer(async (req, res) => {
12096
12367
 
12097
12368
  if (url.pathname === "/api/events" && req.method === "GET") {
12098
12369
  const tab = getRequestedTab(req, url);
12370
+ const resolvedDefault = resolvedOutputModeDefault();
12371
+ const negotiated = negotiateOutputMode({
12372
+ requestedMode: url.searchParams.get("outputMode"),
12373
+ protocolVersion: url.searchParams.get("outputModeProtocol"),
12374
+ serverDefault: resolvedDefault.mode,
12375
+ });
12376
+ const client = {
12377
+ res,
12378
+ requestedMode: negotiated.requestedMode,
12379
+ protocolVersion: negotiated.protocolVersion,
12380
+ activeMode: negotiated.activeMode,
12381
+ pendingMode: undefined,
12382
+ defaultSource: resolvedDefault.source,
12383
+ };
12099
12384
  res.writeHead(200, {
12100
12385
  "content-type": "text/event-stream; charset=utf-8",
12101
12386
  "cache-control": "no-cache, no-transform",
@@ -12103,13 +12388,20 @@ const server = createServer(async (req, res) => {
12103
12388
  "x-content-type-options": "nosniff",
12104
12389
  });
12105
12390
  res.write(": connected\n\n");
12106
- tab.sseClients.add(res);
12107
- sendSse(res, {
12391
+ tab.sseClients.add(client);
12392
+ sendSseToClient(client, {
12108
12393
  type: "webui_connected",
12109
12394
  version: packageJson.version,
12110
12395
  piVersion: String(piPackageJson.version || ""),
12111
12396
  webuiDev: webuiDevServer,
12112
12397
  webuiMode: webuiDevServer ? "dev" : "production",
12398
+ outputMode: {
12399
+ protocolVersion: negotiated.protocolVersion,
12400
+ requestedMode: negotiated.requestedMode,
12401
+ activeMode: negotiated.activeMode,
12402
+ serverDefault: resolvedDefault.mode,
12403
+ serverDefaultSource: resolvedDefault.source,
12404
+ },
12113
12405
  tabId: tab.id,
12114
12406
  tabTitle: tab.title,
12115
12407
  pid: tab.rpc.child?.pid,
@@ -12119,13 +12411,13 @@ const server = createServer(async (req, res) => {
12119
12411
  pendingExtensionUiRequestCount: pendingExtensionUiRequests(tab).length,
12120
12412
  activeRun: publicAppRunnerState(tab.appRunner),
12121
12413
  });
12122
- replayExtensionStatuses(tab, res);
12123
- replayExtensionWidgets(tab, res);
12124
- replayPendingExtensionUiRequests(tab, res);
12414
+ replayExtensionStatuses(tab, client);
12415
+ replayExtensionWidgets(tab, client);
12416
+ replayPendingExtensionUiRequests(tab, client);
12125
12417
  const keepAlive = setInterval(() => res.write(": keepalive\n\n"), 15000);
12126
12418
  req.on("close", () => {
12127
12419
  clearInterval(keepAlive);
12128
- tab.sseClients.delete(res);
12420
+ tab.sseClients.delete(client);
12129
12421
  });
12130
12422
  return;
12131
12423
  }
@@ -12142,6 +12434,7 @@ const server = createServer(async (req, res) => {
12142
12434
  piPid: status.piPid,
12143
12435
  piRunning: status.piRunning,
12144
12436
  cwd: status.cwd,
12437
+ outputMode: status.outputMode,
12145
12438
  network: status.network,
12146
12439
  tabs: status.tabs,
12147
12440
  restorableTabs: status.restorableTabs,
package/index.ts CHANGED
@@ -33,6 +33,7 @@ type StartWebuiOptions = WebuiAddress & {
33
33
  open: boolean;
34
34
  noSession: boolean;
35
35
  remoteAuth: boolean;
36
+ outputMode?: "normal" | "compact-v1";
36
37
  name?: string;
37
38
  piArgs: string[];
38
39
  };
@@ -87,6 +88,13 @@ function parseStartWebuiArgs(args: string): StartWebuiOptions {
87
88
  options.noSession = true;
88
89
  continue;
89
90
  }
91
+ if (token === "--output-mode") {
92
+ const outputMode = takeValue(tokens, i, token);
93
+ if (outputMode !== "normal" && outputMode !== "compact-v1") throw new Error("--output-mode must be normal or compact-v1");
94
+ options.outputMode = outputMode;
95
+ i++;
96
+ continue;
97
+ }
90
98
  if (token === "--remote-auth") {
91
99
  options.remoteAuth = true;
92
100
  continue;
@@ -450,6 +458,7 @@ async function startWebui(options: StartWebuiOptions, ctx: ExtensionCommandConte
450
458
  const args = [webuiBin, "--host", options.host, "--port", String(options.port), "--cwd", ctx.cwd];
451
459
  if (options.noSession) args.push("--no-session");
452
460
  if (options.remoteAuth) args.push("--remote-auth");
461
+ if (options.outputMode) args.push("--output-mode", options.outputMode);
453
462
  if (options.name) args.push("--name", options.name);
454
463
  if (options.piArgs.length > 0) args.push("--", ...options.piArgs);
455
464
 
@@ -696,7 +705,7 @@ function formatWebuiStatus(result: WebuiStatusFetchResult, requestedDetailed: bo
696
705
 
697
706
  function usage(): string {
698
707
  return [
699
- "Usage: /webui-start [port] [--port N] [--no-open] [--no-session] [--remote-auth] [--name NAME] [-- --model provider/model]",
708
+ "Usage: /webui-start [port] [--port N] [--no-open] [--no-session] [--remote-auth] [--output-mode normal|compact-v1] [--name NAME] [-- --model provider/model]",
700
709
  "Starts the Pi Web UI companion server for the current cwd, prints the localhost URL, and opens it in your default browser.",
701
710
  ].join("\n");
702
711
  }