@clawchatsai/connector 0.2.2 → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/server/gateway.js +2 -1
- package/server/index.js +5 -2
- package/server/peer/sharing.js +196 -44
- package/server/peer/sharing.test.js +283 -3
- package/server/team.js +10 -4
- package/server/team.test.js +33 -0
- package/server/util/chat-abort.js +53 -0
- package/server/util/chat-abort.test.js +61 -0
package/package.json
CHANGED
package/server/gateway.js
CHANGED
|
@@ -135,7 +135,8 @@ export class GatewayClient {
|
|
|
135
135
|
this.ws.send(JSON.stringify({ type: 'req', id: 'gw-connect-1', method: 'connect', params: this._connectParams(msg.payload?.nonce || '', ['tool-events', 'chat-queue-status']) }));
|
|
136
136
|
return;
|
|
137
137
|
}
|
|
138
|
-
|
|
138
|
+
// hello-ok is kept per connection (server.version: feature checks such as util/chat-abort.js).
|
|
139
|
+
if (msg.type === 'res' && msg.payload?.type === 'hello-ok') { console.log('Gateway handshake complete'); this.hello = msg.payload; this.connected = true; this.attachmentLimits = attachmentLimitsOf(msg.payload); this.broadcastGatewayStatus(true); if (this.attachmentLimits) this.broadcastToBrowsers(this.attachmentLimitsFrame()); this.sync?.onConnected(); this.onConnected?.(); this.request('sessions.subscribe', {}).catch(e => console.warn(`[lens] sessions.subscribe failed: ${e.message}`)); this.lens?.seedWithRetry(); }
|
|
139
140
|
// Session events arrive through the connector's own subscription; the lens filters them
|
|
140
141
|
// for the browser (session.message only for chats a browser subscribed to).
|
|
141
142
|
if (msg.type === 'event' && (msg.event === 'sessions.changed' || msg.event === 'session.message')) {
|
package/server/index.js
CHANGED
|
@@ -9,6 +9,7 @@ import { GATEWAY_WS_URL, AUTH_TOKEN, discoverWorkspaceDir } from './config.js';
|
|
|
9
9
|
import { DebugLogger } from './debug.js';
|
|
10
10
|
import { GatewayClient } from './gateway.js';
|
|
11
11
|
import { withGatewayRetry } from './util/gateway-retry.js';
|
|
12
|
+
import { createChatAbort } from './util/chat-abort.js';
|
|
12
13
|
import { handleServeFile, handleWorkspaceList, handleWorkspaceFileRead, handleWorkspaceFileWrite, handleWorkspaceFileDelete, handleWorkspaceUpload, handleWorkspaceCreate, handleWorkspaceMove, handleWorkspaceCopy } from './controllers/filesystem.js';
|
|
13
14
|
import { handleTranscribe } from './controllers/transcribe.js';
|
|
14
15
|
import { createGatewayMediaHandler } from './controllers/gateway-media.js';
|
|
@@ -83,15 +84,17 @@ export function createApp(config = {}) {
|
|
|
83
84
|
// The connector's own requests wait out a gateway that is still starting (2026.11.4+ refuses writes with a retryable
|
|
84
85
|
// UNAVAILABLE; util/gateway-retry.js). Frames a browser relays don't pass here: the frontend retries those.
|
|
85
86
|
const gwRequest = withGatewayRetry((m, p, t) => gatewayClient.request(m, p, t));
|
|
87
|
+
// Stop for the connector's own runs, fenced to the run's session where the gateway supports it (util/chat-abort.js).
|
|
88
|
+
const chatAbort = createChatAbort(gwRequest, { hello: () => gatewayClient.hello });
|
|
86
89
|
// Gateway sharing (server/peer/): other people's agents in team chats, and ours in theirs. The
|
|
87
90
|
// plugin host (src/index.ts) supplies the signal server link and the peer transport (config.peer).
|
|
88
91
|
const peerKey = loadOrCreatePeerKey(DATA_DIR);
|
|
89
92
|
const sharing = config.peer ? new SharingManager({
|
|
90
|
-
getDb: () => globalDbCache.get(), request: gwRequest, key: peerKey, broadcast,
|
|
93
|
+
getDb: () => globalDbCache.get(), request: gwRequest, chatAbort, key: peerKey, broadcast,
|
|
91
94
|
gatewayId: config.peer.gatewayId, signal: config.peer.signal, openPeer: config.peer.openPeer,
|
|
92
95
|
}) : null;
|
|
93
96
|
// Team chats: several agents in one thread (server/team.js).
|
|
94
|
-
const team = new TeamCoordinator({ store: createTeamStore(() => globalDbCache.get()), request: gwRequest, broadcast, titler: createTitler(config.llm), remote: sharing });
|
|
97
|
+
const team = new TeamCoordinator({ store: createTeamStore(() => globalDbCache.get()), request: gwRequest, chatAbort, broadcast, titler: createTitler(config.llm), remote: sharing });
|
|
95
98
|
gatewayClient.onEvent = msg => { team.onGatewayEvent(msg); sharing?.onGatewayEvent(msg); };
|
|
96
99
|
gatewayClient.onApprovalEvent = msg => sharing?.onApprovalEvent(msg);
|
|
97
100
|
gatewayClient.onConnected = () => { sharing?.migrateGuestAgents().catch(e => console.warn(`[sharing] guest migration failed: ${e.message}`)); };
|
package/server/peer/sharing.js
CHANGED
|
@@ -17,6 +17,7 @@ import crypto from 'node:crypto';
|
|
|
17
17
|
import { PeerLink } from './link.js';
|
|
18
18
|
import { canonicalJson, verifySignature, fingerprint } from './keys.js';
|
|
19
19
|
import { redactSecrets } from '../util/redact.js';
|
|
20
|
+
import { createChatAbort } from '../util/chat-abort.js';
|
|
20
21
|
import { hasGuestRestrictions, ensureGuestRestrictions, findGuestAgent, isGuestAgent, restrictionsPending } from './guest-agent.js';
|
|
21
22
|
|
|
22
23
|
const TURN_TIMEOUT_MS = 10 * 60_000;
|
|
@@ -24,6 +25,15 @@ const TURN_TIMEOUT_MS = 10 * 60_000;
|
|
|
24
25
|
export const EMPTY_REPLY_ERROR = /empty response|did not produce a visible reply/i;
|
|
25
26
|
const DEFAULT_DAILY_CAP = 50;
|
|
26
27
|
const MAX_CONCURRENT_TURNS = 2; // per share: the daily cap alone would allow 50 parallel 10-minute runs
|
|
28
|
+
// Owner side: finished guest turns, so a resend after a dropped link gets the result instead of a new run.
|
|
29
|
+
const RECENT_TURN_MS = 10 * 60_000;
|
|
30
|
+
const RECENT_TURNS_MAX = 200;
|
|
31
|
+
// Requester side: waits before sending a turn again after its link dropped (one resend per entry).
|
|
32
|
+
const RESEND_BACKOFF_MS = [2_000, 5_000];
|
|
33
|
+
// Owner side: a turn its gateway's restart cut off. 2026.11.x resumes it a few seconds after it's back (a "Gateway
|
|
34
|
+
// restarted" turn of its own, under another run id); this long for that to start, polled this often.
|
|
35
|
+
const RECOVERY_WAIT_MS = 30_000;
|
|
36
|
+
const RECOVERY_POLL_MS = 2_000;
|
|
27
37
|
const ACCESS_MODES = { restricted: 'read-only', trusted: 'guarded' };
|
|
28
38
|
/**
|
|
29
39
|
* Requests one contact's gateway may make of this one over the sharing link: [burst, per ms] token
|
|
@@ -51,6 +61,8 @@ const GUEST_NOTE = name => `(Shared session: you are answering ${name}'s team ch
|
|
|
51
61
|
const ACTING_FOR_NOTE = (name, byPerson) => `(Shared session: in your owner's team chat, you are answering ${byPerson ? name : `${name}'s agent`}, so you act for ${name}, not for your owner. ${name} is not your owner — don't reveal your owner's private information or act on your owner's accounts for them.)`;
|
|
52
62
|
|
|
53
63
|
const today = () => new Date().toISOString().slice(0, 10);
|
|
64
|
+
/** A guest turn's emit with secrets redacted from streamed text (see _guestTurn). */
|
|
65
|
+
const redacting = emit => emit && ((event, data) => emit(event, event === 'delta' ? redactSecrets(data) : data));
|
|
54
66
|
/** A name that came from the other side, safe to show and to use as a chat label (no brackets, newlines, controls). */
|
|
55
67
|
const cleanName = (v, max = 40) => String(v || '').replace(/[\u0000-\u001f\u007f-\u009f\[\]]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, max);
|
|
56
68
|
const firstName = p => cleanName(String(p?.name || p?.email || 'Someone').split(/[\s@]/)[0], 30) || 'Someone';
|
|
@@ -73,16 +85,19 @@ export class SharingManager {
|
|
|
73
85
|
* @param {(shareId: string) => Promise<{ dc, dtls }>} o.openPeer open a peer DataChannel (requester)
|
|
74
86
|
* @param {(data: string) => void} o.broadcast frame to this gateway's browsers
|
|
75
87
|
*/
|
|
76
|
-
constructor({ getDb, request, key, gatewayId, signal, openPeer, broadcast = () => {}, log = console }) {
|
|
77
|
-
Object.assign(this, { getDb, request, key, gatewayId, signal, openPeer, broadcast, log });
|
|
88
|
+
constructor({ getDb, request, chatAbort = null, key, gatewayId, signal, openPeer, broadcast = () => {}, log = console, resendBackoffMs = RESEND_BACKOFF_MS, recovery = { waitMs: RECOVERY_WAIT_MS, pollMs: RECOVERY_POLL_MS } }) {
|
|
89
|
+
Object.assign(this, { getDb, request, key, gatewayId, signal, openPeer, broadcast, log, resendBackoffMs, recovery });
|
|
90
|
+
this.chatAbort = chatAbort || createChatAbort((m, p, t) => this.request(m, p, t)); // Stop, fenced where supported
|
|
78
91
|
this._shares = []; // latest share-list from the signal server
|
|
79
92
|
this.serverEnabled = false; // the signal server sends a share-list only to accounts with sharing on
|
|
80
93
|
this._links = new Map(); // shareId -> PeerLink (requester side, one per share)
|
|
81
94
|
this._linking = new Map(); // shareId -> Promise<PeerLink>
|
|
82
95
|
this._served = new Set(); // owner-side PeerLinks
|
|
83
96
|
this._runs = new Map(); // runId -> { resolve, timer, text } (owner-side guest runs)
|
|
84
|
-
// Owner-side guest turns, keyed by an id made here (never the requester's):
|
|
97
|
+
// Owner-side guest turns, keyed by an id made here (never the requester's):
|
|
98
|
+
// { shareId, clientTurnId, same, sessionKey, runId, sessionId, aborted, emit, result }
|
|
85
99
|
this._turns = new Map();
|
|
100
|
+
this._finished = new Map(); // `${shareId}|${clientTurnId}` -> { same, result | error, at } (RECENT_TURN_MS)
|
|
86
101
|
this._buckets = new Map(); // `${gateway}|${kind}` -> { tokens, at } (PEER_RATES)
|
|
87
102
|
this._ready = false;
|
|
88
103
|
}
|
|
@@ -272,7 +287,7 @@ export class SharingManager {
|
|
|
272
287
|
|
|
273
288
|
_abortTurn(t) {
|
|
274
289
|
t.aborted = true;
|
|
275
|
-
if (t.runId) this.
|
|
290
|
+
if (t.runId) this.chatAbort.abort({ sessionKey: t.sessionKey, runId: t.runId, sessionId: t.sessionId }).catch(() => {});
|
|
276
291
|
}
|
|
277
292
|
|
|
278
293
|
/** Remember an agent created here as a guest version (ClawChats → Sharing). */
|
|
@@ -584,40 +599,80 @@ export class SharingManager {
|
|
|
584
599
|
if (!agent) throw Object.assign(new Error('That agent is not shared'), { code: 'not_shared' });
|
|
585
600
|
const roomId = String(p.roomId || '').slice(0, 200);
|
|
586
601
|
if (!roomId || typeof p.message !== 'string' || !p.message.trim()) throw Object.assign(new Error('Bad turn'), { code: 'bad_request' });
|
|
587
|
-
|
|
588
|
-
//
|
|
589
|
-
// so reusing one can't hide a turn from the limit or from "Stop sharing".
|
|
602
|
+
// The requester's turn id only names the turn (for its Stop, and for a resend after its link dropped); the turn
|
|
603
|
+
// itself is tracked under an id made here, so reusing one can't hide a turn from the limit or from "Stop sharing".
|
|
590
604
|
const clientTurnId = typeof p.turnId === 'string' && p.turnId ? p.turnId.slice(0, 200) : null;
|
|
605
|
+
const same = JSON.stringify([agent.id, roomId, p.message]); // what a resend repeats exactly
|
|
606
|
+
const recentKey = clientTurnId && `${shareId}|${clientTurnId}`;
|
|
607
|
+
if (clientTurnId) {
|
|
608
|
+
const live = [...this._turns.values()].find(t => t.shareId === shareId && t.clientTurnId === clientTurnId);
|
|
609
|
+
const done = !live && this._recentTurn(recentKey);
|
|
610
|
+
if ((live || done) && (live || done).same !== same) throw Object.assign(new Error('That turn was already sent with another message'), { code: 'bad_request' });
|
|
611
|
+
// A resend: no new run, and it isn't counted again.
|
|
612
|
+
if (live) return this._reattach(live, emit);
|
|
613
|
+
if (done?.error) throw Object.assign(new Error(done.error.message), { code: done.error.code, partial: done.error.partial });
|
|
614
|
+
if (done) return { ...done.result };
|
|
615
|
+
}
|
|
616
|
+
if (this._usage(shareId) >= grant.dailyCap) throw Object.assign(new Error(`Daily limit reached (${grant.dailyCap} replies)`), { code: 'cap' });
|
|
591
617
|
const running = [...this._turns.values()].filter(t => t.shareId === shareId);
|
|
592
|
-
if (clientTurnId && running.some(t => t.clientTurnId === clientTurnId)) throw Object.assign(new Error('That turn is already running'), { code: 'bad_request' });
|
|
593
618
|
if (running.length >= MAX_CONCURRENT_TURNS) throw Object.assign(new Error('Too many replies at once; try again shortly'), { code: 'busy' });
|
|
594
619
|
const turnKey = crypto.randomUUID();
|
|
595
|
-
|
|
620
|
+
// Everything the guest's agent says leaves this gateway (to the other person, or into a room they see). The
|
|
621
|
+
// gateway stopped masking secrets in tool output in 2026.10.10, so a credential an agent read can come out in
|
|
622
|
+
// its reply: redact it here (util/redact.js), in the streamed text, the final one and a failed turn's partial.
|
|
623
|
+
// `emit` is the link that asked last (a resend after a dropped link takes over the stream).
|
|
624
|
+
const turn = { shareId, clientTurnId, same, sessionKey: null, runId: null, sessionId: null, aborted: false, emit: redacting(emit), result: null };
|
|
625
|
+
this._turns.set(turnKey, turn); // counts toward the limit from here on
|
|
596
626
|
// Counted before any await, so parallel turns can't both pass the cap.
|
|
597
627
|
this._db().prepare('INSERT INTO peer_usage (share_id, day, turns) VALUES (?, ?, 1) ON CONFLICT(share_id, day) DO UPDATE SET turns = turns + 1').run(shareId, today());
|
|
598
628
|
this._changed(); // the owner's Sharing view shows today's count
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
if (!p.inOwnerRoom && r?.text) try { this.onGuestReply?.(grant.requesterGatewayId, roomId, shareId, agent.id, r.text); } catch { /* best effort */ }
|
|
608
|
-
return r;
|
|
609
|
-
}
|
|
610
|
-
catch (e) {
|
|
611
|
-
if (typeof e?.partial === 'string') e.partial = redactSecrets(e.partial);
|
|
612
|
-
// A reply that failed without saying anything doesn't use up the day's replies. A timeout still
|
|
613
|
-
// counts: it ran for the full turn timeout.
|
|
614
|
-
if (!e.partial && !/timed out/i.test(e.message)) {
|
|
615
|
-
this._db().prepare('UPDATE peer_usage SET turns = MAX(0, turns - 1) WHERE share_id = ? AND day = ?').run(shareId, today());
|
|
616
|
-
this._changed();
|
|
629
|
+
turn.result = (async () => {
|
|
630
|
+
try {
|
|
631
|
+
const r = await this._runGuestTurn(shareId, grant, agent, roomId, p, (event, data) => turn.emit?.(event, data), turn);
|
|
632
|
+
if (typeof r?.text === 'string') r.text = redactSecrets(r.text);
|
|
633
|
+
// What this gateway's agent said for that gateway's room: its copy of the room may show it as ours (team.js).
|
|
634
|
+
if (!p.inOwnerRoom && r?.text) try { this.onGuestReply?.(grant.requesterGatewayId, roomId, shareId, agent.id, r.text); } catch { /* best effort */ }
|
|
635
|
+
if (recentKey) this._rememberTurn(recentKey, { same, result: { ...r } });
|
|
636
|
+
return r;
|
|
617
637
|
}
|
|
618
|
-
|
|
638
|
+
catch (e) {
|
|
639
|
+
if (typeof e?.partial === 'string') e.partial = redactSecrets(e.partial);
|
|
640
|
+
// A reply that failed without saying anything doesn't use up the day's replies. A timeout still
|
|
641
|
+
// counts: it ran for the full turn timeout.
|
|
642
|
+
if (!e.partial && !/timed out/i.test(e.message)) {
|
|
643
|
+
this._db().prepare('UPDATE peer_usage SET turns = MAX(0, turns - 1) WHERE share_id = ? AND day = ?').run(shareId, today());
|
|
644
|
+
this._changed();
|
|
645
|
+
}
|
|
646
|
+
if (recentKey) this._rememberTurn(recentKey, { same, error: { message: e.message, code: e.code, partial: e.partial } });
|
|
647
|
+
throw e;
|
|
648
|
+
}
|
|
649
|
+
finally { this._turns.delete(turnKey); }
|
|
650
|
+
})();
|
|
651
|
+
return turn.result;
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
/** A resend of a turn still running here (its link dropped): the new link gets the text so far, then the same result. */
|
|
655
|
+
_reattach(turn, emit) {
|
|
656
|
+
turn.emit = redacting(emit);
|
|
657
|
+
const run = turn.runId && this._runs.get(turn.runId);
|
|
658
|
+
if (run?.text) turn.emit?.('delta', run.text); // deltas are cumulative
|
|
659
|
+
if (run?.waiting) turn.emit?.('status', { waiting: 'approval', what: run.waiting.what, expiresAtMs: run.waiting.expiresAtMs });
|
|
660
|
+
return turn.result;
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
_recentTurn(key) {
|
|
664
|
+
const e = this._finished.get(key);
|
|
665
|
+
return e && Date.now() - e.at < RECENT_TURN_MS ? e : null;
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
/** Keep a finished turn's result (already redacted) for a while, oldest dropped first. */
|
|
669
|
+
_rememberTurn(key, entry) {
|
|
670
|
+
this._finished.delete(key);
|
|
671
|
+
this._finished.set(key, { ...entry, at: Date.now() });
|
|
672
|
+
for (const [k, e] of this._finished) {
|
|
673
|
+
if (this._finished.size <= RECENT_TURNS_MAX && Date.now() - e.at < RECENT_TURN_MS) break;
|
|
674
|
+
this._finished.delete(k);
|
|
619
675
|
}
|
|
620
|
-
finally { this._turns.delete(turnKey); }
|
|
621
676
|
}
|
|
622
677
|
|
|
623
678
|
async _runGuestTurn(shareId, grant, agent, roomId, p, emit, turn) {
|
|
@@ -636,7 +691,11 @@ export class SharingManager {
|
|
|
636
691
|
const mcpServers = Object.fromEntries(Object.keys(cfg?.parsed?.mcp?.servers || {}).sort().map(n => [n, false]));
|
|
637
692
|
const toolOverrides = { webSearch: false, ...(Object.keys(mcpServers).length ? { mcpServers } : {}) };
|
|
638
693
|
const sessionKey = await this._guestSession(shareId, roomId, agent.id, { name, roomTitle: String(p.roomTitle || 'team chat').slice(0, 80), permissionMode, toolOverrides });
|
|
639
|
-
|
|
694
|
+
// Made from the requester's turn id when there is one: a resend (after a dropped link, or after this connector
|
|
695
|
+
// restarted) reuses the idempotency key, so the gateway answers with the first run instead of starting another.
|
|
696
|
+
const runId = turn.clientTurnId
|
|
697
|
+
? `peer-${crypto.createHash('sha256').update(`${shareId}|${turn.clientTurnId}`).digest('hex').slice(0, 32)}`
|
|
698
|
+
: `peer-${crypto.randomUUID()}`;
|
|
640
699
|
const done = new Promise(resolve => {
|
|
641
700
|
const timer = setTimeout(() => { this._runs.delete(runId); resolve({ state: 'error', errorMessage: 'timed out' }); }, TURN_TIMEOUT_MS + 30_000);
|
|
642
701
|
timer.unref?.();
|
|
@@ -646,13 +705,34 @@ export class SharingManager {
|
|
|
646
705
|
try {
|
|
647
706
|
if (!this._grant(shareId)) throw Object.assign(new Error('Sharing has ended'), { code: 'revoked' }); // revoked while setting up
|
|
648
707
|
if (turn.aborted) return { state: 'aborted', text: '' }; // stopped while setting up
|
|
649
|
-
|
|
650
|
-
|
|
708
|
+
// A resend this connector has no record of (it restarted): if the turn's input is already in the session, the
|
|
709
|
+
// transcript decides, not the ack. 2026.9.7 forgets its chat.send dedupe on a gateway restart and would start a
|
|
710
|
+
// run with no new input (a reply to nothing). Only this connector reloaded, so its run is still going: the send
|
|
711
|
+
// below is answered "in_flight" and the run's events finish the turn.
|
|
712
|
+
const sent = defangLocalPaths(`${p.inOwnerRoom ? ACTING_FOR_NOTE(name, p.byPerson) : GUEST_NOTE(name)}\n\n${p.message}`);
|
|
713
|
+
if (turn.clientTurnId) {
|
|
714
|
+
const earlier = await this._replyTo(sessionKey, runId);
|
|
715
|
+
if (earlier && earlier.input.trim() !== sent.trim()) throw Object.assign(new Error('That turn was already sent with another message'), { code: 'bad_request' });
|
|
716
|
+
const s = earlier && await this.request('sessions.describe', { key: sessionKey }, 5000).then(r => r?.session || null, () => null);
|
|
717
|
+
const ownRunGoing = s?.hasActiveRun !== false && (!Array.isArray(s?.activeRunIds) || s.activeRunIds.includes(runId));
|
|
718
|
+
if (earlier && !ownRunGoing) return this._afterRestart(sessionKey, runId, turn);
|
|
719
|
+
}
|
|
720
|
+
const ack = await this.request('chat.send', {
|
|
721
|
+
sessionKey, message: sent, deliver: false, idempotencyKey: runId,
|
|
651
722
|
timeoutMs: TURN_TIMEOUT_MS, suppressCommandInterpretation: true,
|
|
652
723
|
expectedPermissionMode: permissionMode, expectedToolOverrides: toolOverrides,
|
|
653
|
-
}, 30_000)
|
|
724
|
+
}, 30_000).catch(e => {
|
|
725
|
+
// The same key with another message (2026.11.5+): the requester has to resend the identical one.
|
|
726
|
+
if (e?.details?.reason === 'chat-request-conflict') throw Object.assign(new Error('That turn was already sent with another message'), { code: 'bad_request' });
|
|
727
|
+
throw e;
|
|
728
|
+
});
|
|
729
|
+
// The session the run started in: a later Stop is fenced to it.
|
|
730
|
+
this.chatAbort.sessionIdOf(sessionKey).then(id => { turn.sessionId = id; });
|
|
654
731
|
// Stopped or revoked while the send was on its way (the abort may have reached the gateway before the run).
|
|
655
732
|
if (turn.aborted || !this._grant(shareId)) this._abortTurn(turn);
|
|
733
|
+
// The gateway already has this input and nothing here tracked it (a resend after a restart): its reply is, or
|
|
734
|
+
// will be, in the session. "in_flight" means it is still going: its events arrive as for a new run.
|
|
735
|
+
if (ack?.status === 'ok') return this._afterRestart(sessionKey, runId, turn);
|
|
656
736
|
const r = await done;
|
|
657
737
|
if (r.state === 'final') return { state: 'final', text: r.message ? messageText(r.message) : await this._lastReply(sessionKey) };
|
|
658
738
|
if (r.state === 'aborted') return { state: 'aborted', text: r.text || '' };
|
|
@@ -703,12 +783,66 @@ export class SharingManager {
|
|
|
703
783
|
return key;
|
|
704
784
|
}
|
|
705
785
|
|
|
786
|
+
/** The input sent under `runId` and the reply to it, if that input is in the session: { input, text } (text '' when none), else null. */
|
|
787
|
+
async _replyTo(sessionKey, runId) {
|
|
788
|
+
const h = await this.request('chat.history', { sessionKey, limit: 200 }, 30_000).catch(() => null);
|
|
789
|
+
const msgs = h?.messages || [];
|
|
790
|
+
const at = msgs.findIndex(m => m.role === 'user' && m.__openclaw?.idempotencyKey === `${runId}:user`);
|
|
791
|
+
if (at < 0) return null;
|
|
792
|
+
let reply = null;
|
|
793
|
+
for (const m of msgs.slice(at + 1)) {
|
|
794
|
+
if (m.role === 'user' && m.provenance?.kind === 'internal_system') continue; // the gateway's own "restarted, continue" turn
|
|
795
|
+
if (m.role === 'user') break;
|
|
796
|
+
if (m.role === 'assistant' && messageText(m).trim()) reply = m;
|
|
797
|
+
}
|
|
798
|
+
return { input: await this._fullText(sessionKey, msgs[at]), text: reply ? await this._fullText(sessionKey, reply) : '' };
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
/**
|
|
802
|
+
* A turn whose input is in the session but which no run here is following (this connector or its gateway restarted):
|
|
803
|
+
* wait for whatever runs there to finish (on 2026.11.x the gateway resumes a run its restart cut off, under another
|
|
804
|
+
* run id, a few seconds after it's back), then answer with the reply. Stop and "Stop sharing" abort that run.
|
|
805
|
+
*/
|
|
806
|
+
async _afterRestart(sessionKey, runId, turn) {
|
|
807
|
+
const started = Date.now();
|
|
808
|
+
const end = started + TURN_TIMEOUT_MS;
|
|
809
|
+
let ran = false;
|
|
810
|
+
for (;;) {
|
|
811
|
+
const s = await this.request('sessions.describe', { key: sessionKey }, 5000).then(r => r?.session || null, () => null);
|
|
812
|
+
if (s?.hasActiveRun) {
|
|
813
|
+
ran = true;
|
|
814
|
+
if (turn.aborted) {
|
|
815
|
+
const ids = Array.isArray(s.activeRunIds) ? s.activeRunIds : [];
|
|
816
|
+
if (ids.length) for (const id of ids) this.chatAbort.abort({ sessionKey, runId: id, sessionId: s.sessionId }).catch(() => {});
|
|
817
|
+
else this.request('chat.abort', { sessionKey }).catch(() => {});
|
|
818
|
+
return { state: 'aborted', text: '' };
|
|
819
|
+
}
|
|
820
|
+
} else {
|
|
821
|
+
if (turn.aborted) return { state: 'aborted', text: '' };
|
|
822
|
+
const r = await this._replyTo(sessionKey, runId);
|
|
823
|
+
if (r?.text) return { state: 'final', text: r.text };
|
|
824
|
+
if (ran || Date.now() - started >= this.recovery.waitMs) break;
|
|
825
|
+
}
|
|
826
|
+
if (Date.now() >= end) break;
|
|
827
|
+
await new Promise(r => setTimeout(r, this.recovery.pollMs));
|
|
828
|
+
}
|
|
829
|
+
throw Object.assign(new Error('The reply was interrupted'), { code: 'run_failed', partial: '' });
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
/** A history message's whole text: chat.history caps long ones (`__openclaw.truncated`, ~8 KB); chat.message.get doesn't. */
|
|
833
|
+
async _fullText(sessionKey, m) {
|
|
834
|
+
const text = messageText(m);
|
|
835
|
+
if (!m?.__openclaw?.truncated || !m.__openclaw.id) return text;
|
|
836
|
+
const r = await this.request('chat.message.get', { sessionKey, messageId: m.__openclaw.id, maxChars: 2_000_000 }, 30_000).catch(() => null);
|
|
837
|
+
return (r?.ok && r.message && messageText(r.message)) || text;
|
|
838
|
+
}
|
|
839
|
+
|
|
706
840
|
async _lastReply(sessionKey) {
|
|
707
841
|
const h = await this.request('chat.history', { sessionKey, limit: 20 }, 30_000).catch(() => null);
|
|
708
842
|
const msgs = h?.messages || [];
|
|
709
843
|
for (let i = msgs.length - 1; i >= 0; i--) {
|
|
710
844
|
if (msgs[i].role === 'user') return '';
|
|
711
|
-
if (msgs[i].role === 'assistant'
|
|
845
|
+
if (msgs[i].role === 'assistant' && messageText(msgs[i]).trim()) return this._fullText(sessionKey, msgs[i]);
|
|
712
846
|
}
|
|
713
847
|
return '';
|
|
714
848
|
}
|
|
@@ -830,18 +964,36 @@ export class SharingManager {
|
|
|
830
964
|
return p;
|
|
831
965
|
}
|
|
832
966
|
|
|
833
|
-
/**
|
|
834
|
-
|
|
967
|
+
/**
|
|
968
|
+
* Run a turn on a shared agent. Returns { state, text }; throws with `.partial` on failure.
|
|
969
|
+
* A link that drops mid-turn is dialled again and the identical request sent again (at most twice, within the
|
|
970
|
+
* turn's timeout): the owner attaches it to the run still going there, or answers from the finished one, so the
|
|
971
|
+
* turn never runs twice. `stopped()`: the room was stopped, so it isn't sent again.
|
|
972
|
+
*/
|
|
973
|
+
async turn(agentId, { turnId, roomId, roomTitle, message }, { onDelta, onStatus, stopped = () => false } = {}) {
|
|
835
974
|
const id = SharingManager.parseRemoteId(agentId);
|
|
836
975
|
if (!id) throw new Error('not a shared agent');
|
|
837
|
-
const
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
976
|
+
const params = { turnId, agentId: id.remoteId, roomId, roomTitle, message };
|
|
977
|
+
const onEvent = (event, data) => {
|
|
978
|
+
if (event === 'delta' && typeof data === 'string') onDelta?.(data);
|
|
979
|
+
else if (event === 'status' && data && typeof data === 'object') onStatus?.(data);
|
|
980
|
+
};
|
|
981
|
+
const deadline = Date.now() + TURN_TIMEOUT_MS + 60_000;
|
|
982
|
+
for (let resend = 0; ; resend++) {
|
|
983
|
+
try {
|
|
984
|
+
const link = await this._link(id.shareId);
|
|
985
|
+
return await link.request('turn', params, { onEvent, timeoutMs: deadline - Date.now() });
|
|
986
|
+
} catch (e) {
|
|
987
|
+
// Only a dropped link (or, while resending, the link not back yet): local errors, without a code. Never
|
|
988
|
+
// something the other side answered (refused, cap, revoked...): those always carry one.
|
|
989
|
+
const dropped = !e.code && (e.message === 'peer link closed' || resend > 0);
|
|
990
|
+
const wait = this.resendBackoffMs[resend];
|
|
991
|
+
if (!dropped || !turnId || wait === undefined || stopped() || Date.now() + wait >= deadline) throw e;
|
|
992
|
+
this.log.info?.(`[sharing] turn ${turnId}: link to ${id.shareId} dropped, sending it again in ${wait / 1000} s`);
|
|
993
|
+
await new Promise(r => setTimeout(r, wait));
|
|
994
|
+
if (stopped()) throw e;
|
|
995
|
+
}
|
|
996
|
+
}
|
|
845
997
|
}
|
|
846
998
|
|
|
847
999
|
// ── Acting for someone else (team chats on this gateway) ──────────
|
|
@@ -42,9 +42,9 @@ function setup({ reply = p => `jarvis says: ${p.message.split('\n\n').pop()}`, c
|
|
|
42
42
|
return { ok: true };
|
|
43
43
|
};
|
|
44
44
|
const ownerDb = new Database(':memory:'), reqDb = new Database(':memory:');
|
|
45
|
-
owner = new SharingManager({ getDb: () => ownerDb, request: ownerRequest, key: kOwner, gatewayId: () => 'gwK', signal: m => ownerSignals.push(m), openPeer: async () => { throw new Error('owner never dials'); }, log: quiet });
|
|
45
|
+
owner = new SharingManager({ getDb: () => ownerDb, request: ownerRequest, recovery: { waitMs: 60, pollMs: 5 }, key: kOwner, gatewayId: () => 'gwK', signal: m => ownerSignals.push(m), openPeer: async () => { throw new Error('owner never dials'); }, log: quiet });
|
|
46
46
|
const req = new SharingManager({
|
|
47
|
-
getDb: () => reqDb, request: async () => ({}), key: kReq, gatewayId: () => 'gwH', signal: m => reqSignals.push(m), log: quiet,
|
|
47
|
+
getDb: () => reqDb, request: async () => ({}), key: kReq, gatewayId: () => 'gwH', signal: m => reqSignals.push(m), log: quiet, resendBackoffMs: [5, 10],
|
|
48
48
|
openPeer: async shareId => {
|
|
49
49
|
const [a, b] = pair();
|
|
50
50
|
owner.servePeer({ dc: b, dtls: { local: 'FK', remote: 'FH' }, shareId, requesterGatewayId: 'gwH' });
|
|
@@ -679,6 +679,7 @@ test('a guest can\'t reuse a turn id: the limit counts turns made here, and stop
|
|
|
679
679
|
s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }], dailyCap: 20 });
|
|
680
680
|
s.activate();
|
|
681
681
|
const results = [];
|
|
682
|
+
// The same turn id for other rooms isn't a resend: refused, and it starts no run.
|
|
682
683
|
for (let i = 0; i < 4; i++) results.push(s.req.turn('peer:sh1:jarvis', { turnId: 'same', roomId: `r${i}`, message: 'x' }).catch(e => e));
|
|
683
684
|
results.push(s.req.turn('peer:sh1:jarvis', { turnId: 'other', roomId: 'r9', message: 'x' }).catch(e => e));
|
|
684
685
|
await wait(30);
|
|
@@ -692,7 +693,7 @@ test('a guest can\'t reuse a turn id: the limit counts turns made here, and stop
|
|
|
692
693
|
const aborted = new Set(s.ownerCalls.filter(c => c.method === 'chat.abort').map(c => c.params.runId));
|
|
693
694
|
for (const runId of sends()) assert.ok(aborted.has(runId), `run ${runId} kept going after "Stop sharing"`);
|
|
694
695
|
const done = await Promise.all(results);
|
|
695
|
-
assert.
|
|
696
|
+
assert.equal(done.filter(r => r instanceof Error && r.code === 'bad_request').length, 3, 'a reused turn id is refused');
|
|
696
697
|
});
|
|
697
698
|
|
|
698
699
|
test('stop sharing while a guest turn is being sent: it is aborted once it has started', async () => {
|
|
@@ -780,3 +781,282 @@ test('peer requests are rate limited per contact (turns, and everything else), w
|
|
|
780
781
|
assert.equal(other.filter(r => r === 'ok').length, 120);
|
|
781
782
|
assert.ok(other.slice(120).every(r => r === 'rate_limited'));
|
|
782
783
|
});
|
|
784
|
+
|
|
785
|
+
test('a link that drops mid-turn: the turn is sent again and joins the run still going (one run, counted once)', async () => {
|
|
786
|
+
const s = setup({ reply: () => null });
|
|
787
|
+
s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }], dailyCap: 10 });
|
|
788
|
+
s.activate();
|
|
789
|
+
const deltas = [];
|
|
790
|
+
const run = s.req.turn('peer:sh1:jarvis', { turnId: 'team-1', roomId: 'r', message: 'hi' }, { onDelta: t => deltas.push(t) });
|
|
791
|
+
await wait(20);
|
|
792
|
+
[...s.owner._served][0].close(); // the DataChannel drops
|
|
793
|
+
await wait(60);
|
|
794
|
+
const sends = s.ownerCalls.filter(c => c.method === 'chat.send');
|
|
795
|
+
assert.equal(sends.length, 1, 'the resend started no second run');
|
|
796
|
+
assert.equal(s.owner._served.size, 1, 'the requester dialled again');
|
|
797
|
+
assert.deepEqual(deltas, ['jar', 'jar'], 'the new link got the text so far');
|
|
798
|
+
s.owner.onGatewayEvent({ event: 'chat', payload: { runId: sends[0].params.idempotencyKey, state: 'final', message: { content: [{ type: 'text', text: 'done' }] } } });
|
|
799
|
+
assert.deepEqual(await run, { state: 'final', text: 'done' });
|
|
800
|
+
assert.equal(s.owner._usage('sh1'), 1, 'counted once');
|
|
801
|
+
});
|
|
802
|
+
|
|
803
|
+
test('a resend of a finished turn gets its result, with no new run; another message under that turn id is refused', async () => {
|
|
804
|
+
const s = setup();
|
|
805
|
+
s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }], dailyCap: 10 });
|
|
806
|
+
s.activate();
|
|
807
|
+
const turn = { turnId: 'team-2', roomId: 'r', message: 'hi' };
|
|
808
|
+
const first = await s.req.turn('peer:sh1:jarvis', turn);
|
|
809
|
+
assert.deepEqual(await s.req.turn('peer:sh1:jarvis', turn), first);
|
|
810
|
+
assert.equal(s.ownerCalls.filter(c => c.method === 'chat.send').length, 1);
|
|
811
|
+
assert.equal(s.owner._usage('sh1'), 1);
|
|
812
|
+
await assert.rejects(s.req.turn('peer:sh1:jarvis', { ...turn, message: 'something else' }), e => e.code === 'bad_request');
|
|
813
|
+
await assert.rejects(s.req.turn('peer:sh1:jarvis', { ...turn, roomId: 'other' }), e => e.code === 'bad_request');
|
|
814
|
+
});
|
|
815
|
+
|
|
816
|
+
test('another message under a running turn id is refused, and the run goes on', async () => {
|
|
817
|
+
const s = setup({ reply: () => null });
|
|
818
|
+
s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }] });
|
|
819
|
+
s.activate();
|
|
820
|
+
const run = s.req.turn('peer:sh1:jarvis', { turnId: 'team-3', roomId: 'r', message: 'hi' });
|
|
821
|
+
await wait(20);
|
|
822
|
+
await assert.rejects(s.req.turn('peer:sh1:jarvis', { turnId: 'team-3', roomId: 'r', message: 'changed' }), e => e.code === 'bad_request');
|
|
823
|
+
await s.req.abort('peer:sh1:jarvis', 'team-3');
|
|
824
|
+
assert.deepEqual(await run, { state: 'aborted', text: 'jar' });
|
|
825
|
+
});
|
|
826
|
+
|
|
827
|
+
test('the run id comes from the share and the turn id, so a resend after a restart reuses the idempotency key', async () => {
|
|
828
|
+
const s = setup();
|
|
829
|
+
s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }] });
|
|
830
|
+
s.activate();
|
|
831
|
+
await s.req.turn('peer:sh1:jarvis', { turnId: 'team-4', roomId: 'r', message: 'hi' });
|
|
832
|
+
await s.req.turn('peer:sh1:jarvis', { roomId: 'r', message: 'no turn id' });
|
|
833
|
+
const keys = s.ownerCalls.filter(c => c.method === 'chat.send').map(c => c.params.idempotencyKey);
|
|
834
|
+
const crypto = await import('node:crypto');
|
|
835
|
+
assert.equal(keys[0], `peer-${crypto.createHash('sha256').update('sh1|team-4').digest('hex').slice(0, 32)}`);
|
|
836
|
+
assert.match(keys[1], /^peer-[0-9a-f-]{36}$/, 'without a turn id it stays random');
|
|
837
|
+
});
|
|
838
|
+
|
|
839
|
+
test('the gateway says the key was used for other input (chat-request-conflict): bad_request', async () => {
|
|
840
|
+
const s = setup();
|
|
841
|
+
s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }], dailyCap: 10 });
|
|
842
|
+
s.activate();
|
|
843
|
+
const request = s.owner.request;
|
|
844
|
+
s.owner.request = async (method, params) => {
|
|
845
|
+
if (method === 'chat.send') throw Object.assign(new Error('This message ID was already used for different input.'), { gatewayCode: 'INVALID_REQUEST', details: { reason: 'chat-request-conflict' } });
|
|
846
|
+
return request(method, params);
|
|
847
|
+
};
|
|
848
|
+
await assert.rejects(s.req.turn('peer:sh1:jarvis', { turnId: 'team-5', roomId: 'r', message: 'hi' }), e => e.code === 'bad_request');
|
|
849
|
+
assert.equal(s.owner._usage('sh1'), 0, 'a refused turn is not counted');
|
|
850
|
+
});
|
|
851
|
+
|
|
852
|
+
test('after a restart the gateway answers the resend with "ok" (that run already ran): its reply is read from the session', async () => {
|
|
853
|
+
const s = setup();
|
|
854
|
+
let input = null; // in the session once sent
|
|
855
|
+
const sentText = () => input;
|
|
856
|
+
s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }] });
|
|
857
|
+
s.activate();
|
|
858
|
+
const request = s.owner.request;
|
|
859
|
+
s.owner.request = async (method, params) => {
|
|
860
|
+
if (method === 'chat.send') { s.ownerCalls.push({ method, params }); input = params.message; return { runId: params.idempotencyKey, status: 'ok' }; }
|
|
861
|
+
if (method === 'chat.history') return { messages: input === null ? [] : [{ role: 'user', content: sentText(params), __openclaw: { idempotencyKey: `${[...s.owner._turns.values()][0]?.runId}:user` } }, { role: 'assistant', content: [{ type: 'text', text: 'the earlier reply' }] }] };
|
|
862
|
+
return request(method, params);
|
|
863
|
+
};
|
|
864
|
+
assert.deepEqual(await s.req.turn('peer:sh1:jarvis', { turnId: 'team-6', roomId: 'r', message: 'hi' }), { state: 'final', text: 'the earlier reply' });
|
|
865
|
+
assert.equal(s.owner._runs.size, 0);
|
|
866
|
+
});
|
|
867
|
+
|
|
868
|
+
test('a room stopped while its link was down: the turn is not sent again', async () => {
|
|
869
|
+
const s = setup({ reply: () => null });
|
|
870
|
+
s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }] });
|
|
871
|
+
s.activate();
|
|
872
|
+
let stopped = false;
|
|
873
|
+
const run = s.req.turn('peer:sh1:jarvis', { turnId: 'team-7', roomId: 'r', message: 'hi' }, { stopped: () => stopped }).catch(e => e);
|
|
874
|
+
await wait(20);
|
|
875
|
+
stopped = true;
|
|
876
|
+
[...s.owner._served][0].close();
|
|
877
|
+
assert.match((await run).message, /peer link closed/);
|
|
878
|
+
await wait(30);
|
|
879
|
+
assert.equal(s.owner._served.size, 0, 'no new link for it');
|
|
880
|
+
for (const t of s.owner._turns.values()) s.owner._abortTurn(t);
|
|
881
|
+
});
|
|
882
|
+
|
|
883
|
+
test('Stop after a reconnect still finds the turn, and is fenced to the session the run started in', async () => {
|
|
884
|
+
const s = setup({ reply: () => null });
|
|
885
|
+
s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }] });
|
|
886
|
+
s.activate();
|
|
887
|
+
const request = s.owner.request;
|
|
888
|
+
s.owner.request = async (method, params) => (method === 'sessions.describe' ? { session: { key: params.key, sessionId: 'phys-1' } } : request(method, params));
|
|
889
|
+
const run = s.req.turn('peer:sh1:jarvis', { turnId: 'team-8', roomId: 'r', message: 'hi' });
|
|
890
|
+
await wait(20);
|
|
891
|
+
[...s.owner._served][0].close();
|
|
892
|
+
await wait(60);
|
|
893
|
+
await s.req.abort('peer:sh1:jarvis', 'team-8');
|
|
894
|
+
assert.deepEqual(await run, { state: 'aborted', text: 'jar' });
|
|
895
|
+
const abort = s.ownerCalls.find(c => c.method === 'chat.abort').params;
|
|
896
|
+
assert.equal(abort.sessionId, 'phys-1');
|
|
897
|
+
assert.equal(abort.runId, s.ownerCalls.find(c => c.method === 'chat.send').params.idempotencyKey);
|
|
898
|
+
});
|
|
899
|
+
|
|
900
|
+
/** The owner's gateway after a restart (2026.9.7): it forgot its dedupe, the session still has the turn's input. */
|
|
901
|
+
async function restartedOwner(s, { reply, active = false, input = 'hi' }) {
|
|
902
|
+
// What the owner sends for that message (the guest note + the message), from a turn in another room.
|
|
903
|
+
await s.req.turn('peer:sh1:jarvis', { turnId: 'warm-up', roomId: 'r0', message: input });
|
|
904
|
+
const sent = s.ownerCalls.filter(c => c.method === 'chat.send').at(-1).params.message;
|
|
905
|
+
s.ownerCalls.length = 0;
|
|
906
|
+
const request = s.owner.request;
|
|
907
|
+
s.owner.request = async (method, params) => {
|
|
908
|
+
if (method === 'chat.history') {
|
|
909
|
+
const key = s.owner._turns.size && [...s.owner._turns.values()][0].runId;
|
|
910
|
+
return { messages: [
|
|
911
|
+
{ role: 'user', content: 'an older turn', __openclaw: { idempotencyKey: 'peer-old:user' } },
|
|
912
|
+
{ role: 'assistant', content: [{ type: 'text', text: 'older reply' }] },
|
|
913
|
+
{ role: 'user', content: sent, __openclaw: { idempotencyKey: `${key}:user` } },
|
|
914
|
+
...(reply ? [{ role: 'assistant', content: [{ type: 'text', text: reply }] }] : []),
|
|
915
|
+
] };
|
|
916
|
+
}
|
|
917
|
+
if (method === 'sessions.describe') return { session: { key: params.key, hasActiveRun: active } };
|
|
918
|
+
return request(method, params);
|
|
919
|
+
};
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
test('a resend after the owner restarted: the turn already ran there, so its reply is returned and nothing runs again', async () => {
|
|
923
|
+
const s = setup();
|
|
924
|
+
s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }], dailyCap: 10 });
|
|
925
|
+
s.activate();
|
|
926
|
+
await restartedOwner(s, { reply: 'the reply it gave' });
|
|
927
|
+
assert.deepEqual(await s.req.turn('peer:sh1:jarvis', { turnId: 'team-9', roomId: 'r', message: 'hi' }), { state: 'final', text: 'the reply it gave' });
|
|
928
|
+
assert.equal(s.ownerCalls.filter(c => c.method === 'chat.send').length, 0, 'no reply to nothing');
|
|
929
|
+
});
|
|
930
|
+
|
|
931
|
+
test('a resend after only the connector reloaded: the run is still going, so the send joins it and waits for it', async () => {
|
|
932
|
+
const s = setup({ reply: () => 'finished' });
|
|
933
|
+
s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }] });
|
|
934
|
+
s.activate();
|
|
935
|
+
await restartedOwner(s, { reply: null, active: true });
|
|
936
|
+
assert.deepEqual(await s.req.turn('peer:sh1:jarvis', { turnId: 'team-10', roomId: 'r', message: 'hi' }), { state: 'final', text: 'finished' });
|
|
937
|
+
assert.equal(s.ownerCalls.filter(c => c.method === 'chat.send').length, 1);
|
|
938
|
+
});
|
|
939
|
+
|
|
940
|
+
test('a resend of a turn its restart cut off (input there, no reply, nothing running): failed, not counted', async () => {
|
|
941
|
+
const s = setup();
|
|
942
|
+
s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }], dailyCap: 10 });
|
|
943
|
+
s.activate();
|
|
944
|
+
await restartedOwner(s, { reply: null });
|
|
945
|
+
s.owner._db().prepare('DELETE FROM peer_usage').run();
|
|
946
|
+
await assert.rejects(s.req.turn('peer:sh1:jarvis', { turnId: 'team-11', roomId: 'r', message: 'hi' }), e => e.code === 'run_failed' && /interrupted/.test(e.message));
|
|
947
|
+
assert.equal(s.ownerCalls.filter(c => c.method === 'chat.send').length, 0);
|
|
948
|
+
assert.equal(s.owner._usage('sh1'), 0);
|
|
949
|
+
});
|
|
950
|
+
|
|
951
|
+
test('a resend after the owner restarted with another message under that turn id: refused, nothing runs', async () => {
|
|
952
|
+
const s = setup();
|
|
953
|
+
s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }] });
|
|
954
|
+
s.activate();
|
|
955
|
+
await restartedOwner(s, { reply: 'the reply it gave' });
|
|
956
|
+
await assert.rejects(s.req.turn('peer:sh1:jarvis', { turnId: 'team-12', roomId: 'r', message: 'something else' }), e => e.code === 'bad_request');
|
|
957
|
+
assert.equal(s.ownerCalls.filter(c => c.method === 'chat.send').length, 0);
|
|
958
|
+
});
|
|
959
|
+
|
|
960
|
+
test('history caps long messages: the input check and the reply read the whole message (chat.message.get)', async () => {
|
|
961
|
+
const s = setup();
|
|
962
|
+
s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }] });
|
|
963
|
+
s.activate();
|
|
964
|
+
const long = 'x'.repeat(9000);
|
|
965
|
+
await s.req.turn('peer:sh1:jarvis', { turnId: 'warm-up', roomId: 'r0', message: long });
|
|
966
|
+
const sent = s.ownerCalls.filter(c => c.method === 'chat.send').at(-1).params.message;
|
|
967
|
+
s.ownerCalls.length = 0;
|
|
968
|
+
const full = { u1: sent, a1: `${'y'.repeat(9000)} the end` };
|
|
969
|
+
const cut = t => [{ type: 'text', text: `${t.slice(0, 8000)}\n...(truncated)...` }];
|
|
970
|
+
const request = s.owner.request;
|
|
971
|
+
s.owner.request = async (method, params) => {
|
|
972
|
+
if (method === 'chat.history') {
|
|
973
|
+
const key = [...s.owner._turns.values()][0].runId;
|
|
974
|
+
return { messages: [
|
|
975
|
+
{ role: 'user', content: cut(full.u1), __openclaw: { id: 'u1', idempotencyKey: `${key}:user`, truncated: true } },
|
|
976
|
+
{ role: 'assistant', content: cut(full.a1), __openclaw: { id: 'a1', truncated: true } },
|
|
977
|
+
] };
|
|
978
|
+
}
|
|
979
|
+
if (method === 'chat.message.get') return { ok: true, message: { role: 'x', content: [{ type: 'text', text: full[params.messageId] }] } };
|
|
980
|
+
if (method === 'sessions.describe') return { session: { key: params.key, hasActiveRun: false } };
|
|
981
|
+
return request(method, params);
|
|
982
|
+
};
|
|
983
|
+
const r = await s.req.turn('peer:sh1:jarvis', { turnId: 'team-13', roomId: 'r', message: long });
|
|
984
|
+
assert.equal(r.text, full.a1, 'the whole reply, not the capped one');
|
|
985
|
+
assert.equal(s.ownerCalls.filter(c => c.method === 'chat.send').length, 0);
|
|
986
|
+
});
|
|
987
|
+
|
|
988
|
+
test('a resend of a running turn rejoins it even when the share is at its cap or busy; its catch-up text is redacted', async () => {
|
|
989
|
+
const s = setup({ reply: () => null });
|
|
990
|
+
s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }], dailyCap: 2 });
|
|
991
|
+
s.activate();
|
|
992
|
+
const deltas = [];
|
|
993
|
+
const a = s.req.turn('peer:sh1:jarvis', { turnId: 'a', roomId: 'r1', message: 'x' }, { onDelta: t => deltas.push(t) });
|
|
994
|
+
const b = s.req.turn('peer:sh1:jarvis', { turnId: 'b', roomId: 'r2', message: 'x' }).catch(e => e);
|
|
995
|
+
await wait(20);
|
|
996
|
+
const runA = s.ownerCalls.find(c => c.method === 'chat.send' && /^peer-/.test(c.params.idempotencyKey)).params.idempotencyKey;
|
|
997
|
+
s.owner.onGatewayEvent({ event: 'chat', payload: { runId: runA, state: 'delta', message: { content: [{ type: 'text', text: 'key sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789' }] } } });
|
|
998
|
+
assert.equal(s.owner._usage('sh1'), 2, 'at the cap');
|
|
999
|
+
[...s.owner._served][0].close();
|
|
1000
|
+
await wait(60);
|
|
1001
|
+
assert.equal(s.ownerCalls.filter(c => c.method === 'chat.send').length, 2, 'no new run');
|
|
1002
|
+
assert.ok(deltas.length >= 2 && !/abcdefghijklmnop/.test(deltas.at(-1)), `catch-up delta redacted: ${deltas.at(-1)}`);
|
|
1003
|
+
await s.req.abort('peer:sh1:jarvis', 'a'); await s.req.abort('peer:sh1:jarvis', 'b');
|
|
1004
|
+
assert.equal((await a).state, 'aborted');
|
|
1005
|
+
await b;
|
|
1006
|
+
});
|
|
1007
|
+
|
|
1008
|
+
test('finished turns are kept at most 200, oldest dropped first', () => {
|
|
1009
|
+
const s = setup();
|
|
1010
|
+
for (let i = 0; i < 205; i++) s.owner._rememberTurn(`sh1|t${i}`, { same: 'x', result: { state: 'final', text: String(i) } });
|
|
1011
|
+
assert.equal(s.owner._finished.size, 200);
|
|
1012
|
+
assert.equal(s.owner._recentTurn('sh1|t4'), null);
|
|
1013
|
+
assert.equal(s.owner._recentTurn('sh1|t5').result.text, '5');
|
|
1014
|
+
});
|
|
1015
|
+
|
|
1016
|
+
/** The owner's gateway restarted mid-run and resumes it (2026.11.x): a run of its own starts after a few polls. */
|
|
1017
|
+
async function recoveringOwner(s, { finish = true } = {}) {
|
|
1018
|
+
await s.req.turn('peer:sh1:jarvis', { turnId: 'warm-up', roomId: 'r0', message: 'hi' });
|
|
1019
|
+
const sent = s.ownerCalls.filter(c => c.method === 'chat.send').at(-1).params.message;
|
|
1020
|
+
s.ownerCalls.length = 0;
|
|
1021
|
+
let polls = 0;
|
|
1022
|
+
const request = s.owner.request;
|
|
1023
|
+
s.owner.request = async (method, params) => {
|
|
1024
|
+
const key = [...s.owner._turns.values()][0]?.runId;
|
|
1025
|
+
if (method === 'sessions.describe') {
|
|
1026
|
+
s.ownerCalls.push({ method });
|
|
1027
|
+
polls++;
|
|
1028
|
+
const running = polls >= 3 && (!finish || polls < 6);
|
|
1029
|
+
return { session: { key: params.key, sessionId: 'phys-2', hasActiveRun: running, activeRunIds: running ? ['recovery-run'] : [] } };
|
|
1030
|
+
}
|
|
1031
|
+
if (method === 'chat.history') return { messages: [
|
|
1032
|
+
{ role: 'user', content: sent, __openclaw: { idempotencyKey: `${key}:user` } },
|
|
1033
|
+
...(polls >= 6 && finish ? [
|
|
1034
|
+
{ role: 'user', content: 'The Gateway restarted while you were working. Resume your work…', provenance: { kind: 'internal_system', sourceTool: 'restart' } },
|
|
1035
|
+
{ role: 'assistant', content: [{ type: 'text', text: 'the resumed reply' }] },
|
|
1036
|
+
] : []),
|
|
1037
|
+
] };
|
|
1038
|
+
return request(method, params);
|
|
1039
|
+
};
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
test("a turn the owner's gateway restart cut off: the gateway's own resumed run is waited for, and its reply returned", async () => {
|
|
1043
|
+
const s = setup();
|
|
1044
|
+
s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }] });
|
|
1045
|
+
s.activate();
|
|
1046
|
+
await recoveringOwner(s);
|
|
1047
|
+
assert.deepEqual(await s.req.turn('peer:sh1:jarvis', { turnId: 'team-14', roomId: 'r', message: 'hi' }), { state: 'final', text: 'the resumed reply' });
|
|
1048
|
+
assert.equal(s.ownerCalls.filter(c => c.method === 'chat.send').length, 0, 'not sent again');
|
|
1049
|
+
});
|
|
1050
|
+
|
|
1051
|
+
test('Stop while the gateway resumes a turn: the resumed run is aborted, fenced, and the turn ends aborted', async () => {
|
|
1052
|
+
const s = setup();
|
|
1053
|
+
s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }] });
|
|
1054
|
+
s.activate();
|
|
1055
|
+
await recoveringOwner(s, { finish: false });
|
|
1056
|
+
const run = s.req.turn('peer:sh1:jarvis', { turnId: 'team-15', roomId: 'r', message: 'hi' });
|
|
1057
|
+
await wait(40);
|
|
1058
|
+
await s.req.abort('peer:sh1:jarvis', 'team-15');
|
|
1059
|
+
assert.deepEqual(await run, { state: 'aborted', text: '' });
|
|
1060
|
+
const abort = s.ownerCalls.find(c => c.method === 'chat.abort' && c.params.runId === 'recovery-run')?.params;
|
|
1061
|
+
assert.ok(abort, 'the resumed run was aborted');
|
|
1062
|
+
});
|
package/server/team.js
CHANGED
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
|
|
16
16
|
import crypto from 'node:crypto';
|
|
17
17
|
import { defangLocalPaths, EMPTY_REPLY_ERROR } from './peer/sharing.js';
|
|
18
|
+
import { createChatAbort } from './util/chat-abort.js';
|
|
18
19
|
|
|
19
20
|
// An agent passes with our own token, a visible reply to the gateway. Not NO_REPLY: since 2026.10.1 a user-triggered
|
|
20
21
|
// turn must produce a reply, so NO_REPLY ends a claude-cli run with "CLI backend returned an empty response." (no
|
|
@@ -113,9 +114,10 @@ export class TeamCoordinator {
|
|
|
113
114
|
* @param {(method: string, params: object, timeoutMs?: number) => Promise<any>} opts.request gateway RPC
|
|
114
115
|
* @param {(data: string) => void} opts.broadcast frame to all browsers
|
|
115
116
|
*/
|
|
116
|
-
constructor({ store, request, broadcast, titler = null, remote = null, logger = console }) {
|
|
117
|
+
constructor({ store, request, chatAbort = null, broadcast, titler = null, remote = null, logger = console }) {
|
|
117
118
|
this.store = store;
|
|
118
119
|
this.request = request;
|
|
120
|
+
this.chatAbort = chatAbort || createChatAbort((m, p, t) => this.request(m, p, t)); // chat.abort, fenced to the run's session where supported (util/chat-abort.js)
|
|
119
121
|
this.broadcast = broadcast;
|
|
120
122
|
this.remote = remote; // other people's agents (peer/sharing.js): remoteAgents(), turn(), abort()
|
|
121
123
|
this.titler = titler; // main-model title fallback (controllers/title.js createTitler)
|
|
@@ -548,7 +550,7 @@ export class TeamCoordinator {
|
|
|
548
550
|
? this.remote?.abortLocalFor(agentId, r.actingFor, r.runId).catch(e => this.log.warn?.(`[team] abort: ${e.message}`))
|
|
549
551
|
: r.remote
|
|
550
552
|
? this.remote?.abort(agentId, r.runId).catch(e => this.log.warn?.(`[team] remote abort: ${e.message}`))
|
|
551
|
-
: this.
|
|
553
|
+
: this.chatAbort.abort({ sessionKey: r.workKey, runId: r.runId, sessionId: r.sessionId }).catch(e => this.log.warn?.(`[team] abort: ${e.message}`)))));
|
|
552
554
|
this._status(roomKey);
|
|
553
555
|
}
|
|
554
556
|
|
|
@@ -688,14 +690,17 @@ export class TeamCoordinator {
|
|
|
688
690
|
const runId = `team-${crypto.randomUUID()}`;
|
|
689
691
|
const live = this._live(roomKey);
|
|
690
692
|
const done = this._waitRun(runId);
|
|
691
|
-
|
|
693
|
+
const running = { workKey, runId, sessionId: null };
|
|
694
|
+
live.running.set(agentId, running);
|
|
692
695
|
this._status(roomKey);
|
|
693
696
|
let result;
|
|
694
697
|
try {
|
|
695
698
|
await this.request('chat.send', { sessionKey: workKey, message, deliver: false, idempotencyKey: runId }, 30_000);
|
|
699
|
+
// The session the run started in: a later Stop is fenced to it.
|
|
700
|
+
this.chatAbort.sessionIdOf(workKey).then(id => { running.sessionId = id; });
|
|
696
701
|
// Stop pressed while the send was on its way (or being retried while the gateway starts): its abort reached the
|
|
697
702
|
// gateway before the run existed and was a no-op (an unknown runId aborts nothing), so the run is stopped now.
|
|
698
|
-
if (stopped()) this.
|
|
703
|
+
if (stopped()) this.chatAbort.abort({ sessionKey: workKey, runId }).catch(e => this.log.warn?.(`[team] abort: ${e.message}`));
|
|
699
704
|
this._setSeen(roomKey, agentId, OWNER_LANE, fresh);
|
|
700
705
|
result = await done;
|
|
701
706
|
} finally {
|
|
@@ -751,6 +756,7 @@ export class TeamCoordinator {
|
|
|
751
756
|
this._setSeen(roomKey, agentId, REMOTE_LANE, fresh);
|
|
752
757
|
result = await this.remote.turn(agentId, { turnId: runId, roomId: roomKey, roomTitle: await this._roomTitle(roomKey), message: this._prompt(self, agents, fresh, mode, earlier) },
|
|
753
758
|
{
|
|
759
|
+
stopped, // a turn whose link dropped is sent again, unless the room was stopped meanwhile
|
|
754
760
|
onDelta: text => { partial = text; delta(text); },
|
|
755
761
|
onStatus: s => waiting(s?.waiting === 'approval' ? { owner, what: String(s.what || 'something').slice(0, 80), expiresAtMs: Number(s.expiresAtMs) || null } : null),
|
|
756
762
|
});
|
package/server/team.test.js
CHANGED
|
@@ -4,6 +4,7 @@ import { Database } from './bootstrap/native.js';
|
|
|
4
4
|
import { createTeamStore } from './store/team-store.js';
|
|
5
5
|
import { TeamCoordinator, parseMentions, namedIn, splitLabel, entryId } from './team.js';
|
|
6
6
|
import { SessionLens } from './session-lens.js';
|
|
7
|
+
import { createChatAbort } from './util/chat-abort.js';
|
|
7
8
|
|
|
8
9
|
const AGENTS = [{ id: 'main', identity: {} }, { id: 'dev', identity: { name: 'Dev' } }, { id: 'atlas', identity: { name: 'Atlas' } }];
|
|
9
10
|
|
|
@@ -1202,3 +1203,35 @@ test("other people's lines (and our agents' answers for them) are quoted to an a
|
|
|
1202
1203
|
assert.doesNotMatch(guest, /Only your owner's messages/);
|
|
1203
1204
|
assert.match(guest, /\(another person in this chat/);
|
|
1204
1205
|
});
|
|
1206
|
+
|
|
1207
|
+
test('stop is fenced to the session the run started in (where the gateway takes sessionId)', async () => {
|
|
1208
|
+
const pending = [];
|
|
1209
|
+
const h = harness(agent => new Promise(resolve => pending.push({ agent, resolve })));
|
|
1210
|
+
const request = h.team.request;
|
|
1211
|
+
h.team.chatAbort = createChatAbort(async (m, p) => (m === 'sessions.describe' ? { session: { key: p.key, sessionId: 'phys-1' } } : request(m, p)));
|
|
1212
|
+
const { roomKey } = await h.team.createRoom({ agentIds: ['dev', 'atlas'] });
|
|
1213
|
+
await h.team.send(roomKey, { text: '@dev one', userLabel: 'H' });
|
|
1214
|
+
for (let i = 0; i < 20; i++) await new Promise(r => setImmediate(r));
|
|
1215
|
+
await h.team.stop(roomKey);
|
|
1216
|
+
const abort = h.calls.find(c => c.method === 'chat.abort').params;
|
|
1217
|
+
assert.equal(abort.sessionId, 'phys-1');
|
|
1218
|
+
assert.equal(abort.runId, h.calls.find(c => c.method === 'chat.send').params.idempotencyKey);
|
|
1219
|
+
pending[0].resolve(null);
|
|
1220
|
+
await h.settle();
|
|
1221
|
+
});
|
|
1222
|
+
|
|
1223
|
+
test("a shared agent's turn gets the room's stopped(), so a dropped link isn't resent after Stop", async () => {
|
|
1224
|
+
let opts;
|
|
1225
|
+
const remote = {
|
|
1226
|
+
remoteAgents: () => [{ agentId: 'peer:sh1:jarvis', name: 'Jarvis · Kamil', ownerName: 'Kamil', shareId: 'sh1' }],
|
|
1227
|
+
ownerOf: () => 'gwK',
|
|
1228
|
+
turn: async (agentId, p, o) => { opts = o; return { state: 'final', text: 'hi' }; },
|
|
1229
|
+
abort: async () => {},
|
|
1230
|
+
};
|
|
1231
|
+
const h = harness(() => 'ok', { remote });
|
|
1232
|
+
const { roomKey } = await h.team.createRoom({ agentIds: ['dev', 'peer:sh1:jarvis'] });
|
|
1233
|
+
await h.team.send(roomKey, { text: '@Jarvis hello', userLabel: 'H' });
|
|
1234
|
+
await h.settle();
|
|
1235
|
+
assert.equal(typeof opts?.stopped, 'function');
|
|
1236
|
+
assert.equal(opts.stopped(), false);
|
|
1237
|
+
});
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// chat.abort with the physical-session fence (2026.11.5+): `sessionId` next to the exact `runId` means a Stop lands
|
|
2
|
+
// only on the session the run started in, never on the one that replaced it (owner hit /new, the session was made
|
|
3
|
+
// again). 2026.9.7's ChatAbortParams is a closed object and refuses the field, so it's sent only to a gateway that
|
|
4
|
+
// takes it: by the hello-ok version, or, when that's unknown, by trying once and falling back for this connection.
|
|
5
|
+
|
|
6
|
+
const FENCE_SINCE = [2026, 11, 5];
|
|
7
|
+
|
|
8
|
+
/** [year, month, patch] of "2026.11.6" / "2026.11.5-beta.3" / "v2026.11.6", or null. */
|
|
9
|
+
export function parseGatewayVersion(v) {
|
|
10
|
+
const m = /^v?(\d+)\.(\d+)\.(\d+)/.exec(String(v || ''));
|
|
11
|
+
return m ? m.slice(1, 4).map(Number) : null;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const atLeast = (v, min) => { for (let i = 0; i < 3; i++) if (v[i] !== min[i]) return v[i] > min[i]; return true; };
|
|
15
|
+
|
|
16
|
+
const NO_HELLO = {};
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* @param {(m: string, p: object, t?: number) => Promise<any>} request gateway RPC
|
|
20
|
+
* @param {{ hello?: () => object|null }} o the current connection's hello-ok payload (gateway.js), a new object per connect
|
|
21
|
+
*/
|
|
22
|
+
export function createChatAbort(request, { hello = () => null } = {}) {
|
|
23
|
+
let refusedBy = null; // the connection (hello) that refused sessionId
|
|
24
|
+
const conn = () => hello() || NO_HELLO;
|
|
25
|
+
const supported = () => {
|
|
26
|
+
if (refusedBy === conn()) return false;
|
|
27
|
+
const v = parseGatewayVersion(hello()?.server?.version);
|
|
28
|
+
return v ? atLeast(v, FENCE_SINCE) : true; // unknown: try it
|
|
29
|
+
};
|
|
30
|
+
return {
|
|
31
|
+
supported,
|
|
32
|
+
/** The session's physical id, to fence a later abort (null on a gateway without the fence, or on failure). */
|
|
33
|
+
async sessionIdOf(sessionKey) {
|
|
34
|
+
if (!supported()) return null;
|
|
35
|
+
const r = await request('sessions.describe', { key: sessionKey }, 5000).catch(() => null);
|
|
36
|
+
return typeof r?.session?.sessionId === 'string' && r.session.sessionId ? r.session.sessionId : null;
|
|
37
|
+
},
|
|
38
|
+
/** Abort one run; `sessionId` goes along when the gateway takes it. */
|
|
39
|
+
async abort({ sessionKey, runId, sessionId }) {
|
|
40
|
+
if (sessionId && runId && supported()) {
|
|
41
|
+
const c = conn();
|
|
42
|
+
try { return await request('chat.abort', { sessionKey, runId, sessionId }); }
|
|
43
|
+
catch (e) {
|
|
44
|
+
// Only the schema refusal (9.7: "invalid chat.abort params: at root: unexpected property 'sessionId'"); a fence
|
|
45
|
+
// that doesn't match must never be retried without it.
|
|
46
|
+
if (e?.gatewayCode !== 'INVALID_REQUEST' || !/unexpected property\W+sessionId/.test(e.message || '')) throw e;
|
|
47
|
+
refusedBy = c;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return request('chat.abort', { sessionKey, runId });
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { test } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { createChatAbort, parseGatewayVersion } from './chat-abort.js';
|
|
4
|
+
|
|
5
|
+
const hello = version => ({ type: 'hello-ok', server: { version, connId: 'c' } });
|
|
6
|
+
/** A gateway whose chat.abort takes sessionId or (9.7) refuses it as an unknown property. */
|
|
7
|
+
function gateway({ fence }) {
|
|
8
|
+
const calls = [];
|
|
9
|
+
const request = async (method, params) => {
|
|
10
|
+
calls.push({ method, params });
|
|
11
|
+
if (method === 'sessions.describe') return { session: { key: params.key, sessionId: 'phys-1' } };
|
|
12
|
+
if (method === 'chat.abort' && 'sessionId' in params && !fence) {
|
|
13
|
+
throw Object.assign(new Error("invalid chat.abort params: at root: unexpected property 'sessionId'"), { gatewayCode: 'INVALID_REQUEST' });
|
|
14
|
+
}
|
|
15
|
+
return { ok: true };
|
|
16
|
+
};
|
|
17
|
+
return { calls, request, aborts: () => calls.filter(c => c.method === 'chat.abort').map(c => c.params) };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
test('versions: release, beta, v-prefix; nothing else', () => {
|
|
21
|
+
assert.deepEqual(parseGatewayVersion('2026.11.6'), [2026, 11, 6]);
|
|
22
|
+
assert.deepEqual(parseGatewayVersion('2026.11.5-beta.3'), [2026, 11, 5]);
|
|
23
|
+
assert.deepEqual(parseGatewayVersion('v2026.9.7'), [2026, 9, 7]);
|
|
24
|
+
assert.equal(parseGatewayVersion('dev'), null);
|
|
25
|
+
assert.equal(parseGatewayVersion(undefined), null);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test('2026.11.5+: Stop carries the session fence', async () => {
|
|
29
|
+
const g = gateway({ fence: true });
|
|
30
|
+
const a = createChatAbort(g.request, { hello: () => hello('2026.11.6') });
|
|
31
|
+
const sessionId = await a.sessionIdOf('k');
|
|
32
|
+
assert.equal(sessionId, 'phys-1');
|
|
33
|
+
await a.abort({ sessionKey: 'k', runId: 'r1', sessionId });
|
|
34
|
+
assert.deepEqual(g.aborts(), [{ sessionKey: 'k', runId: 'r1', sessionId: 'phys-1' }]);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
test('2026.9.7 (known from hello-ok): no fence, and no describe call for it', async () => {
|
|
38
|
+
const g = gateway({ fence: false });
|
|
39
|
+
const a = createChatAbort(g.request, { hello: () => hello('2026.9.7') });
|
|
40
|
+
assert.equal(await a.sessionIdOf('k'), null);
|
|
41
|
+
await a.abort({ sessionKey: 'k', runId: 'r1', sessionId: 'phys-1' });
|
|
42
|
+
assert.deepEqual(g.calls, [{ method: 'chat.abort', params: { sessionKey: 'k', runId: 'r1' } }]);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test('version unknown: tried once; a gateway that refuses the field is asked again without it, and not again on that connection', async () => {
|
|
46
|
+
const g = gateway({ fence: false });
|
|
47
|
+
let h = { type: 'hello-ok' };
|
|
48
|
+
const a = createChatAbort(g.request, { hello: () => h });
|
|
49
|
+
await a.abort({ sessionKey: 'k', runId: 'r1', sessionId: 's' });
|
|
50
|
+
await a.abort({ sessionKey: 'k', runId: 'r2', sessionId: 's' });
|
|
51
|
+
assert.deepEqual(g.aborts(), [{ sessionKey: 'k', runId: 'r1', sessionId: 's' }, { sessionKey: 'k', runId: 'r1' }, { sessionKey: 'k', runId: 'r2' }]);
|
|
52
|
+
h = { type: 'hello-ok' }; // reconnected (maybe to an upgraded gateway): asked again
|
|
53
|
+
await a.abort({ sessionKey: 'k', runId: 'r3', sessionId: 's' });
|
|
54
|
+
assert.equal('sessionId' in g.aborts()[3], true);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test('any other refusal is not retried without the fence', async () => {
|
|
58
|
+
const request = async () => { throw Object.assign(new Error('sessionId requires an exact runId'), { gatewayCode: 'INVALID_REQUEST' }); };
|
|
59
|
+
const a = createChatAbort(request, { hello: () => hello('2026.11.6') });
|
|
60
|
+
await assert.rejects(a.abort({ sessionKey: 'k', runId: 'r', sessionId: 's' }), /exact runId/);
|
|
61
|
+
});
|