sideby 0.19.0 → 0.20.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 (161) hide show
  1. package/README.md +7 -4
  2. package/ai-tasks.json +28 -0
  3. package/dist/build.json +1 -1
  4. package/dist/src/cli/commands.d.ts +22 -1
  5. package/dist/src/cli/commands.js +815 -21
  6. package/dist/src/cli/format.d.ts +4 -0
  7. package/dist/src/cli/format.js +42 -4
  8. package/dist/src/cli/json-schemas.js +334 -4
  9. package/dist/src/cli/main.js +159 -13
  10. package/dist/src/core/accounts.d.ts +6 -0
  11. package/dist/src/core/accounts.js +12 -0
  12. package/dist/src/core/autostart.d.ts +11 -0
  13. package/dist/src/core/autostart.js +32 -5
  14. package/dist/src/core/browser-profiles.d.ts +23 -2
  15. package/dist/src/core/browser-profiles.js +148 -37
  16. package/dist/src/core/claude-settings-file.d.ts +18 -0
  17. package/dist/src/core/claude-settings-file.js +52 -3
  18. package/dist/src/core/config.d.ts +5 -0
  19. package/dist/src/core/config.js +12 -1
  20. package/dist/src/core/edit-settings.d.ts +7 -0
  21. package/dist/src/core/edit-settings.js +10 -5
  22. package/dist/src/core/file-memo.js +26 -4
  23. package/dist/src/core/history-group.d.ts +28 -0
  24. package/dist/src/core/history-group.js +47 -0
  25. package/dist/src/core/history-index.d.ts +145 -0
  26. package/dist/src/core/history-index.js +447 -0
  27. package/dist/src/core/history-project.d.ts +13 -0
  28. package/dist/src/core/history-project.js +87 -0
  29. package/dist/src/core/history.d.ts +210 -0
  30. package/dist/src/core/history.js +952 -0
  31. package/dist/src/core/inbound.d.ts +62 -0
  32. package/dist/src/core/inbound.js +215 -0
  33. package/dist/src/core/launch.d.ts +9 -1
  34. package/dist/src/core/launch.js +58 -24
  35. package/dist/src/core/live-sessions-copy.d.ts +5 -0
  36. package/dist/src/core/live-sessions-copy.js +46 -0
  37. package/dist/src/core/live-sessions-procs.d.ts +89 -0
  38. package/dist/src/core/live-sessions-procs.js +296 -0
  39. package/dist/src/core/live-sessions-title.d.ts +28 -0
  40. package/dist/src/core/live-sessions-title.js +80 -0
  41. package/dist/src/core/live-sessions.d.ts +68 -0
  42. package/dist/src/core/live-sessions.js +163 -0
  43. package/dist/src/core/login-check.d.ts +15 -0
  44. package/dist/src/core/login-check.js +32 -0
  45. package/dist/src/core/messages.d.ts +83 -0
  46. package/dist/src/core/messages.js +433 -0
  47. package/dist/src/core/project-categories.d.ts +14 -0
  48. package/dist/src/core/project-categories.js +48 -0
  49. package/dist/src/core/quota-fetch.d.ts +3 -3
  50. package/dist/src/core/quota-fetch.js +5 -5
  51. package/dist/src/core/quota-levels.d.ts +5 -0
  52. package/dist/src/core/quota-levels.js +5 -0
  53. package/dist/src/core/remote-control.d.ts +2 -0
  54. package/dist/src/core/remote-control.js +34 -59
  55. package/dist/src/core/run-link.d.ts +76 -0
  56. package/dist/src/core/run-link.js +245 -0
  57. package/dist/src/core/same-login.d.ts +4 -3
  58. package/dist/src/core/same-login.js +10 -7
  59. package/dist/src/core/session-select.d.ts +31 -0
  60. package/dist/src/core/session-select.js +44 -0
  61. package/dist/src/families/browser.d.ts +7 -18
  62. package/dist/src/families/browser.js +19 -8
  63. package/dist/src/families/claude/deliver.d.ts +2 -0
  64. package/dist/src/families/claude/deliver.js +43 -0
  65. package/dist/src/families/claude/history.d.ts +2 -0
  66. package/dist/src/families/claude/history.js +192 -0
  67. package/dist/src/families/claude/live-sessions.d.ts +13 -0
  68. package/dist/src/families/claude/live-sessions.js +117 -0
  69. package/dist/src/families/claude/messaging.d.ts +69 -0
  70. package/dist/src/families/claude/messaging.js +165 -0
  71. package/dist/src/families/claude/mod.d.ts +26 -0
  72. package/dist/src/families/claude/mod.js +105 -0
  73. package/dist/src/families/claude/session-files.d.ts +21 -0
  74. package/dist/src/families/claude/session-files.js +54 -0
  75. package/dist/src/families/codex/deliver.d.ts +5 -0
  76. package/dist/src/families/codex/deliver.js +76 -0
  77. package/dist/src/families/codex/history.d.ts +7 -0
  78. package/dist/src/families/codex/history.js +174 -0
  79. package/dist/src/families/codex/index.js +2 -0
  80. package/dist/src/families/codex/live-sessions.d.ts +12 -0
  81. package/dist/src/families/codex/live-sessions.js +193 -0
  82. package/dist/src/families/codex/quota.d.ts +3 -0
  83. package/dist/src/families/codex/quota.js +123 -0
  84. package/dist/src/families/codex/rate-limits.js +2 -0
  85. package/dist/src/families/codex/rollout.js +1 -1
  86. package/dist/src/families/grok/browser.d.ts +3 -0
  87. package/dist/src/families/grok/browser.js +5 -0
  88. package/dist/src/families/grok/history.d.ts +2 -0
  89. package/dist/src/families/grok/history.js +157 -0
  90. package/dist/src/families/grok/live-sessions.d.ts +4 -0
  91. package/dist/src/families/grok/live-sessions.js +80 -0
  92. package/dist/src/families/grok/login-key.d.ts +14 -0
  93. package/dist/src/families/grok/login-key.js +37 -0
  94. package/dist/src/families/history.d.ts +20 -0
  95. package/dist/src/families/history.js +81 -0
  96. package/dist/src/families/live-sessions.d.ts +26 -0
  97. package/dist/src/families/live-sessions.js +9 -0
  98. package/dist/src/families/login-keys.js +5 -1
  99. package/dist/src/families/messaging.d.ts +27 -0
  100. package/dist/src/families/messaging.js +6 -0
  101. package/dist/src/families/pi/history.d.ts +2 -0
  102. package/dist/src/families/pi/history.js +124 -0
  103. package/dist/src/families/pi/live-sessions.d.ts +2 -0
  104. package/dist/src/families/pi/live-sessions.js +70 -0
  105. package/dist/src/families/shared/history-text.d.ts +65 -0
  106. package/dist/src/families/shared/history-text.js +261 -0
  107. package/dist/src/menubar/hotkey.d.ts +86 -0
  108. package/dist/src/menubar/hotkey.js +159 -0
  109. package/dist/src/menubar/script.d.ts +2 -0
  110. package/dist/src/menubar/script.js +118 -22
  111. package/dist/src/menubar/snapshot.d.ts +8 -4
  112. package/dist/src/menubar/snapshot.js +45 -13
  113. package/dist/src/menubar/strings.d.ts +24 -6
  114. package/dist/src/menubar/strings.js +24 -6
  115. package/dist/src/panel/handler.d.ts +69 -0
  116. package/dist/src/panel/handler.js +686 -15
  117. package/dist/src/panel/i18n.d.ts +304 -3
  118. package/dist/src/panel/i18n.js +669 -67
  119. package/dist/src/panel/orca.d.ts +48 -0
  120. package/dist/src/panel/orca.js +153 -0
  121. package/dist/src/panel/page-logic.d.ts +255 -13
  122. package/dist/src/panel/page-logic.js +483 -1
  123. package/dist/src/panel/page-script.js +2265 -207
  124. package/dist/src/panel/page-styles.js +404 -32
  125. package/dist/src/panel/page.js +1 -0
  126. package/dist/src/plugins/account-script.js +61 -27
  127. package/dist/src/plugins/check.js +16 -4
  128. package/dist/src/plugins/loader.d.ts +8 -1
  129. package/dist/src/plugins/loader.js +72 -7
  130. package/dist/src/runtime.d.ts +5 -0
  131. package/dist/src/runtime.js +27 -5
  132. package/dist/src/types.d.ts +116 -1
  133. package/dist/testing/index.d.ts +5 -0
  134. package/dist/testing/index.js +5 -0
  135. package/mods/claude/.claude-plugin/plugin.json +7 -0
  136. package/mods/claude/hooks/hooks.json +1 -0
  137. package/mods/claude/hooks/register.js +261 -0
  138. package/package.json +5 -2
  139. package/schemas/autostart.json +74 -1
  140. package/schemas/browser-set.json +110 -0
  141. package/schemas/browser.json +22 -2
  142. package/schemas/config.json +26 -1
  143. package/schemas/history-index.json +209 -0
  144. package/schemas/history-projects.json +133 -0
  145. package/schemas/history-show.json +275 -0
  146. package/schemas/history.json +410 -0
  147. package/schemas/menubar-hotkey.json +139 -0
  148. package/schemas/menubar-snapshot.json +36 -2
  149. package/schemas/menubar.json +74 -1
  150. package/schemas/messages-inbound.json +258 -0
  151. package/schemas/messages.json +164 -0
  152. package/schemas/send.json +165 -0
  153. package/schemas/sessions-copy.json +113 -0
  154. package/schemas/sessions-open-run.json +97 -0
  155. package/schemas/sessions.json +237 -0
  156. package/skills/sideby/SKILL.md +10 -5
  157. package/skills/sideby/references/accounts.md +11 -0
  158. package/skills/sideby/references/ai-tasks.md +17 -1
  159. package/skills/sideby/references/panel.md +6 -4
  160. package/skills/sideby/references/quota.md +2 -2
  161. package/skills/sideby/references/sessions.md +79 -0
@@ -1,7 +1,7 @@
1
1
  // Browser Sign-ins (spec §3.24, ADR-0023): which Browser Profile of Google Chrome signed in to each Account's vendor
2
2
  // website, from Chrome's local data on this computer only. Read-only: `Local State` gives each profile's folder,
3
3
  // display name and the email of the Google account it is signed in to Chrome with, `Local Storage/leveldb` the key
4
- // names of claude.ai and chatgpt.com (core/leveldb-keys.ts). Never Cookies, Login Data, IndexedDB or the Keychain,
4
+ // names of each Family website's origin (core/leveldb-keys.ts). Never Cookies, Login Data, IndexedDB or the Keychain,
5
5
  // never a value, never the network. The Host-side id each match needs (families/browser.ts) is compared in memory
6
6
  // and never leaves this module. Opening a website starts Chrome unchanged with `open`, through `DesktopDeps.exec`,
7
7
  // so tests never start a real browser. On WSL the Chrome is the one installed on Windows: its folders come from one
@@ -12,6 +12,7 @@ import { matchedOrigins, websiteDef } from '../families/browser.js';
12
12
  import { editConfigBrowser } from './config.js';
13
13
  import { depsFor, findApp } from './desktop-app.js';
14
14
  import { UserError } from './errors.js';
15
+ import { cleanEmail } from './identity.js';
15
16
  import { localStorageKeys } from './leveldb-keys.js';
16
17
  import { askWindowsDirs } from './windows-dirs.js';
17
18
  const OPEN = '/usr/bin/open';
@@ -134,8 +135,9 @@ async function profileKeys(dir, origins) {
134
135
  keyMemo.set(dir, { sig, value });
135
136
  return value;
136
137
  }
137
- const BOUNDARY = /[A-Za-z0-9_]/;
138
- /** `id` appears in `key` as a whole segment: not glued to another letter, digit or underscore. */
138
+ // `_` separates, as in cursor.com's `radar_last_evaluated_<id>`; ids that hold one (`user_…`) still match whole.
139
+ const BOUNDARY = /[A-Za-z0-9]/;
140
+ /** `id` appears in `key` as a whole segment: not glued to another letter or digit. */
139
141
  export function keyHasId(key, id) {
140
142
  const k = key.toLowerCase();
141
143
  const i0 = id.toLowerCase();
@@ -147,22 +149,23 @@ export function keyHasId(key, id) {
147
149
  }
148
150
  return false;
149
151
  }
150
- /** Accounts that a Browser Sign-in can apply to: Subscription Accounts of built-in Families with a website. */
152
+ /** Accounts that a Browser Sign-in can apply to: Subscription Accounts of Families with a website. */
151
153
  function eligible(rt, accounts) {
152
- return accounts.filter((a) => a.kind !== 'api' &&
153
- websiteDef(a.family) &&
154
- rt.plugins.some((p) => p.source === 'builtin' && p.families.includes(a.family)));
154
+ return accounts.filter((a) => a.kind !== 'api' && websiteDef(rt.families, a.family));
155
155
  }
156
+ /** Shorter ids would match key names by chance. */
157
+ const MIN_SIGN_IN_ID = 8;
156
158
  /** The Browser Report for `sideby browser` and the Panel. Reads nothing of the browser while it is off. */
157
159
  export async function browserReport(rt, accounts) {
158
160
  const enabled = rt.config.browser?.signIns === true;
159
161
  const list = eligible(rt, accounts);
160
162
  const fams = [...new Set(list.map((a) => a.family))];
161
163
  const families = {
162
- matched: fams.filter((f) => websiteDef(f)?.match),
163
- openOnly: fams.filter((f) => !websiteDef(f)?.match),
164
+ matched: fams.filter((f) => websiteDef(rt.families, f)?.match),
165
+ openOnly: fams.filter((f) => !websiteDef(rt.families, f)?.match),
164
166
  };
165
- const base = { enabled, browser: CHROME.title, families };
167
+ const sites = Object.fromEntries(fams.map((f) => [f, websiteDef(rt.families, f)?.url ?? '']));
168
+ const base = { enabled, browser: CHROME.title, families, sites, choices: {} };
166
169
  if (!enabled)
167
170
  return { ...base, found: false, profiles: [], problems: [] };
168
171
  const problems = [];
@@ -174,12 +177,22 @@ export async function browserReport(rt, accounts) {
174
177
  return { ...base, found: false, profiles: [], problems };
175
178
  const ids = [];
176
179
  for (const a of list) {
177
- const m = websiteDef(a.family)?.match;
178
- const id = m ? await m.signInId(a) : undefined;
179
- if (m && id)
180
- ids.push({ ref: a.ref, origin: m.origin, id });
180
+ const m = websiteDef(rt.families, a.family)?.match;
181
+ if (!m)
182
+ continue;
183
+ let id;
184
+ try {
185
+ id = await m.signInId(a);
186
+ }
187
+ catch {
188
+ // A plugin's reader may fail; its message could quote the login file, so only the Family is named.
189
+ problems.push(`${a.ref}: the ${a.family} family could not read its sign-in id`);
190
+ continue;
191
+ }
192
+ if (typeof id === 'string' && id.trim().length >= MIN_SIGN_IN_ID)
193
+ ids.push({ ref: a.ref, origin: m.origin, id: id.trim() });
181
194
  }
182
- const origins = matchedOrigins();
195
+ const origins = matchedOrigins(rt.families);
183
196
  const read = [];
184
197
  for (const e of entries) {
185
198
  const r = await profileKeys(join(userData, e.dir, 'Local Storage', 'leveldb'), origins);
@@ -209,8 +222,66 @@ export async function browserReport(rt, accounts) {
209
222
  ...(changedAt ? { changedAt } : {}),
210
223
  };
211
224
  });
225
+ await narrowByEmail(rt, list, profiles);
226
+ const choices = applyChoices(rt, list, profiles, problems);
212
227
  profiles.sort((a, b) => (b.changedAt ?? '').localeCompare(a.changedAt ?? '') || a.dir.localeCompare(b.dir));
213
- return { ...base, found: true, profiles, problems };
228
+ return { ...base, choices, found: true, profiles, problems };
229
+ }
230
+ /** The login email of an Account, lower case, from its Family's identity reader; undefined on any problem. */
231
+ async function loginEmail(rt, account) {
232
+ try {
233
+ return cleanEmail((await rt.families.get(account.family)?.identity?.(account))?.email)?.toLowerCase();
234
+ }
235
+ catch {
236
+ return undefined;
237
+ }
238
+ }
239
+ /**
240
+ * A website keeps the keys of every login a browser user ever had, so one Account can show up in several (spec §3.24
241
+ * "按 Google 账号收窄"). Where some of them use the Account's login email as their Google account in Chrome, only those
242
+ * are kept. An Account found nowhere gets the one browser user, if exactly one, whose Google account is its login.
243
+ */
244
+ async function narrowByEmail(rt, list, profiles) {
245
+ for (const a of list) {
246
+ const email = await loginEmail(rt, a);
247
+ if (!email)
248
+ continue;
249
+ const same = (p) => p.email?.toLowerCase() === email;
250
+ const found = profiles.filter((p) => p.signIns.includes(a.ref));
251
+ if (found.length > 1 && found.some(same)) {
252
+ for (const p of found)
253
+ if (!same(p))
254
+ p.signIns = p.signIns.filter((r) => r !== a.ref);
255
+ }
256
+ else if (!found.length) {
257
+ const only = profiles.filter(same);
258
+ if (only.length === 1)
259
+ only[0].signIns.push(a.ref);
260
+ }
261
+ }
262
+ }
263
+ /**
264
+ * The user's own choice (config `browser.choices`) replaces what was found: the Account is in that profile's
265
+ * `signIns` alone. A choice whose folder is gone is skipped with a problem, and the Account is found as usual.
266
+ */
267
+ function applyChoices(rt, list, profiles, problems) {
268
+ const out = {};
269
+ const chosen = rt.config.browser?.choices ?? {};
270
+ for (const a of list) {
271
+ const dir = chosen[a.ref];
272
+ if (!dir)
273
+ continue;
274
+ const p = profiles.find((x) => x.dir === dir);
275
+ if (!p) {
276
+ problems.push(`the browser user chosen for ${a.ref} (${dir}) is gone; finding it again (\`sideby browser set ${a.ref} --auto\` clears the choice)`);
277
+ continue;
278
+ }
279
+ for (const x of profiles)
280
+ x.signIns = x.signIns.filter((r) => r !== a.ref);
281
+ p.signIns.push(a.ref);
282
+ out[a.ref] = dir;
283
+ }
284
+ return out;
214
285
  }
215
286
  /**
216
287
  * Opens an Account's vendor website in one Browser Profile: the one given (folder or name), else the only profile
@@ -220,10 +291,10 @@ export async function browserReport(rt, accounts) {
220
291
  export async function openInBrowser(rt, account, profile) {
221
292
  const deps = depsFor(rt);
222
293
  if (deps.platform !== 'darwin' && !deps.wslMount)
223
- throw new UserError(`opening a browser user works on macOS and WSL only for now (this is ${deps.platform}); open ${websiteDef(account.family)?.url ?? 'the website'} yourself`, { code: 'unsupported' });
224
- const site = websiteDef(account.family);
294
+ throw new UserError(`opening a browser user works on macOS and WSL only for now (this is ${deps.platform}); open ${websiteDef(rt.families, account.family)?.url ?? 'the website'} yourself`, { code: 'unsupported' });
295
+ const site = websiteDef(rt.families, account.family);
225
296
  if (!site || account.kind === 'api' || !eligible(rt, [account]).length)
226
- throw new UserError(`${account.ref} has no website to open; only Claude, Codex and Grok subscription accounts do`, {
297
+ throw new UserError(`${account.ref} has no website to open; only subscription accounts of Claude, Codex, Grok and plugin families that set \`website\` do`, {
227
298
  code: 'no-website',
228
299
  });
229
300
  const problems = [];
@@ -238,20 +309,11 @@ export async function openInBrowser(rt, account, profile) {
238
309
  code: 'no-profiles',
239
310
  });
240
311
  let pick;
241
- if (profile) {
242
- pick = entries.find((e) => e.dir === profile);
243
- if (!pick) {
244
- const p = profile.toLowerCase();
245
- const byName = entries.filter((e) => e.name.toLowerCase() === p);
246
- if (!byName.length)
247
- byName.push(...entries.filter((e) => e.email?.toLowerCase() === p));
248
- if (byName.length > 1)
249
- throw new UserError(`several browser users are named "${profile}"; pass the folder instead: ${byName.map((e) => e.dir).join(', ')}`, { code: 'profile-ambiguous' });
250
- pick = byName[0];
251
- }
252
- if (!pick)
253
- throw new UserError(`no browser user "${profile}"; choose one of: ${entries.map((e) => `${e.name} (${e.dir})`).join(', ')}`, { code: 'profile-unknown' });
254
- }
312
+ const chosen = entries.find((e) => e.dir === rt.config.browser?.choices?.[account.ref]);
313
+ if (profile)
314
+ pick = findProfile(entries, profile);
315
+ else if (chosen)
316
+ pick = chosen;
255
317
  else {
256
318
  const report = rt.config.browser?.signIns === true ? await browserReport(rt, [account]) : undefined;
257
319
  const found = report?.profiles.filter((p) => p.signIns.includes(account.ref)) ?? [];
@@ -266,11 +328,12 @@ export async function openInBrowser(rt, account, profile) {
266
328
  const choices = (found.length ? found : entries).map((e) => `${e.name} (${e.dir})`).join(', ');
267
329
  throw new UserError(`${why}; pass --profile with one of: ${choices}`, { code: 'profile-needed' });
268
330
  }
269
- pick = entries.find((e) => e.dir === found[0]?.dir);
270
- if (!pick)
331
+ const only = entries.find((e) => e.dir === found[0]?.dir);
332
+ if (!only)
271
333
  throw new UserError('that browser user is gone; run `sideby browser` again', {
272
334
  code: 'profile-unknown',
273
335
  });
336
+ pick = only;
274
337
  }
275
338
  const [cmd, ...args] = launch.command(`--profile-directory=${pick.dir}`, site.url);
276
339
  const r = await deps.exec(cmd, args);
@@ -283,6 +346,54 @@ export async function openInBrowser(rt, account, profile) {
283
346
  command: [cmd, ...args],
284
347
  };
285
348
  }
349
+ /** The browser user `profile` names: its folder, else its name or Google account, which must be unique. */
350
+ function findProfile(entries, profile) {
351
+ const byDir = entries.find((e) => e.dir === profile);
352
+ if (byDir)
353
+ return byDir;
354
+ const p = profile.toLowerCase();
355
+ const byName = entries.filter((e) => e.name.toLowerCase() === p);
356
+ if (!byName.length)
357
+ byName.push(...entries.filter((e) => e.email?.toLowerCase() === p));
358
+ if (byName.length > 1)
359
+ throw new UserError(`several browser users are named "${profile}"; pass the folder instead: ${byName.map((e) => e.dir).join(', ')}`, { code: 'profile-ambiguous' });
360
+ if (!byName[0])
361
+ throw new UserError(`no browser user "${profile}"; choose one of: ${entries.map((e) => `${e.name} (${e.dir})`).join(', ')}`, { code: 'profile-unknown' });
362
+ return byName[0];
363
+ }
364
+ /**
365
+ * `sideby browser set` and the Panel (spec §3.24 "手动指定"): remembers which Chrome browser user is an Account's, in
366
+ * config `browser.choices`, or with `profile` null forgets it so sideby finds it again. Only sideby's config is written.
367
+ */
368
+ export async function setBrowserChoice(rt, account, profile) {
369
+ if (!websiteDef(rt.families, account.family) || account.kind === 'api' || !eligible(rt, [account]).length)
370
+ throw new UserError(`${account.ref} has no website; only subscription accounts of Claude, Codex, Grok and plugin families that set \`website\` have a browser user`, { code: 'no-website' });
371
+ let pick;
372
+ if (profile !== null) {
373
+ const problems = [];
374
+ const deps = depsFor(rt);
375
+ const userData = deps.platform === 'darwin' || deps.wslMount ? await userDataFor(rt, deps, problems) : null;
376
+ const entries = userData ? ((await profileEntries(userData, problems)) ?? []) : [];
377
+ if (!entries.length)
378
+ throw new UserError(`${CHROME.title} has no browser users on this computer yet; open it once, then try again`, {
379
+ code: 'no-profiles',
380
+ });
381
+ pick = findProfile(entries, profile);
382
+ }
383
+ const r = await editConfigBrowser(rt.paths.configFile, (cur) => {
384
+ const choices = { ...cur.choices };
385
+ if (pick)
386
+ choices[account.ref] = pick.dir;
387
+ else
388
+ delete choices[account.ref];
389
+ const next = { ...cur, choices };
390
+ if (!Object.keys(choices).length)
391
+ delete next.choices;
392
+ return next;
393
+ });
394
+ rt.config.browser = r.after;
395
+ return { ref: account.ref, profile: pick ? { dir: pick.dir, name: pick.name } : null, changed: r.changed };
396
+ }
286
397
  /** How to start Chrome here: `open` on macOS, `cmd.exe /c start` with Windows' chrome.exe on WSL; null when absent. */
287
398
  async function chromeLauncher(deps, problems) {
288
399
  if (deps.platform === 'darwin') {
@@ -313,8 +424,8 @@ async function chromeLauncher(deps, problems) {
313
424
  /** What turning Browser Sign-ins on reads, for the confirmation in the CLI and the Panel. */
314
425
  export const BROWSER_READS = [
315
426
  "the name of each Google Chrome browser user and the Google account email it uses in Chrome (from Chrome's Local State)",
316
- 'the key names claude.ai and chatgpt.com keep in each browser user’s Local Storage, never their values',
317
- 'the account id in each Claude and Codex login file, only to compare; it is never shown or saved',
427
+ 'the key names claude.ai, chatgpt.com, grok.com and the websites of plugin tools that declare one keep in each browser user’s Local Storage, never their values',
428
+ 'the account id in each Claude, Codex and Grok login file, and the one a plugin tool reads from its own, only to compare; it is never shown or saved',
318
429
  ];
319
430
  /** Turns Browser Sign-ins on or off in config `browser.signIns`; without `apply`, shows the change only. */
320
431
  export async function setBrowserSignIns(rt, on, opts) {
@@ -15,3 +15,21 @@ export declare function locate(account: Account): Promise<{
15
15
  exists: boolean;
16
16
  broken?: boolean;
17
17
  }>;
18
+ /** The Claude Accounts of `accounts` grouped by the real file their `settings.json` is (a link joins its target's). */
19
+ export declare function settingsFileGroups(accounts: readonly Account[]): Promise<{
20
+ file: string;
21
+ accounts: string[];
22
+ where: Awaited<ReturnType<typeof locate>>;
23
+ }[]>;
24
+ /**
25
+ * Rewrites one settings file through `writeIfUnchanged`, keeping its mode, every other key and its indentation.
26
+ * `expect` refuses with a message when the file no longer holds what the change assumed. Returns null when written,
27
+ * else what went wrong in plain words.
28
+ */
29
+ export declare function writeSettingsKey(file: string, change: (obj: Json) => Json, expect: (obj: Json) => string | null): Promise<string | null>;
30
+ /** Where sideby keeps the undo record of one key it wrote in `file`: `<state>/<dir>/<hash of file>.json`. */
31
+ export declare const keyRecordPath: (stateDir: string, dir: string, file: string) => string;
32
+ /** Writes an undo record (mode 600) under the state directory. */
33
+ export declare function writeKeyRecord(stateDir: string, dir: string, file: string, record: object): Promise<void>;
34
+ /** The parsed undo record of `file`, or null when there is none or it does not name `file`. */
35
+ export declare function readKeyRecord(stateDir: string, dir: string, file: string): Promise<Json | null>;
@@ -1,8 +1,9 @@
1
1
  // One Claude Account's `settings.json`, as the writers of a single key use it (tune apply, ADR-0012; Remote Control,
2
- // ADR-0017): where it really lives, a safe read, and rendering it back with the file's own indentation.
3
- import { readFile, stat } from 'node:fs/promises';
2
+ // ADR-0017; Cross-session inbound, ADR-0040): where it really lives, a safe read, rendering it back with the file's
3
+ // own indentation, the write of one key and its undo record.
4
+ import { mkdir, readFile, stat } from 'node:fs/promises';
4
5
  import { join } from 'node:path';
5
- import { lstatOrNull, realpathOrNull } from './fs-safe.js';
6
+ import { lstatOrNull, realpathOrNull, sha256, writeFileAtomic, writeIfUnchanged } from './fs-safe.js';
6
7
  const MAX_BYTES = 5_000_000;
7
8
  export const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
8
9
  function detectIndent(text) {
@@ -51,3 +52,51 @@ export async function locate(account) {
51
52
  ? { file: real, link: true, exists: true }
52
53
  : { file: path, link: true, exists: false, broken: true };
53
54
  }
55
+ /** The Claude Accounts of `accounts` grouped by the real file their `settings.json` is (a link joins its target's). */
56
+ export async function settingsFileGroups(accounts) {
57
+ const byFile = new Map();
58
+ for (const account of accounts) {
59
+ if (account.family !== 'claude')
60
+ continue;
61
+ const where = await locate(account);
62
+ const have = byFile.get(where.file);
63
+ if (have)
64
+ have.accounts.push(account.ref);
65
+ else
66
+ byFile.set(where.file, { file: where.file, accounts: [account.ref], where });
67
+ }
68
+ return [...byFile.values()];
69
+ }
70
+ /**
71
+ * Rewrites one settings file through `writeIfUnchanged`, keeping its mode, every other key and its indentation.
72
+ * `expect` refuses with a message when the file no longer holds what the change assumed. Returns null when written,
73
+ * else what went wrong in plain words.
74
+ */
75
+ export async function writeSettingsKey(file, change, expect) {
76
+ const read = await readObject(file);
77
+ if ('error' in read)
78
+ return `settings.json cannot be changed safely: ${read.error}.`;
79
+ const refused = expect(read.obj);
80
+ if (refused)
81
+ return refused;
82
+ const mode = (await stat(file)).mode & 0o777;
83
+ const wrote = await writeIfUnchanged(file, sha256(read.text), render(change({ ...read.obj }), read.text), mode);
84
+ return wrote ? null : 'settings.json changed while sideby was writing, so nothing was changed. Try again.';
85
+ }
86
+ /** Where sideby keeps the undo record of one key it wrote in `file`: `<state>/<dir>/<hash of file>.json`. */
87
+ export const keyRecordPath = (stateDir, dir, file) => join(stateDir, dir, `${sha256(file).slice(0, 16)}.json`);
88
+ /** Writes an undo record (mode 600) under the state directory. */
89
+ export async function writeKeyRecord(stateDir, dir, file, record) {
90
+ await mkdir(join(stateDir, dir), { recursive: true });
91
+ await writeFileAtomic(keyRecordPath(stateDir, dir, file), `${JSON.stringify(record, null, 2)}\n`, 0o600);
92
+ }
93
+ /** The parsed undo record of `file`, or null when there is none or it does not name `file`. */
94
+ export async function readKeyRecord(stateDir, dir, file) {
95
+ try {
96
+ const r = JSON.parse(await readFile(keyRecordPath(stateDir, dir, file), 'utf8'));
97
+ return isObj(r) && r.file === file ? r : null;
98
+ }
99
+ catch {
100
+ return null;
101
+ }
102
+ }
@@ -64,6 +64,7 @@ export declare const ConfigSchema: Type.TObject<{
64
64
  credential: Type.TOptional<Type.TBoolean>;
65
65
  }>>>>;
66
66
  accountTitle: Type.TOptional<Type.TBoolean>;
67
+ claudeMod: Type.TOptional<Type.TBoolean>;
67
68
  resumeRouting: Type.TOptional<Type.TBoolean>;
68
69
  handoff: Type.TOptional<Type.TObject<{
69
70
  auto: Type.TOptional<Type.TBoolean>;
@@ -83,8 +84,12 @@ export declare const ConfigSchema: Type.TObject<{
83
84
  check: Type.TOptional<Type.TBoolean>;
84
85
  auto: Type.TOptional<Type.TBoolean>;
85
86
  }>>;
87
+ history: Type.TOptional<Type.TObject<{
88
+ index: Type.TOptional<Type.TBoolean>;
89
+ }>>;
86
90
  browser: Type.TOptional<Type.TObject<{
87
91
  signIns: Type.TOptional<Type.TBoolean>;
92
+ choices: Type.TOptional<Type.TRecord<"^.*$", Type.TString>>;
88
93
  }>>;
89
94
  display: Type.TOptional<Type.TObject<{
90
95
  families: Type.TOptional<Type.TArray<Type.TString>>;
@@ -94,7 +94,7 @@ export const ConfigSchema = Type.Object({
94
94
  menubar: Type.Optional(Type.Object({
95
95
  hotkey: Type.Optional(Type.String({
96
96
  pattern: '^(off|((ctrl|opt|cmd|shift)\\+)+[a-z0-9])$',
97
- description: 'The shortcut that opens the menu bar item from anywhere, such as `opt+cmd+s` (default), or `off`.',
97
+ description: 'The shortcut that opens the menu bar item from anywhere, such as `opt+x` (default), or `off`.',
98
98
  })),
99
99
  }, { additionalProperties: false, description: 'The Menu Bar Item on macOS (spec §3.31).' })),
100
100
  terminal: Type.Optional(Type.Object({
@@ -143,6 +143,9 @@ export const ConfigSchema = Type.Object({
143
143
  accountTitle: Type.Optional(Type.Boolean({
144
144
  description: 'Set the terminal title to `[<short command or account>]` when sideby starts an Account, and keep Hosts that allow it (Codex) from replacing it. Off by default.',
145
145
  })),
146
+ claudeMod: Type.Optional(Type.Boolean({
147
+ description: "Load sideby's Claude Code mod (`--plugin-dir`, Claude Code 2.1.287 or later) when sideby starts a Claude Code account: a band with the Session Label, a toast when a Message arrives and a `/sessions` pane. On by default; false turns it off.",
148
+ })),
146
149
  resumeRouting: Type.Optional(Type.Boolean({
147
150
  description: 'Make `sideby shell-init` also define Host-named functions (`claude`, `codex`, `grok`) that resume a session by id in the Account that holds it. Off by default.',
148
151
  })),
@@ -155,10 +158,18 @@ export const ConfigSchema = Type.Object({
155
158
  description: 'Install a newer version by itself after a check, when no `sideby run` is running and the version is not a major one. Off by default.',
156
159
  })),
157
160
  }, { additionalProperties: false, description: 'Update Check and Auto Update (ADR-0021).' })),
161
+ history: Type.Optional(Type.Object({
162
+ index: Type.Optional(Type.Boolean({
163
+ description: "Keep a local History Index of every Session's title, Project, typed prompts and model replies (never tool output) in sideby's state folder, so Session History opens and searches at once. On by default; false stops it and deletes the index.",
164
+ })),
165
+ }, { additionalProperties: false, description: 'Session History (spec §3.33, ADR-0042).' })),
158
166
  browser: Type.Optional(Type.Object({
159
167
  signIns: Type.Optional(Type.Boolean({
160
168
  description: "Look in Google Chrome's local data for which browser user signed in to each Account's website (key names only, never cookies or passwords; nothing leaves this computer). Off by default.",
161
169
  })),
170
+ choices: Type.Optional(Type.Record(Type.String({ pattern: '^[a-z0-9][a-z0-9-]*:[a-z0-9][a-z0-9-]*$' }), Type.String({ pattern: '^[\\w .-]{1,64}$' }), {
171
+ description: 'The Chrome browser user (its folder, such as `Profile 7`) the user chose for an Account, by ref. It replaces what sideby found for that Account; set with `sideby browser set` or the Panel.',
172
+ })),
162
173
  }, { additionalProperties: false, description: 'Browser Sign-ins (spec §3.24, ADR-0023).' })),
163
174
  display: Type.Optional(Type.Object({
164
175
  families: Type.Optional(Type.Array(Type.String({ minLength: 1 }), {
@@ -22,3 +22,10 @@ export declare function hostSettingsFile(def: Pick<FamilyDef, 'settingsFile'> |
22
22
  export declare function editSettings(rt: Runtime, ref: string, opts?: {
23
23
  open?: boolean;
24
24
  }): Promise<EditSettingsResult>;
25
+ /**
26
+ * Opens `file` with the system's default program (on macOS its default text editor, unless `text` is false);
27
+ * returns the command, or throws what to do instead.
28
+ */
29
+ export declare function openWithDefault(rt: Runtime, file: string, opts?: {
30
+ text?: boolean;
31
+ }): Promise<string[]>;
@@ -55,15 +55,20 @@ export async function editSettings(rt, ref, opts = {}) {
55
55
  return { ...base, opened: false };
56
56
  return { ...base, opened: true, command: await openWithDefault(rt, real) };
57
57
  }
58
- /** Opens `file` with the system's default program; returns the command, or throws what to do instead. */
59
- async function openWithDefault(rt, file) {
58
+ /**
59
+ * Opens `file` with the system's default program (on macOS its default text editor, unless `text` is false);
60
+ * returns the command, or throws what to do instead.
61
+ */
62
+ export async function openWithDefault(rt, file, opts = {}) {
60
63
  const deps = depsFor(rt);
61
- const yourself = `open ${file} in your editor yourself`;
64
+ const text = opts.text !== false;
65
+ const yourself = text ? `open ${file} in your editor yourself` : `open ${file} in your browser yourself`;
62
66
  if (deps.platform === 'darwin') {
63
- const r = await deps.exec('/usr/bin/open', ['-t', file]);
67
+ const args = text ? ['-t', file] : [file];
68
+ const r = await deps.exec('/usr/bin/open', args);
64
69
  if (r.code !== 0)
65
70
  throw new UserError(`macOS could not open the file; ${yourself}`, { code: 'open-failed' });
66
- return ['/usr/bin/open', '-t', file];
71
+ return ['/usr/bin/open', ...args];
67
72
  }
68
73
  if (deps.platform === 'linux' && deps.wslMount) {
69
74
  const w = await deps.exec('wslpath', ['-w', file]);
@@ -5,6 +5,11 @@ export function fileSignature(st) {
5
5
  export const persistedMemos = new Map();
6
6
  export class FileMemo {
7
7
  #scopes = new Map();
8
+ /**
9
+ * Parses running now, by scope and path: a second reader of the same file version (two passes at once, such as an
10
+ * Account's own identity and the Same Login check) waits for that parse instead of starting another.
11
+ */
12
+ #running = new Map();
8
13
  /** Counters for tests and timing. */
9
14
  stats = { hits: 0, misses: 0 };
10
15
  /** True when a pass changed what is remembered since the last `dump`. */
@@ -29,11 +34,28 @@ export class FileMemo {
29
34
  seen.set(path, hit);
30
35
  return hit.value;
31
36
  }
37
+ const key = `${scope}\0${path}`;
38
+ const running = this.#running.get(key);
39
+ if (running && running.sig === sig) {
40
+ this.stats.hits++;
41
+ const value = await running.value;
42
+ if (!keep || keep(value))
43
+ seen.set(path, { sig, value });
44
+ return value;
45
+ }
32
46
  this.stats.misses++;
33
- const value = await parse();
34
- if (!keep || keep(value))
35
- seen.set(path, { sig, value });
36
- return value;
47
+ const started = parse();
48
+ this.#running.set(key, { sig, value: started });
49
+ try {
50
+ const value = await started;
51
+ if (!keep || keep(value))
52
+ seen.set(path, { sig, value });
53
+ return value;
54
+ }
55
+ finally {
56
+ if (this.#running.get(key)?.value === started)
57
+ this.#running.delete(key);
58
+ }
37
59
  },
38
60
  done: () => {
39
61
  if (!before || before.size !== seen.size || [...seen].some(([k, v]) => before.get(k) !== v))
@@ -0,0 +1,28 @@
1
+ import type { Outline } from './history-index.ts';
2
+ export type GroupBy = 'project' | 'category' | 'account' | 'family' | 'day' | 'none';
3
+ export declare const GROUP_BYS: readonly GroupBy[];
4
+ /** Day groups, newest first. */
5
+ export declare const DAY_GROUPS: readonly ['today', 'yesterday', 'week', 'month', 'older'];
6
+ export interface GroupItem extends Outline {
7
+ /** Higher first: the ranked score when searching, else the last activity. */
8
+ score: number;
9
+ }
10
+ export interface GroupCount {
11
+ key: string;
12
+ sessions: number;
13
+ /** Newest last activity in the group, ms. */
14
+ updatedAt: number;
15
+ }
16
+ /** The day group of a time: today, yesterday, the last 7 days, the last 30 days, or older, by local midnight. */
17
+ export declare function dayGroup(t: number, now?: Date): (typeof DAY_GROUPS)[number];
18
+ /**
19
+ * Orders `items` group by group: groups by their best score (or in the order of `fixed`, as days are), the group
20
+ * without a key ('') last; inside a group by score. Returns the groups with their counts and the items outside
21
+ * `collapsed`, in order.
22
+ */
23
+ export declare function orderGroups(items: GroupItem[], keyOf: (o: Outline) => string, collapsed?: ReadonlySet<string>, fixed?: readonly string[]): {
24
+ groups: GroupCount[];
25
+ items: (GroupItem & {
26
+ group: string;
27
+ })[];
28
+ };
@@ -0,0 +1,47 @@
1
+ export const GROUP_BYS = ['project', 'category', 'account', 'family', 'day', 'none'];
2
+ /** Day groups, newest first. */
3
+ export const DAY_GROUPS = ['today', 'yesterday', 'week', 'month', 'older'];
4
+ /** The day group of a time: today, yesterday, the last 7 days, the last 30 days, or older, by local midnight. */
5
+ export function dayGroup(t, now = new Date()) {
6
+ const midnight = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
7
+ const daysAgo = (n) => new Date(now.getFullYear(), now.getMonth(), now.getDate() - n).getTime();
8
+ if (t >= midnight)
9
+ return 'today';
10
+ if (t >= daysAgo(1))
11
+ return 'yesterday';
12
+ if (t >= daysAgo(7))
13
+ return 'week';
14
+ if (t >= daysAgo(30))
15
+ return 'month';
16
+ return 'older';
17
+ }
18
+ /**
19
+ * Orders `items` group by group: groups by their best score (or in the order of `fixed`, as days are), the group
20
+ * without a key ('') last; inside a group by score. Returns the groups with their counts and the items outside
21
+ * `collapsed`, in order.
22
+ */
23
+ export function orderGroups(items, keyOf, collapsed = new Set(), fixed) {
24
+ const stats = new Map();
25
+ const keyed = items.map((it) => {
26
+ const group = keyOf(it);
27
+ const s = stats.get(group);
28
+ if (s) {
29
+ s.sessions++;
30
+ s.best = Math.max(s.best, it.score);
31
+ s.updatedAt = Math.max(s.updatedAt, it.updatedAt);
32
+ }
33
+ else
34
+ stats.set(group, { key: group, sessions: 1, best: it.score, updatedAt: it.updatedAt });
35
+ return { ...it, group };
36
+ });
37
+ const order = [...stats.values()].sort((a, b) => Number(a.key === '') - Number(b.key === '') ||
38
+ (fixed ? fixed.indexOf(a.key) - fixed.indexOf(b.key) : 0) ||
39
+ b.best - a.best ||
40
+ b.updatedAt - a.updatedAt ||
41
+ a.key.localeCompare(b.key));
42
+ const rank = new Map(order.map((g, i) => [g.key, i]));
43
+ const visible = keyed
44
+ .filter((it) => !collapsed.has(it.group))
45
+ .sort((a, b) => rank.get(a.group) - rank.get(b.group) || b.score - a.score || b.id - a.id);
46
+ return { groups: order.map(({ best: _best, ...g }) => g), items: visible };
47
+ }