@firstpick/pi-package-webui 0.8.2 → 0.8.4

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 (52) hide show
  1. package/README.md +76 -19
  2. package/bin/pi-webui.mjs +864 -140
  3. package/lib/WEBUI_TUI_NATIVE_PARITY.json +26 -0
  4. package/lib/git-workflow-preferences.mjs +246 -19
  5. package/lib/optional-feature-catalog.mjs +29 -0
  6. package/lib/optional-feature-migration.mjs +410 -0
  7. package/lib/session-summary-core.mjs +320 -0
  8. package/lib/session-summary-preferences.mjs +267 -0
  9. package/lib/thinking-stream-recovery.mjs +156 -0
  10. package/lib/ui-layout-settings.mjs +254 -0
  11. package/package.json +5 -40
  12. package/public/app.js +2898 -92
  13. package/public/index.html +77 -14
  14. package/public/service-worker.js +1 -1
  15. package/public/styles.css +669 -2
  16. package/session-summary.ts +403 -0
  17. package/tests/aur-review-widget-static.test.mjs +3 -2
  18. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  19. package/tests/browser/composer-action-grid-reorder.spec.mjs +303 -0
  20. package/tests/browser/feature-decision-output-popup.spec.mjs +156 -0
  21. package/tests/browser/interaction-continuity.spec.mjs +29 -0
  22. package/tests/browser/persistent-ui-layout.spec.mjs +744 -0
  23. package/tests/browser/session-summary.spec.mjs +271 -0
  24. package/tests/codex-fast-mode-static.test.mjs +10 -9
  25. package/tests/composer-action-grid-reorder-static.test.mjs +63 -0
  26. package/tests/fast-mode-client-static.test.mjs +2 -2
  27. package/tests/feature-decision-output-popup-static.test.mjs +172 -0
  28. package/tests/fixtures/fake-pi.mjs +51 -1
  29. package/tests/git-workflow-preferences.test.mjs +4 -2
  30. package/tests/http-endpoints-harness.test.mjs +507 -4
  31. package/tests/interaction-state-stability-static.test.mjs +3 -0
  32. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  33. package/tests/mobile-foundation-static.test.mjs +3 -3
  34. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  35. package/tests/mobile-static.test.mjs +118 -103
  36. package/tests/native-parity-harness.test.mjs +9 -1
  37. package/tests/native-parity.test.mjs +23 -1
  38. package/tests/open-issue-wizard-static.test.mjs +1 -1
  39. package/tests/optional-feature-migration-frontend.test.mjs +72 -0
  40. package/tests/optional-feature-migration.test.mjs +142 -0
  41. package/tests/persistent-ui-layout-static.test.mjs +267 -0
  42. package/tests/questionnaire-dialog.test.mjs +511 -0
  43. package/tests/queue-edit-reorder-static.test.mjs +1 -0
  44. package/tests/remote-auth-settings-harness.test.mjs +1 -1
  45. package/tests/session-summary-core.test.mjs +491 -0
  46. package/tests/session-summary-preferences.test.mjs +103 -0
  47. package/tests/side-panel-resize-static.test.mjs +1 -0
  48. package/tests/side-panel-section-reorder-static.test.mjs +3 -3
  49. package/tests/subagent-launch-slots.test.mjs +1 -1
  50. package/tests/thinking-stream-recovery.test.mjs +88 -0
  51. package/tests/ui-layout-settings.test.mjs +92 -0
  52. package/tests/webui-settings-locking.test.mjs +159 -0
@@ -0,0 +1,410 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+
5
+ export const OPTIONAL_FEATURE_MIGRATION_SCHEMA_VERSION = 1;
6
+ export const OPTIONAL_FEATURE_AUDIT_DEADLINE_MS = 10_000;
7
+ export const OPTIONAL_FEATURE_AUDIT_PHASES = Object.freeze([
8
+ "checking", "ready", "action-required", "migrating", "partial", "complete", "degraded",
9
+ ]);
10
+ export const OPTIONAL_FEATURE_AUDIT_STATES = Object.freeze([
11
+ "registered", "local-resource", "legacy-migratable", "missing", "update-available", "conflict", "disabled", "unknown",
12
+ ]);
13
+
14
+ function plainObject(value) {
15
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
16
+ }
17
+
18
+ function normalizedFeatureInventory(value) {
19
+ const features = {};
20
+ for (const [featureId, raw] of Object.entries(plainObject(value))) {
21
+ if (!featureId || featureId.length > 160) continue;
22
+ const feature = plainObject(raw);
23
+ features[featureId] = {
24
+ available: feature.available === true,
25
+ enabled: feature.enabled === true,
26
+ sourceKind: String(feature.sourceKind || "unknown").slice(0, 80),
27
+ installedVersion: String(feature.installedVersion || "").slice(0, 120),
28
+ };
29
+ }
30
+ return features;
31
+ }
32
+
33
+ function normalizedRecord(value) {
34
+ const record = plainObject(value);
35
+ const last = plainObject(record.lastSuccessfulAudit);
36
+ const pending = plainObject(record.pendingUpgrade);
37
+ const dismissed = plainObject(record.dismissedMigration);
38
+ return {
39
+ schemaVersion: OPTIONAL_FEATURE_MIGRATION_SCHEMA_VERSION,
40
+ ...(last.completedAt ? {
41
+ lastSuccessfulAudit: {
42
+ webuiVersion: String(last.webuiVersion || "").slice(0, 120),
43
+ completedAt: String(last.completedAt || "").slice(0, 80),
44
+ features: normalizedFeatureInventory(last.features),
45
+ },
46
+ } : {}),
47
+ ...(pending.startedAt ? {
48
+ pendingUpgrade: {
49
+ fromVersion: String(pending.fromVersion || "").slice(0, 120),
50
+ startedAt: String(pending.startedAt || "").slice(0, 80),
51
+ featureIds: [...new Set((Array.isArray(pending.featureIds) ? pending.featureIds : []).filter((id) => typeof id === "string").slice(0, 256))],
52
+ },
53
+ } : {}),
54
+ ...(dismissed.dismissedAt ? {
55
+ dismissedMigration: {
56
+ revision: String(dismissed.revision || "").slice(0, 160),
57
+ dismissedAt: String(dismissed.dismissedAt || "").slice(0, 80),
58
+ featureIds: [...new Set((Array.isArray(dismissed.featureIds) ? dismissed.featureIds : []).filter((id) => typeof id === "string").slice(0, 256))],
59
+ },
60
+ } : {}),
61
+ };
62
+ }
63
+
64
+ export class OptionalFeatureMigrationStore {
65
+ constructor({ filePath }) {
66
+ if (!filePath) throw new Error("OptionalFeatureMigrationStore requires filePath");
67
+ this.filePath = path.resolve(filePath);
68
+ this.writeQueue = Promise.resolve();
69
+ }
70
+
71
+ async read() {
72
+ try {
73
+ return normalizedRecord(JSON.parse(await readFile(this.filePath, "utf8")));
74
+ } catch (error) {
75
+ if (error?.code === "ENOENT") return { schemaVersion: OPTIONAL_FEATURE_MIGRATION_SCHEMA_VERSION };
76
+ throw new Error(`Optional feature migration state is unreadable: ${error?.code || error?.name || "invalid-json"}`);
77
+ }
78
+ }
79
+
80
+ #enqueueWrite(operation) {
81
+ const task = this.writeQueue.then(operation, operation);
82
+ this.writeQueue = task.catch(() => {});
83
+ return task;
84
+ }
85
+
86
+ async #write(record) {
87
+ const normalized = normalizedRecord(record);
88
+ const parent = path.dirname(this.filePath);
89
+ await mkdir(parent, { recursive: true, mode: 0o700 });
90
+ const temporary = `${this.filePath}.${process.pid}.${randomUUID()}.tmp`;
91
+ try {
92
+ await writeFile(temporary, `${JSON.stringify(normalized, null, 2)}\n`, { encoding: "utf8", mode: 0o600, flag: "wx" });
93
+ await rename(temporary, this.filePath);
94
+ await chmod(this.filePath, 0o600).catch(() => {});
95
+ } finally {
96
+ await rm(temporary, { force: true }).catch(() => {});
97
+ }
98
+ return normalized;
99
+ }
100
+
101
+ write(record) {
102
+ return this.#enqueueWrite(() => this.#write(record));
103
+ }
104
+
105
+ update(mutator) {
106
+ return this.#enqueueWrite(async () => this.#write(await mutator(await this.read())));
107
+ }
108
+
109
+ dismiss({ revision, featureIds, now = new Date() }) {
110
+ return this.update((record) => ({
111
+ ...record,
112
+ dismissedMigration: {
113
+ revision,
114
+ dismissedAt: now.toISOString(),
115
+ featureIds,
116
+ },
117
+ }));
118
+ }
119
+
120
+ markPendingUpgrade({ fromVersion, featureIds, now = new Date() }) {
121
+ return this.update((record) => ({
122
+ ...record,
123
+ pendingUpgrade: {
124
+ fromVersion,
125
+ startedAt: now.toISOString(),
126
+ featureIds,
127
+ },
128
+ }));
129
+ }
130
+
131
+ completeMigration() {
132
+ return this.update((record) => {
133
+ delete record.pendingUpgrade;
134
+ delete record.dismissedMigration;
135
+ return record;
136
+ });
137
+ }
138
+ }
139
+
140
+ function featureSourceKind(state) {
141
+ if (state === "registered" || state === "update-available") return "pi-package";
142
+ if (state === "local-resource") return "top-level-resource";
143
+ if (state === "legacy-migratable") return "legacy-webui-bundled";
144
+ return "none";
145
+ }
146
+
147
+ export function classifyOptionalFeature(status, previousFeature) {
148
+ const previous = plainObject(previousFeature);
149
+ const previouslyAvailable = previous.available === true;
150
+ const previouslyEnabled = previous.enabled === true;
151
+ let state;
152
+ if (status?.resourceConflict) state = "conflict";
153
+ else if (status?.disabled === true || (previouslyAvailable && previous.enabled === false && !status?.configured && !status?.locallyConfigured)) state = "disabled";
154
+ else if (status?.updateAvailable && (status?.configured || status?.locallyConfigured)) state = "update-available";
155
+ else if (status?.configured && status?.installed) state = "registered";
156
+ else if (status?.locallyConfigured) state = "local-resource";
157
+ else if (status?.legacyEvidence === true || previouslyAvailable) state = "legacy-migratable";
158
+ else if (status?.auditUnknown === true || (status?.installed && !status?.configured && !status?.locallyConfigured)) state = "unknown";
159
+ else state = "missing";
160
+ return {
161
+ ...status,
162
+ state,
163
+ sourceKind: featureSourceKind(state),
164
+ previouslyAvailable,
165
+ previouslyEnabled,
166
+ selectedByDefault: state === "legacy-migratable" && previouslyEnabled,
167
+ };
168
+ }
169
+
170
+ function installKindFor(record, statuses, webuiVersion) {
171
+ if (record.pendingUpgrade?.startedAt) return "upgrade";
172
+ if (record.lastSuccessfulAudit?.completedAt && record.lastSuccessfulAudit.webuiVersion !== webuiVersion) return "upgrade";
173
+ if (statuses.some((status) => status.legacyEvidence === true)) return "upgrade";
174
+ if (statuses.some((status) => status.auditUnknown === true)) return "unknown";
175
+ return "fresh";
176
+ }
177
+
178
+ function snapshotSummary(features) {
179
+ return {
180
+ ready: features.filter(({ state }) => ["registered", "local-resource", "update-available"].includes(state)).length,
181
+ migratable: features.filter(({ state }) => state === "legacy-migratable").length,
182
+ missing: features.filter(({ state }) => state === "missing").length,
183
+ conflicts: features.filter(({ state }) => state === "conflict").length,
184
+ disabled: features.filter(({ state }) => state === "disabled").length,
185
+ unknown: features.filter(({ state }) => state === "unknown").length,
186
+ };
187
+ }
188
+
189
+ function stableRevision(payload) {
190
+ return `sha256:${createHash("sha256").update(JSON.stringify(payload)).digest("hex")}`;
191
+ }
192
+
193
+ function sanitizedDiagnostic(error) {
194
+ const code = String(error?.code || error?.name || "audit-failed").replace(/[^a-zA-Z0-9_.-]/g, "").slice(0, 80);
195
+ return { kind: code || "audit-failed", message: "Optional feature audit could not establish a safe resource configuration. Recheck from localhost." };
196
+ }
197
+
198
+ function withDeadline(promise, deadlineAt) {
199
+ const remainingMs = Math.max(0, deadlineAt - Date.now());
200
+ return new Promise((resolve, reject) => {
201
+ const timer = setTimeout(() => {
202
+ const error = new Error("Optional feature audit exceeded its startup deadline");
203
+ error.code = "audit-timeout";
204
+ reject(error);
205
+ }, remainingMs);
206
+ timer.unref?.();
207
+ Promise.resolve(promise).then(
208
+ (value) => {
209
+ clearTimeout(timer);
210
+ resolve(value);
211
+ },
212
+ (error) => {
213
+ clearTimeout(timer);
214
+ reject(error);
215
+ },
216
+ );
217
+ });
218
+ }
219
+
220
+ function browserFeature(feature) {
221
+ const {
222
+ installedRoot: _installedRoot,
223
+ topLevelResources: _topLevelResources,
224
+ configuredPackages: _configuredPackages,
225
+ legacyPath: _legacyPath,
226
+ ...safe
227
+ } = feature;
228
+ return safe;
229
+ }
230
+
231
+ function deepFreeze(value) {
232
+ if (!value || typeof value !== "object" || Object.isFrozen(value)) return value;
233
+ Object.freeze(value);
234
+ for (const child of Object.values(value)) deepFreeze(child);
235
+ return value;
236
+ }
237
+
238
+ function migrationDismissalApplies(features, record) {
239
+ const actionableIds = features.filter(({ state }) => state === "legacy-migratable").map(({ featureId }) => featureId).sort();
240
+ const dismissedIds = [...new Set(record.dismissedMigration?.featureIds || [])].sort();
241
+ return actionableIds.length > 0
242
+ && actionableIds.length === dismissedIds.length
243
+ && actionableIds.every((featureId, index) => featureId === dismissedIds[index]);
244
+ }
245
+
246
+ function phaseFor(features, record) {
247
+ const actionable = features.filter(({ state }) => state === "legacy-migratable");
248
+ const dismissalApplies = migrationDismissalApplies(features, record);
249
+ if (features.some(({ state }) => state === "conflict") || (actionable.length && !dismissalApplies)) return "action-required";
250
+ return "ready";
251
+ }
252
+
253
+ function auditInventory(features, webuiVersion, completedAt) {
254
+ const inventory = {};
255
+ for (const feature of features) {
256
+ inventory[feature.featureId] = {
257
+ available: ["registered", "local-resource", "legacy-migratable", "update-available", "disabled"].includes(feature.state),
258
+ enabled: !["missing", "disabled", "unknown"].includes(feature.state),
259
+ sourceKind: feature.sourceKind,
260
+ installedVersion: feature.installedVersion || "",
261
+ };
262
+ }
263
+ return { webuiVersion, completedAt, features: inventory };
264
+ }
265
+
266
+ export class OptionalFeatureAuditCoordinator {
267
+ constructor({ catalog, collectStatuses, store, webuiVersion, deadlineMs = OPTIONAL_FEATURE_AUDIT_DEADLINE_MS, onEvent = () => {}, now = () => new Date() }) {
268
+ this.catalog = catalog;
269
+ this.collectStatuses = collectStatuses;
270
+ this.store = store;
271
+ this.webuiVersion = webuiVersion;
272
+ this.deadlineMs = deadlineMs;
273
+ this.onEvent = onEvent;
274
+ this.now = now;
275
+ this.inFlight = null;
276
+ this.mutation = null;
277
+ this.snapshot = deepFreeze({
278
+ phase: "checking",
279
+ revision: "pending",
280
+ installKind: "unknown",
281
+ summary: { ready: 0, migratable: 0, missing: 0, conflicts: 0, disabled: 0, unknown: 0 },
282
+ features: [],
283
+ progress: null,
284
+ completedAt: null,
285
+ diagnostic: null,
286
+ });
287
+ }
288
+
289
+ current() {
290
+ return this.snapshot;
291
+ }
292
+
293
+ publish(next, event = "snapshot") {
294
+ this.snapshot = deepFreeze(next);
295
+ this.onEvent({ type: "webui_optional_feature_migration", event, snapshot: this.snapshot });
296
+ return this.snapshot;
297
+ }
298
+
299
+ recheck({ reason = "manual" } = {}) {
300
+ if (this.inFlight) return this.inFlight;
301
+ this.publish({ ...this.snapshot, phase: "checking", progress: null, diagnostic: null }, "checking");
302
+ const task = this.#runAudit(reason).finally(() => {
303
+ if (this.inFlight === task) this.inFlight = null;
304
+ });
305
+ this.inFlight = task;
306
+ return task;
307
+ }
308
+
309
+ async #runAudit(reason) {
310
+ const deadlineAt = Date.now() + this.deadlineMs;
311
+ try {
312
+ const statuses = await withDeadline(Promise.resolve().then(() => this.collectStatuses()), deadlineAt);
313
+ const record = await withDeadline(this.store.read(), deadlineAt);
314
+ const previous = record.lastSuccessfulAudit?.features || {};
315
+ const features = statuses.map((status) => classifyOptionalFeature(status, previous[status.featureId]));
316
+ const installKind = installKindFor(record, statuses, this.webuiVersion);
317
+ const revisionPayload = {
318
+ schemaVersion: OPTIONAL_FEATURE_MIGRATION_SCHEMA_VERSION,
319
+ installKind,
320
+ features: features.map(({ featureId, state, installedVersion, previouslyAvailable, previouslyEnabled, selectedByDefault }) => ({
321
+ featureId, state, installedVersion: installedVersion || "", previouslyAvailable, previouslyEnabled, selectedByDefault,
322
+ })),
323
+ };
324
+ const revision = stableRevision(revisionPayload);
325
+ const completedAt = this.now().toISOString();
326
+ const dismissed = migrationDismissalApplies(features, record);
327
+ const selectedFeatures = features.map((feature) => ({ ...feature, selectedByDefault: dismissed ? false : feature.selectedByDefault }));
328
+ const nextRecord = await withDeadline(
329
+ this.store.update((latest) => ({ ...latest, lastSuccessfulAudit: auditInventory(selectedFeatures, this.webuiVersion, completedAt) })),
330
+ deadlineAt,
331
+ );
332
+ return this.publish({
333
+ phase: phaseFor(selectedFeatures, nextRecord),
334
+ revision,
335
+ installKind,
336
+ summary: snapshotSummary(selectedFeatures),
337
+ features: selectedFeatures.map(browserFeature),
338
+ progress: null,
339
+ completedAt,
340
+ diagnostic: null,
341
+ reason,
342
+ }, "audit-complete");
343
+ } catch (error) {
344
+ const revision = stableRevision({ degraded: true, kind: error?.code || error?.name || "audit-failed", nonce: randomUUID() });
345
+ return this.publish({
346
+ phase: "degraded",
347
+ revision,
348
+ installKind: "unknown",
349
+ summary: { ready: 0, migratable: 0, missing: 0, conflicts: 0, disabled: 0, unknown: this.catalog.length },
350
+ features: this.catalog.map(({ featureId, packageName, expectedSpec }) => ({
351
+ featureId, packageName, expectedSpec, state: "unknown", sourceKind: "none", previouslyAvailable: false, previouslyEnabled: false, selectedByDefault: false,
352
+ })),
353
+ progress: null,
354
+ completedAt: this.now().toISOString(),
355
+ diagnostic: sanitizedDiagnostic(error),
356
+ reason,
357
+ }, "degraded");
358
+ }
359
+ }
360
+
361
+ assertRevision(revision) {
362
+ if (["checking", "degraded"].includes(this.snapshot.phase) || typeof revision !== "string" || revision !== this.snapshot.revision) {
363
+ const error = new Error("Optional feature audit revision is stale or not actionable; refetch /api/optional-features and retry");
364
+ error.statusCode = 409;
365
+ throw error;
366
+ }
367
+ }
368
+
369
+ assertIdle() {
370
+ if (this.mutation) {
371
+ const error = new Error("An optional feature mutation is already in progress");
372
+ error.statusCode = 409;
373
+ throw error;
374
+ }
375
+ }
376
+
377
+ async dismiss(revision) {
378
+ this.assertIdle();
379
+ this.assertRevision(revision);
380
+ const featureIds = this.snapshot.features.filter(({ state }) => state === "legacy-migratable").map(({ featureId }) => featureId);
381
+ await this.store.dismiss({ revision, featureIds, now: this.now() });
382
+ return this.publish({
383
+ ...this.snapshot,
384
+ phase: this.snapshot.summary.conflicts > 0 ? "action-required" : "ready",
385
+ features: this.snapshot.features.map((feature) => ({ ...feature, selectedByDefault: false })),
386
+ }, "dismissed");
387
+ }
388
+
389
+ async runMutation(revision, operation) {
390
+ this.assertRevision(revision);
391
+ this.assertIdle();
392
+ const task = Promise.resolve().then(operation).finally(() => {
393
+ if (this.mutation === task) this.mutation = null;
394
+ });
395
+ this.mutation = task;
396
+ return task;
397
+ }
398
+
399
+ setProgress(progress) {
400
+ const phase = progress?.phase || "migrating";
401
+ return this.publish({ ...this.snapshot, phase, progress: progress ? { ...progress } : null }, "progress");
402
+ }
403
+
404
+ excludedPackageNames() {
405
+ if (this.snapshot.phase === "checking" || this.snapshot.phase === "degraded") {
406
+ return new Set(this.catalog.map(({ packageName }) => packageName));
407
+ }
408
+ return new Set(this.snapshot.features.filter(({ state }) => state === "conflict").map(({ packageName }) => packageName));
409
+ }
410
+ }