@firstpick/pi-package-webui 0.7.8 → 0.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.
Files changed (41) hide show
  1. package/README.md +10 -4
  2. package/bin/pi-webui.mjs +696 -69
  3. package/lib/git-workflow-preferences.mjs +16 -0
  4. package/lib/git-worktrees.mjs +43 -4
  5. package/lib/queue-mutation.mjs +109 -0
  6. package/lib/scoped-models.mjs +19 -0
  7. package/lib/webui-workspaces.mjs +265 -0
  8. package/package.json +4 -2
  9. package/public/app.js +2074 -188
  10. package/public/index.html +105 -4
  11. package/public/service-worker.js +1 -1
  12. package/public/styles.css +618 -73
  13. package/public/voice-conversation.mjs +1 -1
  14. package/tests/boot-failure-diagnostics.test.mjs +2 -2
  15. package/tests/codex-fast-mode-static.test.mjs +56 -0
  16. package/tests/compaction-mutation-contract.test.mjs +166 -0
  17. package/tests/compaction-resume-harness.test.mjs +113 -2
  18. package/tests/compaction-static.test.mjs +5 -0
  19. package/tests/composer-skill-tag-layout.test.mjs +70 -0
  20. package/tests/cwd-footer-reliability-static.test.mjs +5 -0
  21. package/tests/fast-mode-client-static.test.mjs +8 -8
  22. package/tests/file-selection-overlay-static.test.mjs +21 -0
  23. package/tests/file-viewer-search-static.test.mjs +65 -0
  24. package/tests/fixtures/fake-pi.mjs +216 -43
  25. package/tests/git-panel-file-preview-static.test.mjs +20 -5
  26. package/tests/git-workflow-preferences.test.mjs +8 -0
  27. package/tests/guided-git-publication-backend-static.test.mjs +40 -0
  28. package/tests/http-endpoints-harness.test.mjs +422 -2
  29. package/tests/mobile-static.test.mjs +111 -42
  30. package/tests/native-parity.test.mjs +1 -1
  31. package/tests/open-issue-wizard-static.test.mjs +1 -1
  32. package/tests/queue-edit-reorder-static.test.mjs +101 -0
  33. package/tests/queue-mutation-contract.test.mjs +143 -0
  34. package/tests/scoped-models.test.mjs +42 -0
  35. package/tests/side-panel-resize-static.test.mjs +8 -1
  36. package/tests/subagents-helper.test.mjs +216 -3
  37. package/tests/terminal-tab-workspace-static.test.mjs +4 -2
  38. package/tests/webui-workspaces-harness.test.mjs +223 -0
  39. package/tests/webui-workspaces.test.mjs +106 -0
  40. package/tests/workspace-save-load-static.test.mjs +69 -0
  41. package/webui-rpc-helper.mjs +300 -41
@@ -26,6 +26,8 @@ export function supportedGitWorkflowThinkingLevels(model) {
26
26
 
27
27
  const WEBUI_SETTINGS_VERSION = 4;
28
28
  const WEBUI_SETTINGS_FILE_ENV = "PI_WEBUI_SETTINGS_FILE";
29
+ export const WEBUI_SIDE_PANEL_WIDTH_MIN_PX = 320;
30
+ export const WEBUI_SIDE_PANEL_WIDTH_MAX_PX = 4096;
29
31
  const webuiSettingsUpdateQueues = new Map();
30
32
 
31
33
  function cleanBoundedString(value, maxLength = 512) {
@@ -138,6 +140,16 @@ export function normalizeResourceDefaults(value) {
138
140
  };
139
141
  }
140
142
 
143
+ export function normalizeInterfacePreferences(value) {
144
+ const rawSidePanelWidth = value?.sidePanelWidth;
145
+ const sidePanelWidth = rawSidePanelWidth === null || rawSidePanelWidth === undefined ? Number.NaN : Number(rawSidePanelWidth);
146
+ return {
147
+ sidePanelWidth: Number.isFinite(sidePanelWidth)
148
+ ? Math.max(WEBUI_SIDE_PANEL_WIDTH_MIN_PX, Math.min(WEBUI_SIDE_PANEL_WIDTH_MAX_PX, Math.round(sidePanelWidth)))
149
+ : null,
150
+ };
151
+ }
152
+
141
153
  function settingsObject(value) {
142
154
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
143
155
  }
@@ -156,6 +168,7 @@ export function normalizeWebuiSettings(value) {
156
168
  outputModeDefault: normalizeOutputMode(source.outputModeDefault, OUTPUT_MODE_NORMAL),
157
169
  gitWorkflow: normalizeGitWorkflowPreferences(source.gitWorkflow),
158
170
  resourceDefaults: normalizeResourceDefaults(source.resourceDefaults),
171
+ interfacePreferences: normalizeInterfacePreferences(source.interfacePreferences),
159
172
  subagentLaunchSlots: normalizeSubagentLaunchSlots(source.subagentLaunchSlots),
160
173
  };
161
174
  }
@@ -198,6 +211,9 @@ function mergeWebuiSettings(rawCurrent, patch) {
198
211
  skills: { ...current.resourceDefaults.skills, ...(patchValue.resourceDefaults.skills || {}) },
199
212
  }
200
213
  : current.resourceDefaults,
214
+ interfacePreferences: patchValue.interfacePreferences
215
+ ? { ...current.interfacePreferences, ...patchValue.interfacePreferences }
216
+ : current.interfacePreferences,
201
217
  };
202
218
  if (persistLaunchSlots) {
203
219
  source.subagentLaunchSlots = hasLaunchSlotPatch
@@ -342,6 +342,33 @@ async function branchExists(repoRoot, branch) {
342
342
  throw makeGitWorktreeError(WORKTREE_ERROR_CODES.GIT_COMMAND_FAILED, gitFailureMessage(["show-ref", "--verify", "--quiet", `refs/heads/${branch}`], result), { branch });
343
343
  }
344
344
 
345
+ function configuredRemoteForRef(remoteRef, remoteNames = []) {
346
+ return remoteNames
347
+ .filter((remoteName) => remoteRef.startsWith(`${remoteName}/`))
348
+ .sort((left, right) => right.length - left.length || left.localeCompare(right))[0] || "";
349
+ }
350
+
351
+ async function verifyTrackingRemoteRef(repo, branch, value) {
352
+ if (typeof value !== "string" || !value || value !== value.trim() || value.includes("\0")) {
353
+ throw makeGitWorktreeError(WORKTREE_ERROR_CODES.GIT_COMMAND_FAILED, "remoteRef must be a non-empty exact remote-tracking ref", { branch });
354
+ }
355
+ const remoteNames = (await runGit(["remote"], { cwd: repo.repoRoot, timeoutMs: 5000, maxOutputLength: 20_000 }))
356
+ .split(/\r?\n/)
357
+ .map((line) => line.trim())
358
+ .filter(Boolean);
359
+ const remoteName = configuredRemoteForRef(value, remoteNames);
360
+ if (!remoteName || value.slice(remoteName.length + 1) !== branch) {
361
+ throw makeGitWorktreeError(WORKTREE_ERROR_CODES.GIT_COMMAND_FAILED, `Remote git branch ${value} does not match local branch ${branch}`, { branch, remoteRef: value });
362
+ }
363
+ const fullRef = `refs/remotes/${value}`;
364
+ const output = await runGit(["for-each-ref", "--format=%(refname)%09%(symref)", fullRef], { cwd: repo.repoRoot, timeoutMs: 5000, maxOutputLength: 20_000 });
365
+ const exactRef = output.split(/\r?\n/).map((line) => line.split("\t", 2)).find(([ref]) => ref === fullRef);
366
+ if (!exactRef || exactRef[1]) {
367
+ throw makeGitWorktreeError(WORKTREE_ERROR_CODES.GIT_COMMAND_FAILED, `Unknown remote git branch: ${value}`, { branch, remoteRef: value });
368
+ }
369
+ return value;
370
+ }
371
+
345
372
  export function slugifyWorktreeBranch(branch) {
346
373
  const slug = String(branch || "")
347
374
  .toLowerCase()
@@ -416,6 +443,7 @@ function occupiedBranch(worktrees, branch) {
416
443
 
417
444
  export async function createGitWorktree(cwd, request = {}) {
418
445
  const branch = cleanBranchName(request.branchName || request.branch);
446
+ const trackingRemoteRequested = Object.hasOwn(request, "remoteRef");
419
447
  let data = await readWorktreeData(cwd);
420
448
  await validateBranchName(data, branch);
421
449
 
@@ -423,6 +451,9 @@ export async function createGitWorktree(cwd, request = {}) {
423
451
  data = await readWorktreeData(cwd);
424
452
  const existing = occupiedBranch(data.worktrees, branch);
425
453
  if (existing) {
454
+ if (trackingRemoteRequested) {
455
+ throw makeGitWorktreeError(WORKTREE_ERROR_CODES.BRANCH_CHECKED_OUT_ELSEWHERE, `Branch ${branch} is already checked out at ${existing.path}. Refresh the picker and open that worktree instead.`, { branch, remoteRef: request.remoteRef, worktreePath: existing.path });
456
+ }
426
457
  return {
427
458
  ok: true,
428
459
  created: false,
@@ -434,12 +465,20 @@ export async function createGitWorktree(cwd, request = {}) {
434
465
  };
435
466
  }
436
467
 
437
- const targetPath = await resolveCreateTarget(data, branch, data.worktrees, request.path);
438
468
  const exists = await branchExists(data.repoRoot, branch);
469
+ if (trackingRemoteRequested && exists) {
470
+ throw makeGitWorktreeError(WORKTREE_ERROR_CODES.GIT_COMMAND_FAILED, `Local git branch already exists: ${branch}`, { branch, remoteRef: request.remoteRef });
471
+ }
472
+ const targetPath = await resolveCreateTarget(data, branch, data.worktrees, request.path);
473
+ // Re-read the exact remote ref under the mutation lock immediately before
474
+ // `worktree add`; symbolic, stale, and colliding selections fail closed.
475
+ const trackingRemoteRef = trackingRemoteRequested ? await verifyTrackingRemoteRef(data, branch, request.remoteRef) : "";
439
476
  const baseRef = String(request.baseRef || "").trim();
440
- const args = exists
441
- ? ["worktree", "add", targetPath, branch]
442
- : ["worktree", "add", "-b", branch, targetPath, ...(baseRef ? [baseRef] : [])];
477
+ const args = trackingRemoteRef
478
+ ? ["worktree", "add", "--track", "-b", branch, targetPath, trackingRemoteRef]
479
+ : exists
480
+ ? ["worktree", "add", targetPath, branch]
481
+ : ["worktree", "add", "-b", branch, targetPath, ...(baseRef ? [baseRef] : [])];
443
482
  const worktreeAddCwd = data.currentWorktreePath || data.repoRoot;
444
483
 
445
484
  try {
@@ -0,0 +1,109 @@
1
+ export const PI_RUNTIME_QUEUE_SOURCE = "pi-runtime";
2
+
3
+ function queueSnapshot(steering, followUp) {
4
+ return {
5
+ source: PI_RUNTIME_QUEUE_SOURCE,
6
+ steering: [...steering],
7
+ followUp: [...followUp],
8
+ };
9
+ }
10
+
11
+ function arraysEqual(left, right) {
12
+ return left.length === right.length && left.every((value, index) => value === right[index]);
13
+ }
14
+
15
+ function exactMessageText(message) {
16
+ if (!message || typeof message !== "object" || !Array.isArray(message.content)) return undefined;
17
+ const textParts = message.content.filter((part) => part?.type === "text");
18
+ if (textParts.length !== 1 || typeof textParts[0].text !== "string") return undefined;
19
+ return textParts[0].text;
20
+ }
21
+
22
+ function matchingQueueMessages(tracked, messages) {
23
+ return Array.isArray(messages)
24
+ && tracked.length === messages.length
25
+ && messages.every((message, index) => exactMessageText(message) === tracked[index]);
26
+ }
27
+
28
+ function mutationFailure(reason, steering, followUp) {
29
+ return { mutated: false, reason, queue: queueSnapshot(steering, followUp) };
30
+ }
31
+
32
+ function isStringArray(value) {
33
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
34
+ }
35
+
36
+ function validExpectedSnapshot(expected) {
37
+ return expected
38
+ && typeof expected === "object"
39
+ && isStringArray(expected.steering)
40
+ && isStringArray(expected.followUp);
41
+ }
42
+
43
+ function validIndex(value, length) {
44
+ return Number.isInteger(value) && value >= 0 && value < length;
45
+ }
46
+
47
+ /**
48
+ * Mutate the paired private AgentSession follow-up structures synchronously.
49
+ * The installed Pi runtime exposes no public item mutation API, so unknown
50
+ * queue/message layouts deliberately fail closed before either array changes.
51
+ */
52
+ export function mutatePiRuntimeFollowUpQueue(session, payload = {}) {
53
+ const steering = session?._steeringMessages;
54
+ const followUp = session?._followUpMessages;
55
+ const steeringMessages = session?.agent?.steeringQueue?.messages;
56
+ const followUpMessages = session?.agent?.followUpQueue?.messages;
57
+ if (!Array.isArray(steering) || !Array.isArray(followUp)
58
+ || !Array.isArray(steeringMessages) || !Array.isArray(followUpMessages)
59
+ || typeof session?._emitQueueUpdate !== "function") {
60
+ return { mutated: false, reason: "queue-unsupported", queue: { source: PI_RUNTIME_QUEUE_SOURCE, steering: [], followUp: [] } };
61
+ }
62
+
63
+ const current = queueSnapshot(steering, followUp);
64
+ if (!matchingQueueMessages(steering, steeringMessages) || !matchingQueueMessages(followUp, followUpMessages)) {
65
+ return mutationFailure("queue-desynchronized", steering, followUp);
66
+ }
67
+ if (payload?.source !== PI_RUNTIME_QUEUE_SOURCE || payload?.kind !== "followUp" || !validExpectedSnapshot(payload.expected)) {
68
+ return mutationFailure("invalid-request", steering, followUp);
69
+ }
70
+ if (!arraysEqual(payload.expected.steering, steering) || !arraysEqual(payload.expected.followUp, followUp)) {
71
+ return mutationFailure("queue-changed", steering, followUp);
72
+ }
73
+
74
+ const operation = payload.operation;
75
+ if (!operation || typeof operation !== "object" || typeof operation.expectedText !== "string") {
76
+ return mutationFailure("invalid-request", steering, followUp);
77
+ }
78
+
79
+ const nextTracked = [...followUp];
80
+ const nextMessages = [...followUpMessages];
81
+ if (operation.type === "edit") {
82
+ if (!validIndex(operation.index, followUp.length) || followUp[operation.index] !== operation.expectedText
83
+ || typeof operation.text !== "string" || !operation.text.trim()) {
84
+ return mutationFailure("invalid-request", steering, followUp);
85
+ }
86
+ const original = followUpMessages[operation.index];
87
+ const textPartIndex = original.content.findIndex((part) => part?.type === "text");
88
+ const nextContent = original.content.map((part, index) => index === textPartIndex ? { ...part, text: operation.text } : part);
89
+ nextTracked[operation.index] = operation.text;
90
+ nextMessages[operation.index] = { ...original, content: nextContent };
91
+ } else if (operation.type === "move") {
92
+ if (!validIndex(operation.from, followUp.length) || !validIndex(operation.to, followUp.length)
93
+ || operation.from === operation.to || followUp[operation.from] !== operation.expectedText) {
94
+ return mutationFailure("invalid-request", steering, followUp);
95
+ }
96
+ const [tracked] = nextTracked.splice(operation.from, 1);
97
+ const [message] = nextMessages.splice(operation.from, 1);
98
+ // `to` is the final zero-based index after the item has been removed.
99
+ nextTracked.splice(operation.to, 0, tracked);
100
+ nextMessages.splice(operation.to, 0, message);
101
+ } else {
102
+ return mutationFailure("invalid-request", steering, followUp);
103
+ }
104
+
105
+ session._followUpMessages = nextTracked;
106
+ session.agent.followUpQueue.messages = nextMessages;
107
+ session._emitQueueUpdate();
108
+ return { mutated: true, source: PI_RUNTIME_QUEUE_SOURCE, queue: queueSnapshot(steering, nextTracked) };
109
+ }
@@ -0,0 +1,19 @@
1
+ import { resolveModelScopeWithDiagnostics } from "@earendil-works/pi-coding-agent";
2
+
3
+ /**
4
+ * Resolve WebUI scoped-model patterns with Pi's canonical matching semantics.
5
+ * The RPC model list is already Pi's authenticated/available model catalog.
6
+ */
7
+ export async function resolveScopedModelsFromPatterns(patterns, models) {
8
+ const safePatterns = Array.isArray(patterns)
9
+ ? patterns.filter((pattern) => typeof pattern === "string" && pattern.trim())
10
+ : [];
11
+ const availableModels = Array.isArray(models)
12
+ ? models.filter((model) => model?.provider && model?.id)
13
+ : [];
14
+ if (!safePatterns.length || !availableModels.length) return [];
15
+
16
+ const modelRuntime = { getAvailable: async () => availableModels };
17
+ const { scopedModels } = await resolveModelScopeWithDiagnostics(safePatterns, modelRuntime);
18
+ return scopedModels.map(({ model }) => model);
19
+ }
@@ -0,0 +1,265 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import path from "node:path";
5
+
6
+ export const WEBUI_WORKSPACES_VERSION = 1;
7
+ export const WEBUI_WORKSPACE_LIMIT = 20;
8
+ export const WEBUI_WORKSPACE_TAB_LIMIT = 30;
9
+
10
+ const WEBUI_WORKSPACES_FILE_ENV = "PI_WEBUI_WORKSPACES_FILE";
11
+ const workspaceUpdateQueues = new Map();
12
+
13
+ function boundedString(value, maxLength) {
14
+ const text = typeof value === "string" ? value.trim() : "";
15
+ return text ? text.slice(0, maxLength) : undefined;
16
+ }
17
+
18
+ function normalizedId(value, seenIds = new Set()) {
19
+ const id = boundedString(value, 128);
20
+ if (!id || !/^[A-Za-z0-9._:-]+$/.test(id) || seenIds.has(id)) return undefined;
21
+ seenIds.add(id);
22
+ return id;
23
+ }
24
+
25
+ function normalizedSavedAt(value) {
26
+ const savedAt = boundedString(value, 128);
27
+ return savedAt && Number.isFinite(Date.parse(savedAt)) ? savedAt : undefined;
28
+ }
29
+
30
+ function workspaceDocument(value) {
31
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
32
+ }
33
+
34
+ export function webuiWorkspacesFile(env = process.env) {
35
+ if (env[WEBUI_WORKSPACES_FILE_ENV]) return path.resolve(String(env[WEBUI_WORKSPACES_FILE_ENV]).replace(/^~(?=$|[\\/])/, homedir()));
36
+ const configRoot = env.XDG_CONFIG_HOME || path.join(homedir(), ".config");
37
+ return path.join(configRoot, "pi-webui", "workspaces.json");
38
+ }
39
+
40
+ export function normalizeWorkspaceTabDescriptor(value, seenIds = new Set()) {
41
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
42
+ const id = normalizedId(value.id, seenIds);
43
+ const cwd = boundedString(value.cwd || value.workspace?.cwd, 4096);
44
+ if (!id || !cwd) return null;
45
+ const descriptor = {
46
+ id,
47
+ title: boundedString(value.title, 160),
48
+ titleSource: ["explicit", "auto", "default"].includes(value.titleSource) ? value.titleSource : undefined,
49
+ cwd,
50
+ conversationStarted: value.conversationStarted === true,
51
+ sessionFile: boundedString(value.sessionFile || value.state?.sessionFile, 4096),
52
+ };
53
+ if (Number.isInteger(value.index) && value.index > 0) descriptor.index = value.index;
54
+ return descriptor;
55
+ }
56
+
57
+ export function normalizeWorkspaceGroups(value, tabIds = new Set()) {
58
+ if (!Array.isArray(value)) return [];
59
+ const groups = [];
60
+ const seen = new Set();
61
+ for (const item of value.slice(0, WEBUI_WORKSPACE_TAB_LIMIT)) {
62
+ const title = boundedString(item?.title, 160);
63
+ if (!title) continue;
64
+ const tabIdsForGroup = [];
65
+ for (const tabId of Array.isArray(item?.tabIds) ? item.tabIds.slice(0, WEBUI_WORKSPACE_TAB_LIMIT) : []) {
66
+ const normalized = boundedString(tabId, 128);
67
+ if (!normalized || !tabIds.has(normalized) || tabIdsForGroup.includes(normalized)) continue;
68
+ tabIdsForGroup.push(normalized);
69
+ }
70
+ if (!tabIdsForGroup.length) continue;
71
+ const key = `${title}\u0000${tabIdsForGroup.join("\u0000")}`;
72
+ if (seen.has(key)) continue;
73
+ seen.add(key);
74
+ groups.push({ title, tabIds: tabIdsForGroup });
75
+ }
76
+ return groups;
77
+ }
78
+
79
+ export function normalizeWebuiWorkspace(value, seenWorkspaceIds = new Set()) {
80
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
81
+ const id = normalizedId(value.id, seenWorkspaceIds);
82
+ const name = boundedString(value.name, 160);
83
+ const savedAt = normalizedSavedAt(value.savedAt);
84
+ const seenTabIds = new Set();
85
+ const tabs = (Array.isArray(value.tabs) ? value.tabs : [])
86
+ .slice(0, WEBUI_WORKSPACE_TAB_LIMIT)
87
+ .map((item) => normalizeWorkspaceTabDescriptor(item, seenTabIds))
88
+ .filter(Boolean);
89
+ if (!id || !name || !savedAt || !tabs.length) return null;
90
+ const tabIds = new Set(tabs.map((tab) => tab.id));
91
+ const activeTabId = boundedString(value.activeTabId, 128);
92
+ return {
93
+ id,
94
+ name,
95
+ savedAt,
96
+ activeTabId: activeTabId && tabIds.has(activeTabId) ? activeTabId : null,
97
+ tabs,
98
+ groups: normalizeWorkspaceGroups(value.groups, tabIds),
99
+ };
100
+ }
101
+
102
+ export function normalizeWebuiWorkspaces(value) {
103
+ const source = workspaceDocument(value);
104
+ const seenWorkspaceIds = new Set();
105
+ const workspaces = (Array.isArray(source.workspaces) ? source.workspaces : [])
106
+ .map((item) => normalizeWebuiWorkspace(item, seenWorkspaceIds))
107
+ .filter(Boolean)
108
+ .sort((left, right) => Date.parse(left.savedAt) - Date.parse(right.savedAt))
109
+ .slice(-WEBUI_WORKSPACE_LIMIT);
110
+ return { version: WEBUI_WORKSPACES_VERSION, workspaces };
111
+ }
112
+
113
+ export function workspaceMetadata(workspace) {
114
+ const normalized = normalizeWebuiWorkspace(workspace);
115
+ if (!normalized) return null;
116
+ return {
117
+ id: normalized.id,
118
+ name: normalized.name,
119
+ savedAt: normalized.savedAt,
120
+ tabCount: normalized.tabs.length,
121
+ groupCount: normalized.groups.length,
122
+ cwds: [...new Set(normalized.tabs.map((tab) => tab.cwd))],
123
+ };
124
+ }
125
+
126
+ function warningMessage(storageFile, error) {
127
+ return `failed to read Pi Web UI workspaces at ${storageFile}; treating it as empty: ${error instanceof Error ? error.message : String(error)}`;
128
+ }
129
+
130
+ async function readWorkspaceDocument(storageFile, { onWarning = console.warn } = {}) {
131
+ try {
132
+ const parsed = JSON.parse(await readFile(storageFile, "utf8"));
133
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("workspace document must be an object");
134
+ if (parsed.version !== undefined && parsed.version !== WEBUI_WORKSPACES_VERSION) {
135
+ throw new Error(`unsupported workspace document version ${JSON.stringify(parsed.version)}`);
136
+ }
137
+ if (parsed.workspaces !== undefined && !Array.isArray(parsed.workspaces)) throw new Error("workspaces must be an array");
138
+ return normalizeWebuiWorkspaces(parsed);
139
+ } catch (error) {
140
+ if (error?.code === "ENOENT") return normalizeWebuiWorkspaces({});
141
+ onWarning?.(warningMessage(storageFile, error));
142
+ return normalizeWebuiWorkspaces({});
143
+ }
144
+ }
145
+
146
+ export async function readWebuiWorkspaces(storageFile = webuiWorkspacesFile(), options = {}) {
147
+ return readWorkspaceDocument(storageFile, options);
148
+ }
149
+
150
+ export async function listWebuiWorkspaces(storageFile = webuiWorkspacesFile(), options = {}) {
151
+ const document = await readWorkspaceDocument(storageFile, options);
152
+ return document.workspaces.slice().reverse().map(workspaceMetadata).filter(Boolean);
153
+ }
154
+
155
+ async function writeWorkspaceDocument(document, storageFile) {
156
+ const normalized = normalizeWebuiWorkspaces(document);
157
+ await mkdir(path.dirname(storageFile), { recursive: true });
158
+ const temporaryFile = `${storageFile}.${process.pid}.${Date.now()}.${randomUUID()}.tmp`;
159
+ try {
160
+ await writeFile(temporaryFile, `${JSON.stringify(normalized, null, 2)}\n`, { mode: 0o600 });
161
+ await rename(temporaryFile, storageFile);
162
+ } catch (error) {
163
+ await rm(temporaryFile, { force: true }).catch(() => {});
164
+ throw error;
165
+ }
166
+ return normalized;
167
+ }
168
+
169
+ function enqueueWorkspaceUpdate(storageFile, update) {
170
+ const queueKey = path.resolve(storageFile);
171
+ const previous = workspaceUpdateQueues.get(queueKey) || Promise.resolve();
172
+ const current = previous.catch(() => {}).then(update);
173
+ workspaceUpdateQueues.set(queueKey, current);
174
+ return current.finally(() => {
175
+ if (workspaceUpdateQueues.get(queueKey) === current) workspaceUpdateQueues.delete(queueKey);
176
+ });
177
+ }
178
+
179
+ async function mutateWorkspaces(updater, storageFile) {
180
+ return enqueueWorkspaceUpdate(storageFile, async () => {
181
+ const document = await readWorkspaceDocument(storageFile);
182
+ const result = await updater(document);
183
+ if (result?.write !== false) await writeWorkspaceDocument(document, storageFile);
184
+ return result?.data;
185
+ });
186
+ }
187
+
188
+ function automaticWorkspaceName(tabs, savedAt) {
189
+ const cwd = tabs[0]?.cwd || "";
190
+ const base = path.basename(cwd) || "workspace";
191
+ return `${base} ${savedAt.slice(0, 10)}`.slice(0, 160);
192
+ }
193
+
194
+ function normalizedNewWorkspace({ name, tabs, groups, activeTabId, savedAt = new Date().toISOString(), id = `ws-${randomUUID()}` }) {
195
+ const seenTabIds = new Set();
196
+ const normalizedTabs = (Array.isArray(tabs) ? tabs : [])
197
+ .slice(0, WEBUI_WORKSPACE_TAB_LIMIT)
198
+ .map((item) => normalizeWorkspaceTabDescriptor(item, seenTabIds))
199
+ .filter(Boolean);
200
+ if (!normalizedTabs.length) throw new Error("A workspace requires at least one tab");
201
+ const tabIds = new Set(normalizedTabs.map((tab) => tab.id));
202
+ const normalizedName = boundedString(name, 160) || automaticWorkspaceName(normalizedTabs, savedAt);
203
+ return {
204
+ id,
205
+ name: normalizedName,
206
+ savedAt,
207
+ activeTabId: tabIds.has(boundedString(activeTabId, 128)) ? boundedString(activeTabId, 128) : null,
208
+ tabs: normalizedTabs,
209
+ groups: normalizeWorkspaceGroups(groups, tabIds),
210
+ };
211
+ }
212
+
213
+ export async function saveWebuiWorkspace({ name, tabs, groups, activeTabId, overwrite = false } = {}, storageFile = webuiWorkspacesFile()) {
214
+ return mutateWorkspaces((document) => {
215
+ const savedAt = new Date().toISOString();
216
+ const candidate = normalizedNewWorkspace({ name, tabs, groups, activeTabId, savedAt });
217
+ const existingIndex = document.workspaces.findIndex((workspace) => workspace.name === candidate.name);
218
+ if (existingIndex !== -1 && overwrite !== true) {
219
+ const error = new Error("A workspace with that name already exists");
220
+ error.code = "WORKSPACE_NAME_CONFLICT";
221
+ throw error;
222
+ }
223
+ const existing = existingIndex === -1 ? null : document.workspaces[existingIndex];
224
+ const workspace = existing ? { ...candidate, id: existing.id } : candidate;
225
+ const evicted = [];
226
+ if (existingIndex !== -1) document.workspaces.splice(existingIndex, 1);
227
+ document.workspaces.push(workspace);
228
+ document.workspaces.sort((left, right) => Date.parse(left.savedAt) - Date.parse(right.savedAt));
229
+ while (document.workspaces.length > WEBUI_WORKSPACE_LIMIT) {
230
+ const removed = document.workspaces.shift();
231
+ const metadata = workspaceMetadata(removed);
232
+ if (metadata) evicted.push(metadata);
233
+ }
234
+ return {
235
+ data: {
236
+ workspace: workspaceMetadata(workspace),
237
+ workspaces: document.workspaces.slice().reverse().map(workspaceMetadata).filter(Boolean),
238
+ evicted,
239
+ },
240
+ };
241
+ }, storageFile);
242
+ }
243
+
244
+ export async function getWebuiWorkspace(id, storageFile = webuiWorkspacesFile()) {
245
+ const requestedId = boundedString(id, 128);
246
+ if (!requestedId) return null;
247
+ const document = await readWorkspaceDocument(storageFile);
248
+ return document.workspaces.find((workspace) => workspace.id === requestedId) || null;
249
+ }
250
+
251
+ export async function deleteWebuiWorkspace(id, storageFile = webuiWorkspacesFile()) {
252
+ const requestedId = boundedString(id, 128);
253
+ if (!requestedId) return null;
254
+ return mutateWorkspaces((document) => {
255
+ const index = document.workspaces.findIndex((workspace) => workspace.id === requestedId);
256
+ if (index === -1) return { write: false, data: null };
257
+ document.workspaces.splice(index, 1);
258
+ return {
259
+ data: {
260
+ deletedId: requestedId,
261
+ workspaces: document.workspaces.slice().reverse().map(workspaceMetadata).filter(Boolean),
262
+ },
263
+ };
264
+ }, storageFile);
265
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@firstpick/pi-package-webui",
3
- "version": "0.7.8",
3
+ "version": "0.8.0",
4
4
  "description": "Pi Web UI companion package with a local browser UI CLI plus /webui-start and /webui-status commands.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/Firstp1ck/pi-coding-agent-forge/tree/main/pi-package-webui#readme",
@@ -26,6 +26,7 @@
26
26
  "node_modules/@firstpick/pi-extension-bang-command-autocomplete/index.ts",
27
27
  "node_modules/@firstpick/pi-extension-fish-user-bash/index.ts",
28
28
  "node_modules/@firstpick/pi-extension-btw/index.ts",
29
+ "node_modules/@firstpick/pi-extension-codex-fast-mode/index.ts",
29
30
  "node_modules/@firstpick/pi-extension-git-footer-status/index.ts",
30
31
  "node_modules/@firstpick/pi-extension-release-aur/index.ts",
31
32
  "node_modules/@firstpick/pi-extension-release-npm/index.ts",
@@ -55,7 +56,7 @@
55
56
  "test": "node tests/run-all.mjs"
56
57
  },
57
58
  "dependencies": {
58
- "@earendil-works/pi-coding-agent": "^0.82.1",
59
+ "@earendil-works/pi-coding-agent": "^0.83.0",
59
60
  "@firstpick/pi-utils": "^0.2.5",
60
61
  "mermaid": "^11.15.0",
61
62
  "typebox": "^1.3.6"
@@ -63,6 +64,7 @@
63
64
  "optionalDependencies": {
64
65
  "@firstpick/pi-extension-bang-command-autocomplete": "^0.2.2",
65
66
  "@firstpick/pi-extension-btw": "^0.1.4",
67
+ "@firstpick/pi-extension-codex-fast-mode": "^0.1.0",
66
68
  "@firstpick/pi-extension-fish-user-bash": "^0.2.2",
67
69
  "@firstpick/pi-extension-git-footer-status": "^0.4.3",
68
70
  "@firstpick/pi-extension-release-aur": "^0.1.8",