@wonderwhy-er/desktop-commander 0.2.48 → 0.2.51

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.
@@ -12,6 +12,40 @@ export class DesktopCommanderIntegration {
12
12
  this.mcpClient = null;
13
13
  this.mcpTransport = null;
14
14
  this.isReady = false;
15
+ this.isShuttingDown = false;
16
+ this.disconnectHandler = null;
17
+ this.reinitPromise = null;
18
+ }
19
+ /** True only while the local stdio child is actually reachable. */
20
+ get ready() {
21
+ return this.isReady && this.mcpClient !== null;
22
+ }
23
+ /**
24
+ * Register a callback fired when the local MCP child dies unexpectedly.
25
+ * The device uses this to stop advertising itself as online — the remote
26
+ * channel staying healthy says nothing about the local half being alive.
27
+ */
28
+ onDisconnect(handler) {
29
+ this.disconnectHandler = handler;
30
+ }
31
+ /**
32
+ * The local child exited or its pipe broke. Previously nothing observed this:
33
+ * `isReady` was a one-shot latch set in initialize() and cleared only by
34
+ * shutdown(), so every later callClientTool() sailed past the readiness guard
35
+ * and died inside the SDK with a bare "Not connected", forever, while the
36
+ * device still reported itself online.
37
+ */
38
+ handleLocalDisconnect(reason) {
39
+ if (this.isShuttingDown)
40
+ return; // expected teardown, not a fault
41
+ if (!this.isReady)
42
+ return; // already handled; don't double-fire
43
+ this.isReady = false;
44
+ this.mcpClient = null;
45
+ this.mcpTransport = null;
46
+ console.error(` - ❌ Local Desktop Commander MCP went away (${reason}); will restart on next tool call`);
47
+ void captureRemote('desktop_integration_local_disconnected', { reason });
48
+ this.disconnectHandler?.(reason);
15
49
  }
16
50
  async initialize() {
17
51
  console.debug('[DEBUG] DesktopCommanderIntegration.initialize() called');
@@ -43,16 +77,70 @@ export class DesktopCommanderIntegration {
43
77
  console.debug('[DEBUG] Connecting MCP client to transport');
44
78
  await this.mcpClient.connect(this.mcpTransport);
45
79
  this.isReady = true;
80
+ // Supervise the local half. Without these, a child crash is silent:
81
+ // the SDK clears its transport and every subsequent call throws
82
+ // "Not connected" with nothing tying it back to the death.
83
+ //
84
+ // These MUST hang off the client, not the transport. connect() wraps
85
+ // transport.onclose/onerror with its own handlers and the SDK states
86
+ // that "The Protocol object assumes ownership of the Transport,
87
+ // replacing any callbacks that have already been set". Assigning to
88
+ // the transport here instead would drop the SDK's wrapper, and with
89
+ // it Protocol._onclose() — the only place a pending response is
90
+ // rejected with ConnectionClosed. The call in flight when the child
91
+ // died would then hang for the SDK's 60s default request timeout
92
+ // before the user heard anything.
93
+ this.mcpClient.onclose = () => this.handleLocalDisconnect('stdio transport closed');
94
+ // Diagnostics only. Protocol.onerror is raised for eleven non-fatal
95
+ // conditions that say nothing about the child's health — a response
96
+ // for an unknown message id, an unknown progress token, a failed
97
+ // cancellation send, an uncaught notification-handler error — and
98
+ // treating any of those as death takes a working device offline and
99
+ // respawns a live child. Real death arrives through onclose, which
100
+ // only fires once the transport has actually closed.
101
+ this.mcpClient.onerror = (err) => console.error(` - ⚠️ Local Desktop Commander MCP error: ${err?.message ?? String(err)}`);
46
102
  console.log(' - 🔌 Connected to Desktop Commander MCP');
47
103
  console.debug('[DEBUG] Desktop Commander MCP connection successful');
48
104
  }
49
105
  catch (error) {
50
106
  console.error(' - ❌ Failed to connect to Desktop Commander MCP:', error);
51
107
  console.debug('[DEBUG] MCP connection error:', error);
108
+ // Leave no half-built client behind, or ensureReady() would treat the
109
+ // corpse as live on the next attempt.
110
+ this.isReady = false;
111
+ this.mcpClient = null;
112
+ if (this.mcpTransport) {
113
+ try {
114
+ await this.mcpTransport.close();
115
+ }
116
+ catch { /* already dead — nothing to salvage */ }
117
+ this.mcpTransport = null;
118
+ }
52
119
  await captureRemote('desktop_integration_init_failed', { error });
53
120
  throw error;
54
121
  }
55
122
  }
123
+ /**
124
+ * Guarantee a live local child before proxying a call, restarting it if the
125
+ * previous one died. Restart is lazy (on demand) rather than a retry loop:
126
+ * if the child is crashing on startup, each tool call fails with the real
127
+ * reason instead of spinning respawns in the background.
128
+ */
129
+ async ensureReady() {
130
+ if (this.ready)
131
+ return;
132
+ if (this.isShuttingDown) {
133
+ throw new Error('Desktop Commander integration is shutting down');
134
+ }
135
+ if (!this.reinitPromise) {
136
+ console.log(' - ♻️ Local Desktop Commander MCP is not running; restarting it...');
137
+ this.reinitPromise = this.initialize().finally(() => {
138
+ this.reinitPromise = null;
139
+ });
140
+ }
141
+ // Concurrent calls share the single in-flight restart.
142
+ await this.reinitPromise;
143
+ }
56
144
  async resolveMcpConfig() {
57
145
  console.debug('[DEBUG] Resolving MCP config...');
58
146
  // Option 1: Development/Local Build
@@ -106,10 +194,10 @@ export class DesktopCommanderIntegration {
106
194
  return null;
107
195
  }
108
196
  async callClientTool(toolName, args, metadata) {
109
- if (!this.isReady || !this.mcpClient) {
110
- console.debug('[DEBUG] callClientTool() failed - not ready or no client');
111
- throw new Error('DesktopIntegration not initialized');
112
- }
197
+ // Restart the child if it died since the last call, so a one-off crash
198
+ // costs one failed call instead of wedging the device until a human
199
+ // restarts `desktop-commander remote`.
200
+ await this.ensureReady();
113
201
  // Proxy other tools to MCP server
114
202
  try {
115
203
  console.debug('[DEBUG] Calling MCP tool:', toolName, 'args:', JSON.stringify(args).substring(0, 100));
@@ -150,6 +238,9 @@ export class DesktopCommanderIntegration {
150
238
  }
151
239
  async shutdown() {
152
240
  console.debug('[DEBUG] DesktopCommanderIntegration.shutdown() called');
241
+ // Closing the transport fires onclose; flag this as intentional so it is
242
+ // not reported as a crash.
243
+ this.isShuttingDown = true;
153
244
  const closeWithTimeout = async (operation, name, timeoutMs = 3000) => {
154
245
  return Promise.race([
155
246
  operation(),
@@ -2,6 +2,7 @@ import open from 'open';
2
2
  import os from 'os';
3
3
  import crypto from 'crypto';
4
4
  import { captureRemote } from '../utils/capture.js';
5
+ import { observeServerDate } from './remote-channel.js';
5
6
  const CLIENT_ID = 'mcp-device';
6
7
  export class DeviceAuthenticator {
7
8
  constructor(baseServerUrl) {
@@ -40,6 +41,7 @@ export class DeviceAuthenticator {
40
41
  code_challenge_method: 'S256',
41
42
  }),
42
43
  });
44
+ observeServerDate(response.headers.get('date'));
43
45
  if (!response.ok) {
44
46
  const error = await response.json().catch(() => ({ error: 'Unknown error' }));
45
47
  const errorMessage = error.error_description || 'Failed to start device flow';
@@ -52,9 +54,9 @@ export class DeviceAuthenticator {
52
54
  }
53
55
  displayUserInstructions(deviceAuth) {
54
56
  console.log('📋 Please complete authentication:\n');
55
- console.log(' 1. Open this URL in your browser:');
56
- console.log(` ${deviceAuth.verification_uri}\n`);
57
- console.log(' 2. Enter this code when prompted:');
57
+ console.log(' 1. Verify this device in your browser:');
58
+ console.log(` ${deviceAuth.verification_uri_complete}\n`);
59
+ console.log(' 2. Make sure the code matches:');
58
60
  console.log(` ${deviceAuth.user_code}\n`);
59
61
  console.log(` Code expires in ${Math.floor(deviceAuth.expires_in / 60)} minutes.\n`);
60
62
  // Try to open browser automatically
@@ -82,6 +84,9 @@ export class DeviceAuthenticator {
82
84
  code_verifier: codeVerifier,
83
85
  }),
84
86
  });
87
+ // The response that delivers the session states the server's
88
+ // time; correct the clock before that session is used.
89
+ observeServerDate(response.headers.get('date'));
85
90
  // Parse response body exactly once
86
91
  const data = await response.json().catch(() => ({ error: 'unknown' }));
87
92
  // Successful authentication
@@ -1,7 +1,9 @@
1
1
  #!/usr/bin/env node
2
+ import { type AuthSession } from './remote-channel.js';
2
3
  export interface MCPDeviceOptions {
3
4
  persistSession?: boolean;
4
5
  }
6
+ export declare function getRemoteDeviceConfigPath(): string;
5
7
  export declare class MCPDevice {
6
8
  private baseServerUrl;
7
9
  private remoteChannel;
@@ -10,17 +12,38 @@ export declare class MCPDevice {
10
12
  private configPath;
11
13
  private persistSession;
12
14
  private desktop;
15
+ /**
16
+ * Serialises config writes. Rotations are 45 minutes apart in normal
17
+ * running, but a save that stalls must not land after a newer one and
18
+ * persist a token that is already spent. Shutdown awaits this to drain
19
+ * whatever is still in flight.
20
+ */
21
+ private configWriteChain;
13
22
  /** Call ids already handled by THIS process (insertion-ordered, bounded). */
14
23
  private seenCallIds;
15
24
  constructor(options?: MCPDeviceOptions);
16
25
  private setupShutdownHandlers;
17
26
  start(): Promise<void>;
27
+ private findPersistedDeviceWithRetry;
18
28
  loadPersistedConfig(): Promise<any>;
19
- savePersistedConfig(): Promise<void>;
29
+ clearPersistedConfig(): Promise<void>;
30
+ /**
31
+ * Queue a config write. Returns the queued write, so a caller that must not
32
+ * outlive it - shutdown() - can await it.
33
+ */
34
+ savePersistedConfig(rotated?: AuthSession): Promise<void>;
35
+ private writePersistedConfig;
20
36
  fetchSupabaseConfig(): Promise<{
21
37
  supabaseUrl: any;
22
38
  anonKey: any;
23
39
  }>;
40
+ /**
41
+ * The local Desktop Commander child died. A healthy remote channel says
42
+ * nothing about the local half being alive, so without this the device kept
43
+ * reporting itself online and every routed tool call came back "Not
44
+ * connected" until someone restarted the process by hand.
45
+ */
46
+ private handleLocalMcpLoss;
24
47
  /** Record a handled call id, evicting the oldest once the cap is reached. */
25
48
  private rememberCallId;
26
49
  handleNewToolCall(payload: any): Promise<void>;
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { RemoteChannel } from './remote-channel.js';
2
+ import { RemoteChannel, observeServerDate } from './remote-channel.js';
3
3
  import { DeviceAuthenticator } from './device-authenticator.js';
4
4
  import { DesktopCommanderIntegration } from './desktop-commander-integration.js';
5
5
  import { fileURLToPath } from 'url';
@@ -15,20 +15,37 @@ import { captureRemote } from '../utils/capture.js';
15
15
  * (the device process, not the shared server).
16
16
  */
17
17
  const SEEN_CALL_IDS_MAX = 100;
18
+ const PERSISTED_DEVICE_LOOKUP_ATTEMPTS = 3;
19
+ const PERSISTED_DEVICE_LOOKUP_RETRY_MS = 250;
20
+ export function getRemoteDeviceConfigPath() {
21
+ return path.join(os.homedir(), '.desktop-commander-device', 'device.json');
22
+ }
18
23
  export class MCPDevice {
19
24
  constructor(options = {}) {
25
+ /**
26
+ * Serialises config writes. Rotations are 45 minutes apart in normal
27
+ * running, but a save that stalls must not land after a newer one and
28
+ * persist a token that is already spent. Shutdown awaits this to drain
29
+ * whatever is still in flight.
30
+ */
31
+ this.configWriteChain = Promise.resolve();
20
32
  /** Call ids already handled by THIS process (insertion-ordered, bounded). */
21
33
  this.seenCallIds = new Set();
22
34
  this.baseServerUrl = process.env.MCP_SERVER_URL || 'https://mcp.desktopcommander.app';
23
35
  this.remoteChannel = new RemoteChannel();
24
36
  this.deviceId = undefined;
25
37
  this.isShuttingDown = false;
26
- this.configPath = path.join(os.homedir(), '.desktop-commander-device', 'device.json');
38
+ this.configPath = getRemoteDeviceConfigPath();
27
39
  // Default ON. Off meant a full re-authorization on every start, and each
28
40
  // one mints a fresh GoTrue session that nothing ever revokes; the orphaned
29
41
  // refresh-token families get replayed, trip GoTrue's reuse detection, and
30
42
  // take the whole family down including the token a healthy connector holds.
31
43
  this.persistSession = options.persistSession ?? true;
44
+ // The session refreshes every 45 minutes and auth-js rotates the refresh
45
+ // token each time. Without this the config keeps whichever token the
46
+ // process started with, and a restart hours later replays a spent one -
47
+ // GoTrue refuses it and an unattended device waits for a browser.
48
+ this.remoteChannel.onSessionRefreshed((session) => void this.savePersistedConfig(session));
32
49
  // Initialize desktop integration
33
50
  this.desktop = new DesktopCommanderIntegration();
34
51
  // Graceful shutdown handlers (only set once)
@@ -86,6 +103,7 @@ export class MCPDevice {
86
103
  }
87
104
  // Initialize desktop integration
88
105
  await this.desktop.initialize();
106
+ this.desktop.onDisconnect((reason) => void this.handleLocalMcpLoss(reason));
89
107
  console.log(`⏳ Connecting to Remote MCP ${this.baseServerUrl}`);
90
108
  const { supabaseUrl, anonKey } = await this.fetchSupabaseConfig();
91
109
  console.log(` - 🔌 Connected to Remote MCP`);
@@ -102,6 +120,20 @@ export class MCPDevice {
102
120
  }
103
121
  else {
104
122
  console.log(' - ✅ Session restored');
123
+ console.log(' - ℹ️ To log out locally: npx @wonderwhy-er/desktop-commander@latest remote --logout');
124
+ // Revoking a device removes its server-side mcp_devices row, but the
125
+ // local config can still hold a valid user session + the now-deleted
126
+ // device ID. Do not silently recreate the revoked device with that
127
+ // old session: revocation must require a fresh browser authorization.
128
+ if (this.deviceId) {
129
+ const persistedDevice = await this.findPersistedDeviceWithRetry(this.deviceId);
130
+ if (!persistedDevice) {
131
+ console.log(` - ⚠️ Persisted device ${this.deviceId} was revoked or removed`);
132
+ await this.clearPersistedConfig();
133
+ this.deviceId = undefined;
134
+ session = null;
135
+ }
136
+ }
105
137
  }
106
138
  }
107
139
  if (!session) {
@@ -156,6 +188,22 @@ export class MCPDevice {
156
188
  process.exit(1);
157
189
  }
158
190
  }
191
+ async findPersistedDeviceWithRetry(deviceId) {
192
+ let lastError;
193
+ for (let attempt = 1; attempt <= PERSISTED_DEVICE_LOOKUP_ATTEMPTS; attempt++) {
194
+ try {
195
+ return await this.remoteChannel.findDevice(deviceId);
196
+ }
197
+ catch (error) {
198
+ lastError = error;
199
+ if (attempt === PERSISTED_DEVICE_LOOKUP_ATTEMPTS)
200
+ break;
201
+ console.warn(` - ⚠️ Device lookup failed (${attempt}/${PERSISTED_DEVICE_LOOKUP_ATTEMPTS}); retrying...`);
202
+ await new Promise((resolve) => setTimeout(resolve, PERSISTED_DEVICE_LOOKUP_RETRY_MS * attempt));
203
+ }
204
+ }
205
+ throw lastError;
206
+ }
159
207
  async loadPersistedConfig() {
160
208
  try {
161
209
  console.debug('[DEBUG] Loading persisted config from:', this.configPath);
@@ -194,11 +242,38 @@ export class MCPDevice {
194
242
  // No need to ensure device ID here
195
243
  }
196
244
  }
197
- async savePersistedConfig() {
245
+ async clearPersistedConfig() {
246
+ try {
247
+ await fs.rm(this.configPath, { force: true });
248
+ console.debug('[DEBUG] Cleared stale persisted config:', this.configPath);
249
+ }
250
+ catch (error) {
251
+ console.warn('⚠️ Failed to clear stale config:', error.message);
252
+ await captureRemote('remote_device_config_clear_error', { error });
253
+ }
254
+ }
255
+ /**
256
+ * Queue a config write. Returns the queued write, so a caller that must not
257
+ * outlive it - shutdown() - can await it.
258
+ */
259
+ async savePersistedConfig(rotated) {
260
+ this.configWriteChain = this.configWriteChain.then(() => this.writePersistedConfig(rotated));
261
+ return this.configWriteChain;
262
+ }
263
+ async writePersistedConfig(rotated) {
198
264
  try {
199
265
  console.debug('[DEBUG] Saving persisted config, persistSession:', this.persistSession);
200
- const currentSessionStore = await this.remoteChannel.getSession();
201
- const session = currentSessionStore.data.session;
266
+ // Prefer the session TOKEN_REFRESHED handed us over re-reading it. A
267
+ // sign-out landing in that gap answers null, and the write below would
268
+ // replace a usable refresh token with nothing.
269
+ const session = rotated ?? (await this.remoteChannel.getSession()).data.session;
270
+ // Never trade a good token for an empty one. Deliberate clearing is
271
+ // what clearPersistedConfig() is for; --no-persist-session still
272
+ // writes null below, because persistSession is false there.
273
+ if (this.persistSession && !session?.refresh_token) {
274
+ console.debug('[DEBUG] Skipping config save - nothing to persist');
275
+ return;
276
+ }
202
277
  const config = {
203
278
  deviceId: this.deviceId,
204
279
  // Only save session if --persist-session flag is set
@@ -210,7 +285,16 @@ export class MCPDevice {
210
285
  // Ensure the config directory exists
211
286
  console.debug('[DEBUG] Creating config directory:', path.dirname(this.configPath));
212
287
  await fs.mkdir(path.dirname(this.configPath), { recursive: true });
213
- await fs.writeFile(this.configPath, JSON.stringify(config, null, 2), { mode: 0o600 });
288
+ // Write then rename: the rename is the commit boundary, so a write
289
+ // cut short leaves the previous complete session rather than a
290
+ // truncated file. loadPersistedConfig() answers a JSON.parse
291
+ // failure with null, which costs a full browser reauthorization.
292
+ // Same shape as ConfigManager's atomic save; the pid keeps two
293
+ // processes off each other's temp file, and configWriteChain keeps
294
+ // this one off its own.
295
+ const tempPath = `${this.configPath}.${process.pid}.tmp`;
296
+ await fs.writeFile(tempPath, JSON.stringify(config, null, 2), { mode: 0o600 });
297
+ await fs.rename(tempPath, this.configPath);
214
298
  console.debug('[DEBUG] Config saved to:', this.configPath);
215
299
  }
216
300
  catch (error) {
@@ -223,6 +307,11 @@ export class MCPDevice {
223
307
  // No auth header needed for this public endpoint
224
308
  console.debug('[DEBUG] Fetching Supabase config from:', `${this.baseServerUrl}/api/mcp-info`);
225
309
  const response = await fetch(`${this.baseServerUrl}/api/mcp-info`);
310
+ // First request of the run, and it already states the server's time.
311
+ // auth-js judges the session handed to setSession() against this
312
+ // device's Date.now() with no skew tolerance, so the clock has to be
313
+ // right BEFORE that call - clockAwareFetch only corrects it afterwards.
314
+ observeServerDate(response.headers.get('date'));
226
315
  if (!response.ok) {
227
316
  console.debug('[DEBUG] Supabase config fetch failed, status:', response.status, response.statusText);
228
317
  throw new Error(`Failed to fetch Supabase config: ${response.statusText}`);
@@ -235,6 +324,32 @@ export class MCPDevice {
235
324
  };
236
325
  }
237
326
  // Methods moved to RemoteChannel
327
+ /**
328
+ * The local Desktop Commander child died. A healthy remote channel says
329
+ * nothing about the local half being alive, so without this the device kept
330
+ * reporting itself online and every routed tool call came back "Not
331
+ * connected" until someone restarted the process by hand.
332
+ */
333
+ async handleLocalMcpLoss(reason) {
334
+ if (this.deviceId) {
335
+ await this.remoteChannel.setOnlineStatus(this.deviceId, 'offline')
336
+ .catch((e) => console.error('Failed to mark device offline:', e.message));
337
+ }
338
+ // Recover proactively rather than waiting for the next tool call to
339
+ // trigger the lazy restart: we just went offline, so no further calls
340
+ // would be routed here and that wait would never end.
341
+ try {
342
+ await this.desktop.ensureReady();
343
+ if (this.deviceId) {
344
+ await this.remoteChannel.setOnlineStatus(this.deviceId, 'online');
345
+ }
346
+ console.log('♻️ Local Desktop Commander MCP restarted; device is online again');
347
+ }
348
+ catch (error) {
349
+ console.error(`❌ Could not restart local Desktop Commander MCP: ${error.message}`);
350
+ await captureRemote('remote_device_local_mcp_restart_failed', { error, reason });
351
+ }
352
+ }
238
353
  /** Record a handled call id, evicting the oldest once the cap is reached. */
239
354
  rememberCallId(callId) {
240
355
  this.seenCallIds.add(callId);
@@ -271,8 +386,9 @@ export class MCPDevice {
271
386
  // DB claim second — keeps the row state machine honest, gives
272
387
  // cross-restart/cross-process protection, and is observable. It may
273
388
  // fail open (returns true on a transient write error); the local
274
- // guard above is what makes execution exactly-once.
275
- const claimed = await this.remoteChannel.markCallExecuting(call_id);
389
+ // guard above is what makes execution exactly-once. The doorbell
390
+ // path claims before dispatch and marks the payload `claimed`.
391
+ const claimed = payload.claimed === true || await this.remoteChannel.markCallExecuting(call_id);
276
392
  if (!claimed) {
277
393
  // markCallExecuting already logged the duplicate-delivery skip.
278
394
  return;
@@ -306,10 +422,8 @@ export class MCPDevice {
306
422
  result = await this.desktop.callClientTool(tool_name, tool_args, metadata);
307
423
  }
308
424
  console.log(`✅ Tool call ${tool_name} completed:\r\n ${JSON.stringify(result)}`);
309
- // Update database with result, THEN ring the doorbell — the server
310
- // fetches the row by id on the doorbell, so the write must land first.
425
+ // The result write itself notifies the server (a DB trigger).
311
426
  await this.remoteChannel.updateCallResult(call_id, 'completed', result);
312
- await this.remoteChannel.notifyResult(call_id);
313
427
  }
314
428
  catch (error) {
315
429
  console.error(`❌ Tool call ${tool_name} failed:`, error.message);
@@ -319,7 +433,6 @@ export class MCPDevice {
319
433
  try {
320
434
  await captureRemote('remote_device_tool_call_failed', { error, tool_name });
321
435
  await this.remoteChannel.updateCallResult(call_id, 'failed', null, error.message);
322
- await this.remoteChannel.notifyResult(call_id);
323
436
  }
324
437
  catch (reportError) {
325
438
  console.error(`❌ Could not report failure for ${call_id}:`, reportError?.message);
@@ -348,6 +461,10 @@ export class MCPDevice {
348
461
  console.log(' → Marking device offline...');
349
462
  console.debug('[DEBUG] Calling setOffline() with deviceId:', this.deviceId);
350
463
  await this.remoteChannel.setOffline(this.deviceId);
464
+ // Drain any config write still in flight - a rotation can land as
465
+ // teardown begins, and losing it costs the next start a browser.
466
+ console.debug('[DEBUG] Draining pending config writes');
467
+ await this.configWriteChain;
351
468
  // Shutdown desktop integration
352
469
  console.log(' → Shutting down desktop integration...');
353
470
  console.debug('[DEBUG] Calling desktop.shutdown()');
@@ -28,6 +28,8 @@ export declare class RemoteChannel {
28
28
  private statusWriteChain;
29
29
  /** Tokens from the last setSession / TOKEN_REFRESHED, for setOffline(). */
30
30
  private lastKnownSession;
31
+ /** Notified when auth-js rotates the session; the device persists it. */
32
+ private sessionRefreshedHandler;
31
33
  /** Set by unsubscribe(): suppresses status/heartbeat writes so they can't
32
34
  * land after setOffline()'s durable write. */
33
35
  private shuttingDown;
@@ -63,6 +65,13 @@ export declare class RemoteChannel {
63
65
  private _user;
64
66
  get user(): User | null;
65
67
  initialize(url: string, key: string): void;
68
+ /**
69
+ * Register a callback fired when auth-js rotates the session. auth-js
70
+ * rotates the refresh token on every refresh and the previous one is spent,
71
+ * so a config written once at startup replays a dead token on the next
72
+ * restart and the device demands browser authorization again.
73
+ */
74
+ onSessionRefreshed(handler: (session: AuthSession) => void): void;
66
75
  setSession(session: AuthSession): Promise<{
67
76
  error: any;
68
77
  }>;
@@ -96,7 +105,7 @@ export declare class RemoteChannel {
96
105
  /**
97
106
  * Publish presence, retrying a non-'ok' result — track() resolves with a
98
107
  * status rather than rejecting, and absent presence reads as offline on the
99
- * server. `presenceTracked` lets the health check retry later.
108
+ * dashboard. `presenceTracked` lets the health check retry later.
100
109
  */
101
110
  private trackPresenceWithRetry;
102
111
  private trackPresenceInner;
@@ -107,9 +116,8 @@ export declare class RemoteChannel {
107
116
  private capabilitiesPayload;
108
117
  /**
109
118
  * Advertise (or withdraw) the broadcast capability. Only true while genuinely
110
- * reachable that way — the server uses it to pick a transport, to read absent
111
- * presence as offline, and to choose the sweep tier, so every change must
112
- * re-arm the heartbeat.
119
+ * reachable that way — the server fails dispatch fast without it and picks
120
+ * the offline-sweep tier from it, so every change must re-arm the heartbeat.
113
121
  */
114
122
  private setTransportCapable;
115
123
  /** Create and subscribe the private channel (initial join and recreation). */
@@ -118,17 +126,11 @@ export declare class RemoteChannel {
118
126
  * and an unhandled rejection terminates the process. */
119
127
  private dispatchToolCall;
120
128
  /**
121
- * Handle a 'new_call' doorbell. It carries ids only; the row is fetched by
122
- * primary key and fed through the same handler as a postgres_changes
123
- * payload, so device.ts stays transport-agnostic.
129
+ * Handle a 'new_call' doorbell. It carries ids only; one conditional update
130
+ * claims the row (pending -> executing) and returns it, and it is handed to
131
+ * device.ts marked as claimed.
124
132
  */
125
133
  private onDoorbell;
126
- /**
127
- * Tell the server a result row is written. Fire-and-forget: a failed send
128
- * just falls back to the server's 10s recovery poll. MUST run only after
129
- * updateCallResult() resolves, so the server's fetch-by-id sees a terminal row.
130
- */
131
- notifyResult(callId: string): Promise<void>;
132
134
  /**
133
135
  * Compact connection state for logs — e.g. "socket=open(1) ch=errored attempt=3".
134
136
  * readyState 1=OPEN (a 1 while joins keep failing = a half-open socket being reused),