@pi-chamber/web 1.0.6-rc.4 → 1.0.6-rc.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 (119) hide show
  1. package/dist/assets/{DiagramView-BZ--w7Lh.js → DiagramView--XO16VPB.js} +1 -1
  2. package/dist/assets/{DiffView-Dtn6otnT.js → DiffView-Duy2_7Gp.js} +6 -6
  3. package/dist/assets/{FileSaveConflictDialog-p1ik30al.js → FileSaveConflictDialog-B1DvL9zy.js} +1 -1
  4. package/dist/assets/{FilesView-D0Z0VmQm.js → FilesView-CjjPpE4c.js} +4 -4
  5. package/dist/assets/{GitHubDetailScaffold-a27RksFo.js → GitHubDetailScaffold-DqxAKqCT.js} +2 -2
  6. package/dist/assets/{GitHubLinkPicker-B0CfzNfk.js → GitHubLinkPicker-ELF_chia.js} +1 -1
  7. package/dist/assets/GitHubListPrimitives-C2nGTntk.js +1 -0
  8. package/dist/assets/{GitView-BNkoaVYl.js → GitView-5fIq2nzM.js} +4 -4
  9. package/dist/assets/IssuesSurface-Dq5A_bWq.js +7 -0
  10. package/dist/assets/{JsonTreeView-CEiJsFnP.js → JsonTreeView-BjFFSUwi.js} +1 -1
  11. package/dist/assets/{MarkdownRendererImpl-418ChlsN.js → MarkdownRendererImpl-B9Cu4TCh.js} +2 -2
  12. package/dist/assets/{PatchDiff-BtOv_oLB.js → PatchDiff-CTqTTcg7.js} +1 -1
  13. package/dist/assets/{PierreDiffViewer-CkuyY9ne.js → PierreDiffViewer-H2f4pJ1k.js} +1 -1
  14. package/dist/assets/PullRequestsSurface-DPpb2RW_.js +2 -0
  15. package/dist/assets/{SessionSwitcherContent-DkfjRgwv.js → SessionSwitcherContent-B5DaBWZU.js} +1 -1
  16. package/dist/assets/{SessionSwitcherDropdown-CEw8BEs6.js → SessionSwitcherDropdown-D86FaZg_.js} +2 -2
  17. package/dist/assets/SessionUnreadDot-CY9-1iV2.js +1 -0
  18. package/dist/assets/SettingsView-CiIuOi_E.js +6 -0
  19. package/dist/assets/{SettingsWindow-D03Z9QyW.js → SettingsWindow-Bw1dUoJ1.js} +1 -1
  20. package/dist/assets/{StickyHorizontalScrollbar-CONTbZgX.js → StickyHorizontalScrollbar-DNsbTLS7.js} +1 -1
  21. package/dist/assets/{ToolOutputDialog-DibddNlz.js → ToolOutputDialog-aR4kcgKL.js} +5 -5
  22. package/dist/assets/{ToolPartDiffPreview-Bx7T1M2f.js → ToolPartDiffPreview-B_wWmhtE.js} +1 -1
  23. package/dist/assets/{VirtualizedFileDiff-BY-mDMT8.js → VirtualizedFileDiff-BYby097w.js} +4 -4
  24. package/dist/assets/{Virtualizer-cIf8dSOQ.js → Virtualizer-okhy9Aq3.js} +1 -1
  25. package/dist/assets/{collapsible-BhQdnj8G.js → collapsible-Dz0bPrJ_.js} +1 -1
  26. package/dist/assets/{computeVirtualFileMetrics-CzkFqhaU.js → computeVirtualFileMetrics-8MuwxSC6.js} +1 -1
  27. package/dist/assets/{contextFileOpenGuard-CjCOK8EB.js → contextFileOpenGuard-fZ2NIQMQ.js} +1 -1
  28. package/dist/assets/{fileTreeStatus-CPTpyKOV.js → fileTreeStatus-BzhMMLA9.js} +2 -2
  29. package/dist/assets/{gitStatusPredicates-_GNbGCCb.js → gitStatusPredicates-Cyh9UhYX.js} +1 -1
  30. package/dist/assets/{githubLink-CwIFogWd.js → githubLink-D2PznPcI.js} +2 -2
  31. package/dist/assets/{index-DjOKW10B.js → index-BX5pAOQX.js} +1 -1
  32. package/dist/assets/index-Cs2nBW_t.js +11 -0
  33. package/dist/assets/{index-D7k62S9M.css → index-tmO0fZa4.css} +1 -1
  34. package/dist/assets/{main-1wmEZ4Is.js → main-7vBNPBMb.js} +4 -4
  35. package/dist/assets/{main-C51a3z3b.js → main-BI6qe8pz.js} +2 -2
  36. package/dist/assets/{markdownCore-Dsr6dY5C.js → markdownCore-D5jiabKe.js} +1 -1
  37. package/dist/assets/{miniChat-DCxCx1fF.js → miniChat-B3up4Bnz.js} +2 -2
  38. package/dist/assets/{mobile-D6Ac2Mu3.js → mobile-B4vLFgBc.js} +2 -2
  39. package/dist/assets/{nativeFileSave-P_Eg5Dgb.js → nativeFileSave-DpBH1Sa3.js} +1 -1
  40. package/dist/assets/{pi-session-focus-preference-DjDyjZ1C.js → pi-session-focus-preference-BrB72skF.js} +3 -3
  41. package/dist/assets/{renderDiffWithHighlighter-CK_inhQE.js → renderDiffWithHighlighter-B6T04JGG.js} +1 -1
  42. package/dist/assets/{renderElectronMiniChatApp-wBNgFl0U.js → renderElectronMiniChatApp-CX10w321.js} +2 -2
  43. package/dist/assets/{renderFileWithHighlighter-B_PFeRW5.js → renderFileWithHighlighter-DtAcGyJr.js} +1 -1
  44. package/dist/assets/{renderMobileApp-B3mhxGnb.js → renderMobileApp-C9n-BhPZ.js} +3 -3
  45. package/dist/assets/runtimeEndpointReset-aGyXPXPs.js +62 -0
  46. package/dist/assets/{runtimeSurface-C3YPOBlg.js → runtimeSurface-DiP2a57a.js} +1 -1
  47. package/dist/assets/{useAppFontEffects-CoFst31H.js → useAppFontEffects-Oyin3dgQ.js} +92 -92
  48. package/dist/assets/useGitHubRemoteSearch-CZ9Hauw0.js +1 -0
  49. package/dist/assets/{useSwitcherItems-DHCCg4GF.js → useSwitcherItems-BSqDA1IF.js} +1 -1
  50. package/dist/assets/{vendor-aparajita-capacitor-secure-storage-B9_YeZyx.js → vendor-aparajita-capacitor-secure-storage-DVZvgYu4.js} +1 -1
  51. package/dist/assets/{vendor-base-ui-CKSCJw-4.js → vendor-base-ui-BCqPBzDj.js} +1 -1
  52. package/dist/assets/{vendor-boot-Ciu-Edvy.js → vendor-boot-3SaHYVb1.js} +1 -1
  53. package/dist/assets/{vendor-capacitor-app-Bpy_aPMq.js → vendor-capacitor-app-NbQ-WiPS.js} +1 -1
  54. package/dist/assets/{vendor-capacitor-keyboard-DO8AIjrZ.js → vendor-capacitor-keyboard-CgrHt8iN.js} +1 -1
  55. package/dist/assets/{vendor-capacitor-status-bar-SQkytwUW.js → vendor-capacitor-status-bar-CWt0OF5t.js} +1 -1
  56. package/dist/assets/{vendor-codemirror-autocomplete-CInQsE8a.js → vendor-codemirror-autocomplete-WThuuUAz.js} +1 -1
  57. package/dist/assets/{vendor-codemirror-lang-angular-QbsN3LGE.js → vendor-codemirror-lang-angular-BbLGCxF6.js} +1 -1
  58. package/dist/assets/{vendor-codemirror-lang-cpp-BT5U7lxV.js → vendor-codemirror-lang-cpp-Cceks-9O.js} +1 -1
  59. package/dist/assets/{vendor-codemirror-lang-css-dF-Dxbty.js → vendor-codemirror-lang-css-D1wpUg3Z.js} +1 -1
  60. package/dist/assets/{vendor-codemirror-lang-go-e4dp1bar.js → vendor-codemirror-lang-go-Cv0zXHHM.js} +1 -1
  61. package/dist/assets/{vendor-codemirror-lang-html-DKcbBVQ4.js → vendor-codemirror-lang-html-DbL8oT9H.js} +1 -1
  62. package/dist/assets/{vendor-codemirror-lang-java-CB2-FWv6.js → vendor-codemirror-lang-java-CNugenuC.js} +1 -1
  63. package/dist/assets/{vendor-codemirror-lang-javascript-B1zJk7xE.js → vendor-codemirror-lang-javascript-Bx_FIyZF.js} +1 -1
  64. package/dist/assets/{vendor-codemirror-lang-jinja-BsERjdSd.js → vendor-codemirror-lang-jinja-DDGjB3Zq.js} +1 -1
  65. package/dist/assets/{vendor-codemirror-lang-json-C0pZ0NhY.js → vendor-codemirror-lang-json-DIvqf9Pb.js} +1 -1
  66. package/dist/assets/{vendor-codemirror-lang-less-_N9HmR4h.js → vendor-codemirror-lang-less-D8r9dGG1.js} +1 -1
  67. package/dist/assets/{vendor-codemirror-lang-liquid-D02xJRCD.js → vendor-codemirror-lang-liquid-B24mguYi.js} +1 -1
  68. package/dist/assets/{vendor-codemirror-lang-markdown-_6ojeUuZ.js → vendor-codemirror-lang-markdown-v3yG2sbf.js} +1 -1
  69. package/dist/assets/{vendor-codemirror-lang-php-DguCnbJA.js → vendor-codemirror-lang-php-BcZGalqy.js} +1 -1
  70. package/dist/assets/{vendor-codemirror-lang-python-Byr5gw5f.js → vendor-codemirror-lang-python-b-JqEwQy.js} +1 -1
  71. package/dist/assets/{vendor-codemirror-lang-rust-DN6Wh0eK.js → vendor-codemirror-lang-rust-B1uZxDW-.js} +1 -1
  72. package/dist/assets/{vendor-codemirror-lang-sass-DOlEW7q1.js → vendor-codemirror-lang-sass-DqPrngKp.js} +1 -1
  73. package/dist/assets/{vendor-codemirror-lang-sql-BJzE9Dby.js → vendor-codemirror-lang-sql-UyCnpt-k.js} +1 -1
  74. package/dist/assets/{vendor-codemirror-lang-vue-DR8E-2nr.js → vendor-codemirror-lang-vue-xDwYkovV.js} +1 -1
  75. package/dist/assets/{vendor-codemirror-lang-wast-n6lcDH5S.js → vendor-codemirror-lang-wast-CF3169p_.js} +1 -1
  76. package/dist/assets/{vendor-codemirror-lang-xml-Cf2lmlmY.js → vendor-codemirror-lang-xml-FCtVhuOb.js} +1 -1
  77. package/dist/assets/{vendor-codemirror-lang-yaml-DSR_E0yh.js → vendor-codemirror-lang-yaml-g0sPmAnv.js} +1 -1
  78. package/dist/assets/{vendor-codemirror-language-data-CSid5JuX.js → vendor-codemirror-language-data-B03xgzP2.js} +2 -2
  79. package/dist/assets/{vendor-codemirror-search-8lY3lt6q.js → vendor-codemirror-search-Dw3Wpu15.js} +1 -1
  80. package/dist/assets/{vendor-lezer-cpp-DZYTDKiD.js → vendor-lezer-cpp-Cu3E-KUI.js} +1 -1
  81. package/dist/assets/{vendor-lezer-css-6qV4fYNQ.js → vendor-lezer-css-Cb8vp67u.js} +1 -1
  82. package/dist/assets/{vendor-lezer-go-BDi_Iblq.js → vendor-lezer-go-BTsIaOm7.js} +1 -1
  83. package/dist/assets/{vendor-lezer-html-BjqcY-oJ.js → vendor-lezer-html-UQMsUwj-.js} +1 -1
  84. package/dist/assets/{vendor-lezer-java-J2BXqz1h.js → vendor-lezer-java-BIWrFrAx.js} +1 -1
  85. package/dist/assets/{vendor-lezer-javascript-CiQ9F8yX.js → vendor-lezer-javascript-BH2Etgoy.js} +1 -1
  86. package/dist/assets/{vendor-lezer-json-BxN83KKR.js → vendor-lezer-json-CE-QUCwM.js} +1 -1
  87. package/dist/assets/{vendor-lezer-lr-BVsDua_K.js → vendor-lezer-lr-HY6Yc0Vr.js} +1 -1
  88. package/dist/assets/{vendor-lezer-markdown-BkMtRQ3X.js → vendor-lezer-markdown-xFL3Evwf.js} +1 -1
  89. package/dist/assets/{vendor-lezer-php-B3XqnXdP.js → vendor-lezer-php-Cr_mQGrG.js} +1 -1
  90. package/dist/assets/{vendor-lezer-python-D342CidI.js → vendor-lezer-python-BNRFWCb0.js} +1 -1
  91. package/dist/assets/{vendor-lezer-rust-Dbfg_4LA.js → vendor-lezer-rust-BvfOK5cU.js} +1 -1
  92. package/dist/assets/{vendor-lezer-sass-ClxPaFt1.js → vendor-lezer-sass-qoxiLisk.js} +1 -1
  93. package/dist/assets/{vendor-lezer-xml-I_S6FQ1u.js → vendor-lezer-xml--x8SSpqU.js} +1 -1
  94. package/dist/assets/{vendor-lezer-yaml-COA6HWLP.js → vendor-lezer-yaml-BDo1JaEr.js} +1 -1
  95. package/dist/assets/{vendor-replit-codemirror-vim-7IE2zVmx.js → vendor-replit-codemirror-vim-D1Fe7FiY.js} +1 -1
  96. package/dist/assets/{web-components-CzkvK_V5.js → web-components-CkTNGkJ2.js} +4 -4
  97. package/dist/index.html +4 -4
  98. package/dist/mini-chat.html +3 -3
  99. package/dist/mobile.html +3 -3
  100. package/package.json +1 -1
  101. package/server/lib/pi/archive-store.js +38 -10
  102. package/server/lib/pi/archive-store.test.js +10 -0
  103. package/server/lib/pi/routes.js +60 -17
  104. package/server/lib/pi/routes.test.js +186 -8
  105. package/server/lib/pi/session-daemon/DOCUMENTATION.md +5 -1
  106. package/server/lib/pi/session-daemon/session-daemon-engines.test.js +18 -0
  107. package/server/lib/pi/session-daemon/session-daemon.js +24 -1
  108. package/server/lib/pi/session-shelf-store.js +155 -84
  109. package/server/lib/pi/session-shelf-store.test.js +134 -33
  110. package/server/lib/pi/ui-settings-store.js +59 -0
  111. package/server/lib/pi/ui-settings-store.test.js +105 -6
  112. package/dist/assets/GitHubListPrimitives-LFdR70l6.js +0 -1
  113. package/dist/assets/IssuesSurface-D4kD7_VW.js +0 -7
  114. package/dist/assets/PullRequestsSurface-PML07zr-.js +0 -2
  115. package/dist/assets/SessionUnreadDot-DXUn8-ss.js +0 -1
  116. package/dist/assets/SettingsView-BvUeFUqw.js +0 -6
  117. package/dist/assets/index-Cfrwo5uQ.js +0 -11
  118. package/dist/assets/runtimeEndpointReset-D8lAOCUB.js +0 -62
  119. package/dist/assets/useGitHubRemoteSearch-C0-6hhMJ.js +0 -1
@@ -4333,7 +4333,7 @@ export function createSessionDaemon({
4333
4333
  'providers.login.respond', 'providers.login.status', 'providers.logout', 'settings.get', 'settings.set',
4334
4334
  'resources.list', 'resources.update', 'resources.prompts.create', 'resources.prompts.update', 'resources.prompts.delete',
4335
4335
  'extensions.list', 'extensions.respond', 'extensions.draft',
4336
- 'openUrl.publish',
4336
+ 'openUrl.publish', 'archive.publish',
4337
4337
  'extensions.custom.input', 'extensions.custom.viewport', 'extensions.custom.close', 'extensions.custom.focus', 'extensions.custom.refresh',
4338
4338
  ],
4339
4339
  ...(Number.isInteger(healthMetadata.daemonPid) ? { daemonPid: healthMetadata.daemonPid } : {}),
@@ -4588,6 +4588,29 @@ export function createSessionDaemon({
4588
4588
  });
4589
4589
  return;
4590
4590
  }
4591
+ case 'archive.publish': {
4592
+ // The PiChamber server changed a session's archive mark (its own
4593
+ // metadata, not Pi state). Publishing it on the session's stream
4594
+ // tells every device to re-list that folder; the server's archive
4595
+ // store stays the authority.
4596
+ const sessionId = message.payload?.sessionId;
4597
+ if (typeof sessionId !== 'string' || sessionId.length === 0 || sessionId.length > 256 || typeof message.payload?.archived !== 'boolean') {
4598
+ throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'A session id and an archived flag are required.');
4599
+ }
4600
+ const requestedDirectory = typeof message.payload?.directory === 'string' && message.payload.directory.length > 0 && message.payload.directory.length <= 4096
4601
+ ? message.payload.directory
4602
+ : undefined;
4603
+ const residentCwd = runtimeRegistry?.findBySessionId?.(sessionId)?.cwd;
4604
+ const directory = requestedDirectory ?? (typeof residentCwd === 'string' && residentCwd.length > 0 ? residentCwd : undefined);
4605
+ publish('session.archive', { archived: message.payload.archived }, sessionId, directory);
4606
+ writeFrame(socket, {
4607
+ protocolVersion: PROTOCOL_VERSION,
4608
+ kind: 'response',
4609
+ requestId: message.requestId,
4610
+ result: { published: true },
4611
+ });
4612
+ return;
4613
+ }
4591
4614
  case 'openUrl.publish': {
4592
4615
  // An Open request from the PiChamber server's intake. Not
4593
4616
  // session-scoped on input: the daemon attributes it and publishes a
@@ -7,7 +7,6 @@ import { withCrossProcessLock } from '../server/cross-process-lock.js';
7
7
  const MAX_FILE_BYTES = 4 * 1024 * 1024;
8
8
  const MAX_SESSION_ID_LENGTH = 512;
9
9
  const FORBIDDEN_KEYS = new Set(['__proto__', 'prototype', 'constructor']);
10
- const SETTLED_STATES = new Set(['settled', 'active']);
11
10
 
12
11
  const invalidShelf = () => {
13
12
  const error = new Error('Pi session shelf metadata is invalid.');
@@ -26,18 +25,22 @@ const isTimestamp = (value) => Number.isSafeInteger(value) && value > 0;
26
25
  const isSessionId = (value) => typeof value === 'string' && value.length > 0
27
26
  && value.length <= MAX_SESSION_ID_LENGTH && !FORBIDDEN_KEYS.has(value);
28
27
 
29
- // One session's entry, or null when it holds nothing. Fields only travel in
30
- // pairs: a settled override without its time, or a snooze without its wake,
31
- // is malformed.
32
- const validateEntry = (value) => {
28
+ // One session's stored entry, or null when it holds nothing. A snooze
29
+ // travels with its start time. Files written before Archive replaced Settle
30
+ // may also carry `settled` ('settled' with its `settledAt`, or 'active');
31
+ // those fields are kept here only so the migration can read them.
32
+ const validateStoredEntry = (value) => {
33
33
  if (!isRecord(value)) throw invalidShelf();
34
34
  const entry = {};
35
35
  if (value.settled !== undefined) {
36
- if (!SETTLED_STATES.has(value.settled)) throw invalidShelf();
37
- entry.settled = value.settled;
38
36
  if (value.settled === 'settled') {
39
37
  if (!isTimestamp(value.settledAt)) throw invalidShelf();
38
+ entry.settled = 'settled';
40
39
  entry.settledAt = value.settledAt;
40
+ } else if (value.settled === 'active') {
41
+ entry.settled = 'active';
42
+ } else {
43
+ throw invalidShelf();
41
44
  }
42
45
  }
43
46
  if (value.snoozedUntil !== undefined) {
@@ -48,38 +51,73 @@ const validateEntry = (value) => {
48
51
  return Object.keys(entry).length > 0 ? entry : null;
49
52
  };
50
53
 
51
- const validateShelf = (value) => {
54
+ const validateStoredShelf = (value) => {
52
55
  if (!isRecord(value)) throw invalidShelf();
53
56
  const shelf = {};
54
57
  for (const [sessionId, raw] of Object.entries(value)) {
55
58
  if (!isSessionId(sessionId)) throw invalidShelf();
56
- const entry = validateEntry(raw);
59
+ const entry = validateStoredEntry(raw);
57
60
  if (entry) shelf[sessionId] = entry;
58
61
  }
59
62
  return shelf;
60
63
  };
61
64
 
65
+ const hasLegacySettled = (shelf) => Object.values(shelf).some((entry) => entry.settled !== undefined);
66
+
67
+ // The shelf without the retired settled fields; entries left empty go.
68
+ const withoutSettled = (shelf) => {
69
+ const next = {};
70
+ for (const [sessionId, entry] of Object.entries(shelf)) {
71
+ if (entry.snoozedUntil === undefined) continue;
72
+ next[sessionId] = { snoozedUntil: entry.snoozedUntil, snoozedAt: entry.snoozedAt };
73
+ }
74
+ return next;
75
+ };
76
+
77
+ // The snooze-only shelf with the settled fields from `stored` put back, for
78
+ // a write while the migration is still pending. `dropSessionId` loses its
79
+ // settled mark.
80
+ const withSettledKept = (shelf, stored, dropSessionId) => {
81
+ const next = {};
82
+ for (const sessionId of new Set([...Object.keys(stored), ...Object.keys(shelf)])) {
83
+ const entry = {};
84
+ const legacy = stored[sessionId];
85
+ if (legacy?.settled !== undefined && sessionId !== dropSessionId) {
86
+ entry.settled = legacy.settled;
87
+ if (legacy.settled === 'settled') entry.settledAt = legacy.settledAt;
88
+ }
89
+ if (shelf[sessionId]) Object.assign(entry, shelf[sessionId]);
90
+ if (Object.keys(entry).length > 0) next[sessionId] = entry;
91
+ }
92
+ return next;
93
+ };
94
+
62
95
  /**
63
- * PiChamber-owned sidebar shelf metadata: whether a session was settled or
64
- * kept active by hand, and when a snoozed session wakes. Like the archive
65
- * sidecar, it is keyed only by opaque Pi session IDs, leaves Pi JSONL
66
- * untouched, and every write is atomic under a cross-process lock.
96
+ * PiChamber-owned sidebar shelf metadata: when a snoozed session wakes. Like
97
+ * the archive sidecar, it is keyed only by opaque Pi session IDs, leaves Pi
98
+ * JSONL untouched, and every write is atomic under a cross-process lock.
99
+ *
100
+ * - `snoozedUntil` hides a session until that time; `null` wakes it.
101
+ * - `clearForActivity` drops the snooze when the user sends to the session.
67
102
  *
68
- * - `settled: 'settled'` moves a session to Settled; `settled: 'active'`
69
- * keeps it out of Settled even when it would auto-settle. `null` clears
70
- * the override so the client's auto-settle rule applies again.
71
- * - `snoozedUntil` hides a session until that time. Snoozing clears a
72
- * settled override, so the session wakes into the active list.
73
- * - Settling clears a snooze.
74
- * - `clearForActivity` drops both when the user sends to the session.
103
+ * Settle was replaced by Archive. A file that still holds settled marks is
104
+ * migrated once, under the shelf lock: hand-settled sessions are archived at
105
+ * their settle time (sessions already archived keep theirs), the archive
106
+ * file is written first, then the shelf file without the settled fields. If
107
+ * the archive write fails, the migration runs again on the next read or
108
+ * write. Until then reads answer with the snooze state, and snooze writes
109
+ * still go through with every settled mark left in the file. A send or a
110
+ * delete drops that one session's settled mark, so the retried migration
111
+ * never archives a session the user just used.
75
112
  */
76
113
  export const createPiSessionShelfStore = ({
77
114
  file = join(resolvePiChamberDataDir(), 'pi', 'session-shelf.json'),
78
115
  now = () => Date.now(),
116
+ archiveStore,
79
117
  } = {}) => {
80
118
  let writeChain = Promise.resolve();
81
119
 
82
- const read = async () => {
120
+ const readStored = async () => {
83
121
  let raw;
84
122
  try {
85
123
  raw = await readFile(file, 'utf8');
@@ -89,92 +127,125 @@ export const createPiSessionShelfStore = ({
89
127
  }
90
128
  if (Buffer.byteLength(raw) > MAX_FILE_BYTES) throw invalidShelf();
91
129
  try {
92
- return validateShelf(JSON.parse(raw));
130
+ return validateStoredShelf(JSON.parse(raw));
93
131
  } catch {
94
132
  throw invalidShelf();
95
133
  }
96
134
  };
97
135
 
98
- // Serializes writes in this process and across processes sharing the
99
- // data directory. `change` receives the current entry (or null) and
100
- // returns the next entry (or null to remove it).
101
- const mutate = (sessionId, change) => {
136
+ const writeStored = async (shelf) => {
137
+ const serialized = JSON.stringify(shelf);
138
+ if (Buffer.byteLength(serialized) > MAX_FILE_BYTES) throw invalidShelf();
139
+ await mkdir(dirname(file), { recursive: true, mode: 0o700 });
140
+ const temporary = `${file}.tmp`;
141
+ await writeFile(temporary, serialized, { mode: 0o600 });
142
+ await rename(temporary, file);
143
+ };
144
+
145
+ // Runs under the shelf lock. Returns the migrated shelf; throws (leaving
146
+ // the shelf file untouched) when the archive write fails.
147
+ const migrateLocked = async (stored) => {
148
+ if (!hasLegacySettled(stored)) return stored;
149
+ const toArchive = {};
150
+ for (const [sessionId, entry] of Object.entries(stored)) {
151
+ if (entry.settled === 'settled') toArchive[sessionId] = entry.settledAt;
152
+ }
153
+ if (Object.keys(toArchive).length > 0) {
154
+ if (typeof archiveStore?.archiveMissing !== 'function') {
155
+ throw Object.assign(new Error('No archive store for the settled migration.'), { code: 'SESSION_SHELF_MIGRATION_UNAVAILABLE' });
156
+ }
157
+ await archiveStore.archiveMissing(toArchive);
158
+ }
159
+ const migrated = withoutSettled(stored);
160
+ await writeStored(migrated);
161
+ return migrated;
162
+ };
163
+
164
+ // Serializes writes in this process and across processes sharing the data
165
+ // directory. `change` receives the migrated shelf (snooze state only) and
166
+ // may edit it in place; it returns whether the file needs writing, the
167
+ // result, and optionally a session whose settled mark should go too.
168
+ // While the migration keeps failing, writes still go through: the file
169
+ // keeps every other unmigrated settled mark, so the next read retries.
170
+ const locked = (change) => {
102
171
  const operation = writeChain.then(() => withCrossProcessLock(`${file}.lock`, async () => {
103
- const current = await read();
104
- const previous = current[sessionId] ?? null;
105
- const next = change(previous);
106
- if (next) current[sessionId] = next;
107
- else delete current[sessionId];
108
- if (JSON.stringify(previous) === JSON.stringify(next ?? null)) return next ?? null;
109
- const serialized = JSON.stringify(current);
110
- if (Buffer.byteLength(serialized) > MAX_FILE_BYTES) throw invalidShelf();
111
- await mkdir(dirname(file), { recursive: true, mode: 0o700 });
112
- const temporary = `${file}.tmp`;
113
- await writeFile(temporary, serialized, { mode: 0o600 });
114
- await rename(temporary, file);
115
- return next ?? null;
172
+ const stored = await readStored();
173
+ let shelf;
174
+ let unmigrated = null;
175
+ try {
176
+ shelf = await migrateLocked(stored);
177
+ } catch (error) {
178
+ if (error?.code === 'SESSION_SHELF_INVALID') throw error;
179
+ console.warn('[pi] could not migrate settled sessions to the archive; will retry', error?.code ?? error);
180
+ shelf = withoutSettled(stored);
181
+ unmigrated = stored;
182
+ }
183
+ const { write, result, dropSettled } = change(shelf);
184
+ const dropsMark = unmigrated !== null && dropSettled !== undefined && unmigrated[dropSettled]?.settled !== undefined;
185
+ if (write || dropsMark) await writeStored(unmigrated ? withSettledKept(shelf, unmigrated, dropSettled) : shelf);
186
+ return result;
116
187
  }));
117
188
  writeChain = operation.catch(() => {});
118
189
  return operation;
119
190
  };
120
191
 
192
+ const read = async () => {
193
+ const stored = await readStored();
194
+ if (!hasLegacySettled(stored)) return stored;
195
+ try {
196
+ return await locked((shelf) => ({ write: false, result: shelf }));
197
+ } catch (error) {
198
+ if (error?.code === 'SESSION_SHELF_INVALID') throw error;
199
+ console.warn('[pi] could not read the session shelf under its lock', error?.code ?? error);
200
+ return withoutSettled(stored);
201
+ }
202
+ };
203
+
204
+ // `change` receives the current entry (or null) and returns the next entry
205
+ // (or null to remove it). `dropSettled` also removes the session's
206
+ // unmigrated settled mark (a send or a delete), so a retried migration
207
+ // cannot archive it afterwards.
208
+ const mutate = (sessionId, change, { dropSettled = false } = {}) => locked((shelf) => {
209
+ const previous = shelf[sessionId] ?? null;
210
+ const next = change(previous);
211
+ if (next) shelf[sessionId] = next;
212
+ else delete shelf[sessionId];
213
+ return {
214
+ write: JSON.stringify(previous) !== JSON.stringify(next ?? null),
215
+ result: next ?? null,
216
+ ...(dropSettled ? { dropSettled: sessionId } : {}),
217
+ };
218
+ });
219
+
121
220
  /**
122
- * Apply `{ settled?, snoozedUntil? }`. An omitted field is left alone;
123
- * `null` clears it. Returns the session's entry after the write, or null.
221
+ * Apply `{ snoozedUntil }`: a timestamp snoozes, `null` wakes. Returns the
222
+ * session's entry after the write, or null.
124
223
  */
125
224
  const update = async (sessionId, patch) => {
126
225
  if (!isSessionId(sessionId) || !isRecord(patch)) throw invalidArgument();
127
- const hasSettled = Object.hasOwn(patch, 'settled');
128
- const hasSnooze = Object.hasOwn(patch, 'snoozedUntil');
129
- if (!hasSettled && !hasSnooze) throw invalidArgument();
130
- if (hasSettled && patch.settled !== null && !SETTLED_STATES.has(patch.settled)) throw invalidArgument();
131
- if (hasSnooze && patch.snoozedUntil !== null && !isTimestamp(patch.snoozedUntil)) throw invalidArgument();
132
- if (hasSettled && hasSnooze && patch.settled === 'settled' && patch.snoozedUntil !== null) throw invalidArgument();
133
-
134
- return mutate(sessionId, (previous) => {
135
- const at = now();
136
- const next = { ...previous };
137
- if (hasSettled) {
138
- delete next.settled;
139
- delete next.settledAt;
140
- if (patch.settled === 'settled') {
141
- next.settled = 'settled';
142
- next.settledAt = previous?.settled === 'settled' && previous.settledAt ? previous.settledAt : at;
143
- delete next.snoozedUntil;
144
- delete next.snoozedAt;
145
- } else if (patch.settled === 'active') {
146
- next.settled = 'active';
147
- }
148
- }
149
- if (hasSnooze) {
150
- delete next.snoozedUntil;
151
- delete next.snoozedAt;
152
- if (patch.snoozedUntil !== null) {
153
- next.snoozedUntil = patch.snoozedUntil;
154
- next.snoozedAt = at;
155
- if (next.settled === 'settled') {
156
- delete next.settled;
157
- delete next.settledAt;
158
- }
159
- }
160
- }
161
- return Object.keys(next).length > 0 ? next : null;
162
- });
226
+ if (Object.keys(patch).some((key) => key !== 'snoozedUntil') || !Object.hasOwn(patch, 'snoozedUntil')) throw invalidArgument();
227
+ if (patch.snoozedUntil !== null && !isTimestamp(patch.snoozedUntil)) throw invalidArgument();
228
+
229
+ return mutate(sessionId, () => (patch.snoozedUntil === null
230
+ ? null
231
+ : { snoozedUntil: patch.snoozedUntil, snoozedAt: now() }));
163
232
  };
164
233
 
165
- /** A message the user sent ends a snooze and drops any settled override. */
234
+ // Whether the file holds anything for this session: a snooze or an
235
+ // unmigrated settled mark (empty entries are never kept).
236
+ const holds = async (sessionId) => Boolean((await readStored())[sessionId]);
237
+
238
+ /** A message the user sent ends a snooze. */
166
239
  const clearForActivity = async (sessionId) => {
167
240
  if (!isSessionId(sessionId)) return null;
168
- const shelf = await read();
169
- if (!shelf[sessionId]) return null;
170
- return mutate(sessionId, () => null);
241
+ if (!(await holds(sessionId))) return null;
242
+ return mutate(sessionId, () => null, { dropSettled: true });
171
243
  };
172
244
 
173
245
  const remove = async (sessionId) => {
174
246
  if (!isSessionId(sessionId)) return;
175
- const shelf = await read();
176
- if (!shelf[sessionId]) return;
177
- await mutate(sessionId, () => null);
247
+ if (!(await holds(sessionId))) return;
248
+ await mutate(sessionId, () => null, { dropSettled: true });
178
249
  };
179
250
 
180
251
  return { read, update, clearForActivity, remove };
@@ -1,14 +1,28 @@
1
- import { mkdtemp, readFile, writeFile } from 'node:fs/promises';
1
+ import { mkdtemp, readFile, writeFile, mkdir } from 'node:fs/promises';
2
2
  import { tmpdir } from 'node:os';
3
3
  import { join } from 'node:path';
4
- import { describe, expect, it } from 'vitest';
4
+ import { describe, expect, it, vi } from 'vitest';
5
5
 
6
+ import { createPiArchiveStore } from './archive-store.js';
6
7
  import { createPiSessionShelfStore } from './session-shelf-store.js';
7
8
 
8
- const createStore = async (clock = { now: 1_000 }) => {
9
+ const createStore = async (clock = { now: 1_000 }, { archiveStore } = {}) => {
9
10
  const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-shelf-'));
10
11
  const file = join(root, 'pi', 'session-shelf.json');
11
- return { file, clock, store: createPiSessionShelfStore({ file, now: () => clock.now }) };
12
+ const archiveFile = join(root, 'pi', 'session-archive.json');
13
+ const archive = archiveStore ?? createPiArchiveStore({ file: archiveFile });
14
+ return {
15
+ file,
16
+ archiveFile,
17
+ archive,
18
+ clock,
19
+ store: createPiSessionShelfStore({ file, now: () => clock.now, archiveStore: archive }),
20
+ };
21
+ };
22
+
23
+ const writeLegacyShelf = async (file, shelf) => {
24
+ await mkdir(join(file, '..'), { recursive: true });
25
+ await writeFile(file, JSON.stringify(shelf));
12
26
  };
13
27
 
14
28
  describe('Pi session shelf sidecar', () => {
@@ -17,57 +31,144 @@ describe('Pi session shelf sidecar', () => {
17
31
  await expect(store.read()).resolves.toEqual({});
18
32
  });
19
33
 
20
- it('settles, keeps active, and clears an override', async () => {
34
+ it('snoozes and wakes a session', async () => {
21
35
  const { store, clock } = await createStore();
22
- await expect(store.update('s1', { settled: 'settled' })).resolves.toEqual({ settled: 'settled', settledAt: 1_000 });
36
+ await expect(store.update('s1', { snoozedUntil: 9_000 })).resolves.toEqual({ snoozedUntil: 9_000, snoozedAt: 1_000 });
23
37
  clock.now = 2_000;
24
- // Settling again keeps the first settle time.
25
- await expect(store.update('s1', { settled: 'settled' })).resolves.toEqual({ settled: 'settled', settledAt: 1_000 });
26
- await expect(store.update('s1', { settled: 'active' })).resolves.toEqual({ settled: 'active' });
27
- await expect(store.update('s1', { settled: null })).resolves.toBeNull();
38
+ await expect(store.update('s1', { snoozedUntil: 12_000 })).resolves.toEqual({ snoozedUntil: 12_000, snoozedAt: 2_000 });
39
+ await expect(store.update('s1', { snoozedUntil: null })).resolves.toBeNull();
28
40
  await expect(store.read()).resolves.toEqual({});
29
41
  });
30
42
 
31
- it('snoozing clears a settled override and settling clears a snooze', async () => {
32
- const { store, clock } = await createStore();
33
- await store.update('s1', { settled: 'settled' });
34
- clock.now = 5_000;
35
- await expect(store.update('s1', { snoozedUntil: 9_000 })).resolves.toEqual({ snoozedUntil: 9_000, snoozedAt: 5_000 });
36
- await expect(store.update('s1', { settled: 'settled' })).resolves.toEqual({ settled: 'settled', settledAt: 5_000 });
37
- await store.update('s2', { settled: 'active' });
38
- await expect(store.update('s2', { snoozedUntil: 9_000 })).resolves.toEqual({ settled: 'active', snoozedUntil: 9_000, snoozedAt: 5_000 });
39
- await expect(store.update('s2', { snoozedUntil: null })).resolves.toEqual({ settled: 'active' });
40
- });
41
-
42
- it('clears both on activity and on delete without touching other sessions', async () => {
43
+ it('clears on activity and on delete without touching other sessions', async () => {
43
44
  const { store } = await createStore();
44
45
  await store.update('s1', { snoozedUntil: 9_000 });
45
- await store.update('s2', { settled: 'settled' });
46
- await store.update('s3', { settled: 'active' });
46
+ await store.update('s2', { snoozedUntil: 9_000 });
47
+ await store.update('s3', { snoozedUntil: 9_000 });
47
48
  await expect(store.clearForActivity('s1')).resolves.toBeNull();
48
49
  await expect(store.clearForActivity('missing')).resolves.toBeNull();
49
50
  await store.remove('s2');
50
- await expect(store.read()).resolves.toEqual({ s3: { settled: 'active' } });
51
+ await expect(store.read()).resolves.toEqual({ s3: { snoozedUntil: 9_000, snoozedAt: 1_000 } });
51
52
  });
52
53
 
53
- it('rejects invalid requests', async () => {
54
+ it('rejects invalid requests, including the retired settled field', async () => {
54
55
  const { store } = await createStore();
55
56
  await expect(store.update('s1', {})).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' });
56
- await expect(store.update('s1', { settled: 'done' })).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' });
57
+ await expect(store.update('s1', { settled: 'settled' })).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' });
57
58
  await expect(store.update('s1', { snoozedUntil: -1 })).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' });
58
- await expect(store.update('s1', { settled: 'settled', snoozedUntil: 9_000 })).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' });
59
- await expect(store.update('__proto__', { settled: 'settled' })).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' });
59
+ await expect(store.update('__proto__', { snoozedUntil: 9_000 })).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' });
60
60
  });
61
61
 
62
62
  it('fails on malformed metadata instead of reading it as empty', async () => {
63
63
  const { store, file } = await createStore();
64
- await store.update('s1', { settled: 'settled' });
64
+ await store.update('s1', { snoozedUntil: 9_000 });
65
65
  await writeFile(file, 'not-json');
66
66
  await expect(store.read()).rejects.toMatchObject({ code: 'SESSION_SHELF_INVALID' });
67
- await writeFile(file, JSON.stringify({ s1: { settled: 'settled' } }));
67
+ await writeFile(file, JSON.stringify({ s1: { snoozedUntil: 9_000 } }));
68
68
  await expect(store.read()).rejects.toMatchObject({ code: 'SESSION_SHELF_INVALID' });
69
69
  // A failed read must not overwrite the file.
70
- await expect(store.update('s2', { settled: 'active' })).rejects.toMatchObject({ code: 'SESSION_SHELF_INVALID' });
71
- expect(JSON.parse(await readFile(file, 'utf8'))).toEqual({ s1: { settled: 'settled' } });
70
+ await expect(store.update('s2', { snoozedUntil: 9_000 })).rejects.toMatchObject({ code: 'SESSION_SHELF_INVALID' });
71
+ expect(JSON.parse(await readFile(file, 'utf8'))).toEqual({ s1: { snoozedUntil: 9_000 } });
72
+ });
73
+
74
+ describe('settled migration', () => {
75
+ it('archives hand-settled sessions at their settle time and drops the settled fields', async () => {
76
+ const { store, file, archive } = await createStore();
77
+ await writeLegacyShelf(file, {
78
+ settledOnly: { settled: 'settled', settledAt: 500 },
79
+ keptActive: { settled: 'active' },
80
+ keptActiveSnoozed: { settled: 'active', snoozedUntil: 9_000, snoozedAt: 700 },
81
+ snoozed: { snoozedUntil: 9_000, snoozedAt: 800 },
82
+ });
83
+
84
+ await expect(store.read()).resolves.toEqual({
85
+ keptActiveSnoozed: { snoozedUntil: 9_000, snoozedAt: 700 },
86
+ snoozed: { snoozedUntil: 9_000, snoozedAt: 800 },
87
+ });
88
+ await expect(archive.read()).resolves.toEqual({ settledOnly: 500 });
89
+ expect(JSON.parse(await readFile(file, 'utf8'))).toEqual({
90
+ keptActiveSnoozed: { snoozedUntil: 9_000, snoozedAt: 700 },
91
+ snoozed: { snoozedUntil: 9_000, snoozedAt: 800 },
92
+ });
93
+ });
94
+
95
+ it('keeps an existing archive time and leaves other archived sessions alone', async () => {
96
+ const { store, file, archive, archiveFile } = await createStore();
97
+ await mkdir(join(archiveFile, '..'), { recursive: true });
98
+ await writeFile(archiveFile, JSON.stringify({ settled: 300, other: 400 }));
99
+ await writeLegacyShelf(file, { settled: { settled: 'settled', settledAt: 500 } });
100
+ await store.read();
101
+ await expect(archive.read()).resolves.toEqual({ settled: 300, other: 400 });
102
+ });
103
+
104
+ it('runs once: an unarchive after the migration sticks', async () => {
105
+ const { store, file, archive } = await createStore();
106
+ await writeLegacyShelf(file, { s1: { settled: 'settled', settledAt: 500 } });
107
+ await store.read();
108
+ await archive.set('s1', false);
109
+ await store.read();
110
+ await store.update('s2', { snoozedUntil: 9_000 });
111
+ await expect(archive.read()).resolves.toEqual({});
112
+ });
113
+
114
+ it('keeps settled marks while the archive write fails, lets snooze writes through, and retries on the next read', async () => {
115
+ const real = createPiArchiveStore({ file: join(await mkdtemp(join(tmpdir(), 'pichamber-pi-archive-')), 'a.json') });
116
+ let failing = true;
117
+ const archiveStore = {
118
+ read: real.read,
119
+ set: real.set,
120
+ archiveMissing: async (entries) => {
121
+ if (failing) throw Object.assign(new Error('disk full'), { code: 'EIO' });
122
+ return real.archiveMissing(entries);
123
+ },
124
+ };
125
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
126
+ const { store, file, clock } = await createStore(undefined, { archiveStore });
127
+ const legacy = {
128
+ s1: { settled: 'settled', settledAt: 500 },
129
+ s2: { snoozedUntil: 9_000, snoozedAt: 800 },
130
+ s4: { settled: 'settled', settledAt: 600, snoozedUntil: 9_500, snoozedAt: 700 },
131
+ };
132
+ await writeLegacyShelf(file, legacy);
133
+
134
+ // Reads answer with the snooze state; the file keeps the legacy data.
135
+ await expect(store.read()).resolves.toEqual({
136
+ s2: { snoozedUntil: 9_000, snoozedAt: 800 },
137
+ s4: { snoozedUntil: 9_500, snoozedAt: 700 },
138
+ });
139
+ expect(JSON.parse(await readFile(file, 'utf8'))).toEqual(legacy);
140
+
141
+ // Snooze and wake still write and leave the settled fields as they
142
+ // were. A send or a delete drops that session's settled mark too, so
143
+ // the retried migration never archives a session the user just used.
144
+ clock.now = 2_000;
145
+ await expect(store.update('s3', { snoozedUntil: 9_000 })).resolves.toEqual({ snoozedUntil: 9_000, snoozedAt: 2_000 });
146
+ await expect(store.update('s1', { snoozedUntil: 8_000 })).resolves.toEqual({ snoozedUntil: 8_000, snoozedAt: 2_000 });
147
+ await expect(store.clearForActivity('s4')).resolves.toBeNull();
148
+ await expect(store.update('s2', { snoozedUntil: null })).resolves.toBeNull();
149
+ expect(JSON.parse(await readFile(file, 'utf8'))).toEqual({
150
+ s1: { settled: 'settled', settledAt: 500, snoozedUntil: 8_000, snoozedAt: 2_000 },
151
+ s3: { snoozedUntil: 9_000, snoozedAt: 2_000 },
152
+ });
153
+ await expect(real.read()).resolves.toEqual({});
154
+ expect(warn).toHaveBeenCalled();
155
+
156
+ failing = false;
157
+ await store.read();
158
+ await expect(real.read()).resolves.toEqual({ s1: 500 });
159
+ expect(JSON.parse(await readFile(file, 'utf8'))).toEqual({
160
+ s1: { snoozedUntil: 8_000, snoozedAt: 2_000 },
161
+ s3: { snoozedUntil: 9_000, snoozedAt: 2_000 },
162
+ });
163
+ warn.mockRestore();
164
+ });
165
+
166
+ it('migrates before a write so settled sessions are never dropped unarchived', async () => {
167
+ const { store, file, archive } = await createStore();
168
+ await writeLegacyShelf(file, { s1: { settled: 'settled', settledAt: 500 } });
169
+ await store.update('s2', { snoozedUntil: 9_000 });
170
+ await expect(archive.read()).resolves.toEqual({ s1: 500 });
171
+ expect(JSON.parse(await readFile(file, 'utf8'))).toEqual({ s2: { snoozedUntil: 9_000, snoozedAt: 1_000 } });
172
+ });
72
173
  });
73
174
  });