gestalt-mobile 0.79.1 → 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-t6olwrqi.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>
@@ -29,7 +29,8 @@ Options:
29
29
  --host <address> Listen address (default: 127.0.0.1)
30
30
  --port <number> Listen port (default: 3000)
31
31
  --public-origin <origin> Exact HTTPS browser origin for passkeys (localhost may use HTTP)
32
- --preview-origin <origin> Enable the preview gateway on 127.0.0.1:8080 for this HTTPS origin
32
+ --preview-origin <origin> Enable the loopback preview gateway for this HTTPS origin
33
+ --preview-gateway-port <number> Loopback port Caddy forwards to (default: 8080)
33
34
  --preview-target-port <number> Loopback dev server port (default: 5173)
34
35
  --disable-passkey-auth Disable passkey access control (unsafe on shared or network hosts)
35
36
  --data-dir <path> Directory for persistent application data
@@ -343,6 +344,7 @@ export async function runCli(dependencies = {}) {
343
344
  testRunnerEnabled: config.testRunnerEnabled,
344
345
  relyingParty: config.relyingParty,
345
346
  passkeyAuthEnabled: config.passkeyAuthEnabled,
347
+ relayPort: config.port,
346
348
  ...(config.preview ? { preview: config.preview } : {}),
347
349
  staticDir: packagedClientDir(moduleUrl),
348
350
  pwaIcon,
@@ -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,13 +10,15 @@ 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';
16
17
  import { ManagedUpgrade } from './platform/maintenance/managed-upgrade.js';
17
18
  import { PreviewService } from './features/previews/application/service.js';
18
- import { createPreviewGateway } from './platform/previews/gateway.js';
19
+ import { readPreviewHostConfig } from './platform/previews/host-config.js';
19
20
  import { findImpeccableHelper } from './platform/previews/impeccable.js';
21
+ import { PreviewPublication } from './platform/previews/publication.js';
20
22
  import { hasImpeccableSkill } from '../shared/contracts/impeccable.js';
21
23
  import { LocalHostTestRunner } from './platform/host-tests/runner.js';
22
24
  import { FilesystemSessionScratch } from './platform/scratch/filesystem-session-scratch.js';
@@ -31,6 +33,7 @@ import { gestaltTestRunnerDynamicTool } from '../shared/contracts/host-tests.js'
31
33
  import { SelfDebugWorkspace } from './platform/self-debug/workspace.js';
32
34
  import { createSelfDebugSession, debugExecutionSettings, } from './features/self-debug/create-session.js';
33
35
  import { startSession } from './features/sessions/start-session/use-case.js';
36
+ import { createSessionReplacement, sessionHandoffMessage, } from './features/sessions/start-session/replace-session.js';
34
37
  import { createStartTurn, readAcceptedTurn, } from './features/sessions/start-turn/use-case.js';
35
38
  import { FilesystemWorkspaceCatalog } from './platform/catalog/filesystem-workspace-catalog.js';
36
39
  import { FilesystemWorkspaceFiles } from './platform/filesystem/filesystem-workspace-files.js';
@@ -178,8 +181,10 @@ export async function composeRelayApp(options) {
178
181
  const workspaceAdmissions = new Map();
179
182
  const replacingWorkspaceSessions = new Map();
180
183
  const assertWorkspaceOwner = (session) => {
181
- if (replacingWorkspaceSessions.size &&
182
- 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)
183
188
  throw new WriterAcquisitionError('workspaceLocked');
184
189
  let owner = orgPlanLaunches.workspaceOwner(session.workspacePath);
185
190
  while (owner &&
@@ -2054,12 +2059,13 @@ export async function composeRelayApp(options) {
2054
2059
  takeoverStore.releaseSession(id);
2055
2060
  if (replacingWorkspaceSessions.size) {
2056
2061
  const workspacePath = canonicalSessionWorkspace(current.workspacePath);
2057
- if (replacingWorkspaceSessions.get(workspacePath)?.sessionId === id)
2062
+ const replacement = replacingWorkspaceSessions.get(workspacePath);
2063
+ if (replacement?.sessionId === id && !replacement.successorId)
2058
2064
  replacingWorkspaceSessions.delete(workspacePath);
2059
2065
  }
2060
2066
  }
2061
2067
  };
2062
- const replaceIdleSession = async (workspacePath, id) => {
2068
+ const replaceIdleSession = async (workspacePath, id, next) => {
2063
2069
  const initial = workspaceSession(workspacePath);
2064
2070
  if (initial?.sessionId !== id || !initial.replaceAllowed)
2065
2071
  return false;
@@ -2068,29 +2074,74 @@ export async function composeRelayApp(options) {
2068
2074
  const occupant = workspaceSession(workspacePath);
2069
2075
  const session = sessions.find(id);
2070
2076
  if (!session ||
2077
+ (next && (occupant?.retryClose || session.updatedAt !== next.priorUpdatedAt)) ||
2071
2078
  forgetOperations.find(id) ||
2072
2079
  workspaceBusy(workspacePath, true) ||
2073
2080
  occupant?.sessionId !== id ||
2074
2081
  !occupant.replaceAllowed)
2075
2082
  return false;
2076
2083
  // Recheck and mark the saved session as released before yielding to provider teardown.
2077
- const replacement = { sessionId: id, closing: true };
2084
+ const replacement = { sessionId: id, closing: true, successorId: next?.session.id };
2078
2085
  replacingWorkspaceSessions.set(workspacePath, replacement);
2079
2086
  try {
2080
2087
  if (!occupant.retryClose)
2081
2088
  saveSession(releaseSessionSnapshot(session));
2082
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
+ }
2083
2099
  return !replacingWorkspaceSessions.has(workspacePath);
2084
2100
  }
2085
2101
  catch {
2086
2102
  if (sessions.find(id)?.desiredState === 'active')
2087
2103
  replacingWorkspaceSessions.delete(workspacePath);
2104
+ replacement.successorId = undefined;
2088
2105
  return false;
2089
2106
  }
2090
2107
  finally {
2091
2108
  replacement.closing = false;
2092
2109
  }
2093
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
+ });
2094
2145
  const prepareOrgPlan = (reference, expectedRevision, skillProfile, ownUnpublishedLaunchId) => {
2095
2146
  const context = expectedRevision ? orgPlanContext : orgPlanContext.forPreview();
2096
2147
  return prepareOrgPlanSupervision(reference, {
@@ -2261,7 +2312,7 @@ export async function composeRelayApp(options) {
2261
2312
  onSettled: ordinaryTurnDependencies.onSettled,
2262
2313
  });
2263
2314
  const preview = (() => {
2264
- if (!options.preview || !authorization)
2315
+ if (!authorization || !relyingParty.publicOrigin.startsWith('https:'))
2265
2316
  return;
2266
2317
  const repository = authorization;
2267
2318
  const clock = options.authorizationClock ?? (() => new Date());
@@ -2271,16 +2322,14 @@ export async function composeRelayApp(options) {
2271
2322
  now: () => clock().getTime(),
2272
2323
  token: () => randomBytes(32).toString('base64url'),
2273
2324
  });
2325
+ const publication = new PreviewPublication(service, async () => (await readPreviewHostConfig(homeDirectory, relyingParty.publicOrigin, options.relayPort ?? 3000)) ?? options.preview, async (id) => {
2326
+ const session = sessions.find(id);
2327
+ if (session)
2328
+ return findImpeccableHelper(session.workspacePath);
2329
+ });
2274
2330
  return {
2275
- routes: { service, origin: options.preview.origin, impeccableAvailable },
2276
- gateway: createPreviewGateway({
2277
- ...options.preview,
2278
- impeccableHelper: async (id) => {
2279
- const session = sessions.find(id);
2280
- if (session)
2281
- return findImpeccableHelper(session.workspacePath);
2282
- },
2283
- }, service),
2331
+ routes: { service, origin: () => publication.refresh(), impeccableAvailable },
2332
+ publication,
2284
2333
  };
2285
2334
  })();
2286
2335
  let app;
@@ -2390,7 +2439,7 @@ export async function composeRelayApp(options) {
2390
2439
  headerIconUrl: options.pwaIcon ? pwaIconUrl(options.pwaIcon) : undefined,
2391
2440
  protocolCompatible: protocol.compatible,
2392
2441
  providers: providerAvailability,
2393
- preview: Boolean(preview),
2442
+ preview: preview && (async () => Boolean(await preview.publication.refresh())),
2394
2443
  impeccable: true,
2395
2444
  },
2396
2445
  selfDebug: runtime
@@ -2479,6 +2528,20 @@ export async function composeRelayApp(options) {
2479
2528
  : undefined,
2480
2529
  sessionRoutes: {
2481
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
+ },
2482
2545
  forget: (id, keepFilesFor) => forgetSessions.execute(id, keepFilesFor),
2483
2546
  forgetOperation: (id) => forgetOperations.find(id),
2484
2547
  createId: randomUUID,
@@ -2800,7 +2863,7 @@ export async function composeRelayApp(options) {
2800
2863
  };
2801
2864
  if (preview)
2802
2865
  app.addHook('onReady', async () => {
2803
- await preview.gateway.start();
2866
+ await preview.publication.refresh();
2804
2867
  });
2805
2868
  app.addHook('onListen', async () => {
2806
2869
  for (const id of forgetOperations.pendingIds())
@@ -2837,9 +2900,10 @@ export async function composeRelayApp(options) {
2837
2900
  // history RPC must not keep us from reaching the normal runtime cleanup.
2838
2901
  app.addHook('preClose', async () => {
2839
2902
  closing = true;
2903
+ replacementShutdown.abort();
2840
2904
  providerRecovery.dispose();
2841
2905
  runtime?.cancelHistoryReads();
2842
- await preview?.gateway.close();
2906
+ await preview?.publication.close();
2843
2907
  });
2844
2908
  app.addHook('onClose', async () => {
2845
2909
  await hostTests?.close();
@@ -15,6 +15,7 @@ const optionNames = new Set([
15
15
  '--data-dir',
16
16
  '--public-origin',
17
17
  '--preview-origin',
18
+ '--preview-gateway-port',
18
19
  '--preview-target-port',
19
20
  '--skills',
20
21
  '--icon',
@@ -70,32 +71,41 @@ export function parseConfig(args, cwd = process.cwd()) {
70
71
  }
71
72
  function parsePreview(values, publicOrigin, relayPort, passkeyAuthEnabled) {
72
73
  const originValue = values.get('--preview-origin');
74
+ const gatewayValue = values.get('--preview-gateway-port');
73
75
  const targetValue = values.get('--preview-target-port');
74
76
  if (!originValue) {
77
+ if (gatewayValue)
78
+ throw new CliUsageError('--preview-gateway-port requires --preview-origin');
75
79
  if (targetValue)
76
80
  throw new CliUsageError('--preview-target-port requires --preview-origin');
77
81
  return;
78
82
  }
83
+ return createPreviewConfig({
84
+ origin: originValue,
85
+ gatewayPort: gatewayValue === undefined ? undefined : Number(gatewayValue),
86
+ targetPort: targetValue === undefined ? undefined : Number(targetValue),
87
+ }, publicOrigin, relayPort, passkeyAuthEnabled);
88
+ }
89
+ export function createPreviewConfig(settings, publicOrigin, relayPort, passkeyAuthEnabled) {
79
90
  if (!passkeyAuthEnabled)
80
91
  throw new CliUsageError('Previews require passkey authentication');
81
- const origin = new URL(normalizePublicOrigin(originValue, '--preview-origin'));
92
+ const origin = new URL(normalizePublicOrigin(settings.origin, '--preview-origin'));
82
93
  const relay = new URL(publicOrigin);
83
94
  if (origin.protocol !== 'https:' || relay.protocol !== 'https:')
84
95
  throw new CliUsageError('Previews require HTTPS origins for Mobile and the preview site');
85
96
  if (origin.hostname === relay.hostname || origin.hostname.endsWith(`.${relay.hostname}`))
86
97
  throw new CliUsageError('--preview-origin requires an independent hostname for preview content');
87
- const port = 8080;
88
- if (relayPort === port)
89
- throw new CliUsageError('The preview gateway requires port 8080');
90
- const targetPort = Number(targetValue ?? '5173');
91
- if (!Number.isInteger(targetPort) ||
92
- targetPort < 1024 ||
93
- targetPort > 65535 ||
94
- targetPort === relayPort ||
95
- targetPort === port)
98
+ const port = settings.gatewayPort ?? 8080;
99
+ if (!isUnprivilegedPort(port) || port === relayPort)
100
+ throw new CliUsageError('--preview-gateway-port must be a distinct unprivileged local port');
101
+ const targetPort = settings.targetPort ?? 5173;
102
+ if (!isUnprivilegedPort(targetPort) || targetPort === relayPort || targetPort === port)
96
103
  throw new CliUsageError('--preview-target-port must be a distinct unprivileged local port');
97
104
  return { origin: origin.origin, port, targetPort };
98
105
  }
106
+ function isUnprivilegedPort(port) {
107
+ return Number.isInteger(port) && port >= 1024 && port <= 65535;
108
+ }
99
109
  function resolveIconPath(cwd, value) {
100
110
  if (!/\.(?:png|svg)$/i.test(value))
101
111
  throw new CliUsageError('--icon must reference an SVG or PNG file');
@@ -4,11 +4,12 @@
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
6
  export async function getBootstrap(deps) {
7
- const [workspaces, profiles, codexModels, kimiModels] = await Promise.all([
7
+ const [workspaces, profiles, codexModels, kimiModels, preview] = await Promise.all([
8
8
  deps.workspaces.list(),
9
9
  deps.profiles.list(),
10
10
  deps.models?.list('codex').catch(() => []) ?? [],
11
11
  deps.models?.list('kimi').catch(() => []) ?? [],
12
+ deps.preview?.(),
12
13
  ]);
13
14
  let sessionDefaults = null;
14
15
  let sessionDefaultsError = false;
@@ -34,7 +35,7 @@ export async function getBootstrap(deps) {
34
35
  git: true,
35
36
  protocolCompatible: deps.protocolCompatible,
36
37
  providers: deps.providers,
37
- ...(deps.preview ? { preview: true } : {}),
38
+ ...(preview ? { preview: true } : {}),
38
39
  ...(deps.impeccable ? { impeccable: true } : {}),
39
40
  },
40
41
  };
@@ -53,9 +53,12 @@ export class PreviewService {
53
53
  const current = this.activePreview();
54
54
  if (current && current.sessionId !== sessionId)
55
55
  return false;
56
- this.preview = undefined;
56
+ this.clear();
57
57
  return true;
58
58
  }
59
+ clear() {
60
+ this.preview = undefined;
61
+ }
59
62
  activePreview() {
60
63
  if (this.preview && !this.deps.sessionActive(this.preview.sessionId))
61
64
  this.preview = undefined;
@@ -16,11 +16,17 @@ export function registerOpenPreview(app, deps) {
16
16
  .code(403)
17
17
  .type('application/problem+json')
18
18
  .send(problem('IMPECCABLE_UNAVAILABLE', 403, 'Impeccable is unavailable in this chat.'));
19
+ const origin = await deps.origin();
20
+ if (!origin)
21
+ return reply
22
+ .code(503)
23
+ .type('application/problem+json')
24
+ .send(problem('PREVIEW_UNAVAILABLE', 503, 'Ask the Mobile host operator to check web preview configuration.', true));
19
25
  const result = login
20
26
  ? deps.service.open(request.params.sessionId, login, impeccable ? 'impeccable' : 'view')
21
27
  : { kind: 'unauthorized' };
22
28
  if (result.kind === 'opened') {
23
- const url = new URL(previewHandoffPath, deps.origin);
29
+ const url = new URL(previewHandoffPath, origin);
24
30
  url.hash = result.code;
25
31
  return { url: url.href };
26
32
  }
@@ -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
  }