@devries-cameron20 / t3code Mirror · read-only / commits / 58427d565d
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 25, 10:00 UTC

Refactor ClaudeCodeAdapter session flow and stream handling

- Replace manual prompt async iterator with `Stream.fromQueue(...).toAsyncIterable` - Use `Ref` for shared session context in tool approval callbacks - Simplify timestamp/ID generation and close sessions via queue shutdown

Julius Marminge committed Feb 27, 2026 at 12:22 UTC 58427d565d91c27f1f37b3e0d1a396348c8afe6a
1 file changed +32 -62
apps/server/src/provider/Layers/ClaudeCodeAdapter.ts
+32 -62
@@ -31,7 +31,7 @@ import {
31 ProviderThreadId,
32 ProviderTurnId,
33 } from "@t3tools/contracts";
34 -import { Cause, DateTime, Deferred, Effect, Layer, Queue, Random, Stream } from "effect";
34 +import { Cause, DateTime, Deferred, Effect, Layer, Queue, Random, Ref, Stream } from "effect";
35
36 import {
37 ProviderAdapterProcessError,
@@ -312,25 +312,12 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
312 readonly options: ClaudeQueryOptions;
313 }) => query({ prompt: input.prompt, options: input.options }) as ClaudeQueryRuntime);
314
315 - const sessions = new Map<
316 - ReturnType<typeof ProviderSessionId.makeUnsafe>,
317 - ClaudeSessionContext
318 - >();
315 + const sessions = new Map<ProviderSessionId, ClaudeSessionContext>();
316 const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
317
321 - const now = (): Effect.Effect<string> =>
322 - DateTime.now.pipe(Effect.map(DateTime.formatIso));
323 - const randomId = (): Effect.Effect<string> => Random.nextUUIDv4;
324 - const makeEventId = (): Effect.Effect<ReturnType<typeof EventId.makeUnsafe>> =>
325 - randomId().pipe(Effect.map((id) => EventId.makeUnsafe(id)));
326 - const makeEventStamp = (): Effect.Effect<{
327 - readonly eventId: ReturnType<typeof EventId.makeUnsafe>;
328 - readonly createdAt: string;
329 - }> =>
330 - Effect.all({
331 - eventId: makeEventId(),
332 - createdAt: now(),
333 - });
318 + const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
319 + const nextEventId = Effect.map(Random.nextUUIDv4, (id) => EventId.makeUnsafe(id));
320 + const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso });
321
322 const offerRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
323 Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid);
@@ -347,7 +334,7 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
334 Effect.gen(function* () {
335 const threadId =
336 context.session.threadId ??
350 - ProviderThreadId.makeUnsafe(`claude-thread-${yield* randomId()}`);
337 + ProviderThreadId.makeUnsafe(`claude-thread-${yield* Random.nextUUIDv4}`);
338 return {
339 threadId,
340 turns: context.turns.map((turn) => ({
@@ -360,9 +347,7 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
347 const updateResumeCursor = (context: ClaudeSessionContext): Effect.Effect<void> =>
348 Effect.gen(function* () {
349 const threadId = context.session.threadId;
363 - if (!threadId) {
364 - return;
365 - }
350 + if (!threadId) return;
351
352 const resumeCursor = {
353 threadId,
@@ -374,7 +359,7 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
359 context.session = {
360 ...context.session,
361 resumeCursor,
377 - updatedAt: yield* now(),
362 + updatedAt: yield* nowIso,
363 };
364 });
365
@@ -387,7 +372,7 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
372 const changed = context.session.threadId !== nextThreadId;
373
374 if (changed) {
390 - const updatedAt = yield* now();
375 + const updatedAt = yield* nowIso;
376 context.session = {
377 ...context.session,
378 threadId: nextThreadId,
@@ -487,7 +472,7 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
472 ...(errorMessage ? { errorMessage } : {}),
473 });
474
490 - const updatedAt = yield* now();
475 + const updatedAt = yield* nowIso;
476 context.turnState = undefined;
477 context.session = {
478 ...context.session,
@@ -697,9 +682,7 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
682 options?: { readonly emitExitEvent?: boolean },
683 ): Effect.Effect<void> =>
684 Effect.gen(function* () {
700 - if (context.stopped) {
701 - return;
702 - }
685 + if (context.stopped) return;
686
687 context.stopped = true;
688
@@ -725,11 +708,11 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
708 yield* completeTurn(context, "interrupted", "Session stopped.");
709 }
710
728 - yield* Queue.offer(context.promptQueue, { type: "terminate" }).pipe(Effect.ignore);
711 + yield* Queue.shutdown(context.promptQueue);
712
730 - yield* Effect.sync(() => context.query.close()).pipe(Effect.ignoreCause);
713 + context.query.close();
714
732 - const updatedAt = yield* now();
715 + const updatedAt = yield* nowIso;
716 context.session = {
717 ...context.session,
718 status: "closed",
@@ -786,44 +769,31 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
769 });
770 }
771
789 - const startedAt = yield* now();
790 - const sessionId = ProviderSessionId.makeUnsafe(`claude-session-${yield* randomId()}`);
772 + const startedAt = yield* nowIso;
773 + const sessionId = ProviderSessionId.makeUnsafe(
774 + `claude-session-${yield* Random.nextUUIDv4}`,
775 + );
776 const resumeState = readClaudeResumeState(input.resumeCursor);
777 const threadId =
778 resumeState?.threadId ??
794 - ProviderThreadId.makeUnsafe(`claude-thread-${yield* randomId()}`);
779 + ProviderThreadId.makeUnsafe(`claude-thread-${yield* Random.nextUUIDv4}`);
780
781 const promptQueue = yield* Queue.unbounded<PromptQueueItem>();
797 - const prompt: AsyncIterable<SDKUserMessage> = {
798 - [Symbol.asyncIterator]() {
799 - return {
800 - next: async (): Promise<IteratorResult<SDKUserMessage>> => {
801 - const item = await Effect.runPromise(Queue.take(promptQueue));
802 - if (item.type === "terminate") {
803 - return {
804 - done: true,
805 - value: undefined,
806 - };
807 - }
808 -
809 - return {
810 - done: false,
811 - value: item.message,
812 - };
813 - },
814 - };
815 - },
816 - };
782 + const prompt = Stream.fromQueue(promptQueue).pipe(
783 + Stream.filter((item) => item.type === "message"),
784 + Stream.map((item) => item.message),
785 + Stream.toAsyncIterable,
786 + );
787
788 const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();
789 const inFlightTools = new Map<number, ToolInFlight>();
790
821 - let contextRef: ClaudeSessionContext | undefined;
791 + const contextRef = yield* Ref.make<ClaudeSessionContext | undefined>(undefined);
792
793 const canUseTool: CanUseTool = (toolName, toolInput, callbackOptions) =>
794 Effect.runPromise(
795 Effect.gen(function* () {
826 - const context = contextRef;
796 + const context = yield* Ref.get(contextRef);
797 if (!context) {
798 return {
799 behavior: "deny",
@@ -839,7 +809,7 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
809 } satisfies PermissionResult;
810 }
811
842 - const requestId = ApprovalRequestId.makeUnsafe(yield* randomId());
812 + const requestId = ApprovalRequestId.makeUnsafe(yield* Random.nextUUIDv4);
813 const requestKind = classifyRequestKind(toolName);
814 const detail = summarizeToolRequest(toolName, toolInput);
815 const decisionDeferred = yield* Deferred.make<ProviderApprovalDecision>();
@@ -988,7 +958,7 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
958 lastThreadStartedId: undefined,
959 stopped: false,
960 };
991 - contextRef = context;
961 + yield* Ref.set(contextRef, context);
962 sessions.set(sessionId, context);
963
964 const sessionStartedStamp = yield* makeEventStamp();
@@ -1027,16 +997,16 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
997 });
998 }
999
1030 - const turnId = ProviderTurnId.makeUnsafe(`claude-turn-${yield* randomId()}`);
1000 + const turnId = ProviderTurnId.makeUnsafe(`claude-turn-${yield* Random.nextUUIDv4}`);
1001 const turnState: ClaudeTurnState = {
1002 turnId,
1033 - assistantItemId: `claude-message-${yield* randomId()}`,
1034 - startedAt: yield* now(),
1003 + assistantItemId: `claude-message-${yield* Random.nextUUIDv4}`,
1004 + startedAt: yield* nowIso,
1005 items: [],
1006 messageCompleted: false,
1007 };
1008
1039 - const updatedAt = yield* now();
1009 + const updatedAt = yield* nowIso;
1010 context.turnState = turnState;
1011 context.session = {
1012 ...context.session,