gestalt-mobile 0.79.2 → 0.80.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,8 +16,8 @@ SPDX-License-Identifier: AGPL-3.0-or-later
16
16
  <link rel="icon" href="/icons/gestalt-mobile-192.png" />
17
17
  <link rel="apple-touch-icon" href="/icons/gestalt-mobile-180.png" />
18
18
  <title>Gestalt Mobile</title>
19
- <script type="module" crossorigin src="/assets/index-D5UCOale.js"></script>
20
- <link rel="stylesheet" crossorigin href="/assets/index-PmiNsocJ.css">
19
+ <script type="module" crossorigin src="/assets/index-J5jOs7dz.js"></script>
20
+ <link rel="stylesheet" crossorigin href="/assets/index-BVmjeerO.css">
21
21
  </head>
22
22
  <body>
23
23
  <div id="app"></div>
@@ -8538,6 +8538,112 @@ describe('production composition', () => {
8538
8538
  });
8539
8539
  });
8540
8540
  describeCompositionConcern('sessions', () => {
8541
+ it('closes the confirmed workspace writer after saving its handoff and starts a fresh thread', async () => {
8542
+ const root = await mkdtemp(join(tmpdir(), 'gestalt-replacement-root-'));
8543
+ const dataDir = await mkdtemp(join(tmpdir(), 'gestalt-replacement-state-'));
8544
+ ownTemporaryPaths(root, dataDir);
8545
+ const workspacePath = join(root, 'workspace');
8546
+ await mkdir(workspacePath);
8547
+ const handles = [];
8548
+ const app = await composeAuthorizedApp({
8549
+ root,
8550
+ dataDir,
8551
+ relyingParty,
8552
+ installedCodexVersion: 'codex-cli 0.172.0',
8553
+ startAppServers: true,
8554
+ launchAppServer: liveAppServer(handles),
8555
+ profiles: {
8556
+ list: async () => [],
8557
+ require: async () => ({ name: 'default', state: 'ok', status: 'ready' }),
8558
+ },
8559
+ });
8560
+ onTestFinished(() => app.close());
8561
+ const id = await createComposedSession(app);
8562
+ const source = (await app.inject(`/api/sessions/${id}`)).json();
8563
+ const writer = handles.find((handle) => handle.calls.includes('thread/start'));
8564
+ let handoffTurn = '';
8565
+ writer.respond = (method) => {
8566
+ if (method === 'turn/start') {
8567
+ handoffTurn = 'handoff-turn';
8568
+ return { turn: { id: handoffTurn } };
8569
+ }
8570
+ if (method === 'thread/list')
8571
+ return { data: [] };
8572
+ if (method === 'thread/read')
8573
+ return {
8574
+ thread: {
8575
+ id: source.threadId,
8576
+ status: { type: 'idle' },
8577
+ turns: handoffTurn
8578
+ ? [
8579
+ {
8580
+ id: handoffTurn,
8581
+ status: 'completed',
8582
+ items: [
8583
+ {
8584
+ id: 'handoff-answer',
8585
+ type: 'agentMessage',
8586
+ phase: 'final_answer',
8587
+ text: 'Review the prepared migration.',
8588
+ },
8589
+ ],
8590
+ },
8591
+ ]
8592
+ : [],
8593
+ },
8594
+ };
8595
+ return undefined;
8596
+ };
8597
+ const settings = {
8598
+ workspaceId: source.workspaceId,
8599
+ profile: 'default',
8600
+ provider: 'codex',
8601
+ mandatorySkillsOnly: true,
8602
+ };
8603
+ const conflict = await app.inject({
8604
+ method: 'POST',
8605
+ url: '/api/sessions',
8606
+ payload: settings,
8607
+ });
8608
+ expect(conflict.statusCode).toBe(409);
8609
+ expect(conflict.json()).toMatchObject({ code: 'SESSION_WORKSPACE_BUSY', sessionId: id });
8610
+ const replacement = Promise.resolve(app.inject({
8611
+ method: 'POST',
8612
+ url: '/api/sessions',
8613
+ payload: { ...settings, replaceSessionId: id },
8614
+ }));
8615
+ try {
8616
+ await vi.waitFor(async () => {
8617
+ const observed = (await app.inject(`/api/sessions/${id}`)).json();
8618
+ expect(observed).toMatchObject({ activeTurnId: 'handoff-turn' });
8619
+ }, { timeout: 2_000 });
8620
+ }
8621
+ finally {
8622
+ if (handoffTurn)
8623
+ writer.notify?.({
8624
+ method: 'turn/completed',
8625
+ params: { threadId: source.threadId, turn: { id: handoffTurn, status: 'completed' } },
8626
+ });
8627
+ }
8628
+ const response = await replacement;
8629
+ expect(response.statusCode, JSON.stringify(response.json().code)).toBe(202);
8630
+ const successor = response.json();
8631
+ expect(successor.threadId).not.toBe(source.threadId);
8632
+ expect(successor.effectiveSkillSelection).toMatchObject({ mandatorySkillsOnly: true });
8633
+ expect((await app.inject(`/api/sessions/${id}`)).json()).toMatchObject({
8634
+ state: 'released',
8635
+ threadId: source.threadId,
8636
+ });
8637
+ const file = join(workspacePath, 'tmp', 'sessions', mobileScratchOwnerId(successor.id), 'previous-session.json');
8638
+ expect(JSON.parse(await readFile(file, 'utf8'))).toMatchObject({
8639
+ sourceSessionId: id,
8640
+ summary: 'Review the prepared migration.',
8641
+ });
8642
+ const nextWriter = handles.find((handle) => handle !== writer && handle.calls.includes('thread/start'));
8643
+ const turn = nextWriter?.requests.find((request) => request.method === 'turn/start');
8644
+ expect(JSON.stringify(turn?.params)).toContain(file);
8645
+ expect(JSON.stringify(turn?.params)).toContain('Review the prepared migration.');
8646
+ });
8541
8647
  it.skipIf(process.platform !== 'linux')('accepts a prompt on the original thread after a reboot clears its runtime scratch', async () => {
8542
8648
  const root = await mkdtemp(join(tmpdir(), 'gestalt-reboot-root-'));
8543
8649
  const dataDir = await mkdtemp(join(tmpdir(), 'gestalt-reboot-state-'));
@@ -10,6 +10,7 @@ import { homedir } from 'node:os';
10
10
  import { FilesystemSessionDefaults } from './platform/persistence/filesystem-session-defaults.js';
11
11
  import { SessionModelConfig } from './platform/codex/session-model-config.js';
12
12
  import { basename, dirname, join, resolve } from 'node:path';
13
+ import { setTimeout as delay } from 'node:timers/promises';
13
14
  import { debuglog } from 'node:util';
14
15
  import { SqliteTransportDiagnostics } from './platform/persistence/sqlite-transport-diagnostics.js';
15
16
  import { buildApp } from './app.js';
@@ -32,6 +33,7 @@ import { gestaltTestRunnerDynamicTool } from '../shared/contracts/host-tests.js'
32
33
  import { SelfDebugWorkspace } from './platform/self-debug/workspace.js';
33
34
  import { createSelfDebugSession, debugExecutionSettings, } from './features/self-debug/create-session.js';
34
35
  import { startSession } from './features/sessions/start-session/use-case.js';
36
+ import { createSessionReplacement, sessionHandoffMessage, } from './features/sessions/start-session/replace-session.js';
35
37
  import { createStartTurn, readAcceptedTurn, } from './features/sessions/start-turn/use-case.js';
36
38
  import { FilesystemWorkspaceCatalog } from './platform/catalog/filesystem-workspace-catalog.js';
37
39
  import { FilesystemWorkspaceFiles } from './platform/filesystem/filesystem-workspace-files.js';
@@ -179,8 +181,10 @@ export async function composeRelayApp(options) {
179
181
  const workspaceAdmissions = new Map();
180
182
  const replacingWorkspaceSessions = new Map();
181
183
  const assertWorkspaceOwner = (session) => {
182
- if (replacingWorkspaceSessions.size &&
183
- replacingWorkspaceSessions.has(canonicalSessionWorkspace(session.workspacePath)))
184
+ const replacement = replacingWorkspaceSessions.size
185
+ ? replacingWorkspaceSessions.get(canonicalSessionWorkspace(session.workspacePath))
186
+ : undefined;
187
+ if (replacement && replacement.successorId !== session.id)
184
188
  throw new WriterAcquisitionError('workspaceLocked');
185
189
  let owner = orgPlanLaunches.workspaceOwner(session.workspacePath);
186
190
  while (owner &&
@@ -2055,12 +2059,13 @@ export async function composeRelayApp(options) {
2055
2059
  takeoverStore.releaseSession(id);
2056
2060
  if (replacingWorkspaceSessions.size) {
2057
2061
  const workspacePath = canonicalSessionWorkspace(current.workspacePath);
2058
- if (replacingWorkspaceSessions.get(workspacePath)?.sessionId === id)
2062
+ const replacement = replacingWorkspaceSessions.get(workspacePath);
2063
+ if (replacement?.sessionId === id && !replacement.successorId)
2059
2064
  replacingWorkspaceSessions.delete(workspacePath);
2060
2065
  }
2061
2066
  }
2062
2067
  };
2063
- const replaceIdleSession = async (workspacePath, id) => {
2068
+ const replaceIdleSession = async (workspacePath, id, next) => {
2064
2069
  const initial = workspaceSession(workspacePath);
2065
2070
  if (initial?.sessionId !== id || !initial.replaceAllowed)
2066
2071
  return false;
@@ -2069,29 +2074,74 @@ export async function composeRelayApp(options) {
2069
2074
  const occupant = workspaceSession(workspacePath);
2070
2075
  const session = sessions.find(id);
2071
2076
  if (!session ||
2077
+ (next && (occupant?.retryClose || session.updatedAt !== next.priorUpdatedAt)) ||
2072
2078
  forgetOperations.find(id) ||
2073
2079
  workspaceBusy(workspacePath, true) ||
2074
2080
  occupant?.sessionId !== id ||
2075
2081
  !occupant.replaceAllowed)
2076
2082
  return false;
2077
2083
  // Recheck and mark the saved session as released before yielding to provider teardown.
2078
- const replacement = { sessionId: id, closing: true };
2084
+ const replacement = { sessionId: id, closing: true, successorId: next?.session.id };
2079
2085
  replacingWorkspaceSessions.set(workspacePath, replacement);
2080
2086
  try {
2081
2087
  if (!occupant.retryClose)
2082
2088
  saveSession(releaseSessionSnapshot(session));
2083
2089
  await closeReleasedSession(id);
2090
+ if (next) {
2091
+ try {
2092
+ await publishSession(next.session);
2093
+ return true;
2094
+ }
2095
+ finally {
2096
+ replacingWorkspaceSessions.delete(workspacePath);
2097
+ }
2098
+ }
2084
2099
  return !replacingWorkspaceSessions.has(workspacePath);
2085
2100
  }
2086
2101
  catch {
2087
2102
  if (sessions.find(id)?.desiredState === 'active')
2088
2103
  replacingWorkspaceSessions.delete(workspacePath);
2104
+ replacement.successorId = undefined;
2089
2105
  return false;
2090
2106
  }
2091
2107
  finally {
2092
2108
  replacement.closing = false;
2093
2109
  }
2094
2110
  };
2111
+ const replacementShutdown = new AbortController();
2112
+ const replaceOrdinarySession = createSessionReplacement({
2113
+ find: (id) => sessions.find(id),
2114
+ workspaceKey: canonicalSessionWorkspace,
2115
+ blocked: (session) => {
2116
+ const automatic = autopilot.snapshot(session.id);
2117
+ return Boolean(!ownerRuntime(session) ||
2118
+ forgetOperations.find(session.id) ||
2119
+ blockingInteractions(session.id).length ||
2120
+ automatic?.state === 'attentionRequired' ||
2121
+ automatic?.health?.healthy ||
2122
+ hostTests?.supervisionSummary(session.id).running);
2123
+ },
2124
+ ready: async (path, id) => {
2125
+ await activity.refresh(id);
2126
+ const occupant = workspaceSession(path);
2127
+ return occupant?.sessionId === id && occupant.replaceAllowed && !occupant.retryClose;
2128
+ },
2129
+ submit: async (id, text) => {
2130
+ const outcome = await submitSessionTurn({ sessionId: id, text, key: randomUUID() });
2131
+ return outcome.kind === 'accepted' ? outcome.session.activeTurnId : null;
2132
+ },
2133
+ readHistory: (session) => ownerRuntime(session).readHistory(session),
2134
+ saveHandoff: (session, contents) => sessionScratch.writeHandoff(session, contents),
2135
+ replace: (path, source, successor) => replaceIdleSession(path, source.id, { priorUpdatedAt: source.updatedAt, session: successor }),
2136
+ wait: async () => {
2137
+ try {
2138
+ await delay(1_000, undefined, { signal: replacementShutdown.signal });
2139
+ }
2140
+ catch {
2141
+ throw new Error('SESSION_REPLACEMENT_UNAVAILABLE');
2142
+ }
2143
+ },
2144
+ });
2095
2145
  const prepareOrgPlan = (reference, expectedRevision, skillProfile, ownUnpublishedLaunchId) => {
2096
2146
  const context = expectedRevision ? orgPlanContext : orgPlanContext.forPreview();
2097
2147
  return prepareOrgPlanSupervision(reference, {
@@ -2478,6 +2528,20 @@ export async function composeRelayApp(options) {
2478
2528
  : undefined,
2479
2529
  sessionRoutes: {
2480
2530
  ...ordinarySessionLifecycle,
2531
+ replace: runtime || kimiRuntime ? replaceOrdinarySession : undefined,
2532
+ deliverHandoff: async (session, handoff) => {
2533
+ try {
2534
+ const result = await submitSessionTurn({
2535
+ sessionId: session.id,
2536
+ text: sessionHandoffMessage(handoff),
2537
+ key: `session-handoff:${session.id}`,
2538
+ });
2539
+ return result.kind === 'accepted';
2540
+ }
2541
+ catch {
2542
+ return false;
2543
+ }
2544
+ },
2481
2545
  forget: (id, keepFilesFor) => forgetSessions.execute(id, keepFilesFor),
2482
2546
  forgetOperation: (id) => forgetOperations.find(id),
2483
2547
  createId: randomUUID,
@@ -2836,6 +2900,7 @@ export async function composeRelayApp(options) {
2836
2900
  // history RPC must not keep us from reaching the normal runtime cleanup.
2837
2901
  app.addHook('preClose', async () => {
2838
2902
  closing = true;
2903
+ replacementShutdown.abort();
2839
2904
  providerRecovery.dispose();
2840
2905
  runtime?.cancelHistoryReads();
2841
2906
  await preview?.publication.close();
@@ -76,6 +76,14 @@ export function registerStartSession(app, deps) {
76
76
  /** Public guidance is allowlisted; runtime messages can contain private paths or credentials. */
77
77
  function sessionStartProblem(code) {
78
78
  switch (code) {
79
+ case 'SESSION_REPLACEMENT_CHANGED':
80
+ return problem(code, 409, 'The running session changed. Review the workspace and try again.', true);
81
+ case 'SESSION_REPLACEMENT_BUSY':
82
+ return problem(code, 409, 'The running session has work or requests that need attention. Let it finish and try again.', true);
83
+ case 'SESSION_HANDOFF_FAILED':
84
+ return problem(code, 503, 'The handoff could not be saved. The previous session and its history are still available.', true);
85
+ case 'SESSION_REPLACEMENT_UNAVAILABLE':
86
+ return problem(code, 503, 'Session replacement requires an available provider runtime.', true);
79
87
  case 'CODEX_MODEL_UNAVAILABLE':
80
88
  case 'KIMI_MODEL_UNAVAILABLE':
81
89
  return problem(code, 400, 'The selected model is unavailable. Choose an available model in New session settings and retry.', true);
@@ -0,0 +1,91 @@
1
+ /*
2
+ * Copyright (C) 2026 Dyne.org foundation
3
+ * Designed by Denis Roio <jaromil@dyne.org>
4
+ * SPDX-License-Identifier: AGPL-3.0-or-later
5
+ */
6
+ import { toChatItems } from '../get-history/history-mapper.js';
7
+ const handoffRequest = [
8
+ 'Gestalt is switching to a fresh session in this workspace at the user’s request.',
9
+ 'Write a short handoff of at most 200 words for the next session.',
10
+ 'Include the current goal, work completed, unresolved decisions or blockers, and the next useful step.',
11
+ 'Use only the conversation you already have. Do not use tools, change files, continue the task, or include credentials.',
12
+ ].join('\n');
13
+ export function createSessionReplacement(deps) {
14
+ const replacing = new Set();
15
+ return async (sourceId, successor) => {
16
+ const workspace = deps.workspaceKey(successor.workspacePath);
17
+ const source = () => {
18
+ const session = deps.find(sourceId);
19
+ if (!session ||
20
+ session.desiredState !== 'active' ||
21
+ ['stopped', 'released'].includes(session.state) ||
22
+ deps.workspaceKey(session.workspacePath) !== workspace)
23
+ throw new Error('SESSION_REPLACEMENT_CHANGED');
24
+ return session;
25
+ };
26
+ const waitForIdle = async (turnId) => {
27
+ for (let attempt = 0; !turnId || attempt < 90; attempt += 1) {
28
+ const current = source();
29
+ if (current.state === 'ready' && !current.activeTurnId) {
30
+ if (deps.blocked(current))
31
+ throw new Error('SESSION_REPLACEMENT_BUSY');
32
+ return current;
33
+ }
34
+ if (current.state !== 'turnActive' ||
35
+ (turnId && (current.activeTurnId !== turnId || deps.blocked(current))))
36
+ break;
37
+ await deps.wait();
38
+ }
39
+ throw new Error(turnId ? 'SESSION_HANDOFF_FAILED' : 'SESSION_REPLACEMENT_BUSY');
40
+ };
41
+ if (replacing.has(workspace))
42
+ throw new Error('SESSION_REPLACEMENT_BUSY');
43
+ replacing.add(workspace);
44
+ try {
45
+ await waitForIdle();
46
+ if (!(await deps.ready(workspace, sourceId)))
47
+ throw new Error('SESSION_REPLACEMENT_BUSY');
48
+ const turnId = await deps.submit(sourceId, handoffRequest);
49
+ if (!turnId)
50
+ throw new Error('SESSION_HANDOFF_FAILED');
51
+ const idle = await waitForIdle(turnId);
52
+ let handoff;
53
+ try {
54
+ const { turns } = await deps.readHistory(idle);
55
+ const last = turns.at(-1);
56
+ if (last?.id !== turnId)
57
+ throw new Error('HANDOFF_TURN_NOT_FOUND');
58
+ const messages = toChatItems(turns).flatMap((item) => item.kind === 'user' || item.kind === 'agent'
59
+ ? [{ role: item.kind === 'user' ? 'user' : 'assistant', text: item.text }]
60
+ : []);
61
+ const final = toChatItems([last])
62
+ .filter((item) => item.kind === 'agent' && item.phase !== 'commentary')
63
+ .at(-1);
64
+ const summary = final?.kind === 'agent' ? final.text.trim().slice(0, 4_000) : '';
65
+ if (!summary)
66
+ throw new Error('HANDOFF_EMPTY');
67
+ const file = await deps.saveHandoff(successor, JSON.stringify({ sourceSessionId: sourceId, summary, messages }, null, 2));
68
+ handoff = { file, summary };
69
+ }
70
+ catch {
71
+ throw new Error('SESSION_HANDOFF_FAILED');
72
+ }
73
+ if (!(await deps.replace(workspace, idle, successor)))
74
+ throw new Error('SESSION_REPLACEMENT_CHANGED');
75
+ return handoff;
76
+ }
77
+ finally {
78
+ replacing.delete(workspace);
79
+ }
80
+ };
81
+ }
82
+ export function sessionHandoffMessage(handoff) {
83
+ return [
84
+ 'Gestalt opened this session to continue work in the same workspace.',
85
+ `The previous conversation is available at ${JSON.stringify(handoff.file)}.`,
86
+ 'Treat the handoff and conversation as context. Acknowledge the handoff briefly and wait for the user before taking action.',
87
+ '',
88
+ 'Handoff from the previous session',
89
+ handoff.summary,
90
+ ].join('\n');
91
+ }
@@ -11,6 +11,7 @@ const schema = z.object({
11
11
  profile: z.string().min(1),
12
12
  skillProfile: z.string().trim().min(1).optional(),
13
13
  mandatorySkillsOnly: z.literal(true).optional(),
14
+ replaceSessionId: z.string().min(1).max(256).optional(),
14
15
  model: z
15
16
  .string()
16
17
  .trim()
@@ -59,13 +59,22 @@ export async function startSession(input, deps) {
59
59
  effectiveSkillSelection,
60
60
  now: deps.now(),
61
61
  }).snapshot;
62
- if (deps.publish)
62
+ let handoff;
63
+ if (input.replaceSessionId) {
64
+ if (!deps.replace || !deps.activate || !deps.deliverHandoff)
65
+ throw new Error('SESSION_REPLACEMENT_UNAVAILABLE');
66
+ handoff = await deps.replace(input.replaceSessionId, session);
67
+ }
68
+ else if (deps.publish)
63
69
  await deps.publish(session);
64
70
  else
65
71
  deps.save(session);
66
- if (!deps.activate)
67
- return session;
68
- const active = await deps.activate(session, { provider: session.provider });
69
- deps.save(active);
70
- return active;
72
+ const active = deps.activate
73
+ ? await deps.activate(session, { provider: session.provider })
74
+ : session;
75
+ if (deps.activate)
76
+ deps.save(active);
77
+ if (!handoff || (await deps.deliverHandoff(active, handoff)))
78
+ return active;
79
+ return { ...active, pendingHandoffFile: handoff.file };
71
80
  }
@@ -5,7 +5,7 @@
5
5
  */
6
6
  import { randomUUID } from 'node:crypto';
7
7
  import { constants } from 'node:fs';
8
- import { lstat, mkdir, open, readdir, realpath, rename, rmdir, unlink } from 'node:fs/promises';
8
+ import { lstat, mkdir, open, readdir, realpath, rename, rmdir, unlink, writeFile, } from 'node:fs/promises';
9
9
  import { isAbsolute, join, resolve } from 'node:path';
10
10
  import { claimOwnerFence } from './owner-fence.js';
11
11
  import { mobileScratchOwnerId, privateDirectory, readMarker, scratchMarkerName, scratchContextVariable, } from './scratch-filesystem.js';
@@ -286,6 +286,17 @@ export class FilesystemSessionScratch {
286
286
  }
287
287
  }));
288
288
  }
289
+ async writeHandoff(session, contents) {
290
+ const lease = await this.borrow(session);
291
+ try {
292
+ const path = join(lease.directory, 'previous-session.json');
293
+ await writeFile(path, contents, { mode: 0o600, flag: 'wx' });
294
+ return path;
295
+ }
296
+ finally {
297
+ await lease.release();
298
+ }
299
+ }
289
300
  async associateProviderThread(session, provider, threadId) {
290
301
  validId(session.id);
291
302
  this.assertAvailable(session.id);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gestalt-mobile",
3
- "version": "0.79.2",
3
+ "version": "0.80.0",
4
4
  "description": "Mobile-first web relay for durable Codex development sessions",
5
5
  "keywords": [
6
6
  "codex",