sideby 0.36.0 → 0.36.1

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.
package/dist/build.json CHANGED
@@ -1 +1 @@
1
- {"id":"20261113T031219-d21513"}
1
+ {"id":"20261113T091614-584b60"}
@@ -1194,12 +1194,21 @@ export async function cmdAdvisor(a, io, runtime) {
1194
1194
  ? `Use ${name} as the advisor?`
1195
1195
  : 'Put back the advisor setting sideby replaced?');
1196
1196
  for (const g of todo) {
1197
- const to = choice === 'off' ? 'removed' : choice ? `"${choice}"` : 'what it was before';
1198
1197
  const file = tildify(g.file, home);
1199
- if (g.state !== choice)
1200
- io.out(` ${file}: advisorModel ${advisorValue(g)} -> ${to}`);
1201
- if (plan?.betas.includes(g))
1202
- io.out(` ${file}: env.${BETAS_VAR} ${g.betasValue} -> removed`);
1198
+ if (choice) {
1199
+ const to = choice === 'off' ? 'removed' : `"${choice}"`;
1200
+ if (g.state !== choice)
1201
+ io.out(` ${file}: advisorModel ${advisorValue(g)} -> ${to}`);
1202
+ if (plan?.betas.includes(g))
1203
+ io.out(` ${file}: env.${BETAS_VAR} ${g.betasValue} -> removed`);
1204
+ }
1205
+ else {
1206
+ // Only what undo really puts back: a change that kept the model only removed the env entry.
1207
+ if (g.undoModel)
1208
+ io.out(` ${file}: advisorModel ${advisorValue(g)} -> ${g.undoModel}`);
1209
+ if (g.undoBetas)
1210
+ io.out(` ${file}: env.${BETAS_VAR} absent -> ${g.undoBetas}`);
1211
+ }
1203
1212
  io.out(c.dim(` used by ${g.accounts.join(', ')}`));
1204
1213
  if (g.apiAccounts?.length && (plan ? plan.betas.includes(g) : g.undoApiBetas))
1205
1214
  io.out(c.dim(` and by API accounts ${g.apiAccounts.join(', ')}`));
@@ -50,6 +50,13 @@ export interface AdvisorGroup {
50
50
  undo: boolean;
51
51
  /** With `undo`: the change turned config `claude.apiBetasOff` on for this file's API Accounts, and undo turns it back. */
52
52
  undoApiBetas?: true;
53
+ /**
54
+ * With `undo`: undo changes `advisorModel`, back to this value as JSON, or `removed` when the file had none. Absent
55
+ * when the change kept the model the file already named (it only removed the `env` entry).
56
+ */
57
+ undoModel?: string;
58
+ /** With `undo`: undo puts `env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` back, with this value as JSON. */
59
+ undoBetas?: string;
53
60
  }
54
61
  export interface AdvisorStatus {
55
62
  groups: AdvisorGroup[];
@@ -65,6 +72,8 @@ export interface AdvisorConfigState {
65
72
  unlock: boolean;
66
73
  apiBetasOff: boolean;
67
74
  }
75
+ /** What a preview showed of one file: a change refuses a file that no longer holds this (`AdvisorGroup` fields). */
76
+ export type AdvisorSeen = Pick<AdvisorGroup, 'file' | 'state' | 'model' | 'betasValue'>;
68
77
  export interface AdvisorChange {
69
78
  ok: boolean;
70
79
  /** One line per group that was meant to change. */
@@ -152,6 +161,8 @@ export declare function advisorNothingToDo(action: AdvisorChoice | 'undo', scope
152
161
  export declare function setAdvisor(accounts: readonly Account[], ctx: ReadContext, to: AdvisorChoice, opts: AdvisorConfigState & {
153
162
  configFile: string;
154
163
  account?: string;
164
+ /** The files as a preview showed them; a file missing here or no longer like this is not written. */
165
+ seen?: readonly AdvisorSeen[];
155
166
  }): Promise<AdvisorChange>;
156
167
  /** Groups sideby can put back: it wrote there and the key still holds what it wrote. */
157
168
  export declare function advisorGroupsToUndo(groups: readonly AdvisorGroup[]): AdvisorGroup[];
@@ -9,7 +9,7 @@
9
9
  // change turns config `claude.apiBetasOff` on, and sideby then sets it when it starts them (gateways often reject the
10
10
  // headers experimental features send).
11
11
  import { rm } from 'node:fs/promises';
12
- import { isObj, keyRecordPath, readKeyRecord, readSettingsGroups, writeKeyRecord, writeSettingsKey, } from './claude-settings-file.js';
12
+ import { isObj, keyRecordPath, lockedSettingsChange, readKeyRecord, readSettingsGroups, writeKeyRecord, writeSettingsKey, } from './claude-settings-file.js';
13
13
  import { editConfigAdvisor, editConfigClaude } from './config.js';
14
14
  import { UserError } from './errors.js';
15
15
  export const ADVISOR_KEY = 'advisorModel';
@@ -29,6 +29,14 @@ export const ADVISOR_OFF_VARS = ['CLAUDE_CODE_DISABLE_ADVISOR_TOOL', BETAS_VAR];
29
29
  const TITLE = { fable: 'Fable', opus: 'Opus', sonnet: 'Sonnet' };
30
30
  const RECORDS = 'advisor';
31
31
  const ENV_NOT_OBJECT = 'settings.json has an `env` that is not a JSON object; fix it in the file, then try again';
32
+ /** Whether `obj` still holds what `seen` showed: the same `advisorModel` reading and the same true env entry. */
33
+ function looksAsSeen(obj, seen) {
34
+ const now = stateOf(obj[ADVISOR_KEY]);
35
+ const betas = isObj(obj.env) ? obj.env[BETAS_VAR] : undefined;
36
+ const value = truthy(betas) ? JSON.stringify(betas) : undefined;
37
+ return now.state === seen.state && now.model === seen.model && value === seen.betasValue;
38
+ }
39
+ const CHANGED_SINCE = 'settings.json changed after sideby read it, so nothing was changed. Look again and try again.';
32
40
  const MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._:@[\]-]{0,99}$/;
33
41
  function stateOf(v) {
34
42
  if (v === undefined)
@@ -92,6 +100,17 @@ async function readRecord(stateDir, file) {
92
100
  delete r.apiBetas;
93
101
  return r;
94
102
  }
103
+ /** What undo would change in `obj`, from the record of the change it undoes (`AdvisorGroup.undoModel` and on). */
104
+ function undoParts(obj, r) {
105
+ const model = r.removed ? r.hadKey : !(r.hadKey && same(r.previous, r.wrote));
106
+ const env = obj.env;
107
+ const betas = r.betas !== undefined && (env === undefined || (isObj(env) && !Object.hasOwn(env, BETAS_VAR)));
108
+ return {
109
+ ...(r.apiBetas ? { undoApiBetas: true } : {}),
110
+ ...(model ? { undoModel: r.hadKey ? JSON.stringify(r.previous) : 'removed' } : {}),
111
+ ...(betas ? { undoBetas: JSON.stringify(r.betas?.previous) } : {}),
112
+ };
113
+ }
95
114
  /** `obj` with `key` set to `value` at `index` among its keys (at the end without one), keeping the others' order. */
96
115
  function insertAt(obj, key, value, index) {
97
116
  const entries = Object.entries(obj).filter(([k]) => k !== key);
@@ -131,7 +150,7 @@ export async function advisorGroups(accounts, ctx) {
131
150
  ...stateOf(g.obj[ADVISOR_KEY]),
132
151
  ...(truthy(betas) ? { betasOff: true, betasValue: JSON.stringify(betas) } : {}),
133
152
  undo,
134
- ...(undo && record.apiBetas ? { undoApiBetas: true } : {}),
153
+ ...(undo ? undoParts(g.obj, record) : {}),
135
154
  });
136
155
  }
137
156
  }
@@ -247,46 +266,50 @@ async function restoreApiBetas(configFile, previous) {
247
266
  * an undo record of exactly those two entries, and of `apiBetas` (the earlier config `claude.apiBetasOff`) when the
248
267
  * same change turned that on for this file's API Accounts.
249
268
  */
250
- async function writeGroup(stateDir, g, to, apiBetas) {
269
+ async function writeGroup(stateDir, g, to, apiBetas, seen = g) {
251
270
  const dropBetas = to !== 'off';
252
271
  const box = {};
253
- const failed = await writeSettingsKey(g.file, (obj) => {
254
- const r = {
255
- file: g.file,
256
- hadKey: Object.hasOwn(obj, ADVISOR_KEY),
257
- at: new Date().toISOString(),
258
- };
259
- if (r.hadKey)
260
- r.previous = obj[ADVISOR_KEY];
261
- if (to === 'off') {
262
- r.removed = true;
272
+ const failed = await lockedSettingsChange(stateDir, g.file, async () => {
273
+ const failed = await writeSettingsKey(g.file, (obj) => {
274
+ const r = {
275
+ file: g.file,
276
+ hadKey: Object.hasOwn(obj, ADVISOR_KEY),
277
+ at: new Date().toISOString(),
278
+ };
263
279
  if (r.hadKey)
264
- r.index = Object.keys(obj).indexOf(ADVISOR_KEY);
265
- delete obj[ADVISOR_KEY];
266
- }
267
- else {
268
- r.wrote = to;
269
- obj[ADVISOR_KEY] = to;
270
- }
271
- const env = obj.env;
272
- if (dropBetas && isObj(env) && truthy(env[BETAS_VAR])) {
273
- r.betas = { previous: env[BETAS_VAR], index: Object.keys(env).indexOf(BETAS_VAR) };
274
- obj.env = Object.fromEntries(Object.entries(env).filter(([k]) => k !== BETAS_VAR));
275
- if (apiBetas && g.apiAccounts?.length)
276
- r.apiBetas = apiBetas;
277
- }
278
- box.record = r;
279
- return obj;
280
- }, (obj) => {
281
- if (obj.env !== undefined && !isObj(obj.env))
282
- return `${ENV_NOT_OBJECT}.`;
283
- const betas = dropBetas && isObj(obj.env) && truthy(obj.env[BETAS_VAR]);
284
- return stateOf(obj[ADVISOR_KEY]).state === to && !betas
285
- ? 'It was set that way meanwhile; nothing changed.'
286
- : null;
280
+ r.previous = obj[ADVISOR_KEY];
281
+ if (to === 'off') {
282
+ r.removed = true;
283
+ if (r.hadKey)
284
+ r.index = Object.keys(obj).indexOf(ADVISOR_KEY);
285
+ delete obj[ADVISOR_KEY];
286
+ }
287
+ else {
288
+ r.wrote = to;
289
+ obj[ADVISOR_KEY] = to;
290
+ }
291
+ const env = obj.env;
292
+ if (dropBetas && isObj(env) && truthy(env[BETAS_VAR])) {
293
+ r.betas = { previous: env[BETAS_VAR], index: Object.keys(env).indexOf(BETAS_VAR) };
294
+ obj.env = Object.fromEntries(Object.entries(env).filter(([k]) => k !== BETAS_VAR));
295
+ if (apiBetas && g.apiAccounts?.length)
296
+ r.apiBetas = apiBetas;
297
+ }
298
+ box.record = r;
299
+ return obj;
300
+ }, (obj) => {
301
+ if (obj.env !== undefined && !isObj(obj.env))
302
+ return `${ENV_NOT_OBJECT}.`;
303
+ const betas = dropBetas && isObj(obj.env) && truthy(obj.env[BETAS_VAR]);
304
+ if (stateOf(obj[ADVISOR_KEY]).state === to && !betas)
305
+ return 'It was set that way meanwhile; nothing changed.';
306
+ // Read under the lock: the write must be the one the plan (or the Panel's preview) was made for.
307
+ return looksAsSeen(obj, seen) ? null : CHANGED_SINCE;
308
+ });
309
+ if (!failed && box.record)
310
+ await writeKeyRecord(stateDir, RECORDS, g.file, box.record);
311
+ return failed;
287
312
  });
288
- if (!failed && box.record)
289
- await writeKeyRecord(stateDir, RECORDS, g.file, box.record);
290
313
  const betas = !failed && box.record?.betas !== undefined;
291
314
  const done = (to === 'off' ? 'Turned off.' : `Set to ${to}.`) + (betas ? ` Removed env.${BETAS_VAR}.` : '');
292
315
  return {
@@ -326,8 +349,20 @@ export async function setAdvisor(accounts, ctx, to, opts) {
326
349
  }
327
350
  }
328
351
  const written = [];
329
- for (const g of plan.todo)
330
- written.push(await writeGroup(ctx.stateDir, g, to, apiPrev));
352
+ for (const g of plan.todo) {
353
+ const seen = opts.seen ? opts.seen.find((s) => s.file === g.file) : g;
354
+ if (seen)
355
+ written.push(await writeGroup(ctx.stateDir, g, to, apiPrev, seen));
356
+ else
357
+ written.push({
358
+ file: g.file,
359
+ accounts: g.accounts,
360
+ ok: false,
361
+ message: CHANGED_SINCE,
362
+ betas: false,
363
+ api: false,
364
+ });
365
+ }
331
366
  const results = written.map(({ betas: _b, api: _a, ...r }) => r);
332
367
  // No file the API Accounts use lost the variable after all: the config goes back as it was.
333
368
  const apiOn = apiPrev !== undefined && written.some((r) => r.api);
@@ -380,33 +415,45 @@ export async function undoAdvisor(accounts, ctx, opts) {
380
415
  let apiPrev;
381
416
  let apiBack = true;
382
417
  for (const g of todo) {
383
- const record = await readRecord(ctx.stateDir, g.file);
384
- if (!record)
385
- continue;
418
+ // The record is read under the lock, so it is the one of the last change that finished.
419
+ const box = {};
386
420
  let back = false;
387
- const failed = await writeSettingsKey(g.file, (obj) => {
388
- let out = obj;
389
- if (record.removed) {
390
- if (record.hadKey)
391
- out = insertAt(out, ADVISOR_KEY, record.previous, record.index);
392
- }
393
- else if (record.hadKey)
394
- out[ADVISOR_KEY] = record.previous;
395
- else
396
- delete out[ADVISOR_KEY];
397
- const b = record.betas;
398
- if (b) {
399
- if (out.env === undefined)
400
- out.env = { [BETAS_VAR]: b.previous };
401
- else if (isObj(out.env) && !Object.hasOwn(out.env, BETAS_VAR))
402
- out.env = insertAt(out.env, BETAS_VAR, b.previous, b.index);
403
- }
404
- back = isObj(out.env) && truthy(out.env[BETAS_VAR]);
405
- return out;
406
- }, (obj) => holds(obj, record) ? null : 'The setting was changed after sideby set it, so it was left alone.');
407
- if (!failed)
408
- await rm(keyRecordPath(ctx.stateDir, RECORDS, g.file), { force: true });
409
- if (record.apiBetas) {
421
+ const failed = await lockedSettingsChange(ctx.stateDir, g.file, async () => {
422
+ const record = await readRecord(ctx.stateDir, g.file);
423
+ if (!record)
424
+ return null;
425
+ box.record = record;
426
+ const failed = await writeSettingsKey(g.file, (obj) => {
427
+ let out = obj;
428
+ if (record.removed) {
429
+ if (record.hadKey)
430
+ out = insertAt(out, ADVISOR_KEY, record.previous, record.index);
431
+ }
432
+ else if (record.hadKey)
433
+ out[ADVISOR_KEY] = record.previous;
434
+ else
435
+ delete out[ADVISOR_KEY];
436
+ const b = record.betas;
437
+ if (b) {
438
+ if (out.env === undefined)
439
+ out.env = { [BETAS_VAR]: b.previous };
440
+ else if (isObj(out.env) && !Object.hasOwn(out.env, BETAS_VAR))
441
+ out.env = insertAt(out.env, BETAS_VAR, b.previous, b.index);
442
+ }
443
+ back = isObj(out.env) && truthy(out.env[BETAS_VAR]);
444
+ return out;
445
+ }, (obj) => holds(obj, record) ? null : 'The setting was changed after sideby set it, so it was left alone.');
446
+ if (!failed)
447
+ await rm(keyRecordPath(ctx.stateDir, RECORDS, g.file), { force: true });
448
+ return failed;
449
+ });
450
+ const record = box.record;
451
+ if (!record && !failed)
452
+ continue;
453
+ // The lock stayed held, so its record was not read: the file may still need config claude.apiBetasOff.
454
+ if (!record)
455
+ apiBack = false;
456
+ if (record?.apiBetas) {
410
457
  apiPrev ??= record.apiBetas.previous;
411
458
  if (failed || !back)
412
459
  apiBack = false;
@@ -27,6 +27,20 @@ export declare function settingsFileGroups(accounts: readonly Account[]): Promis
27
27
  * else what went wrong in plain words.
28
28
  */
29
29
  export declare function writeSettingsKey(file: string, change: (obj: Json) => Json, expect: (obj: Json) => string | null): Promise<string | null>;
30
+ /** How long a change waits for another one of the same file. Mutable for tests only. */
31
+ export declare const settingsLockWait: {
32
+ timeoutMs: number;
33
+ pollMs: number;
34
+ };
35
+ /** What a change says when another sideby change of the same file held it for too long. */
36
+ export declare const SETTINGS_BUSY = "Another sideby change of this settings file is still running, so nothing was changed. Try again in a moment.";
37
+ /**
38
+ * Runs one change of `file` and its undo record while no other sideby process (the CLI, the Panel) changes that file,
39
+ * so a record always describes the write it follows and one change never replaces another's record halfway. The lock
40
+ * is `<state>/settings-locks/<hash of file>.lock`. Returns `fn`'s answer, or `SETTINGS_BUSY` when the lock stayed
41
+ * held.
42
+ */
43
+ export declare function lockedSettingsChange(stateDir: string, file: string, fn: () => Promise<string | null>): Promise<string | null>;
30
44
  /** Where sideby keeps the undo record of one key it wrote in `file`: `<state>/<dir>/<hash of file>.json`. */
31
45
  export declare const keyRecordPath: (stateDir: string, dir: string, file: string) => string;
32
46
  /** Writes an undo record (mode 600) under the state directory. */
@@ -4,6 +4,7 @@
4
4
  import { mkdir, readFile, rm, stat } from 'node:fs/promises';
5
5
  import { join } from 'node:path';
6
6
  import { lstatOrNull, realpathOrNull, sha256, writeFileAtomic, writeIfUnchanged } from './fs-safe.js';
7
+ import { takeFileLock } from './lock.js';
7
8
  const MAX_BYTES = 5_000_000;
8
9
  export const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
9
10
  function detectIndent(text) {
@@ -83,6 +84,33 @@ export async function writeSettingsKey(file, change, expect) {
83
84
  const wrote = await writeIfUnchanged(file, sha256(read.text), render(change({ ...read.obj }), read.text), mode);
84
85
  return wrote ? null : 'settings.json changed while sideby was writing, so nothing was changed. Try again.';
85
86
  }
87
+ /** How long a change waits for another one of the same file. Mutable for tests only. */
88
+ export const settingsLockWait = { timeoutMs: 10_000, pollMs: 50 };
89
+ /** What a change says when another sideby change of the same file held it for too long. */
90
+ export const SETTINGS_BUSY = 'Another sideby change of this settings file is still running, so nothing was changed. Try again in a moment.';
91
+ /**
92
+ * Runs one change of `file` and its undo record while no other sideby process (the CLI, the Panel) changes that file,
93
+ * so a record always describes the write it follows and one change never replaces another's record halfway. The lock
94
+ * is `<state>/settings-locks/<hash of file>.lock`. Returns `fn`'s answer, or `SETTINGS_BUSY` when the lock stayed
95
+ * held.
96
+ */
97
+ export async function lockedSettingsChange(stateDir, file, fn) {
98
+ const dir = join(stateDir, 'settings-locks');
99
+ await mkdir(dir, { recursive: true, mode: 0o700 });
100
+ const release = await takeFileLock(join(dir, `${sha256(file).slice(0, 16)}.lock`), {
101
+ staleMs: 15_000,
102
+ beatMs: 3_000,
103
+ wait: { ...settingsLockWait },
104
+ });
105
+ if (!release)
106
+ return SETTINGS_BUSY;
107
+ try {
108
+ return await fn();
109
+ }
110
+ finally {
111
+ await release();
112
+ }
113
+ }
86
114
  /** Where sideby keeps the undo record of one key it wrote in `file`: `<state>/<dir>/<hash of file>.json`. */
87
115
  export const keyRecordPath = (stateDir, dir, file) => join(stateDir, dir, `${sha256(file).slice(0, 16)}.json`);
88
116
  /** Writes an undo record (mode 600) under the state directory. */
@@ -133,16 +161,19 @@ export function settingsKey(key, records, opts = {}) {
133
161
  async set(stateDir, groups, to, expect, done) {
134
162
  const results = [];
135
163
  for (const g of groups) {
136
- let before = { hadKey: false };
137
- const failed = await writeSettingsKey(g.file, (obj) => {
138
- before = key in obj ? { hadKey: true, previous: obj[key] } : { hadKey: false };
139
- obj[key] = to;
140
- return obj;
141
- }, (obj) => expect(obj[key]));
142
- if (!failed) {
143
- const record = { file: g.file, ...before, wrote: to, at: new Date().toISOString() };
144
- await writeKeyRecord(stateDir, records, g.file, record);
145
- }
164
+ const failed = await lockedSettingsChange(stateDir, g.file, async () => {
165
+ let before = { hadKey: false };
166
+ const failed = await writeSettingsKey(g.file, (obj) => {
167
+ before = key in obj ? { hadKey: true, previous: obj[key] } : { hadKey: false };
168
+ obj[key] = to;
169
+ return obj;
170
+ }, (obj) => expect(obj[key]));
171
+ if (!failed) {
172
+ const record = { file: g.file, ...before, wrote: to, at: new Date().toISOString() };
173
+ await writeKeyRecord(stateDir, records, g.file, record);
174
+ }
175
+ return failed;
176
+ });
146
177
  results.push({ file: g.file, accounts: g.accounts, ok: !failed, message: failed ?? done });
147
178
  }
148
179
  return results;
@@ -151,20 +182,28 @@ export function settingsKey(key, records, opts = {}) {
151
182
  async undo(stateDir, groups) {
152
183
  const results = [];
153
184
  for (const g of groups) {
154
- const record = await readRecord(stateDir, g.file);
155
- if (!record)
185
+ // The record is read under the lock, so it is the one of the last change that finished.
186
+ let found = false;
187
+ const failed = await lockedSettingsChange(stateDir, g.file, async () => {
188
+ const record = await readRecord(stateDir, g.file);
189
+ if (!record)
190
+ return null;
191
+ found = true;
192
+ const failed = await writeSettingsKey(g.file, (obj) => {
193
+ if (record.hadKey)
194
+ obj[key] = record.previous;
195
+ else
196
+ delete obj[key];
197
+ return obj;
198
+ }, (obj) => same(obj[key], record.wrote)
199
+ ? null
200
+ : 'The setting was changed after sideby set it, so it was left alone.');
201
+ if (!failed)
202
+ await rm(keyRecordPath(stateDir, records, g.file), { force: true });
203
+ return failed;
204
+ });
205
+ if (!found && !failed)
156
206
  continue;
157
- const failed = await writeSettingsKey(g.file, (obj) => {
158
- if (record.hadKey)
159
- obj[key] = record.previous;
160
- else
161
- delete obj[key];
162
- return obj;
163
- }, (obj) => same(obj[key], record.wrote)
164
- ? null
165
- : 'The setting was changed after sideby set it, so it was left alone.');
166
- if (!failed)
167
- await rm(keyRecordPath(stateDir, records, g.file), { force: true });
168
207
  results.push({ file: g.file, accounts: g.accounts, ok: !failed, message: failed ?? 'Put back.' });
169
208
  }
170
209
  return results;
@@ -1081,24 +1081,41 @@ export function createPanelHandler(opts) {
1081
1081
  * A change of one key in Claude's settings files that the page showed file by file before the user confirmed
1082
1082
  * (Remote Control, spec §3.22; receiving Messages, ADR-0045). Without `confirm` it writes nothing and names the
1083
1083
  * files; with it, `files` must be exactly the files the page showed, or nothing is written and `changedSince` says
1084
- * so, because a file the user never saw in the preview must not change. Undo passes no `todo`: it only puts back
1085
- * what sideby wrote, and its toast runs before the page has read the new state.
1084
+ * so, because a file the user never saw in the preview must not change. Where what a file holds decides what the
1085
+ * write does (Advisor: whether `env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` goes too), `shown` names that part of a
1086
+ * group: the page sends the groups it showed as `groups`, and a file whose part differs now refuses the same way.
1087
+ * Remote Control and receiving Messages need none: they write one fixed value, whatever the file held. Undo passes
1088
+ * no `todo`: it only puts back what sideby wrote, only while the file still holds that (spec §3.22), and its toast
1089
+ * runs before the page has read the new state.
1086
1090
  */
1087
1091
  const previewedChange = (change) => ({
1088
1092
  writes: (body) => body.confirm === true,
1089
1093
  async run(body) {
1090
1094
  const rt = await getRuntime();
1091
1095
  const home = rt.paths.home;
1092
- const files = change.todo ? (await change.todo(rt, body)).map((g) => tildify(g.file, home)) : undefined;
1096
+ const raw = change.todo ? await change.todo(rt, body) : undefined;
1097
+ const todo = raw?.map((g) => ({ ...g, file: tildify(g.file, home) }));
1098
+ const files = todo?.map((g) => g.file);
1093
1099
  if (!optBool(body, 'confirm'))
1094
1100
  return { applied: false, ...(files ? { files } : {}) };
1095
- if (files) {
1101
+ if (todo && files) {
1096
1102
  const saw = body.files;
1097
1103
  const same = Array.isArray(saw) && saw.length === files.length && files.every((f) => saw.includes(f));
1098
1104
  if (!same)
1099
1105
  return { applied: false, changedSince: true, files };
1106
+ const shown = change.shown;
1107
+ if (shown) {
1108
+ const seen = (Array.isArray(body.groups) ? body.groups : []).filter((x) => typeof x === 'object' && x !== null && !Array.isArray(x));
1109
+ const key = (g) => JSON.stringify(shown(g) ?? null);
1110
+ const alike = todo.every((g) => {
1111
+ const s = seen.find((x) => x.file === g.file);
1112
+ return s !== undefined && key(s) === key(g);
1113
+ });
1114
+ if (!alike)
1115
+ return { applied: false, changedSince: true, files };
1116
+ }
1100
1117
  }
1101
- const r = await change.apply(rt, body);
1118
+ const r = await change.apply(rt, body, raw);
1102
1119
  return { ...r, applied: true, results: r.results.map((x) => ({ ...x, file: tildify(x.file, home) })) };
1103
1120
  },
1104
1121
  });
@@ -1477,9 +1494,12 @@ export function createPanelHandler(opts) {
1477
1494
  const st = await rt.advisor();
1478
1495
  return advisorPlan(advisorScope(st.groups, account), to, st).todo;
1479
1496
  },
1480
- async apply(rt, body) {
1497
+ // What decides the write besides the model the body names: the env entry it removes, and who shares the file.
1498
+ shown: (g) => [g.state ?? null, g.model ?? null, g.betasValue ?? null, g.apiAccounts ?? []],
1499
+ // The files as the page showed them, checked again under each file's lock right before the write.
1500
+ async apply(rt, body, checked) {
1481
1501
  const { to, account } = await advisorBody(rt, body);
1482
- return rt.advisorSet(to, account ? { account } : {});
1502
+ return rt.advisorSet(to, { ...(account ? { account } : {}), ...(checked ? { seen: checked } : {}) });
1483
1503
  },
1484
1504
  }),
1485
1505
  '/api/advisor/undo': previewedChange({ apply: (rt) => rt.advisorUndo() }),
@@ -7980,10 +7980,12 @@ const MAIN = String.raw `
7980
7980
  async function setAdvisorModel(to) {
7981
7981
  const st = advState()
7982
7982
  if (!st) return
7983
- const files = advPlan(st, to).todo.map((g) => g.file)
7983
+ const groups = advPlan(st, to).todo
7984
+ const files = groups.map((g) => g.file)
7984
7985
  advBusy(true)
7985
7986
  try {
7986
- const r = await api('/api/advisor/set', { confirm: true, to, files })
7987
+ // The groups as shown, so the server refuses when a file now holds something the preview did not show.
7988
+ const r = await api('/api/advisor/set', { confirm: true, to, files, groups })
7987
7989
  if (r.changedSince) toast(t('as.changedSince'), { kind: 'fail' })
7988
7990
  else if (r.ok) {
7989
7991
  // Show the new state now; the reload that follows confirms it.
@@ -1,5 +1,5 @@
1
1
  import { type AccountRefError } from './core/accounts.ts';
2
- import { type AdvisorChange, type AdvisorChoice, type AdvisorStatus } from './core/advisor.ts';
2
+ import { type AdvisorChange, type AdvisorChoice, type AdvisorSeen, type AdvisorStatus } from './core/advisor.ts';
3
3
  import { type Config, type DisplayConfig, type HandoffSettings } from './core/config.ts';
4
4
  import { type CreateResult } from './core/create.ts';
5
5
  import { type DesktopDeps } from './core/desktop-app.ts';
@@ -426,10 +426,12 @@ export interface Runtime {
426
426
  advisor(): Promise<AdvisorStatus>;
427
427
  /**
428
428
  * Sets `advisorModel` to `to` (`off` removes it) in every settings file that does not hold it yet, or only in the one
429
- * `opts.account` uses, remembering how to undo it; a model also turns config `advisor.unlock` on.
429
+ * `opts.account` uses, remembering how to undo it; a model also turns config `advisor.unlock` on. With `opts.seen`
430
+ * (the files as a preview showed them), a file that no longer looks like that is not written.
430
431
  */
431
432
  advisorSet(to: AdvisorChoice, opts?: {
432
433
  account?: string;
434
+ seen?: readonly AdvisorSeen[];
433
435
  }): Promise<AdvisorChange>;
434
436
  /** Puts back what `advisorSet` replaced, only where the key still holds what it wrote. */
435
437
  advisorUndo(): Promise<AdvisorChange>;
@@ -1505,6 +1505,7 @@ export async function createRuntime(opts = {}) {
1505
1505
  configFile: paths.configFile,
1506
1506
  ...advisorConfig(),
1507
1507
  ...(account ? { account } : {}),
1508
+ ...(opts.seen ? { seen: opts.seen } : {}),
1508
1509
  });
1509
1510
  await reloadAdvisorConfig();
1510
1511
  return r;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sideby",
3
- "version": "0.36.0",
3
+ "version": "0.36.1",
4
4
  "description": "Run work, personal and API-key accounts at the same time, without their configs drifting apart.",
5
5
  "license": "MIT",
6
6
  "author": "Adonis0123 (https://github.com/Adonis0123)",
@@ -2,7 +2,7 @@
2
2
  name: sideby
3
3
  description: Use when the user runs, or wants to run, several AI coding accounts (Claude Code, Codex, Grok Build, pi) side by side. Covers installing sideby and setting up a new account ("install sideby", "set up another Claude account", "add cc008", "配置一个 cc00x", "再加一个 Codex 账号"), explaining what accounts share and what stays separate ("what do my accounts share?", "这些账号共享了什么"), showing which account a session is ("show [cc001] in the status line", "加上账号标识"), finding a past session of any account ("找一下我上周改登录页的那个会话"), telling another running session something, in any account ("告诉 cc002 ……", "给跑构建的那个会话发消息"; Claude Code's own SendMessage reaches only sessions of the same account), seeing accounts, quota and usage, moving on when one hits its 5-hour or weekly limit, moving the current task to another account ("用 cc008 继续", "交回 cc008"), adding a short command (alias) or a pick command that starts whichever account has the most quota ("加个 cc"), adding an API account from a vendor's docs ("加一个 DeepSeek API 账号"), supporting a new tool, and repairing drifted account directories (skills, hooks, rules or settings not shared, wrong symlinks, credential file permissions). Drives the `sideby` CLI with `--json`; the agent does every step except browser sign-in, filling in secrets and starting interactive sessions, which it hands to the user as one command (inside an Auto Handoff session, `sideby handoff ready --to` moves the task itself).
4
4
  metadata:
5
- version: "0.36.0"
5
+ version: "0.36.1"
6
6
  requires:
7
7
  bins: [sideby, node]
8
8
  cliHelp: sideby --help
@@ -60,7 +60,7 @@ Use `sideby remote-control off --json`, `on --json` or `undo --json`. Exit 10 sh
60
60
 
61
61
  Claude Code's Advisor lets a session consult a stronger model (Fable, Opus or Sonnet) at key moments. `/advisor` is hidden ("Unknown command: /advisor") until it is unlocked: sideby unlocks it in sessions it starts while config `advisor.unlock` is on.
62
62
 
63
- `sideby advisor --json` returns `action: "status"`, `groups`, `unlock` and optional `envOff`. Each group has `file`, `accounts`, `state`, `undo`, optional `model`, `reason`, `betasOff` and `betasValue`. `state` is `fable`, `opus`, `sonnet`, `other` (another value; `model` holds it when it is a plain model id), `off` (`advisorModel` not set), `missing` (no settings.json: suggest `sideby doctor --fix`) or `blocked`. Only Claude subscription accounts appear; API accounts are left out. `betasOff: true` means that file's `env` sets `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` to a true value (`betasValue` is that value as JSON, such as `"1"`): it blocks the Advisor ("/advisor isn't available in this environment") even when unlocked. `envOff` names a variable in the user's own shell environment that hides the Advisor in every session, those sideby starts too: tell the user to remove it from their shell profile; sideby never overrides it. Top-level `apiBetasOff` is config `claude.apiBetasOff`: while it is true, sideby adds `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1` whenever it starts a Claude API account (never a subscription account; a value in the account's `proxy.env` or the environment wins). A group's `apiAccounts` lists the API accounts that share its file (they are not in `accounts`), and `undoApiBetas: true` means undo also turns that config back.
63
+ `sideby advisor --json` returns `action: "status"`, `groups`, `unlock` and optional `envOff`. Each group has `file`, `accounts`, `state`, `undo`, optional `model`, `reason`, `betasOff` and `betasValue`. `state` is `fable`, `opus`, `sonnet`, `other` (another value; `model` holds it when it is a plain model id), `off` (`advisorModel` not set), `missing` (no settings.json: suggest `sideby doctor --fix`) or `blocked`. Only Claude subscription accounts appear; API accounts are left out. `betasOff: true` means that file's `env` sets `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` to a true value (`betasValue` is that value as JSON, such as `"1"`): it blocks the Advisor ("/advisor isn't available in this environment") even when unlocked. `envOff` names a variable in the user's own shell environment that hides the Advisor in every session, those sideby starts too: tell the user to remove it from their shell profile; sideby never overrides it. Top-level `apiBetasOff` is config `claude.apiBetasOff`: while it is true, sideby adds `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1` whenever it starts a Claude API account (never a subscription account; a value in the account's `proxy.env` or the environment wins). A group's `apiAccounts` lists the API accounts that share its file (they are not in `accounts`), and `undoApiBetas: true` means undo also turns that config back. With `undo`, `undoModel` is the `advisorModel` value undo puts back (JSON, or `removed`; absent when the last change kept the model) and `undoBetas` the env value it puts back: name only these when you tell the user what undo changes.
64
64
 
65
65
  Use `sideby advisor opus --json` (or `fable`, `sonnet`, `off`; `--account <ref>` for one account's file only), `sideby advisor undo --json` or `sideby advisor unlock on|off --json`. Exit 10 is a preview with `applied: false`: show each `groups` entry (the file, `advisorModel` from and to, its accounts), any `skipped` files, and, when `unlocks` is true, that sideby will also turn `advisor.unlock` on. When `removesBetas` is true, the preview also removes `env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` from the files with `betasOff` (only that entry; every other `env` entry stays): before the user agrees, tell them this also turns Claude Code's other experimental features back on, and that `undo` puts it back. When the preview has `apiAccounts`, those API accounts share a file that loses the variable, which their gateway may need (it stops `anthropic-beta` headers some gateways reject): with `apiBetasOn: true` the same change turns `claude.apiBetasOff` on (preview line `sideby config: claude.apiBetasOff false -> true`) so sideby gives them the variable at launch; without it, they already get it. Name those accounts to the user. An undo preview with `apiBetasBack: true` also turns the config back to its earlier value; if undo cannot (the config changed, or a file did not get the variable back), it stays on and the message names `sideby config set claude.apiBetasOff false`. Confirm, then rerun with `--yes`. A result has `applied`, `results` (`file`, `accounts`, `ok`, `message`), `unlocked`, `unlock`, `apiBetasOff` and `message`. Exit 1 with `applied: false` and a message means nothing to change (already that model and unlocked, nothing to undo, every file missing or blocked, no subscription account): tell the user, do not retry. `off` removes the key and never touches the env entry; `off` and `undo` leave `advisor.unlock` as it is; `sideby advisor unlock off` stops unlocking.
66
66