sideby 0.35.6 → 0.35.7

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 (55) hide show
  1. package/dist/build.json +1 -1
  2. package/dist/src/cli/commands.d.ts +9 -1
  3. package/dist/src/cli/commands.js +59 -16
  4. package/dist/src/cli/json-schemas.js +20 -0
  5. package/dist/src/cli/main.js +11 -5
  6. package/dist/src/core/cli-commands.js +1 -1
  7. package/dist/src/core/config.d.ts +7 -0
  8. package/dist/src/core/config.js +9 -0
  9. package/dist/src/core/doctor.d.ts +5 -1
  10. package/dist/src/core/doctor.js +16 -0
  11. package/dist/src/core/edit-settings.d.ts +27 -1
  12. package/dist/src/core/edit-settings.js +78 -4
  13. package/dist/src/core/handoff-select.d.ts +3 -1
  14. package/dist/src/core/handoff-select.js +11 -1
  15. package/dist/src/core/handoff.d.ts +13 -1
  16. package/dist/src/core/handoff.js +16 -5
  17. package/dist/src/core/login-mark.d.ts +3 -0
  18. package/dist/src/core/login-mark.js +22 -0
  19. package/dist/src/core/pick-commands.d.ts +4 -2
  20. package/dist/src/core/pick-commands.js +7 -2
  21. package/dist/src/core/quota-fetch.d.ts +7 -1
  22. package/dist/src/core/quota-fetch.js +38 -1
  23. package/dist/src/core/quota-store.d.ts +5 -0
  24. package/dist/src/core/quota-store.js +3 -0
  25. package/dist/src/core/search-catalog.js +9 -0
  26. package/dist/src/families/claude/index.js +3 -0
  27. package/dist/src/families/claude/login-events.d.ts +24 -0
  28. package/dist/src/families/claude/login-events.js +163 -0
  29. package/dist/src/families/claude/quota-fetch.js +14 -0
  30. package/dist/src/menubar/snapshot.d.ts +2 -0
  31. package/dist/src/menubar/snapshot.js +6 -2
  32. package/dist/src/menubar/strings.d.ts +4 -0
  33. package/dist/src/menubar/strings.js +4 -0
  34. package/dist/src/panel/handler.d.ts +14 -1
  35. package/dist/src/panel/handler.js +48 -14
  36. package/dist/src/panel/i18n.d.ts +23 -0
  37. package/dist/src/panel/i18n.js +46 -0
  38. package/dist/src/panel/page-logic.d.ts +44 -2
  39. package/dist/src/panel/page-logic.js +43 -3
  40. package/dist/src/panel/page-script.js +124 -7
  41. package/dist/src/panel/page-styles.js +8 -0
  42. package/dist/src/panel/page.d.ts +7 -0
  43. package/dist/src/panel/page.js +1 -0
  44. package/dist/src/runtime.d.ts +16 -1
  45. package/dist/src/runtime.js +51 -2
  46. package/dist/src/types.d.ts +37 -0
  47. package/package.json +3 -3
  48. package/schemas/config.json +11 -0
  49. package/schemas/edit.json +4 -0
  50. package/schemas/list.json +24 -0
  51. package/schemas/next.json +18 -0
  52. package/skills/sideby/SKILL.md +4 -2
  53. package/skills/sideby/references/accounts.md +9 -0
  54. package/skills/sideby/references/diagnose.md +6 -1
  55. package/skills/sideby/references/panel.md +1 -1
@@ -17,7 +17,9 @@ function lastReset(quota, now, level) {
17
17
  return last;
18
18
  }
19
19
  /** A full Subscription Account a Last Resort may start: no window used up (pressure under 100). */
20
- const lastResortOk = (e) => e.state === 'full' && !e.sameLoginAs && e.pressure !== null && e.pressure < 100;
20
+ const lastResortOk = (e) => e.state === 'full' && !blocked(e) && e.pressure !== null && e.pressure < 100;
21
+ /** An entry that can never be picked whatever its state: the current Account's Same Login, or an Expired Login. */
22
+ export const blocked = (e) => Boolean(e.sameLoginAs || e.skip);
21
23
  function entry(c, now, limits, lastResort) {
22
24
  const pressure = quotaPressure(c.quota, now);
23
25
  const use = limitUse(c.quota, now, limits);
@@ -42,6 +44,14 @@ function entry(c, now, limits, lastResort) {
42
44
  return { ...base, state: 'api' };
43
45
  if (c.login === 'logged-out')
44
46
  return { ...base, state: 'logged-out' };
47
+ return withSkip(c, stateOfQuota(c, base, pressure, now, limits, lastResort));
48
+ }
49
+ function withSkip(c, e) {
50
+ return c.loginProblem?.kind === 'expired'
51
+ ? { ...e, skip: { reason: 'login-expired', command: `sideby login ${c.ref}` } }
52
+ : e;
53
+ }
54
+ function stateOfQuota(c, base, pressure, now, limits, lastResort) {
45
55
  if (pressure === null)
46
56
  return { ...base, state: 'unknown' };
47
57
  // Full once any window reaches its own Takeover Limit: 85 for a Short Window, 95 for a Long one by default.
@@ -79,13 +89,14 @@ opts = {}) {
79
89
  return current?.sameLogin?.includes(c.ref) ? { ...e, sameLoginAs: current.ref } : e;
80
90
  })
81
91
  .sort((a, b) =>
82
- // A Same Login partner of the current Account can never be picked, so it goes with the others that cannot.
83
- Number(Boolean(a.sameLoginAs)) - Number(Boolean(b.sameLoginAs)) ||
92
+ // A Same Login partner of the current Account or an Expired Login can never be picked, so it goes with the
93
+ // others that cannot.
94
+ Number(blocked(a)) - Number(blocked(b)) ||
84
95
  rank(a) - rank(b) ||
85
96
  (a.state === 'ready' || rank(a) === 1.5 ? a.limitUse - b.limitUse : 0) ||
86
97
  (a.state === 'full' ? resetTime(a) - resetTime(b) || 0 : 0) ||
87
98
  tie(a, b));
88
- const usable = (e) => !e.sameLoginAs &&
99
+ const usable = (e) => !blocked(e) &&
89
100
  (e.state === 'ready' ||
90
101
  e.state === 'unknown' ||
91
102
  (opts.lastResort && lastResortOk(e)) ||
@@ -97,7 +108,7 @@ opts = {}) {
97
108
  if (picked?.state === 'full')
98
109
  plan.tight = { limit: limits.short, longLimit: limits.long };
99
110
  if (pick === null) {
100
- const first = accounts.find((e) => e.state === 'full' && e.resetsAt);
111
+ const first = accounts.find((e) => e.state === 'full' && e.resetsAt && !e.skip);
101
112
  if (first?.resetsAt)
102
113
  plan.earliestReset = { ref: first.ref, at: first.resetsAt };
103
114
  }
@@ -0,0 +1,3 @@
1
+ export declare function loginMarkFile(stateDir: string, family: string, name: string): string;
2
+ export declare function readLoginMark(file: string): Promise<string | undefined>;
3
+ export declare function writeLoginMark(file: string, at: Date): Promise<void>;
@@ -0,0 +1,22 @@
1
+ // When a sign-in that sideby started last finished (exit 0) for an Account (ADR-0071): one small file per Account in
2
+ // sideby's state directory, holding only that time. It never says the login works; it lets the Panel say "Sign-in
3
+ // finished, waiting for confirmation" until a successful turn or Quota answer clears the Expired Login.
4
+ import { mkdir, readFile } from 'node:fs/promises';
5
+ import { dirname, join } from 'node:path';
6
+ import { writeFileAtomic } from './fs-safe.js';
7
+ export function loginMarkFile(stateDir, family, name) {
8
+ return join(stateDir, 'login', family, `${name}.json`);
9
+ }
10
+ export async function readLoginMark(file) {
11
+ try {
12
+ const v = JSON.parse(await readFile(file, 'utf8'))?.signedInAt;
13
+ return typeof v === 'string' && Number.isFinite(Date.parse(v)) ? v : undefined;
14
+ }
15
+ catch {
16
+ return undefined;
17
+ }
18
+ }
19
+ export async function writeLoginMark(file, at) {
20
+ await mkdir(dirname(file), { recursive: true, mode: 0o700 });
21
+ await writeFileAtomic(file, `${JSON.stringify({ signedInAt: at.toISOString() })}\n`, 0o600);
22
+ }
@@ -1,4 +1,4 @@
1
- import type { HandoffPlan } from './handoff.ts';
1
+ import { type HandoffPlan } from './handoff.ts';
2
2
  /** The name offered for a built-in Family when its Aliases follow no pattern; pi gets none (`pi` is the Host). */
3
3
  export declare const DEFAULT_PICK_NAMES: Readonly<Record<string, string>>;
4
4
  /**
@@ -36,7 +36,9 @@ export type PickChoice =
36
36
  | {
37
37
  ref: string;
38
38
  reason: 'others-full';
39
- } | {
39
+ }
40
+ /** `signIn`: the Accounts to sign in, signed out or with an Expired Login (ADR-0071). */
41
+ | {
40
42
  ref: null;
41
43
  reason: 'none-usable';
42
44
  earliestReset?: {
@@ -1,3 +1,6 @@
1
+ // Pick Commands (spec §3.13, ADR-0035): a short command bound to a Family that starts the Account a Handoff would
2
+ // pick, or the Main Account when no Account of the Family has Quota data.
3
+ import { blocked } from './handoff.js';
1
4
  /** The name offered for a built-in Family when its Aliases follow no pattern; pi gets none (`pi` is the Host). */
2
5
  export const DEFAULT_PICK_NAMES = { claude: 'cc', codex: 'cx', grok: 'gk' };
3
6
  /**
@@ -16,7 +19,7 @@ export function suggestPickName(family, bin, familyAliases) {
16
19
  * Account with the lowest Limit Use and no window used up (`tight`). Nothing usable (every window used up, signed out or API): nothing starts.
17
20
  */
18
21
  export function choosePick(plan, mainRef) {
19
- const startable = (ref) => plan.accounts.some((e) => e.ref === ref && !e.sameLoginAs && (e.state === 'ready' || e.state === 'unknown'));
22
+ const startable = (ref) => plan.accounts.some((e) => e.ref === ref && !blocked(e) && (e.state === 'ready' || e.state === 'unknown'));
20
23
  if (!plan.hasQuota && mainRef && startable(mainRef))
21
24
  return { ref: mainRef, reason: 'no-quota-data' };
22
25
  if (plan.pick && plan.accounts.some((e) => e.ref === plan.pick && e.state !== 'api')) {
@@ -42,7 +45,9 @@ export function choosePick(plan, mainRef) {
42
45
  ref: null,
43
46
  reason: 'none-usable',
44
47
  ...(plan.earliestReset ? { earliestReset: plan.earliestReset } : {}),
45
- signIn: plan.accounts.filter((e) => e.state === 'logged-out').map((e) => e.ref),
48
+ signIn: plan.accounts
49
+ .filter((e) => e.state === 'logged-out' || e.skip?.reason === 'login-expired')
50
+ .map((e) => e.ref),
46
51
  };
47
52
  }
48
53
  /** The line a Pick Command prints before it starts the Host. */
@@ -1,4 +1,4 @@
1
- import type { Account, Env, QuotaFetch, QuotaResult, ReadContext } from '../types.ts';
1
+ import type { Account, Env, LoginEvents, LoginProblem, QuotaFetch, QuotaResult, ReadContext } from '../types.ts';
2
2
  import { type QuotaStoreEntry } from './quota-store.ts';
3
3
  /**
4
4
  * `wait`: ask when the kept answer is old, and wait for it (the CLI). `background`: ask when old, but show the kept
@@ -15,6 +15,12 @@ export declare function quotaCheckOff(family: string, config: {
15
15
  }, env: Env): string | null;
16
16
  /** The kept answer for `account`, after asking again when `mode` and its age say so. */
17
17
  export declare function fetchedQuota(fq: QuotaFetch, account: Account, ctx: ReadContext, hostEnv: Env, mode: QuotaFetchMode): Promise<QuotaStoreEntry | null>;
18
+ /**
19
+ * The Expired Login of a signed-in Subscription Account (ADR-0071), from what its Host wrote (`events`) and the kept
20
+ * Quota answer: expired when the newest sign that the login expired is newer than every sign that it works (a
21
+ * successful turn, a good Quota answer). `signedInAt` is when a sign-in sideby started last finished.
22
+ */
23
+ export declare function loginProblemOf(ref: string, events: LoginEvents | undefined, kept: QuotaStoreEntry | null, signedInAt?: string): LoginProblem | undefined;
18
24
  /**
19
25
  * What sideby shows from a Family that fetches Quota: the newer reading, or the kept answer when local events can
20
26
  * replay old snapshots (`localFallbackOnly`); else why there is none (`off` is why fetching is off, or null).
@@ -42,11 +42,20 @@ async function runFetch(fq, account, ctx, hostEnv, file) {
42
42
  if (answer?.status === 'unavailable')
43
43
  error = answer.detail ?? answer.reason;
44
44
  const quota = answer?.status === 'ok' ? keptQuota(answer) : kept?.quota;
45
+ const attemptedAt = new Date().toISOString();
46
+ // An answer that asks for a new sign-in marks the login expired; a good answer clears it; any other failure keeps
47
+ // what was known (ADR-0071).
48
+ const loginExpiredAt = answer?.status === 'unavailable' && answer.loginExpired === true
49
+ ? attemptedAt
50
+ : answer?.status === 'ok'
51
+ ? undefined
52
+ : kept?.loginExpiredAt;
45
53
  const entry = {
46
54
  version: 1,
47
- attemptedAt: new Date().toISOString(),
55
+ attemptedAt,
48
56
  ...(quota ? { quota } : {}),
49
57
  ...(error ? { error } : {}),
58
+ ...(loginExpiredAt ? { loginExpiredAt } : {}),
50
59
  };
51
60
  await writeQuotaStore(file, entry).catch(() => { });
52
61
  return entry;
@@ -75,6 +84,34 @@ export async function fetchedQuota(fq, account, ctx, hostEnv, mode) {
75
84
  return kept;
76
85
  return Promise.race([run, sleep(FIRST_WAIT_MS)]).then((e) => e ?? kept);
77
86
  }
87
+ /**
88
+ * The Expired Login of a signed-in Subscription Account (ADR-0071), from what its Host wrote (`events`) and the kept
89
+ * Quota answer: expired when the newest sign that the login expired is newer than every sign that it works (a
90
+ * successful turn, a good Quota answer). `signedInAt` is when a sign-in sideby started last finished.
91
+ */
92
+ export function loginProblemOf(ref, events, kept, signedInAt) {
93
+ const t = (s) => (s ? Date.parse(s) : Number.NaN);
94
+ const newest = (...xs) => {
95
+ let best;
96
+ for (const x of xs)
97
+ if (Number.isFinite(t(x)) && (!best || t(x) > t(best)))
98
+ best = x;
99
+ return best;
100
+ };
101
+ const expired = newest(events?.expiredAt, kept?.loginExpiredAt);
102
+ if (!expired)
103
+ return undefined;
104
+ const working = newest(events?.workingAt, kept?.quota?.observedAt);
105
+ if (working && t(working) >= t(expired))
106
+ return undefined;
107
+ const since = new Date(t(expired)).toISOString();
108
+ return {
109
+ kind: 'expired',
110
+ since,
111
+ message: `sign-in expired; run \`sideby login ${ref}\` to sign in again`,
112
+ ...(signedInAt && t(signedInAt) > t(expired) ? { signedInAt } : {}),
113
+ };
114
+ }
78
115
  /**
79
116
  * What sideby shows from a Family that fetches Quota: the newer reading, or the kept answer when local events can
80
117
  * replay old snapshots (`localFallbackOnly`); else why there is none (`off` is why fetching is off, or null).
@@ -10,6 +10,11 @@ export interface QuotaStoreEntry {
10
10
  quota?: FetchedQuota;
11
11
  /** Why the latest fetch failed, when it did. */
12
12
  error?: string;
13
+ /**
14
+ * When a fetch answered that the login expired (ADR-0071). Kept through later generic failures, dropped by the next
15
+ * good answer.
16
+ */
17
+ loginExpiredAt?: string;
13
18
  }
14
19
  export declare function quotaStoreFile(stateDir: string, family: string, name: string): string;
15
20
  /** Only the fields a Quota reading may carry, so a plugin's extra fields never reach the file. */
@@ -54,6 +54,9 @@ export async function readQuotaStore(file) {
54
54
  attemptedAt: e.attemptedAt,
55
55
  ...(quota ? { quota } : {}),
56
56
  ...(typeof e.error === 'string' ? { error: e.error } : {}),
57
+ ...(typeof e.loginExpiredAt === 'string' && Number.isFinite(Date.parse(e.loginExpiredAt))
58
+ ? { loginExpiredAt: e.loginExpiredAt }
59
+ : {}),
57
60
  };
58
61
  }
59
62
  export async function writeQuotaStore(file, entry) {
@@ -132,6 +132,15 @@ const ENTRIES = [
132
132
  target: { settings: 'general', find: 'terminal' },
133
133
  cliCommand: 'sideby terminal',
134
134
  },
135
+ {
136
+ id: 'setting.editor',
137
+ kind: 'setting',
138
+ title: { en: 'Open settings files in', zh: '设置文件用什么打开' },
139
+ synonyms: ['editor', 'cursor', 'vscode', 'vs code', 'zed', 'windsurf', 'settings.json', '编辑器'],
140
+ panel: at(SET, GENERAL),
141
+ target: { settings: 'general', find: 'editor' },
142
+ cliCommand: 'sideby config set editor cursor',
143
+ },
135
144
  {
136
145
  id: 'setting.menubar',
137
146
  kind: 'setting',
@@ -9,6 +9,7 @@ import { dirWrittenAt, groupedEntryWrittenAt, resumeFlagSession, withoutResumeFl
9
9
  import { claudeAiTaskArgs } from './ai-task.js';
10
10
  import { claudeHandoff } from './handoff.js';
11
11
  import { CLAUDE_LAYOUT } from './layout.js';
12
+ import { readClaudeLoginEvents } from './login-events.js';
12
13
  import { claudeModelChoice } from './model.js';
13
14
  import { readClaudeQuota } from './quota.js';
14
15
  import { claudeQuotaFetch } from './quota-fetch.js';
@@ -124,6 +125,8 @@ export const claudeFamily = {
124
125
  hint: 'Opens the browser to sign this account in to Claude (`claude auth login`).',
125
126
  },
126
127
  loginState,
128
+ // An Expired Login (ADR-0071): the transcripts' own records, never a token or `expiresAt`.
129
+ readLoginEvents: readClaudeLoginEvents,
127
130
  model,
128
131
  modelChoice: claudeModelChoice,
129
132
  identity: claudeIdentity,
@@ -0,0 +1,24 @@
1
+ import { FileMemo } from '../../core/file-memo.ts';
2
+ import type { Account, LoginEvents } from '../../types.ts';
3
+ /** How many of the newest main transcripts are read. */
4
+ export declare const LOGIN_SCAN_SESSIONS = 20;
5
+ /**
6
+ * Phrases Claude Code is known to use for an expired login, compared in lower case with every run of spaces and
7
+ * punctuation as one space. A `/login` hint or "Invalid API key" alone is not one: that is a different problem.
8
+ */
9
+ export declare const EXPIRY_PHRASES: readonly ['login reached its time limit'];
10
+ /** Whether a Host message says the login expired, by the phrases above. */
11
+ export declare function saysLoginExpired(text: string): boolean;
12
+ interface Times {
13
+ expiredAt?: number;
14
+ workingAt?: number;
15
+ }
16
+ /** The newest expiry record and the newest normal assistant turn in the tail of one transcript. */
17
+ export declare function transcriptLoginTimes(file: string): Promise<Times>;
18
+ export declare const LISTING_MS = 60000;
19
+ /** Forgets every kept listing (for tests). */
20
+ export declare function clearLoginListings(): void;
21
+ export declare const claudeLoginMemo: FileMemo<Times>;
22
+ /** `FamilyDef.readLoginEvents` for Claude Code. An API Account is never checked. */
23
+ export declare function readClaudeLoginEvents(account: Account): Promise<LoginEvents>;
24
+ export {};
@@ -0,0 +1,163 @@
1
+ // When Claude Code last said an Account's login expired, and when it last showed it working (ADR-0071), from the
2
+ // tail of its newest main session transcripts (`<dir>/projects/<project>/<session>.jsonl`). Claude Code writes an
3
+ // expired login as an assistant record with `isApiErrorMessage: true`, `error: "authentication_failed"` and a text
4
+ // such as "Login reached its time limit · Please run /login" (Claude Code 2.1.319, 2026-11-08). Only the two times
5
+ // are kept: never the transcript text, a token, the Keychain or `.credentials.json`.
6
+ import { readdir, stat } from 'node:fs/promises';
7
+ import { join } from 'node:path';
8
+ import { FileMemo } from '../../core/file-memo.js';
9
+ import { tailLinesWith } from './session-files.js';
10
+ /** How many of the newest main transcripts are read. */
11
+ export const LOGIN_SCAN_SESSIONS = 20;
12
+ /**
13
+ * Phrases Claude Code is known to use for an expired login, compared in lower case with every run of spaces and
14
+ * punctuation as one space. A `/login` hint or "Invalid API key" alone is not one: that is a different problem.
15
+ */
16
+ export const EXPIRY_PHRASES = ['login reached its time limit'];
17
+ const plain = (text) => text
18
+ .toLowerCase()
19
+ .replace(/[^a-z0-9]+/g, ' ')
20
+ .trim();
21
+ /** Whether a Host message says the login expired, by the phrases above. */
22
+ export function saysLoginExpired(text) {
23
+ const t = ` ${plain(text)} `;
24
+ return EXPIRY_PHRASES.some((p) => t.includes(` ${p} `));
25
+ }
26
+ function textOf(message) {
27
+ const content = message?.content;
28
+ if (typeof content === 'string')
29
+ return content;
30
+ if (!Array.isArray(content))
31
+ return '';
32
+ return content
33
+ .map((b) => (b?.type === 'text' ? b.text : ''))
34
+ .filter((t) => typeof t === 'string')
35
+ .join('\n');
36
+ }
37
+ /** The newest expiry record and the newest normal assistant turn in the tail of one transcript. */
38
+ export async function transcriptLoginTimes(file) {
39
+ const out = {};
40
+ for (const line of await tailLinesWith(file, '"assistant"')) {
41
+ let row;
42
+ try {
43
+ row = JSON.parse(line);
44
+ }
45
+ catch {
46
+ continue;
47
+ }
48
+ if (row?.type !== 'assistant')
49
+ continue;
50
+ // A sub-agent's turn (`isSidechain`) says nothing about the main sign-in, as in history.ts.
51
+ if (row.isSidechain === true)
52
+ continue;
53
+ const at = typeof row.timestamp === 'string' ? Date.parse(row.timestamp) : Number.NaN;
54
+ if (!Number.isFinite(at))
55
+ continue;
56
+ const message = row.message;
57
+ if (row.isApiErrorMessage === true) {
58
+ if (row.error === 'authentication_failed' && saysLoginExpired(textOf(message)))
59
+ out.expiredAt = Math.max(out.expiredAt ?? at, at);
60
+ continue;
61
+ }
62
+ // Claude Code's own notices (interrupted, no response) carry the model `<synthetic>`: no model answered them.
63
+ if (message?.model === '<synthetic>' || row.error !== undefined)
64
+ continue;
65
+ out.workingAt = Math.max(out.workingAt ?? at, at);
66
+ }
67
+ return out;
68
+ }
69
+ /**
70
+ * Each Account's last full listing: every main transcript with its modification time, and each project folder's own
71
+ * modification time when it was listed. A new or removed transcript changes its folder's time, so the listing is
72
+ * redone then; otherwise it is redone at most every `LISTING_MS`, and only the newest `LOGIN_SCAN_SESSIONS` are stat-ed
73
+ * again. A transcript outside them that grows (an old session resumed) is seen at the next full listing.
74
+ */
75
+ const listings = new Map();
76
+ export const LISTING_MS = 60_000;
77
+ async function projectFolders(projects) {
78
+ let names;
79
+ try {
80
+ names = await readdir(projects, { withFileTypes: true });
81
+ }
82
+ catch {
83
+ return null;
84
+ }
85
+ const out = new Map();
86
+ for (const p of names) {
87
+ if (!p.isDirectory())
88
+ continue;
89
+ const st = await stat(join(projects, p.name)).catch(() => null);
90
+ if (st)
91
+ out.set(join(projects, p.name), st.mtimeMs);
92
+ }
93
+ return out;
94
+ }
95
+ const sameFolders = (a, b) => a.size === b.size && [...a].every(([k, v]) => b.get(k) === v);
96
+ async function statAll(files) {
97
+ const out = [];
98
+ for (const file of files) {
99
+ const st = await stat(file).catch(() => null);
100
+ if (st?.isFile())
101
+ out.push({ file, st });
102
+ }
103
+ return out.sort((a, b) => b.st.mtimeMs - a.st.mtimeMs);
104
+ }
105
+ /** The main transcripts of an Account, newest first, at most `LOGIN_SCAN_SESSIONS`. Subagent transcripts are left out. */
106
+ async function newestTranscripts(dir, now = Date.now()) {
107
+ const projects = join(dir, 'projects');
108
+ const folders = await projectFolders(projects);
109
+ if (!folders) {
110
+ listings.delete(dir);
111
+ return [];
112
+ }
113
+ const kept = listings.get(dir);
114
+ if (kept && now - kept.at < LISTING_MS && now >= kept.at && sameFolders(kept.folders, folders)) {
115
+ const top = await statAll(kept.files.slice(0, LOGIN_SCAN_SESSIONS).map((f) => f.file));
116
+ return top.slice(0, LOGIN_SCAN_SESSIONS);
117
+ }
118
+ const files = [];
119
+ for (const folder of folders.keys()) {
120
+ let entries;
121
+ try {
122
+ entries = await readdir(folder, { withFileTypes: true });
123
+ }
124
+ catch {
125
+ continue;
126
+ }
127
+ for (const e of entries)
128
+ if (e.isFile() && e.name.endsWith('.jsonl'))
129
+ files.push(join(folder, e.name));
130
+ }
131
+ const all = await statAll(files);
132
+ listings.set(dir, { folders, files: all.map((f) => ({ file: f.file, mtimeMs: f.st.mtimeMs })), at: now });
133
+ return all.slice(0, LOGIN_SCAN_SESSIONS);
134
+ }
135
+ /** Forgets every kept listing (for tests). */
136
+ export function clearLoginListings() {
137
+ listings.clear();
138
+ }
139
+ export const claudeLoginMemo = new FileMemo({ name: 'claude-login', version: 1 });
140
+ const iso = (t) => (t === undefined ? undefined : new Date(t).toISOString());
141
+ /** `FamilyDef.readLoginEvents` for Claude Code. An API Account is never checked. */
142
+ export async function readClaudeLoginEvents(account) {
143
+ if (account.kind === 'api')
144
+ return {};
145
+ const pass = claudeLoginMemo.pass(account.dir);
146
+ let expiredAt;
147
+ let workingAt;
148
+ try {
149
+ for (const { file, st } of await newestTranscripts(account.dir)) {
150
+ const t = await pass.get(file, st, () => transcriptLoginTimes(file));
151
+ if (t.expiredAt !== undefined)
152
+ expiredAt = Math.max(expiredAt ?? t.expiredAt, t.expiredAt);
153
+ if (t.workingAt !== undefined)
154
+ workingAt = Math.max(workingAt ?? t.workingAt, t.workingAt);
155
+ }
156
+ }
157
+ finally {
158
+ pass.done();
159
+ }
160
+ const e = iso(expiredAt);
161
+ const w = iso(workingAt);
162
+ return { ...(e ? { expiredAt: e } : {}), ...(w ? { workingAt: w } : {}) };
163
+ }
@@ -7,6 +7,7 @@
7
7
  import { spawn } from 'node:child_process';
8
8
  import { join } from 'node:path';
9
9
  import { ownedFolder } from '../../core/fs-safe.js';
10
+ import { saysLoginExpired } from './login-events.js';
10
11
  /**
11
12
  * Hooks off and no MCP servers: a quota check is no session, so the user's hooks (notifications, loggers) must not
12
13
  * run for it and no MCP server needs starting. `/usage` itself needs neither.
@@ -160,6 +161,19 @@ export function claudeUsageAnswer(answer, account, now) {
160
161
  const windows = local ? usageQuota(text, now) : null;
161
162
  if (windows)
162
163
  return { status: 'ok', windows, observedAt: new Date(now).toISOString(), source: QUOTA_FETCH_SOURCE };
164
+ // Only an answer with a known expiry phrase is an Expired Login (ADR-0071, Q10); a `/login` hint, "Not logged in" or
165
+ // an API key problem alone is not.
166
+ // A model turn is never read for sign-in words: its text may merely quote them (it is not a local /usage either).
167
+ if (typeof a.num_turns === 'number' && a.num_turns > 0)
168
+ return failed('this Claude Code version cannot report quota through /usage; update Claude Code, then refresh');
169
+ // Only Claude Code's own error result counts as an expiry.
170
+ if (a.is_error === true && saysLoginExpired(text) && !/invalid api key/i.test(text))
171
+ return {
172
+ status: 'unavailable',
173
+ reason: 'fetch-failed',
174
+ detail: `Claude Code says the sign-in expired; run \`sideby login ${account.ref}\`, then refresh`,
175
+ loginExpired: true,
176
+ };
163
177
  if (/not logged in|please (?:run )?\/login|please log ?in/i.test(text))
164
178
  return failed(`Claude Code is not signed in; run \`sideby login ${account.ref}\`, then refresh`);
165
179
  if (/using your API key|API usage billing/i.test(text))
@@ -121,6 +121,8 @@ export interface MenubarFamilyInput {
121
121
  name: string;
122
122
  kind: Account['kind'];
123
123
  login: LoginState | 'not-needed';
124
+ /** Its sign-in expired (an Expired Login, ADR-0071): marked in its row, never recommended. */
125
+ loginExpired?: true;
124
126
  quota: QuotaResult;
125
127
  /** The other refs of its Same Login: the same subscription, so one quota. */
126
128
  sameLogin?: readonly string[];
@@ -233,6 +233,8 @@ function quotaRow(a, plan, now, s, refreshable, lang) {
233
233
  return noted(s.api);
234
234
  if (a.login === 'logged-out')
235
235
  return noted(s.signedOut);
236
+ if (a.loginExpired)
237
+ return { ...noted(s.loginExpired), tip: fill(s.loginExpiredTip, { account: a.ref }) };
236
238
  const quota = a.quota;
237
239
  if (quota.status !== 'ok')
238
240
  return noted(s.noData);
@@ -352,7 +354,9 @@ function section(f, now, s, lang) {
352
354
  const group = all.filter((y) => y === x || (peers.has(y.a.ref) && !aside(y.a) && !done.has(y.a.ref)));
353
355
  for (const y of group)
354
356
  done.add(y.a.ref);
355
- const lead = x;
357
+ // The shared Quota stays on show: a directory whose sign-in expired does not lead the row while another works
358
+ // (ADR-0071); it is listed in the submenu with its mark.
359
+ const lead = group.find((y) => !y.a.loginExpired) ?? x;
356
360
  const others = group.filter((y) => y !== lead);
357
361
  shown.push(others.length
358
362
  ? {
@@ -365,7 +369,7 @@ function section(f, now, s, lang) {
365
369
  }
366
370
  : lead);
367
371
  for (const y of others) {
368
- const note = fill(s.sameLoginNote, { name: lead.a.name });
372
+ const note = y.a.loginExpired ? s.loginExpired : fill(s.sameLoginNote, { name: lead.a.name });
369
373
  same.push({
370
374
  ...y,
371
375
  r: {
@@ -19,6 +19,8 @@ export declare const MENUBAR_STRINGS: {
19
19
  readonly recommended: 'next';
20
20
  readonly api: 'API key';
21
21
  readonly signedOut: 'signed out';
22
+ readonly loginExpired: '⚠ sign-in expired';
23
+ readonly loginExpiredTip: 'Its sign-in expired: run `sideby login {account}` (or use Sign in again in the Panel)';
22
24
  readonly noData: 'no quota yet';
23
25
  readonly olderReading: 'older reading';
24
26
  readonly observedAt: 'Quota recorded at {time}';
@@ -86,6 +88,8 @@ export declare const MENUBAR_STRINGS: {
86
88
  readonly recommended: '首选';
87
89
  readonly api: 'API 密钥';
88
90
  readonly signedOut: '未登录';
91
+ readonly loginExpired: '⚠ 登录已过期';
92
+ readonly loginExpiredTip: '登录已过期:运行 `sideby login {account}`(或在面板里点“重新登录”)';
89
93
  readonly noData: '暂无额度';
90
94
  readonly olderReading: '旧数据';
91
95
  readonly observedAt: '额度记录时间:{time}';
@@ -19,6 +19,8 @@ export const MENUBAR_STRINGS = {
19
19
  recommended: 'next',
20
20
  api: 'API key',
21
21
  signedOut: 'signed out',
22
+ loginExpired: '⚠ sign-in expired',
23
+ loginExpiredTip: 'Its sign-in expired: run `sideby login {account}` (or use Sign in again in the Panel)',
22
24
  noData: 'no quota yet',
23
25
  olderReading: 'older reading',
24
26
  observedAt: 'Quota recorded at {time}',
@@ -86,6 +88,8 @@ export const MENUBAR_STRINGS = {
86
88
  recommended: '首选',
87
89
  api: 'API 密钥',
88
90
  signedOut: '未登录',
91
+ loginExpired: '⚠ 登录已过期',
92
+ loginExpiredTip: '登录已过期:运行 `sideby login {account}`(或在面板里点“重新登录”)',
89
93
  noData: '暂无额度',
90
94
  olderReading: '旧数据',
91
95
  observedAt: '额度记录时间:{time}',
@@ -2,7 +2,7 @@ import type { IncomingMessage, ServerResponse } from 'node:http';
2
2
  import { type AppProfileStatus } from '../core/app-profiles.ts';
3
3
  import { type AutostartContext, type AutostartStatus } from '../core/autostart.ts';
4
4
  import { type BrowserReport } from '../core/browser-profiles.ts';
5
- import { type DisplayConfig, type HandoffSettings, type PanelConfig } from '../core/config.ts';
5
+ import { type DisplayConfig, type EditorChoice, type HandoffSettings, type PanelConfig } from '../core/config.ts';
6
6
  import { type InboundGroup } from '../core/inbound.ts';
7
7
  import { type LiveSession, type LiveSessionsResult, sessionCopyText } from '../core/live-sessions.ts';
8
8
  import { listMessages, type MessageReceipt, sendMessage } from '../core/messages.ts';
@@ -57,6 +57,17 @@ export interface PanelHandlerOptions {
57
57
  ask?: {
58
58
  bridge: 'postMessage';
59
59
  };
60
+ /**
61
+ * How the Panel's "Open settings.json" opens the file (spec §3.30, ADR-0033 amendment). `{ bridge: 'postMessage' }`
62
+ * is for a Portal that opens files itself, with an app the user chose there: inside a frame, the item asks the
63
+ * Panel's server only where the file really is and posts `{ type: 'local-tools:open', version: 1, path }` (the
64
+ * absolute path of the real file, never its content) to `window.parent`, with the Panel's own origin as the target
65
+ * origin; the Portal opens it. Without it, or opened on its own, the Panel's server opens the file (config `editor`).
66
+ * Checked when the handler is created: anything else throws a TypeError.
67
+ */
68
+ open?: {
69
+ bridge: 'postMessage';
70
+ };
60
71
  }
61
72
  /**
62
73
  * Internal, for tests and screenshots: a property under this key of the handler options replaces where the Sessions
@@ -220,6 +231,8 @@ export interface PanelState {
220
231
  configAliases?: Record<string, string>;
221
232
  /** The config `pickCommands`, name → Family (spec §3.13, ADR-0035). */
222
233
  pickCommands?: Record<string, string>;
234
+ /** Config `editor`: what "Open settings.json" opens the file with (spec §3.30); `system` when not set. */
235
+ editor?: EditorChoice;
223
236
  /**
224
237
  * Family → the Pick Command the page offers to add: a Family with two or more Subscription Accounts and none yet,
225
238
  * with the command on PATH the name would hide; `name: null` when no default name is free (the user types one).