repoburg 1.3.275 → 1.3.277

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.
@@ -41095,6 +41095,7 @@ function createTables(database) {
41095
41095
  workspace_path TEXT NOT NULL DEFAULT '',
41096
41096
  pinned INTEGER NOT NULL DEFAULT 0,
41097
41097
  state TEXT,
41098
+ version INTEGER NOT NULL DEFAULT 0,
41098
41099
  created_at TEXT NOT NULL,
41099
41100
  updated_at TEXT NOT NULL,
41100
41101
  UNIQUE(app_id, workspace_path)
@@ -41150,6 +41151,10 @@ CREATE INDEX IF NOT EXISTS idx_workspaces_path ON workspaces(path);
41150
41151
  if (!sessColumns.some((c) => c.name === "user_touched")) {
41151
41152
  database.exec("ALTER TABLE sessions ADD COLUMN user_touched INTEGER NOT NULL DEFAULT 0");
41152
41153
  }
41154
+ const appInstanceColumns = database.prepare("PRAGMA table_info(app_instances)").all();
41155
+ if (!appInstanceColumns.some((c) => c.name === "version")) {
41156
+ database.exec("ALTER TABLE app_instances ADD COLUMN version INTEGER NOT NULL DEFAULT 0");
41157
+ }
41153
41158
  const turnColumns = database.prepare("PRAGMA table_info(turns)").all();
41154
41159
  if (!turnColumns.some((c) => c.name === "thread_id")) {
41155
41160
  database.exec("ALTER TABLE turns ADD COLUMN thread_id TEXT");
@@ -98312,7 +98317,8 @@ Icons come from ONE library: Lucide (https://lucide.dev/icons, ISC).
98312
98317
  ## Bridge API (window.AgentPane)
98313
98318
 
98314
98319
  - getApp() - app info (id, title)
98315
- - getState() / setState(data) - persistent JSON state, survives page reload
98320
+ - getState() / setState(data, { ifVersion }?) - persistent JSON state, survives page reload; getState reads the stored copy on every call (see "Shared state" below)
98321
+ - onStateChanged(callback) - callback({ version }) when somebody else (an agent, another tab) wrote the state; not fired for this tab's own setState
98316
98322
  - createSession({ cwd, runtime_type, model, model_reasoning_effort, title }) - agent session owned by this app; model_reasoning_effort is the effort for its turns ("low" | "medium" | "high" | "xhigh" | "max" | "ultra", the levels the model supports), omitted = the runtime's default
98317
98323
  - submitTurn(sessionId, prompt, { attachments }?) - send a prompt to a session; attachments (optional) are stored files (id, url or the uploadFile result) or inline Blobs / { name, type, data } sent with that turn only; the agent sees attached images (Claude and Codex)
98318
98324
  - onTurnCompleted(callback) - callback(event, { turnId, response }) when a turn ends
@@ -98324,6 +98330,23 @@ Icons come from ONE library: Lucide (https://lucide.dev/icons, ISC).
98324
98330
  - getFile(ref) - metadata of a stored file ({ id, url, path, type, size }), null when ref (id or url) names no file of this app
98325
98331
  - fileUrl(ref) - synchronous URL to load a stored file from in this pane; any other string comes back unchanged
98326
98332
 
98333
+ ## Shared state
98334
+
98335
+ One state instance (app + workspace) has several writers: this tab, other
98336
+ tabs on the same workspace, the headless runtime (agent tool calls) and
98337
+ agents writing over REST.
98338
+ - on onStateChanged, re-read with getState() and re-render
98339
+ - read-modify-write: apply the change to the data of a fresh getState()
98340
+ and save with setState(data, { ifVersion: state.version }). When
98341
+ somebody wrote in between, nothing is written and the promise rejects
98342
+ with error.code === 'conflict' (error.state = the stored state now):
98343
+ apply the change to error.state.data and retry with its version
98344
+ - never write back an old in-memory copy without ifVersion: it silently
98345
+ replaces whatever an agent wrote since
98346
+ - agents writing over REST do the same: GET /api/apps/<id>/state?workspace=<key>,
98347
+ then PUT { "data": ..., "ifVersion": <version from the GET> };
98348
+ 409 = re-read and retry
98349
+
98327
98350
  ## Files and images
98328
98351
 
98329
98352
  uploadFile stores images (PNG, JPEG, GIF or WebP, max 5 MB) for the app,
@@ -98464,6 +98487,15 @@ function stopAppsWatch() {
98464
98487
  }
98465
98488
 
98466
98489
  // src/apps/instances.ts
98490
+ var StateConflictError = class extends Error {
98491
+ /** The stored state the write was checked against. */
98492
+ current;
98493
+ constructor(expected, current) {
98494
+ super(`App state changed: the write expected version ${expected}, the stored copy is at version ${current.version}`);
98495
+ this.name = "StateConflictError";
98496
+ this.current = current;
98497
+ }
98498
+ };
98467
98499
  function rowToState(row) {
98468
98500
  let data = null;
98469
98501
  try {
@@ -98471,41 +98503,63 @@ function rowToState(row) {
98471
98503
  if (parsed && typeof parsed === "object") data = parsed;
98472
98504
  } catch {
98473
98505
  }
98474
- return { pinned: row.pinned === 1, data };
98506
+ return { pinned: row.pinned === 1, data, version: row.version ?? 0 };
98475
98507
  }
98476
98508
  function writeRow(appId, workspace, state) {
98477
98509
  const now = (/* @__PURE__ */ new Date()).toISOString();
98478
98510
  getDb().prepare(
98479
- `INSERT INTO app_instances (id, app_id, workspace_path, pinned, state, created_at, updated_at)
98480
- VALUES (?, ?, ?, ?, ?, ?, ?)
98511
+ `INSERT INTO app_instances (id, app_id, workspace_path, pinned, state, version, created_at, updated_at)
98512
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
98481
98513
  ON CONFLICT(app_id, workspace_path) DO UPDATE SET
98482
- pinned = excluded.pinned, state = excluded.state, updated_at = excluded.updated_at`
98483
- ).run(v4_default(), appId, workspace, state.pinned ? 1 : 0, JSON.stringify(state.data ?? null), now, now);
98514
+ pinned = excluded.pinned, state = excluded.state, version = excluded.version,
98515
+ updated_at = excluded.updated_at`
98516
+ ).run(
98517
+ v4_default(),
98518
+ appId,
98519
+ workspace,
98520
+ state.pinned ? 1 : 0,
98521
+ JSON.stringify(state.data ?? null),
98522
+ state.version,
98523
+ now,
98524
+ now
98525
+ );
98526
+ }
98527
+ var EMPTY_STATE = { pinned: false, data: null, version: 0 };
98528
+ function readRow(appId, workspace) {
98529
+ const row = getDb().prepare("SELECT * FROM app_instances WHERE app_id = ? AND workspace_path = ?").get(appId, workspace);
98530
+ return row ? rowToState(row) : null;
98484
98531
  }
98485
98532
  function getInstanceState(appId, workspace = "") {
98486
- const db2 = getDb();
98487
- const row = db2.prepare("SELECT * FROM app_instances WHERE app_id = ? AND workspace_path = ?").get(appId, workspace);
98488
- if (row) return rowToState(row);
98533
+ const stored = readRow(appId, workspace);
98534
+ if (stored) return stored;
98489
98535
  if (workspace === "") {
98490
98536
  const legacyFile = path4.join(appDir(appId), "state.json");
98491
98537
  if (fs2.existsSync(legacyFile)) {
98492
- const imported = readState(appId);
98538
+ const legacy = readState(appId);
98539
+ const imported = { pinned: legacy.pinned, data: legacy.data, version: 1 };
98493
98540
  writeRow(appId, "", imported);
98494
98541
  fs2.rmSync(legacyFile, { force: true });
98495
98542
  return imported;
98496
98543
  }
98497
98544
  }
98498
- return { pinned: false, data: null };
98545
+ return { ...EMPTY_STATE };
98499
98546
  }
98500
98547
  function updateInstanceState(appId, workspace, patch) {
98501
- const current = getInstanceState(appId, workspace);
98502
- const { pinned, data } = patch;
98503
- const next = {
98504
- pinned: typeof pinned === "boolean" ? pinned : current.pinned,
98505
- data: data === void 0 ? current.data : data !== null && typeof data === "object" ? data : null
98506
- };
98507
- writeRow(appId, workspace, next);
98508
- return next;
98548
+ getInstanceState(appId, workspace);
98549
+ return getDb().transaction(() => {
98550
+ const current = readRow(appId, workspace) ?? { ...EMPTY_STATE };
98551
+ const { pinned, data, ifVersion } = patch;
98552
+ if (typeof ifVersion === "number" && ifVersion !== current.version) {
98553
+ throw new StateConflictError(ifVersion, current);
98554
+ }
98555
+ const next = {
98556
+ pinned: typeof pinned === "boolean" ? pinned : current.pinned,
98557
+ data: data === void 0 ? current.data : data !== null && typeof data === "object" ? data : null,
98558
+ version: data === void 0 ? current.version : current.version + 1
98559
+ };
98560
+ writeRow(appId, workspace, next);
98561
+ return next;
98562
+ }).immediate();
98509
98563
  }
98510
98564
  function deleteAppInstances(appId) {
98511
98565
  getDb().prepare("DELETE FROM app_instances WHERE app_id = ?").run(appId);
@@ -98586,7 +98640,27 @@ var APP_TS = "app.ts";
98586
98640
  var BRIDGE_DTS_FILE = "agentpane.d.ts";
98587
98641
  var BRIDGE_DTS = `/** AgentPane bridge \u2014 typed contract for mini apps (ambient, no import). */
98588
98642
  interface AgentPaneAppInfo { id: string; title?: string }
98589
- interface AgentPaneState { pinned: boolean; data: Record<string, unknown> | null }
98643
+ interface AgentPaneState {
98644
+ pinned: boolean;
98645
+ data: Record<string, unknown> | null;
98646
+ /** Data writes the instance has seen (0 = never written); pass it to
98647
+ * setState as ifVersion. Absent on panes without versioned state. */
98648
+ version?: number;
98649
+ }
98650
+ interface AgentPaneSetStateOptions {
98651
+ /** Write only while the stored copy is still at this version (from
98652
+ * getState/setState); otherwise setState rejects with an
98653
+ * AgentPaneStateConflict and nothing is written. */
98654
+ ifVersion?: number;
98655
+ }
98656
+ /** setState rejection when ifVersion no longer matches: re-read, re-apply, retry. */
98657
+ interface AgentPaneStateConflict extends Error {
98658
+ code: 'conflict';
98659
+ /** The stored state now. */
98660
+ state: AgentPaneState;
98661
+ }
98662
+ /** onStateChanged payload: somebody else (agent, another tab) wrote this instance. */
98663
+ interface AgentPaneStateChangedPayload { version?: number }
98590
98664
  interface AgentPaneSessionInfo { id: string; title?: string | null }
98591
98665
  interface AgentPaneCreateSessionOptions {
98592
98666
  title?: string;
@@ -98633,15 +98707,21 @@ interface AgentPaneSubmitTurnOptions {
98633
98707
 
98634
98708
  declare const AgentPane: {
98635
98709
  getApp(): Promise<AgentPaneAppInfo>;
98710
+ /** The stored state, read fresh from the pane on every call. */
98636
98711
  getState(): Promise<AgentPaneState>;
98637
- setState(data: Record<string, unknown> | null): Promise<AgentPaneState>;
98712
+ /** Replace the stored data. With opts.ifVersion it rejects with an
98713
+ * AgentPaneStateConflict (error.code === 'conflict') instead of
98714
+ * overwriting a newer copy. */
98715
+ setState(data: Record<string, unknown> | null, opts?: AgentPaneSetStateOptions): Promise<AgentPaneState>;
98638
98716
  createSession(opts?: AgentPaneCreateSessionOptions): Promise<AgentPaneSessionInfo>;
98639
98717
  /** Send a prompt to a session; opts.attachments go with it (the agent sees images). */
98640
98718
  submitTurn(sessionId: string, prompt: string, opts?: AgentPaneSubmitTurnOptions): Promise<unknown>;
98641
98719
  onTurnCompleted(cb: (event: 'turn:completed' | 'turn:failed', payload: AgentPaneTurnPayload | null) => void): void;
98642
98720
  onTurnDelta(cb: (payload: AgentPaneDeltaPayload) => void): void;
98643
98721
  onToolCall(cb: (payload: AgentPaneToolCallPayload) => void): void;
98644
- onStateChanged(cb: (payload: unknown) => void): void;
98722
+ /** Somebody else wrote this instance (an agent, another tab); not fired
98723
+ * for this tab's own setState. Re-read with getState. */
98724
+ onStateChanged(cb: (payload: AgentPaneStateChangedPayload) => void): void;
98645
98725
  /** Fires when the live background-task set of one of the app's sessions
98646
98726
  * changes (also empty sets, when the last task ends). */
98647
98727
  onBackgroundTasks(cb: (payload: AgentPaneBackgroundTasksPayload | null) => void): void;
@@ -99057,9 +99137,23 @@ function getHeadlessToolHandler(appId, workspace = "") {
99057
99137
  // State is scoped to the calling session's workspace instance; '' = global
99058
99138
  // (no known workspace). The open tab keeps its own workspace-scoped view.
99059
99139
  getState: () => Promise.resolve(getInstanceState(appId, workspace)),
99060
- setState: (data) => {
99061
- const next = updateInstanceState(appId, workspace, { data });
99062
- broadcast("app:state_changed", { appId });
99140
+ // opts.ifVersion: write only on top of that version — same contract as
99141
+ // the iframe bridge (rejects with code 'conflict' + the stored state).
99142
+ setState: (data, opts) => {
99143
+ const ifVersion = opts?.ifVersion;
99144
+ let next;
99145
+ try {
99146
+ next = updateInstanceState(appId, workspace, {
99147
+ data,
99148
+ ifVersion: typeof ifVersion === "number" ? ifVersion : void 0
99149
+ });
99150
+ } catch (err) {
99151
+ if (err instanceof StateConflictError) {
99152
+ return Promise.reject(Object.assign(new Error(err.message), { code: "conflict", state: err.current }));
99153
+ }
99154
+ return Promise.reject(err);
99155
+ }
99156
+ broadcast("app:state_changed", { appId, workspace, version: next.version });
99063
99157
  return Promise.resolve(next);
99064
99158
  },
99065
99159
  onToolCall: (cb) => {
@@ -99535,7 +99629,9 @@ async function registerAppRoutes(fastify, opts) {
99535
99629
  type: "object",
99536
99630
  properties: {
99537
99631
  pinned: { type: "boolean" },
99538
- data: { type: ["object", "null"] }
99632
+ data: { type: ["object", "null"] },
99633
+ ifVersion: { type: "integer", minimum: 0 },
99634
+ writer: { type: "string", maxLength: 200 }
99539
99635
  }
99540
99636
  }
99541
99637
  }
@@ -99544,7 +99640,23 @@ async function registerAppRoutes(fastify, opts) {
99544
99640
  const { id } = request.params;
99545
99641
  if (!APP_ID_RE.test(id)) return reply.code(400).send({ error: "Invalid app id" });
99546
99642
  if (!readManifest(id)) return reply.code(404).send({ error: "App not found" });
99547
- return updateInstanceState(id, request.query?.workspace ?? "", request.body || {});
99643
+ const workspace = request.query?.workspace ?? "";
99644
+ const { pinned, data, ifVersion, writer } = request.body || {};
99645
+ let next;
99646
+ try {
99647
+ next = updateInstanceState(id, workspace, { pinned, data, ifVersion });
99648
+ } catch (err) {
99649
+ if (err instanceof StateConflictError) {
99650
+ return reply.code(409).send({ error: err.message, state: err.current });
99651
+ }
99652
+ throw err;
99653
+ }
99654
+ if (data !== void 0) {
99655
+ const change = { appId: id, workspace, version: next.version };
99656
+ if (writer) change.writer = writer;
99657
+ broadcast("app:state_changed", change);
99658
+ }
99659
+ return next;
99548
99660
  }
99549
99661
  );
99550
99662
  fastify.post(
@@ -41121,6 +41121,7 @@ function createTables(database) {
41121
41121
  workspace_path TEXT NOT NULL DEFAULT '',
41122
41122
  pinned INTEGER NOT NULL DEFAULT 0,
41123
41123
  state TEXT,
41124
+ version INTEGER NOT NULL DEFAULT 0,
41124
41125
  created_at TEXT NOT NULL,
41125
41126
  updated_at TEXT NOT NULL,
41126
41127
  UNIQUE(app_id, workspace_path)
@@ -41176,6 +41177,10 @@ CREATE INDEX IF NOT EXISTS idx_workspaces_path ON workspaces(path);
41176
41177
  if (!sessColumns.some((c) => c.name === "user_touched")) {
41177
41178
  database.exec("ALTER TABLE sessions ADD COLUMN user_touched INTEGER NOT NULL DEFAULT 0");
41178
41179
  }
41180
+ const appInstanceColumns = database.prepare("PRAGMA table_info(app_instances)").all();
41181
+ if (!appInstanceColumns.some((c) => c.name === "version")) {
41182
+ database.exec("ALTER TABLE app_instances ADD COLUMN version INTEGER NOT NULL DEFAULT 0");
41183
+ }
41179
41184
  const turnColumns = database.prepare("PRAGMA table_info(turns)").all();
41180
41185
  if (!turnColumns.some((c) => c.name === "thread_id")) {
41181
41186
  database.exec("ALTER TABLE turns ADD COLUMN thread_id TEXT");
@@ -98299,7 +98304,8 @@ Icons come from ONE library: Lucide (https://lucide.dev/icons, ISC).
98299
98304
  ## Bridge API (window.AgentPane)
98300
98305
 
98301
98306
  - getApp() - app info (id, title)
98302
- - getState() / setState(data) - persistent JSON state, survives page reload
98307
+ - getState() / setState(data, { ifVersion }?) - persistent JSON state, survives page reload; getState reads the stored copy on every call (see "Shared state" below)
98308
+ - onStateChanged(callback) - callback({ version }) when somebody else (an agent, another tab) wrote the state; not fired for this tab's own setState
98303
98309
  - createSession({ cwd, runtime_type, model, model_reasoning_effort, title }) - agent session owned by this app; model_reasoning_effort is the effort for its turns ("low" | "medium" | "high" | "xhigh" | "max" | "ultra", the levels the model supports), omitted = the runtime's default
98304
98310
  - submitTurn(sessionId, prompt, { attachments }?) - send a prompt to a session; attachments (optional) are stored files (id, url or the uploadFile result) or inline Blobs / { name, type, data } sent with that turn only; the agent sees attached images (Claude and Codex)
98305
98311
  - onTurnCompleted(callback) - callback(event, { turnId, response }) when a turn ends
@@ -98311,6 +98317,23 @@ Icons come from ONE library: Lucide (https://lucide.dev/icons, ISC).
98311
98317
  - getFile(ref) - metadata of a stored file ({ id, url, path, type, size }), null when ref (id or url) names no file of this app
98312
98318
  - fileUrl(ref) - synchronous URL to load a stored file from in this pane; any other string comes back unchanged
98313
98319
 
98320
+ ## Shared state
98321
+
98322
+ One state instance (app + workspace) has several writers: this tab, other
98323
+ tabs on the same workspace, the headless runtime (agent tool calls) and
98324
+ agents writing over REST.
98325
+ - on onStateChanged, re-read with getState() and re-render
98326
+ - read-modify-write: apply the change to the data of a fresh getState()
98327
+ and save with setState(data, { ifVersion: state.version }). When
98328
+ somebody wrote in between, nothing is written and the promise rejects
98329
+ with error.code === 'conflict' (error.state = the stored state now):
98330
+ apply the change to error.state.data and retry with its version
98331
+ - never write back an old in-memory copy without ifVersion: it silently
98332
+ replaces whatever an agent wrote since
98333
+ - agents writing over REST do the same: GET /api/apps/<id>/state?workspace=<key>,
98334
+ then PUT { "data": ..., "ifVersion": <version from the GET> };
98335
+ 409 = re-read and retry
98336
+
98314
98337
  ## Files and images
98315
98338
 
98316
98339
  uploadFile stores images (PNG, JPEG, GIF or WebP, max 5 MB) for the app,
@@ -98451,6 +98474,15 @@ function stopAppsWatch() {
98451
98474
  }
98452
98475
 
98453
98476
  // src/apps/instances.ts
98477
+ var StateConflictError = class extends Error {
98478
+ /** The stored state the write was checked against. */
98479
+ current;
98480
+ constructor(expected, current) {
98481
+ super(`App state changed: the write expected version ${expected}, the stored copy is at version ${current.version}`);
98482
+ this.name = "StateConflictError";
98483
+ this.current = current;
98484
+ }
98485
+ };
98454
98486
  function rowToState(row) {
98455
98487
  let data = null;
98456
98488
  try {
@@ -98458,41 +98490,63 @@ function rowToState(row) {
98458
98490
  if (parsed && typeof parsed === "object") data = parsed;
98459
98491
  } catch {
98460
98492
  }
98461
- return { pinned: row.pinned === 1, data };
98493
+ return { pinned: row.pinned === 1, data, version: row.version ?? 0 };
98462
98494
  }
98463
98495
  function writeRow(appId, workspace, state) {
98464
98496
  const now = (/* @__PURE__ */ new Date()).toISOString();
98465
98497
  getDb().prepare(
98466
- `INSERT INTO app_instances (id, app_id, workspace_path, pinned, state, created_at, updated_at)
98467
- VALUES (?, ?, ?, ?, ?, ?, ?)
98498
+ `INSERT INTO app_instances (id, app_id, workspace_path, pinned, state, version, created_at, updated_at)
98499
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
98468
98500
  ON CONFLICT(app_id, workspace_path) DO UPDATE SET
98469
- pinned = excluded.pinned, state = excluded.state, updated_at = excluded.updated_at`
98470
- ).run(v4_default(), appId, workspace, state.pinned ? 1 : 0, JSON.stringify(state.data ?? null), now, now);
98501
+ pinned = excluded.pinned, state = excluded.state, version = excluded.version,
98502
+ updated_at = excluded.updated_at`
98503
+ ).run(
98504
+ v4_default(),
98505
+ appId,
98506
+ workspace,
98507
+ state.pinned ? 1 : 0,
98508
+ JSON.stringify(state.data ?? null),
98509
+ state.version,
98510
+ now,
98511
+ now
98512
+ );
98513
+ }
98514
+ var EMPTY_STATE = { pinned: false, data: null, version: 0 };
98515
+ function readRow(appId, workspace) {
98516
+ const row = getDb().prepare("SELECT * FROM app_instances WHERE app_id = ? AND workspace_path = ?").get(appId, workspace);
98517
+ return row ? rowToState(row) : null;
98471
98518
  }
98472
98519
  function getInstanceState(appId, workspace = "") {
98473
- const db2 = getDb();
98474
- const row = db2.prepare("SELECT * FROM app_instances WHERE app_id = ? AND workspace_path = ?").get(appId, workspace);
98475
- if (row) return rowToState(row);
98520
+ const stored = readRow(appId, workspace);
98521
+ if (stored) return stored;
98476
98522
  if (workspace === "") {
98477
98523
  const legacyFile = path4.join(appDir(appId), "state.json");
98478
98524
  if (fs2.existsSync(legacyFile)) {
98479
- const imported = readState(appId);
98525
+ const legacy = readState(appId);
98526
+ const imported = { pinned: legacy.pinned, data: legacy.data, version: 1 };
98480
98527
  writeRow(appId, "", imported);
98481
98528
  fs2.rmSync(legacyFile, { force: true });
98482
98529
  return imported;
98483
98530
  }
98484
98531
  }
98485
- return { pinned: false, data: null };
98532
+ return { ...EMPTY_STATE };
98486
98533
  }
98487
98534
  function updateInstanceState(appId, workspace, patch) {
98488
- const current = getInstanceState(appId, workspace);
98489
- const { pinned, data } = patch;
98490
- const next = {
98491
- pinned: typeof pinned === "boolean" ? pinned : current.pinned,
98492
- data: data === void 0 ? current.data : data !== null && typeof data === "object" ? data : null
98493
- };
98494
- writeRow(appId, workspace, next);
98495
- return next;
98535
+ getInstanceState(appId, workspace);
98536
+ return getDb().transaction(() => {
98537
+ const current = readRow(appId, workspace) ?? { ...EMPTY_STATE };
98538
+ const { pinned, data, ifVersion } = patch;
98539
+ if (typeof ifVersion === "number" && ifVersion !== current.version) {
98540
+ throw new StateConflictError(ifVersion, current);
98541
+ }
98542
+ const next = {
98543
+ pinned: typeof pinned === "boolean" ? pinned : current.pinned,
98544
+ data: data === void 0 ? current.data : data !== null && typeof data === "object" ? data : null,
98545
+ version: data === void 0 ? current.version : current.version + 1
98546
+ };
98547
+ writeRow(appId, workspace, next);
98548
+ return next;
98549
+ }).immediate();
98496
98550
  }
98497
98551
  function deleteAppInstances(appId) {
98498
98552
  getDb().prepare("DELETE FROM app_instances WHERE app_id = ?").run(appId);
@@ -98573,7 +98627,27 @@ var APP_TS = "app.ts";
98573
98627
  var BRIDGE_DTS_FILE = "agentpane.d.ts";
98574
98628
  var BRIDGE_DTS = `/** AgentPane bridge \u2014 typed contract for mini apps (ambient, no import). */
98575
98629
  interface AgentPaneAppInfo { id: string; title?: string }
98576
- interface AgentPaneState { pinned: boolean; data: Record<string, unknown> | null }
98630
+ interface AgentPaneState {
98631
+ pinned: boolean;
98632
+ data: Record<string, unknown> | null;
98633
+ /** Data writes the instance has seen (0 = never written); pass it to
98634
+ * setState as ifVersion. Absent on panes without versioned state. */
98635
+ version?: number;
98636
+ }
98637
+ interface AgentPaneSetStateOptions {
98638
+ /** Write only while the stored copy is still at this version (from
98639
+ * getState/setState); otherwise setState rejects with an
98640
+ * AgentPaneStateConflict and nothing is written. */
98641
+ ifVersion?: number;
98642
+ }
98643
+ /** setState rejection when ifVersion no longer matches: re-read, re-apply, retry. */
98644
+ interface AgentPaneStateConflict extends Error {
98645
+ code: 'conflict';
98646
+ /** The stored state now. */
98647
+ state: AgentPaneState;
98648
+ }
98649
+ /** onStateChanged payload: somebody else (agent, another tab) wrote this instance. */
98650
+ interface AgentPaneStateChangedPayload { version?: number }
98577
98651
  interface AgentPaneSessionInfo { id: string; title?: string | null }
98578
98652
  interface AgentPaneCreateSessionOptions {
98579
98653
  title?: string;
@@ -98620,15 +98694,21 @@ interface AgentPaneSubmitTurnOptions {
98620
98694
 
98621
98695
  declare const AgentPane: {
98622
98696
  getApp(): Promise<AgentPaneAppInfo>;
98697
+ /** The stored state, read fresh from the pane on every call. */
98623
98698
  getState(): Promise<AgentPaneState>;
98624
- setState(data: Record<string, unknown> | null): Promise<AgentPaneState>;
98699
+ /** Replace the stored data. With opts.ifVersion it rejects with an
98700
+ * AgentPaneStateConflict (error.code === 'conflict') instead of
98701
+ * overwriting a newer copy. */
98702
+ setState(data: Record<string, unknown> | null, opts?: AgentPaneSetStateOptions): Promise<AgentPaneState>;
98625
98703
  createSession(opts?: AgentPaneCreateSessionOptions): Promise<AgentPaneSessionInfo>;
98626
98704
  /** Send a prompt to a session; opts.attachments go with it (the agent sees images). */
98627
98705
  submitTurn(sessionId: string, prompt: string, opts?: AgentPaneSubmitTurnOptions): Promise<unknown>;
98628
98706
  onTurnCompleted(cb: (event: 'turn:completed' | 'turn:failed', payload: AgentPaneTurnPayload | null) => void): void;
98629
98707
  onTurnDelta(cb: (payload: AgentPaneDeltaPayload) => void): void;
98630
98708
  onToolCall(cb: (payload: AgentPaneToolCallPayload) => void): void;
98631
- onStateChanged(cb: (payload: unknown) => void): void;
98709
+ /** Somebody else wrote this instance (an agent, another tab); not fired
98710
+ * for this tab's own setState. Re-read with getState. */
98711
+ onStateChanged(cb: (payload: AgentPaneStateChangedPayload) => void): void;
98632
98712
  /** Fires when the live background-task set of one of the app's sessions
98633
98713
  * changes (also empty sets, when the last task ends). */
98634
98714
  onBackgroundTasks(cb: (payload: AgentPaneBackgroundTasksPayload | null) => void): void;
@@ -99044,9 +99124,23 @@ function getHeadlessToolHandler(appId, workspace = "") {
99044
99124
  // State is scoped to the calling session's workspace instance; '' = global
99045
99125
  // (no known workspace). The open tab keeps its own workspace-scoped view.
99046
99126
  getState: () => Promise.resolve(getInstanceState(appId, workspace)),
99047
- setState: (data) => {
99048
- const next = updateInstanceState(appId, workspace, { data });
99049
- broadcast("app:state_changed", { appId });
99127
+ // opts.ifVersion: write only on top of that version — same contract as
99128
+ // the iframe bridge (rejects with code 'conflict' + the stored state).
99129
+ setState: (data, opts) => {
99130
+ const ifVersion = opts?.ifVersion;
99131
+ let next;
99132
+ try {
99133
+ next = updateInstanceState(appId, workspace, {
99134
+ data,
99135
+ ifVersion: typeof ifVersion === "number" ? ifVersion : void 0
99136
+ });
99137
+ } catch (err) {
99138
+ if (err instanceof StateConflictError) {
99139
+ return Promise.reject(Object.assign(new Error(err.message), { code: "conflict", state: err.current }));
99140
+ }
99141
+ return Promise.reject(err);
99142
+ }
99143
+ broadcast("app:state_changed", { appId, workspace, version: next.version });
99050
99144
  return Promise.resolve(next);
99051
99145
  },
99052
99146
  onToolCall: (cb) => {
@@ -99522,7 +99616,9 @@ async function registerAppRoutes(fastify, opts) {
99522
99616
  type: "object",
99523
99617
  properties: {
99524
99618
  pinned: { type: "boolean" },
99525
- data: { type: ["object", "null"] }
99619
+ data: { type: ["object", "null"] },
99620
+ ifVersion: { type: "integer", minimum: 0 },
99621
+ writer: { type: "string", maxLength: 200 }
99526
99622
  }
99527
99623
  }
99528
99624
  }
@@ -99531,7 +99627,23 @@ async function registerAppRoutes(fastify, opts) {
99531
99627
  const { id } = request.params;
99532
99628
  if (!APP_ID_RE.test(id)) return reply.code(400).send({ error: "Invalid app id" });
99533
99629
  if (!readManifest(id)) return reply.code(404).send({ error: "App not found" });
99534
- return updateInstanceState(id, request.query?.workspace ?? "", request.body || {});
99630
+ const workspace = request.query?.workspace ?? "";
99631
+ const { pinned, data, ifVersion, writer } = request.body || {};
99632
+ let next;
99633
+ try {
99634
+ next = updateInstanceState(id, workspace, { pinned, data, ifVersion });
99635
+ } catch (err) {
99636
+ if (err instanceof StateConflictError) {
99637
+ return reply.code(409).send({ error: err.message, state: err.current });
99638
+ }
99639
+ throw err;
99640
+ }
99641
+ if (data !== void 0) {
99642
+ const change = { appId: id, workspace, version: next.version };
99643
+ if (writer) change.writer = writer;
99644
+ broadcast("app:state_changed", change);
99645
+ }
99646
+ return next;
99535
99647
  }
99536
99648
  );
99537
99649
  fastify.post(