sideby 0.42.2 → 0.44.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 (66) hide show
  1. package/ai-tasks.json +10 -0
  2. package/dist/build.json +1 -1
  3. package/dist/src/cli/commands.js +54 -13
  4. package/dist/src/cli/json-schemas.js +65 -1
  5. package/dist/src/cli/main.js +11 -4
  6. package/dist/src/core/ask.d.ts +8 -14
  7. package/dist/src/core/ask.js +66 -30
  8. package/dist/src/core/egress.d.ts +5 -0
  9. package/dist/src/core/egress.js +32 -2
  10. package/dist/src/core/file-memo.d.ts +2 -0
  11. package/dist/src/core/file-memo.js +20 -0
  12. package/dist/src/core/handoff-run.js +41 -8
  13. package/dist/src/core/handoff-select.d.ts +5 -0
  14. package/dist/src/core/handoff-select.js +1 -1
  15. package/dist/src/core/handoff.d.ts +78 -1
  16. package/dist/src/core/handoff.js +100 -9
  17. package/dist/src/core/history-index.d.ts +4 -0
  18. package/dist/src/core/history-index.js +1 -1
  19. package/dist/src/core/live-sessions.d.ts +5 -0
  20. package/dist/src/core/live-sessions.js +12 -1
  21. package/dist/src/core/memo-store.js +32 -8
  22. package/dist/src/core/network.d.ts +37 -0
  23. package/dist/src/core/network.js +65 -1
  24. package/dist/src/core/pick-commands.d.ts +7 -1
  25. package/dist/src/core/pick-commands.js +15 -3
  26. package/dist/src/core/pick-records.d.ts +26 -0
  27. package/dist/src/core/pick-records.js +81 -0
  28. package/dist/src/families/agy/history.d.ts +2 -0
  29. package/dist/src/families/agy/history.js +118 -0
  30. package/dist/src/families/agy/index.js +5 -0
  31. package/dist/src/families/agy/quota.d.ts +5 -1
  32. package/dist/src/families/agy/quota.js +111 -10
  33. package/dist/src/families/history.js +2 -1
  34. package/dist/src/families/quota-watch.d.ts +12 -0
  35. package/dist/src/families/quota-watch.js +24 -0
  36. package/dist/src/network/hook.js +4 -4
  37. package/dist/src/network/page-script.d.ts +40 -0
  38. package/dist/src/network/page-script.js +270 -0
  39. package/dist/src/network/page.d.ts +11 -0
  40. package/dist/src/network/page.js +189 -0
  41. package/dist/src/network/panel.d.ts +5 -0
  42. package/dist/src/network/panel.js +7 -0
  43. package/dist/src/panel/changes.d.ts +57 -0
  44. package/dist/src/panel/changes.js +178 -0
  45. package/dist/src/panel/handler.d.ts +59 -1
  46. package/dist/src/panel/handler.js +374 -99
  47. package/dist/src/panel/i18n.d.ts +49 -0
  48. package/dist/src/panel/i18n.js +100 -2
  49. package/dist/src/panel/page-logic.d.ts +37 -3
  50. package/dist/src/panel/page-logic.js +106 -12
  51. package/dist/src/panel/page-script.js +194 -27
  52. package/dist/src/panel/page-styles.js +18 -8
  53. package/dist/src/panel/page.js +3 -1
  54. package/dist/src/runtime.d.ts +55 -5
  55. package/dist/src/runtime.js +105 -12
  56. package/dist/src/types.d.ts +3 -2
  57. package/package.json +1 -1
  58. package/schemas/network-diagnose.json +196 -0
  59. package/schemas/next.json +67 -2
  60. package/skills/sideby/SKILL.md +3 -2
  61. package/skills/sideby/references/accounts.md +1 -1
  62. package/skills/sideby/references/ai-tasks.md +1 -1
  63. package/skills/sideby/references/handoff.md +6 -2
  64. package/skills/sideby/references/network.md +6 -1
  65. package/skills/sideby/references/quota.md +1 -1
  66. package/skills/sideby/references/sessions.md +1 -1
@@ -4,7 +4,7 @@ import { realpath } from 'node:fs/promises';
4
4
  import { aliasesByAccount, startArgsOf } from '../core/accounts.js';
5
5
  import { advisorPlan, advisorScope, checkAdvisorAccount, isAdvisorChoice, } from '../core/advisor.js';
6
6
  import { listAppProfiles, openAppProfile, removeAppProfile, } from '../core/app-profiles.js';
7
- import { openLoginInTerminal, openPickInTerminal, pickTaskAccount, previewAttachments, promptForTask, setCustomTerminal, setPreferredTerminal, startAiTask, taskContext, terminals, tryAccount, } from '../core/ask.js';
7
+ import { openLoginInTerminal, openRunInTerminal, pickTaskAccount, previewAttachments, promptForTask, setCustomTerminal, setPreferredTerminal, startAiTask, taskContext, terminals, tryAccount, } from '../core/ask.js';
8
8
  import { ATTACHMENT_LIMITS, MAX_ATTACHMENTS, MAX_UPLOAD_BYTES, removeStaged, stagedAttachments, stageUpload, } from '../core/attachments.js';
9
9
  import { applyAutostart, autostartStatus, PANEL_AGENT, planAutostart, } from '../core/autostart.js';
10
10
  import { FAVICON_SVG, ICON_SVG } from '../core/brand-mark.js';
@@ -13,7 +13,7 @@ import { aiTaskPermissions, aliasArgs, aliasRefs, EDITORS, editConfigPanel, edit
13
13
  import { openDesktopApp, withDesktopApps } from '../core/desktop-app.js';
14
14
  import { editSettings, isEditor } from '../core/edit-settings.js';
15
15
  import { UserError } from '../core/errors.js';
16
- import { planHandoff } from '../core/handoff.js';
16
+ import { blocked, planHandoff } from '../core/handoff.js';
17
17
  import { applyHandoffEnable, planHandoffEnable } from '../core/handoff-enable.js';
18
18
  import { handoffOverview } from '../core/handoff-overview.js';
19
19
  import { apiUndecided, handoffRulesView } from '../core/handoff-rules.js';
@@ -25,6 +25,7 @@ import { listMessages, sendMessage } from '../core/messages.js';
25
25
  import { accountModel, setAccountModel } from '../core/model-choice.js';
26
26
  import { GUARDED_FAMILIES, setNetwork } from '../core/network.js';
27
27
  import { tildify } from '../core/paths.js';
28
+ import { readPickRecords } from '../core/pick-records.js';
28
29
  import { PROGRESS_FAMILIES } from '../core/progress.js';
29
30
  import { validEvery } from '../core/progress-state.js';
30
31
  import { quotaAsking } from '../core/quota-fetch.js';
@@ -44,10 +45,13 @@ import { listPendingDecisions, markPendingDone, reopenPendingDecisions } from '.
44
45
  import { readUnattendedConfig } from '../core/unattended-state.js';
45
46
  import * as update from '../core/update.js';
46
47
  import { buildId, localBuild, packageVersion } from '../core/version.js';
48
+ import { quotaWatchDirs } from '../families/quota-watch.js';
47
49
  import { HOOK_FAMILIES } from '../handoff/hook.js';
48
50
  import { MENUBAR_AGENT } from '../menubar/agent.js';
49
51
  import { hotkeyView, iconView, openMenuBarSettings, readMenubarState, setMenubarHotkey, } from '../menubar/hotkey.js';
50
52
  import { MENUBAR_SCRIPT } from '../menubar/script.js';
53
+ import { renderNetworkPage } from '../network/page.js';
54
+ import { createChangeFeed, stateQuotaDir } from './changes.js';
51
55
  import { orcaTabs, switchOrcaTab, systemOrca } from './orca.js';
52
56
  import { renderPage } from './page.js';
53
57
  import { AI_TASK_KINDS } from './page-logic.js';
@@ -64,6 +68,11 @@ export const MAX_QUEUED_WRITES = 4;
64
68
  * does not export it); it may change without notice.
65
69
  */
66
70
  export const LIVE_SESSIONS_SOURCE = Symbol('sideby.panel.liveSessions');
71
+ /**
72
+ * Internal: a property under this key of the handler options serves only the Network view (`src/network/panel.ts`).
73
+ * Not part of the Portal contract (`src/index.ts` does not export it); it may change without notice.
74
+ */
75
+ export const PANEL_VIEW = Symbol('sideby.panel.view');
67
76
  /** The longest text "Send to it" takes; the page's text box has the same limit. */
68
77
  export const MAX_MESSAGE_TEXT = 8000;
69
78
  /** The `ask` and `open` options: `{ bridge: 'postMessage' }` or left out; anything else is a TypeError. */
@@ -258,15 +267,40 @@ async function localSwitchState(rt, method) {
258
267
  }
259
268
  }
260
269
  /** The `handoff` map of the Panel state, from the statuses and Quota already read for the page. */
261
- export function handoffByFamily(rt, accounts, now) {
270
+ export function handoffByFamily(rt, accounts, now, load) {
271
+ const out = {};
272
+ for (const [id, plan] of Object.entries(handoffPlans(rt, accounts, now, load)))
273
+ out[id] = plan.pick;
274
+ return out;
275
+ }
276
+ /** The plan behind each pick of `handoffByFamily`, spread by Room per Session when `load` is given (ADR-0083). */
277
+ export function handoffPlans(rt, accounts, now, load) {
278
+ return nextPicks(familyPlans(rt, accounts, now, load));
279
+ }
280
+ /**
281
+ * The plans that make a Next pick: a pick from Quota data, among two logins or more. Logins, not directories: a Same
282
+ * Login group (spec §3.21) is one Quota, so it alone is no alternative.
283
+ */
284
+ function nextPicks(all) {
285
+ const out = {};
286
+ for (const [id, { plan, logins }] of Object.entries(all))
287
+ if (logins >= 2 && plan.pick && plan.hasQuota)
288
+ out[id] = plan;
289
+ return out;
290
+ }
291
+ /**
292
+ * `sideby next`'s plan for every Family with a Quota source and a signed-in or unknown Subscription Account read
293
+ * already, with how many logins it has: the Next pick takes those with two or more, the "Best to use now" card
294
+ * (spec §3.45) every one.
295
+ */
296
+ export function familyPlans(rt, accounts, now, load) {
262
297
  const out = {};
263
298
  for (const [id, f] of rt.families) {
264
299
  // An Account still being read has no Quota yet; it is neither a pick nor an alternative until it has.
265
300
  const list = accounts.filter((a) => a.family === id && !a.pending);
266
- // Count logins, not directories: a Same Login group (spec §3.21) is one Quota, so it alone is no alternative.
267
301
  const subs = list.filter((a) => a.kind === 'subscription');
268
302
  const logins = subs.filter((a, i) => !subs.slice(0, i).some((b) => a.sameLogin?.includes(b.ref))).length;
269
- if ((!f.readQuota && !f.fetchQuota) || logins < 2)
303
+ if ((!f.readQuota && !f.fetchQuota) || logins < 1)
270
304
  continue;
271
305
  const plan = planHandoff(id, list.map((a) => ({
272
306
  ref: a.ref,
@@ -276,14 +310,45 @@ export function handoffByFamily(rt, accounts, now) {
276
310
  login: a.login ?? 'unknown',
277
311
  ...(a.loginProblem ? { loginProblem: a.loginProblem } : {}),
278
312
  quota: a.quota ?? { status: 'unavailable', reason: 'unrecognized' },
313
+ ...(a.sameLogin ? { sameLogin: a.sameLogin } : {}),
314
+ ...(load ? { liveSessions: load.live.get(a.ref) ?? 0 } : {}),
279
315
  })), now,
280
316
  // The same plan as `sideby next`: the same Takeover Limits, and past them the least used Account (a Last Resort).
281
- { limits: takeoverLimits(rt.handoffSettings().threshold), lastResort: true });
282
- if (plan.pick && plan.hasQuota)
283
- out[id] = plan.pick;
317
+ {
318
+ limits: takeoverLimits(rt.handoffSettings().threshold),
319
+ lastResort: true,
320
+ // Counted over every Account, also one still being read, so a Same Login partner's sessions count.
321
+ ...(load ? { picks: load.picks, live: load.live } : {}),
322
+ });
323
+ out[id] = { plan, logins };
284
324
  }
285
325
  return out;
286
326
  }
327
+ /** The "Best to use now" card's entry of a Family's plan (spec §3.45). */
328
+ export function pickNowOf(plan) {
329
+ const chosen = plan.accounts.find((e) => e.ref === plan.pick);
330
+ if (plan.pick && plan.hasQuota) {
331
+ const reason = plan.reason ?? (plan.tight ? 'tight' : chosen?.state === 'unknown' ? 'unknown' : undefined);
332
+ return {
333
+ pick: plan.pick,
334
+ hasQuota: true,
335
+ ...(reason ? { reason } : {}),
336
+ ...(chosen?.liveSessions ? { running: chosen.liveSessions } : {}),
337
+ };
338
+ }
339
+ // No Subscription Account that can start (signed out, or its sign-in expired): signing in comes first.
340
+ const subs = plan.accounts.filter((e) => e.kind === 'subscription');
341
+ if (!subs.some((e) => e.state !== 'logged-out' && !blocked(e)))
342
+ return { pick: null, hasQuota: plan.hasQuota, why: 'signed-out' };
343
+ if (!plan.hasQuota)
344
+ return { pick: null, hasQuota: false, why: 'no-quota' };
345
+ return {
346
+ pick: null,
347
+ hasQuota: true,
348
+ why: 'used-up',
349
+ ...(plan.earliestReset ? { earliestReset: plan.earliestReset } : {}),
350
+ };
351
+ }
287
352
  class HttpError extends Error {
288
353
  status;
289
354
  /** Machine-readable reason the page acts on, such as `bad-token`. */
@@ -450,52 +515,62 @@ function optBool(body, key) {
450
515
  throw new HttpError(400, `"${key}" must be true or false`);
451
516
  return v;
452
517
  }
453
- async function accountState(rt, account, families) {
454
- const errors = [];
455
- const guard = async (p) => {
456
- try {
457
- return await p;
458
- }
459
- catch (err) {
460
- errors.push(err.message);
461
- return undefined;
462
- }
463
- };
464
- const [status, quota, usage] = await Promise.all([
465
- guard(rt.status(account)),
466
- // The kept answer of a Quota check shows now; a stale one is asked again behind it (spec §3.26).
467
- guard(rt.quota(account, { fetch: 'background' })),
468
- guard(rt.usage(account)),
469
- ]);
470
- const fam = families.find((f) => f.id === account.family);
471
- const base = status ?? {
472
- ...account,
473
- familyTitle: fam?.title ?? account.family,
474
- hostInstalled: fam?.installed ?? false,
475
- login: 'unknown',
476
- };
477
- errors.push(...(status?.problems ?? []));
478
- let modelInfo;
479
- if (rt.families.get(account.family)?.modelChoice) {
480
- const last = usage?.status === 'ok'
481
- ? {
482
- ...(usage.lastModel ? { model: usage.lastModel } : {}),
483
- ...(usage.lastEffort ? { effort: usage.lastEffort } : {}),
518
+ function settle(p) {
519
+ return p.then((value) => ({ value }), (err) => ({ error: err.message }));
520
+ }
521
+ /**
522
+ * Starts the reads of one Account. `full` is its whole state. Usage parses session logs and can take far longer than
523
+ * the rest on a cold start, so `quick()` gives the state without it (`usagePending`) once the rest is in, or null
524
+ * while it is not.
525
+ */
526
+ function accountState(rt, account, families) {
527
+ const status = settle(rt.status(account));
528
+ // The kept answer of a Quota check shows now; a stale one is asked again behind it (spec §3.26).
529
+ const quota = settle(rt.quota(account, { fetch: 'background' }));
530
+ const usage = settle(rt.usage(account));
531
+ let restIn = false;
532
+ void Promise.all([status, quota]).then(() => {
533
+ restIn = true;
534
+ });
535
+ const build = async (u) => {
536
+ const [s, q] = await Promise.all([status, quota]);
537
+ const errors = [s.error, q.error, u?.error].filter((e) => e !== undefined);
538
+ const fam = families.find((f) => f.id === account.family);
539
+ const base = s.value ?? {
540
+ ...account,
541
+ familyTitle: fam?.title ?? account.family,
542
+ hostInstalled: fam?.installed ?? false,
543
+ login: 'unknown',
544
+ };
545
+ errors.push(...(s.value?.problems ?? []));
546
+ let modelInfo;
547
+ if (rt.families.get(account.family)?.modelChoice) {
548
+ const used = u?.value;
549
+ // Given even when empty: without it `accountModel` would wait for the usage itself.
550
+ const last = used?.status === 'ok'
551
+ ? {
552
+ ...(used.lastModel ? { model: used.lastModel } : {}),
553
+ ...(used.lastEffort ? { effort: used.lastEffort } : {}),
554
+ }
555
+ : {};
556
+ try {
557
+ const { ref: _r, family: _f, ...rest } = await accountModel(rt, account, last);
558
+ modelInfo = rest;
559
+ }
560
+ catch (err) {
561
+ errors.push(err.message);
484
562
  }
485
- : {};
486
- const info = await guard(accountModel(rt, account, last));
487
- if (info) {
488
- const { ref: _r, family: _f, ...rest } = info;
489
- modelInfo = rest;
490
563
  }
491
- }
492
- return {
493
- ...base,
494
- ...(modelInfo ? { modelInfo } : {}),
495
- ...(quota ? { quota } : {}),
496
- ...(usage ? { usage } : {}),
497
- ...(errors.length ? { error: errors.join('; ') } : {}),
564
+ return {
565
+ ...base,
566
+ ...(modelInfo ? { modelInfo } : {}),
567
+ ...(q.value ? { quota: q.value } : {}),
568
+ ...(u?.value ? { usage: u.value } : {}),
569
+ ...(u ? {} : { usagePending: true }),
570
+ ...(errors.length ? { error: errors.join('; ') } : {}),
571
+ };
498
572
  };
573
+ return { full: usage.then(build), quick: () => (restIn ? build(undefined) : null) };
499
574
  }
500
575
  /** The model an advisor request asks for, and the Account it is limited to (a ref), checked. */
501
576
  async function advisorBody(rt, body) {
@@ -523,10 +598,32 @@ function advisorView(st, home) {
523
598
  * answer. Mutable for tests only.
524
599
  */
525
600
  export const readBudget = { ms: 2000, hungMs: 60_000 };
601
+ /** How long a state waits, once `readBudget` is over, for an Account's state without its usage. */
602
+ const QUICK_MS = 500;
526
603
  /** An answer kept longer than this is not used: the next state reads the Account again. */
527
604
  const KEPT_MS = 30_000;
528
- /** The Account's state within `readBudget`, or a pending placeholder while its reads go on. */
529
- async function timedAccountState(rt, account, families, mine) {
605
+ /** Forgets every read and every last state: after a change, nothing read before it is shown. */
606
+ function clearReadings(r) {
607
+ r.going.clear();
608
+ r.last.clear();
609
+ }
610
+ /** A read that began longer ago than this goes on after a file change: a cold first read can take a minute. */
611
+ const REREAD_MS = 5000;
612
+ /**
613
+ * After a file Quota lands in changed (spec §3.45): the next state reads again instead of using a read from before
614
+ * the change. The last states stay, for slow rows meanwhile.
615
+ */
616
+ function dropEarlyReadings(r, now) {
617
+ for (const [ref, reading] of r.going)
618
+ if (reading.done || now - reading.started < REREAD_MS)
619
+ r.going.delete(ref);
620
+ }
621
+ /**
622
+ * The Account's state within `readBudget`. While its reads go on: its last complete state (`refreshing`), or else
623
+ * the state without its usage once the rest is in (`usagePending`), or else a pending placeholder.
624
+ */
625
+ async function timedAccountState(rt, account, families, readings) {
626
+ const mine = readings.going;
530
627
  const fam = families.find((f) => f.id === account.family);
531
628
  const placeholder = async (extra) => {
532
629
  // Its Same Login is known without the slow reads, so its rows stay grouped meanwhile.
@@ -540,21 +637,53 @@ async function timedAccountState(rt, account, families, mine) {
540
637
  ...extra,
541
638
  };
542
639
  };
640
+ const last = () => {
641
+ const st = readings.last.get(account.ref);
642
+ return st ? { ...st, refreshing: true } : null;
643
+ };
644
+ // The state without usage still asks the model reader, which a plugin may make slow: it gets a short wait only.
645
+ const partial = async (r) => {
646
+ const quick = r.quick();
647
+ if (!quick)
648
+ return null;
649
+ let timer;
650
+ const late = new Promise((done) => {
651
+ timer = setTimeout(() => done(null), QUICK_MS);
652
+ });
653
+ try {
654
+ return await Promise.race([quick.catch(() => null), late]);
655
+ }
656
+ finally {
657
+ clearTimeout(timer);
658
+ }
659
+ };
543
660
  let r = mine.get(account.ref);
544
661
  if (r?.done && Date.now() - r.done.at > KEPT_MS)
545
662
  r = undefined;
546
- // A read still going after `readBudget.hungMs` has hung (a plugin reader, a Host that never answers).
663
+ // A read still going after `readBudget.hungMs` has hung (a plugin reader, a Host that never answers). A first read
664
+ // on a cold start can parse usage for longer than that: while the rest is in, it goes on.
547
665
  if (r && !r.done && Date.now() - r.started > readBudget.hungMs) {
548
- // Dropped, so the next state starts a new read; this one says what happened instead of spinning on.
666
+ const early = last() ? null : await partial(r);
667
+ if (early)
668
+ return early;
669
+ // Dropped, so the next state starts a new read; this one shows the last state, or says what happened instead
670
+ // of spinning on.
549
671
  mine.delete(account.ref);
672
+ const shown = last();
673
+ if (shown)
674
+ return shown;
550
675
  return placeholder({
551
676
  error: `reading this account took longer than ${Math.round(readBudget.hungMs / 1000)} s; refresh to try again`,
552
677
  });
553
678
  }
554
679
  if (!r) {
555
- const fresh = { promise: accountState(rt, account, families), started: Date.now() };
680
+ const read = accountState(rt, account, families);
681
+ const fresh = { promise: read.full, quick: read.quick, started: Date.now() };
556
682
  fresh.promise.then((state) => {
557
683
  fresh.done = { state, at: Date.now() };
684
+ // Not a read a change has since dropped: its state is from before the change.
685
+ if (mine.get(account.ref) === fresh)
686
+ readings.last.set(account.ref, state);
558
687
  }, () => undefined);
559
688
  mine.set(account.ref, fresh);
560
689
  r = fresh;
@@ -582,9 +711,11 @@ async function timedAccountState(rt, account, families, mine) {
582
711
  mine.delete(account.ref);
583
712
  return state;
584
713
  }
585
- return placeholder({ pending: true });
714
+ return last() ?? (await partial(reading)) ?? placeholder({ pending: true });
586
715
  }
587
716
  async function buildState(rt, opts) {
717
+ // Read alongside the Accounts, so waiting for it adds little.
718
+ const liveNow = opts.live?.() ?? Promise.resolve(new Set());
588
719
  const ctx = rt.readContext();
589
720
  const [families, accounts, history, quotaSetups, remoteControl, advisor, upd] = await Promise.all([
590
721
  rt.familyInfo(),
@@ -600,9 +731,10 @@ async function buildState(rt, opts) {
600
731
  ? await rt.networkStatus().catch(() => undefined)
601
732
  : undefined;
602
733
  // Reads of Accounts that are gone are dropped.
603
- for (const ref of opts.readings.keys())
604
- if (!accounts.some((a) => a.ref === ref))
605
- opts.readings.delete(ref);
734
+ for (const map of [opts.readings.going, opts.readings.last])
735
+ for (const ref of map.keys())
736
+ if (!accounts.some((a) => a.ref === ref))
737
+ map.delete(ref);
606
738
  const aliases = aliasesByAccount(aliasRefs(rt.config.aliases), accounts);
607
739
  // Asks in flight before the reads start: one that ends while they run may have left a row with the older numbers.
608
740
  const askingOf = () => accounts.filter((a) => quotaAsking(rt.paths.stateDir, a.family, a.name)).map((a) => a.ref);
@@ -630,7 +762,31 @@ async function buildState(rt, opts) {
630
762
  ...(withArgs.length ? { aliasArgs: Object.fromEntries(withArgs) } : {}),
631
763
  };
632
764
  });
633
- const handoff = handoffByFamily(rt, list, ctx.now);
765
+ // The Next pick counts Live Sessions and Pick Records as `sideby next` does; it only reads them (ADR-0083).
766
+ const keys = await liveNow;
767
+ const live = new Map();
768
+ for (const key of keys ?? []) {
769
+ const ref = key.slice(0, key.indexOf('\0'));
770
+ live.set(ref, (live.get(ref) ?? 0) + 1);
771
+ }
772
+ // Unknown running sessions leave the Next pick out; the card ranks as if none ran, so it never reads "nothing".
773
+ const load = keys ? { live, picks: await readPickRecords(rt.paths.stateDir, ctx.now) } : undefined;
774
+ const every = familyPlans(rt, list, ctx.now, load);
775
+ const plans = keys ? nextPicks(every) : {};
776
+ // A tool whose quota has only per-model windows (Antigravity CLI) never ranks by quota, so it gets no card.
777
+ const pickNow = Object.fromEntries(Object.entries(every)
778
+ .filter(([f, { plan }]) => plan.hasQuota || !list.some((a) => a.family === f && a.quota?.status === 'ok'))
779
+ .map(([f, { plan }]) => [f, pickNowOf(plan)]));
780
+ const handoff = Object.fromEntries(Object.entries(plans).map(([f, p]) => [f, p.pick]));
781
+ const handoffRunning = Object.fromEntries(Object.entries(plans).flatMap(([f, p]) => {
782
+ const n = p.accounts.find((e) => e.ref === p.pick)?.liveSessions ?? 0;
783
+ return n ? [[f, n]] : [];
784
+ }));
785
+ const handoffReason = Object.fromEntries(Object.entries(plans).flatMap(([f, p]) => {
786
+ const why = p.reason ??
787
+ (p.tight ? 'tight' : p.accounts.find((e) => e.ref === p.pick)?.state === 'unknown' ? 'unknown' : null);
788
+ return why ? [[f, why]] : [];
789
+ }));
634
790
  const pickOffers = {};
635
791
  for (const f of families) {
636
792
  const offer = await rt.pickSuggestion(f.id, accounts).catch(() => null);
@@ -678,6 +834,9 @@ async function buildState(rt, opts) {
678
834
  ...(Object.keys(pickOffers).length ? { pickOffers } : {}),
679
835
  shellSetup: { ...shellSt, rc: tildify(shellSt.rc, ctx.home), block: setupBlock(shellSt.shell) },
680
836
  ...(Object.keys(handoff).length ? { handoff } : {}),
837
+ ...(Object.keys(handoffRunning).length ? { handoffRunning } : {}),
838
+ ...(Object.keys(handoffReason).length ? { handoffReason } : {}),
839
+ ...(Object.keys(pickNow).length ? { pickNow } : {}),
681
840
  ...(remoteControl.length ? { remoteControl: rcView(remoteControl, ctx.home) } : {}),
682
841
  ...(advisor.groups.length ? { advisor: advisorView(advisor, ctx.home) } : {}),
683
842
  ...(appProfiles.length
@@ -1051,6 +1210,9 @@ function layerTheme(colors, portal) {
1051
1210
  }
1052
1211
  export function createPanelHandler(opts) {
1053
1212
  const basePath = normalizeBase(opts.basePath);
1213
+ const view = opts[PANEL_VIEW] ?? 'accounts';
1214
+ if (view !== 'accounts' && view !== 'network')
1215
+ throw new TypeError('panel view must be "accounts" or "network"');
1054
1216
  const allowed = new Set(opts.allowedHosts.map((h) => h.toLowerCase()));
1055
1217
  const readOnly = Boolean(opts.readOnly);
1056
1218
  const version = opts.version ?? PANEL_VERSION;
@@ -1063,8 +1225,16 @@ export function createPanelHandler(opts) {
1063
1225
  const openBridge = resolveBridge('open', opts.open);
1064
1226
  const token = randomBytes(32).toString('base64url');
1065
1227
  const serial = writeQueue();
1066
- const readings = new Map();
1228
+ const readings = { going: new Map(), last: new Map() };
1067
1229
  const getRuntime = typeof opts.runtime === 'function' ? opts.runtime : async () => opts.runtime;
1230
+ // Quota files watched while a page asks (spec §3.45, ADR-0084).
1231
+ const changes = createChangeFeed({
1232
+ dirs: async () => {
1233
+ const rt = await getRuntime();
1234
+ return [stateQuotaDir(rt.paths.stateDir), ...quotaWatchDirs(await rt.accounts())];
1235
+ },
1236
+ onChange: () => dropEarlyReadings(readings, Date.now()),
1237
+ });
1068
1238
  const sessionsSource = opts[LIVE_SESSIONS_SOURCE];
1069
1239
  const liveSessions = sessionsSource?.list ?? listLiveSessions;
1070
1240
  // A change from this page can end a stretch of Unattended Mode: the plugins hear of it now, as after the CLI. The
@@ -1082,14 +1252,19 @@ export function createPanelHandler(opts) {
1082
1252
  const history = () => (historyMod ??= import('../core/history.js'));
1083
1253
  // Which Sessions run now, for the "running" mark of History rows: read at most every 5 s, given 3 s.
1084
1254
  const LIVE_FIRST_MS = 300;
1255
+ // How long the page state waits for the first list of running sessions before it leaves the Next pick out.
1256
+ const LIVE_STATE_MS = 3_000;
1085
1257
  let liveMark;
1086
1258
  // Which past Sessions run now. A search never waits for that list once one is known: it answers with the last
1087
1259
  // one while a fresh one is read, and waits at most LIVE_FIRST_MS for the very first.
1088
- const liveIds = async (rt) => {
1260
+ const liveRead = (rt) => {
1089
1261
  if (!liveMark || Date.now() - liveMark.at > 5_000) {
1090
1262
  const ids = (sessionsSource?.list ? sessionsSource.list(rt) : listLiveSessions(rt, { deadlineMs: 3_000 }))
1091
- .then((r) => new Set(r.sessions.map((x) => liveKey(x.account, x.sessionId))))
1092
- .catch(() => new Set());
1263
+ .then((r) => ({
1264
+ ids: new Set(r.sessions.map((x) => liveKey(x.account, x.sessionId))),
1265
+ complete: !r.partial,
1266
+ }))
1267
+ .catch(() => ({ ids: new Set(), complete: false }));
1093
1268
  const last = liveMark?.last;
1094
1269
  liveMark = { at: Date.now(), ids, ...(last ? { last } : {}) };
1095
1270
  const mark = liveMark;
@@ -1097,19 +1272,26 @@ export function createPanelHandler(opts) {
1097
1272
  mark.last = v;
1098
1273
  });
1099
1274
  }
1100
- if (liveMark.last)
1101
- return liveMark.last;
1275
+ return liveMark;
1276
+ };
1277
+ // The last complete list known, else the one being read, given `waitMs`; past that the last list, even an
1278
+ // incomplete one, or `late` when there is none.
1279
+ const liveWithin = async (rt, waitMs, late) => {
1280
+ const mark = liveRead(rt);
1281
+ if (mark.last?.complete)
1282
+ return mark.last;
1102
1283
  let timer;
1103
- const late = new Promise((r) => {
1104
- timer = setTimeout(() => r(new Set()), LIVE_FIRST_MS);
1284
+ const gave = new Promise((r) => {
1285
+ timer = setTimeout(() => r(mark.last ?? late), waitMs);
1105
1286
  });
1106
1287
  try {
1107
- return await Promise.race([liveMark.ids, late]);
1288
+ return await Promise.race([mark.ids, gave]);
1108
1289
  }
1109
1290
  finally {
1110
1291
  clearTimeout(timer);
1111
1292
  }
1112
1293
  };
1294
+ const liveIds = async (rt) => (await liveWithin(rt, LIVE_FIRST_MS, null))?.ids ?? new Set();
1113
1295
  const toolScans = new Map();
1114
1296
  const dropIdleScans = () => {
1115
1297
  for (const [id, scan] of toolScans)
@@ -1188,6 +1370,21 @@ export function createPanelHandler(opts) {
1188
1370
  };
1189
1371
  },
1190
1372
  });
1373
+ const checkNetworkAsk = (body) => {
1374
+ if (view !== 'network')
1375
+ return;
1376
+ if (body.task !== 'network-diagnose')
1377
+ throw new HttpError(400, 'the Network Panel only runs its fixed diagnosis task');
1378
+ if (Object.keys(body).some((k) => !['task', 'lang', 'context'].includes(k)))
1379
+ throw new HttpError(400, 'the fixed network diagnosis accepts only task, lang and diagnostic context');
1380
+ const context = body.context;
1381
+ if (!context || typeof context !== 'object' || Array.isArray(context))
1382
+ throw new HttpError(400, 'the fixed network diagnosis requires its diagnostic context');
1383
+ if (Object.keys(context).some((k) => !['networkDiagnose', 'version'].includes(k)))
1384
+ throw new HttpError(400, 'the fixed network diagnosis accepts only networkDiagnose and version facts');
1385
+ if (!Array.isArray(context.networkDiagnose))
1386
+ throw new HttpError(400, 'the fixed network diagnosis requires networkDiagnose facts');
1387
+ };
1191
1388
  const routes = {
1192
1389
  // AI Tasks (spec §3.28, ADR-0027). The prompt and the account it would use, read only: for the confirm area,
1193
1390
  // the copy fallback and the read-only Panel.
@@ -1205,6 +1402,7 @@ export function createPanelHandler(opts) {
1205
1402
  writes: () => false,
1206
1403
  queued: false,
1207
1404
  async run(body) {
1405
+ checkNetworkAsk(body);
1208
1406
  const input = askInput(body);
1209
1407
  const rt = await getRuntime();
1210
1408
  const { prompt, removedSecrets } = promptForTask(rt, input, await previewAttachments(rt, input));
@@ -1212,17 +1410,28 @@ export function createPanelHandler(opts) {
1212
1410
  return {
1213
1411
  prompt,
1214
1412
  removedSecrets,
1215
- account: 'account' in pick ? pick.account.ref : null,
1216
- ...('reason' in pick ? { reason: pick.reason } : {}),
1413
+ ...(view === 'network'
1414
+ ? {}
1415
+ : {
1416
+ account: 'account' in pick ? pick.account.ref : null,
1417
+ ...('reason' in pick ? { reason: pick.reason } : {}),
1418
+ }),
1217
1419
  };
1218
1420
  },
1219
1421
  },
1220
1422
  // Writes the task file and opens the terminal. An account the person picked, API ones too, is kept as `ask.account`.
1221
1423
  '/api/ask': {
1222
1424
  async run(body) {
1425
+ checkNetworkAsk(body);
1223
1426
  const input = askInput(body);
1224
1427
  const rt = await getRuntime();
1225
- return opened(await startAiTask(rt, { ...input, remember: Boolean(input.account || input.terminal) }));
1428
+ const result = opened(await startAiTask(rt, view === 'network'
1429
+ ? { ...input, terminal: 'orca', remember: false }
1430
+ : { ...input, remember: Boolean(input.account || input.terminal) }));
1431
+ if (view !== 'network')
1432
+ return result;
1433
+ const { account: _account, ...withoutAccount } = result;
1434
+ return withoutAccount;
1226
1435
  },
1227
1436
  },
1228
1437
  // Runs `sideby login <ref>` in the person's terminal; no AI is involved (spec §3.28 "登录").
@@ -1369,26 +1578,47 @@ export function createPanelHandler(opts) {
1369
1578
  },
1370
1579
  // Pick Commands (spec §3.13, ADR-0035): start the Account with the most room in the Preferred Terminal, add one
1371
1580
  // (a name that hides a command on PATH comes back as `confirm` until the page sends confirm: true), remove one.
1581
+ // `family` instead of `name`: the "Best to use now" card (spec §3.45), the Family's Pick Command when it has one,
1582
+ // else the same rules without one.
1372
1583
  '/api/pick/start': {
1373
1584
  async run(body) {
1374
- const name = optString(body, 'name');
1375
- if (!name)
1376
- throw new HttpError(400, '"name" is required');
1585
+ const fam = optString(body, 'family');
1377
1586
  const rt = await getRuntime();
1378
- const { family, choice } = await rt.pickChoice(name);
1587
+ const name = optString(body, 'name') ??
1588
+ (fam ? Object.entries(rt.config.pickCommands ?? {}).find(([, f]) => f === fam)?.[0] : undefined);
1589
+ if (!name && !fam)
1590
+ throw new HttpError(400, '"name" or "family" is required');
1591
+ // This start counts for the next pick, so its record is written now (ADR-0083).
1592
+ let rec;
1593
+ const po = {
1594
+ record: true,
1595
+ recorded: (r) => {
1596
+ rec = r;
1597
+ },
1598
+ };
1599
+ const { family, choice } = name ? await rt.pickChoice(name, po) : await rt.familyPick(fam, po);
1379
1600
  if (choice.ref === null)
1380
1601
  throw new UserError(choice.earliestReset
1381
1602
  ? `Every signed-in ${family} account has used up its quota; ${choice.earliestReset.ref} is back first.`
1382
1603
  : `No ${family} account can be used now; sign one in first.`, { code: 'none-usable' });
1383
- // The terminal runs the Pick Command itself, so it picks again as it starts and prints which and why.
1384
- const r = opened(await openPickInTerminal(rt, name));
1604
+ // The terminal starts exactly the Account picked here, the one the answer names; picking again there could
1605
+ // start another. A terminal that did not open starts nothing, so the record is taken back.
1606
+ const r = opened(await openRunInTerminal(rt, choice.ref).catch(async (err) => {
1607
+ if (rec)
1608
+ await rt.cancelPick(rec);
1609
+ throw err;
1610
+ }));
1611
+ if (!r.opened && rec)
1612
+ await rt.cancelPick(rec);
1385
1613
  return {
1386
1614
  ...r,
1387
- name,
1615
+ ...(name ? { name } : {}),
1388
1616
  family,
1389
1617
  picked: choice.ref,
1390
1618
  reason: choice.reason,
1391
1619
  ...('pressure' in choice ? { pressure: choice.pressure, window: choice.window } : {}),
1620
+ ...('expiring' in choice && choice.expiring ? { expiring: true } : {}),
1621
+ ...('running' in choice && choice.running ? { running: choice.running } : {}),
1392
1622
  ...('limit' in choice ? { limit: choice.limit, longLimit: choice.longLimit } : {}),
1393
1623
  };
1394
1624
  },
@@ -2142,6 +2372,13 @@ export function createPanelHandler(opts) {
2142
2372
  return (await getRuntime()).networkStatus({ check: true });
2143
2373
  },
2144
2374
  },
2375
+ // Manual offline diagnosis: cached Guard state and a local TCP probe, never an online trace.
2376
+ '/api/network/diagnose': {
2377
+ writes: () => false,
2378
+ async run() {
2379
+ return (await getRuntime()).networkDiagnose();
2380
+ },
2381
+ },
2145
2382
  // Network Guard's switch and countries (spec §3.35): config `network`, shown first like every config change.
2146
2383
  '/api/network/settings': {
2147
2384
  writes: (body) => body.confirm === true,
@@ -2568,18 +2805,28 @@ export function createPanelHandler(opts) {
2568
2805
  if (!allowed.has(host))
2569
2806
  throw new HttpError(403, 'host not allowed');
2570
2807
  const method = req.method ?? 'GET';
2808
+ const networkGetRoutes = new Set([
2809
+ '/',
2810
+ '/index.html',
2811
+ '/favicon.svg',
2812
+ '/icon.svg',
2813
+ '/api/health',
2814
+ '/api/session',
2815
+ ]);
2816
+ if (view === 'network' && (method === 'GET' || method === 'HEAD') && !networkGetRoutes.has(sub))
2817
+ throw new HttpError(404, 'not found');
2571
2818
  if (method === 'GET' || method === 'HEAD') {
2572
2819
  if (sub === '/' || sub === '/index.html') {
2573
2820
  const nonce = randomBytes(16).toString('base64');
2574
2821
  // The theme and language in config (spec §3.29), so the first paint has them; a config that cannot be
2575
2822
  // read leaves the defaults, and /api/state reports the problem.
2576
- const panel = method === 'HEAD'
2823
+ const panel = method === 'HEAD' || view === 'network'
2577
2824
  ? undefined
2578
2825
  : await getRuntime().then((rt) => rt.config.panel, () => undefined);
2579
2826
  // The user's Theme under the Portal's colors (spec §3.34): `?theme=preview` shows the Theme `sideby theme
2580
2827
  // preview` set, for this load only. A Theme that cannot be read leaves the default and Settings says why.
2581
2828
  const preview = new URL(req.url ?? '/', 'http://x').searchParams.get('theme') === 'preview';
2582
- const colors = method === 'HEAD'
2829
+ const colors = method === 'HEAD' || view === 'network'
2583
2830
  ? undefined
2584
2831
  : await getRuntime().then(async (rt) => (preview ? await previewColors(rt.paths) : undefined) ??
2585
2832
  (rt.config.panel?.colorTheme && rt.config.panel.colorTheme !== NO_THEME
@@ -2606,21 +2853,23 @@ export function createPanelHandler(opts) {
2606
2853
  });
2607
2854
  res.end(method === 'HEAD'
2608
2855
  ? undefined
2609
- : renderPage({
2610
- basePath,
2611
- token,
2612
- nonce,
2613
- version,
2614
- build,
2615
- local,
2616
- readOnly,
2617
- theme: pageTheme,
2618
- lang,
2619
- updates,
2620
- ...(ask ? { ask } : {}),
2621
- ...(openBridge ? { open: openBridge } : {}),
2622
- ...(panel ? { panel } : {}),
2623
- }));
2856
+ : view === 'network'
2857
+ ? renderNetworkPage({ basePath, token, nonce, version, theme, lang })
2858
+ : renderPage({
2859
+ basePath,
2860
+ token,
2861
+ nonce,
2862
+ version,
2863
+ build,
2864
+ local,
2865
+ readOnly,
2866
+ theme: pageTheme,
2867
+ lang,
2868
+ updates,
2869
+ ...(ask ? { ask } : {}),
2870
+ ...(openBridge ? { open: openBridge } : {}),
2871
+ ...(panel ? { panel } : {}),
2872
+ }));
2624
2873
  return true;
2625
2874
  }
2626
2875
  // The mark, for a Portal's tab and for this page's favicon (ADR-0006 amendment).
@@ -2660,8 +2909,31 @@ export function createPanelHandler(opts) {
2660
2909
  send(res, 200, await loginItemView(rt, sub === '/api/menubar' ? MENUBAR_AGENT : PANEL_AGENT));
2661
2910
  return true;
2662
2911
  }
2912
+ // Held until a Quota file changes or 25 s pass (spec §3.45, ADR-0084).
2913
+ if (sub === '/api/changes') {
2914
+ const raw = new URL(req.url ?? '/', 'http://x').searchParams.get('since');
2915
+ const since = method === 'GET' && raw !== null && /^\d{1,15}$/.test(raw) ? Number(raw) : null;
2916
+ const gone = new Promise((done) => res.once('close', done));
2917
+ const answer = await changes.wait(since, gone);
2918
+ if (!res.destroyed)
2919
+ send(res, 200, answer);
2920
+ return true;
2921
+ }
2663
2922
  if (sub === '/api/state') {
2664
- send(res, 200, await buildState(await getRuntime(), { version, build, readOnly, updates, readings }));
2923
+ send(res, 200, await buildState(await getRuntime(), {
2924
+ version,
2925
+ build,
2926
+ readOnly,
2927
+ updates,
2928
+ readings,
2929
+ // The Next pick waits for the running sessions, so it never shows a pick that moves once they are known.
2930
+ // A scan that could not list the running programs or left Accounts out counts as not known, like one
2931
+ // that came too late.
2932
+ live: async () => {
2933
+ const scan = await liveWithin(await getRuntime(), LIVE_STATE_MS, null);
2934
+ return scan?.complete ? scan.ids : null;
2935
+ },
2936
+ }));
2665
2937
  return true;
2666
2938
  }
2667
2939
  if (Object.hasOwn(routes, sub) || Object.hasOwn(uploads, sub))
@@ -2670,6 +2942,9 @@ export function createPanelHandler(opts) {
2670
2942
  }
2671
2943
  if (method !== 'POST')
2672
2944
  throw new HttpError(405, 'method not allowed');
2945
+ const networkPostRoutes = new Set(['/api/network/diagnose', '/api/ask/prompt', '/api/ask']);
2946
+ if (view === 'network' && !networkPostRoutes.has(sub))
2947
+ throw new HttpError(404, 'not found');
2673
2948
  const route = Object.hasOwn(routes, sub) ? routes[sub] : undefined;
2674
2949
  const upload = Object.hasOwn(uploads, sub) ? uploads[sub] : undefined;
2675
2950
  if (!route && !upload)
@@ -2694,7 +2969,7 @@ export function createPanelHandler(opts) {
2694
2969
  const result = await (route.queued === false ? route.run(body) : serial(() => route.run(body)));
2695
2970
  // A change may concern an Account whose read began before it: the next state reads again.
2696
2971
  if (route.writes?.(body) ?? true)
2697
- readings.clear();
2972
+ clearReadings(readings);
2698
2973
  send(res, 200, result);
2699
2974
  return true;
2700
2975
  }