Skip to content

Commit f8b57d2

Browse files
adrien2pTrigger.dev RepoOps
authored andcommitted
refactor(sdk): keep each chat's session state in a session client
Mono-RevId: 6bccf66151831a06429f848f9ab81096eb309dba
1 parent 4d81a3f commit f8b57d2

3 files changed

Lines changed: 699 additions & 158 deletions

File tree

Lines changed: 218 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,218 @@
1+
import type { ChatSessionPersistedState } from "./chat.js";
2+
3+
/**
4+
* Internal state for tracking one chat session. Sessions are task-bound and the
5+
* server is the run manager — the transport only needs to know the session-scoped
6+
* PAT to address `.in/append`, `.out`, `end-and-continue`, etc.
7+
* @internal
8+
*/
9+
export type ChatSessionState = {
10+
/** Session-scoped PAT — `read:sessions:{chatId} + write:sessions:{chatId}`. */
11+
publicAccessToken: string;
12+
/** Last SSE event ID — used to resume the stream without replaying old events. */
13+
lastEventId?: string;
14+
/** `.in` append sequence used to filter stale turn boundaries after reconnecting. */
15+
activeInputSeq?: number;
16+
/**
17+
* Set when the stream was aborted mid-turn (stop). Skip chunks until the
18+
* stopped turn's trigger:turn-complete — survives a reconnect and a retry
19+
* send, so the stopped turn's tail never renders into the new turn.
20+
*/
21+
skipToTurnComplete?: boolean;
22+
/** `.in` seq of the turn the gate supersedes; only its boundary (or a later one) clears the gate. */
23+
supersededInputSeq?: number;
24+
/**
25+
* How many sends that write a user record to `.in` (a message, an action or a
26+
* steering message) have begun on this session, whatever became of them. Only ever
27+
* goes up. Not persisted: a stop still on its way for an earlier turn compares it to
28+
* the count it recorded to know a newer record may have landed since, and gives up.
29+
*/
30+
turnSends?: number;
31+
/** Whether the agent is currently streaming a response. Set on first chunk, cleared on turn-complete. */
32+
isStreaming?: boolean;
33+
/**
34+
* The resume cursor from before the current turn's first record. Persisted
35+
* in place of `lastEventId` until the turn ends, so a reload replays the
36+
* whole turn: a cursor from the middle of a turn resumes past chunks the
37+
* client needs to rebuild the message. Set when a turn is sent or its first
38+
* record arrives (which covers reconnects and sessions hydrated without
39+
* `isStreaming`), cleared wherever streaming ends.
40+
*/
41+
turnStart?: { lastEventId: string | undefined };
42+
/** Set once the outstanding turn is declared dead: a later stop must not gate the next turn on it. */
43+
outstandingTurnAbandoned?: boolean;
44+
/** Set once the session is closed. Terminal — sends and reconnects stop. */
45+
closed?: boolean;
46+
/** The reason the session was closed, when one was given. */
47+
closedReason?: string;
48+
};
49+
50+
/** A cursor from a loaded transcript, to seed into a session (`seedCursor`). */
51+
export type TranscriptCursor = { lastEventId: string; lastInEventId: string | undefined };
52+
53+
/**
54+
* What a view bound to a session reads. Replaced only where the transport reports
55+
* a session change, never per chunk: the cursor advances on every record, and a
56+
* snapshot that followed it would re-render every bound view once per chunk.
57+
*/
58+
export type ChatSessionSnapshot = {
59+
readonly chatId: string;
60+
readonly persisted: ChatSessionPersistedState;
61+
};
62+
63+
/**
64+
* The record a host saves for a session. A mid-turn session persists the turn's
65+
* start in place of its cursor, so a reload replays the whole turn.
66+
*/
67+
export function persistedStateOf(state: ChatSessionState): ChatSessionPersistedState {
68+
return {
69+
publicAccessToken: state.publicAccessToken,
70+
lastEventId: state.turnStart ? state.turnStart.lastEventId : state.lastEventId,
71+
activeInputSeq: state.activeInputSeq,
72+
isStreaming: state.isStreaming,
73+
closed: state.closed,
74+
closedReason: state.closedReason,
75+
};
76+
}
77+
78+
/**
79+
* Whether a loaded transcript's `.out` cursor becomes the session's. Only into
80+
* an empty cursor, and with a sent turn outstanding only when the transcript was
81+
* saved after that send was answered: its `.in` cursor is the highest `.in` seq
82+
* the agent had handled. One saved before ends at an earlier boundary, and the
83+
* records after it can hold an earlier reply still running ahead of the send (a
84+
* send that replaces it persists no cursor), which an agent that writes no turn
85+
* markers gives nothing to tell apart. The turn-start lookup places the turn
86+
* then. A transcript with no `.in` cursor can't say, and is taken as before.
87+
* Deliberately conservative: a send still queued holds that floor below its
88+
* seq, so a save whose `.out` cursor would already do is refused until the
89+
* agent takes the send, which costs the lookup, not correctness.
90+
*/
91+
function takesTranscriptCursor(
92+
state: ChatSessionState,
93+
lastInEventId: string | undefined
94+
): boolean {
95+
if (state.lastEventId !== undefined) return false;
96+
if (state.activeInputSeq === undefined || lastInEventId === undefined) return true;
97+
const handledThrough = Number.parseInt(lastInEventId, 10);
98+
return Number.isNaN(handledThrough) || handledThrough >= state.activeInputSeq;
99+
}
100+
101+
/**
102+
* A session's state from a persisted record. `cursor`, a transcript's cursor held
103+
* until the session existed, goes in before the turn start is taken from it.
104+
*/
105+
function stateFromRecord(
106+
record: ChatSessionPersistedState,
107+
cursor: TranscriptCursor | undefined
108+
): ChatSessionState {
109+
const state: ChatSessionState = {
110+
publicAccessToken: record.publicAccessToken,
111+
lastEventId: record.lastEventId,
112+
activeInputSeq: record.activeInputSeq,
113+
isStreaming: record.isStreaming,
114+
closed: record.closed,
115+
closedReason: record.closedReason,
116+
};
117+
if (cursor && takesTranscriptCursor(state, cursor.lastInEventId)) {
118+
state.lastEventId = cursor.lastEventId;
119+
}
120+
if (state.isStreaming) state.turnStart = { lastEventId: state.lastEventId };
121+
return state;
122+
}
123+
124+
/**
125+
* One chat's session state: the live internal record the transport reads and
126+
* writes as records arrive, and a snapshot of it that changes only on `commit`.
127+
*/
128+
export class ChatSessionClient {
129+
private current: ChatSessionState;
130+
private snapshot: ChatSessionSnapshot;
131+
private readonly listeners = new Set<() => void>();
132+
133+
constructor(
134+
readonly chatId: string,
135+
record: ChatSessionPersistedState,
136+
cursor?: TranscriptCursor
137+
) {
138+
this.current = stateFromRecord(record, cursor);
139+
this.snapshot = { chatId, persisted: persistedStateOf(this.current) };
140+
}
141+
142+
/** The live record. Mutated in place as records arrive, with no snapshot change until `commit`. */
143+
get state(): ChatSessionState {
144+
return this.current;
145+
}
146+
147+
/**
148+
* The `.out` resume cursor as read so far. The snapshot's `persisted.lastEventId`
149+
* trails it until the next commit, and holds the turn's start while one streams.
150+
* Kept for the private read in `v3/chat.test.ts`; production reads `state.lastEventId`.
151+
*/
152+
get lastEventId(): string | undefined {
153+
return this.current.lastEventId;
154+
}
155+
156+
getSnapshot(): ChatSessionSnapshot {
157+
return this.snapshot;
158+
}
159+
160+
/** Calls `onChange` at each `commit`; returns the unsubscribe. */
161+
subscribe(onChange: () => void): () => void {
162+
this.listeners.add(onChange);
163+
return () => {
164+
this.listeners.delete(onChange);
165+
};
166+
}
167+
168+
/**
169+
* Replaces the session with one built from `record`, and commits. Returns the state
170+
* it built, not `state` read back: a subscriber can replace the session while it is
171+
* told of this one, and the caller's answer is still the session it installed.
172+
*/
173+
hydrate(record: ChatSessionPersistedState, cursor?: TranscriptCursor): ChatSessionState {
174+
const hydrated = stateFromRecord(record, cursor);
175+
this.current = hydrated;
176+
this.commit();
177+
return hydrated;
178+
}
179+
180+
/**
181+
* Makes `state` the live record again, without a commit. A stream or a token
182+
* renewal that began before a `hydrate` still holds its own state, and
183+
* re-registers it when it recreates the session.
184+
*/
185+
adopt(state: ChatSessionState): void {
186+
this.current = state;
187+
}
188+
189+
/**
190+
* Seeds the resume cursor from a loaded transcript. Never moves an existing cursor
191+
* backward: the transcript load is async, so a live `.out` record can already
192+
* have advanced the session past the snapshot, and overwriting it would replay
193+
* those records. With a sent turn outstanding, the transcript's `.in` cursor
194+
* decides (`takesTranscriptCursor`). Commits only when the cursor is taken.
195+
*/
196+
seedCursor(lastOutEventId: string, lastInEventId?: string): void {
197+
const state = this.current;
198+
if (!takesTranscriptCursor(state, lastInEventId)) return;
199+
state.lastEventId = lastOutEventId;
200+
if (state.turnStart?.lastEventId === undefined && state.isStreaming) {
201+
state.turnStart = { lastEventId: lastOutEventId };
202+
}
203+
this.commit();
204+
}
205+
206+
/**
207+
* Replaces the snapshot with one of `state` and calls the subscribers. `state`
208+
* is the caller's own: a stream or a stop that outlives a `hydrate` or
209+
* `setSession` publishes the state it holds, even when that state has since
210+
* been replaced, matching the transport's `onSessionChange` today. Settle this
211+
* before any view subscribes to `getSnapshot`: such a commit would show it a
212+
* state that is no longer the live one.
213+
*/
214+
commit(state: ChatSessionState = this.current): void {
215+
this.snapshot = { chatId: this.chatId, persisted: persistedStateOf(state) };
216+
for (const listener of [...this.listeners]) listener();
217+
}
218+
}

0 commit comments

Comments
 (0)