[Bug]: Leaking Claude.exe processes for archived threads [windows] #2007
Before submitting#
- I searched existing issues and did not find a duplicate.
- I included enough detail to reproduce or investigate the problem.
Area#
apps/web
Steps to reproduce#
When running t3code for a long time I believe it might be leaking old claude.exe processes. I have quite a large number showing in process hacker as child processes but only have 5 active chats open in t3code itself (+ a bunch that finished and have been archived).
Expected behavior#
When a thread is archived the related process is stopped
Actual behavior#
Lots of claude.exe processes left in memory
Impact#
Blocks work completely
Version or commit#
No response
Environment#
No response
Logs or stack traces#
Screenshots, recordings, or supporting files#
No response
Workaround#
No response
bzbetty(GitHub profile, opens in a new tab) added labelsbug
bzbetty(GitHub profile, opens in a new tab) added labelsneeds-triage
bzbetty(GitHub profile, opens in a new tab) changed the title
Same thing in MacOs
Tons of random processes, from what i suppose are leftover claude code instances left open. Considerable CPU usage and memory usage too.
I put gpt 5.4 to analyze the codebase, and here is what it found.
Im way out of my element here, but I've read the code snippets against the actual codebase and the documentation and it makes sense
I think that perhaps ,for non-archived chat threads, it might be beneficial to actually setup a timeout where it gets terminated after a certain period of inactivity which is something that we do not seem to currently have either.
I am guilty of just starting N ammounts of thread without archiving.
Here is what gpt 5.4 says.
Investigation: Claude/Claude Code Process Leak on Archived Threads#
Issue: pingdotgg/t3code#2007
Date: 2026-04-13
Executive summary#
The current codebase does not stop provider sessions when a thread is archived.
For Claude threads, that means an archived thread can keep its
@anthropic-ai/claude-agent-sdkquery alive, which is important because Anthropic's TypeScript Agent SDK documentsQuery.close()as the call that "terminate[s] the underlying process." In this codebase, the Claude adapter only callsquery.close()during explicit session shutdown.That makes the archive flow a strong match for the issue report:
- Windows screenshots show many
claude.exechildren still attached to T3 Code. - macOS screenshots show both
nodeand Claude versioned binaries (for example2.1.101) withT3 Code (Alpha)as the parent process. - The number of leaked processes can grow with the number of archived Claude threads, so RAM usage is effectively unbounded over time.
My conclusion is that this is not intentional in the current implementation. It looks like an orchestration gap: archive cleans up terminal/UI state, but not provider runtime state.
What the screenshots suggest#
The screenshots are consistent with long-lived Claude runtime sessions that were spawned by T3 Code and never shut down:
- On Windows,
claude.exeinstances remain grouped under the T3 Code desktop process. - On macOS, the leaked processes include both
nodeand the Claude-installed version binary at/Users/nimbus/.local/share/claude/versions/2.1.101, again parented by T3 Code.
That lines up with the Claude integration here: T3 Code creates long-lived Claude SDK query sessions, and those sessions are only torn down when the app explicitly stops them.
Confirmed code path: archive does not stop the provider session#
1. The web archive action only dispatches
thread.archive#apps/web/src/hooks/useThreadActions.tsarchiveThread()dispatchesthread.archiveand then navigates away if needed.- It prevents archiving while a turn is actively running, but it does not dispatch
thread.session.stop.
const archiveThread = useCallback( async (target: ScopedThreadRef) => { const api = readEnvironmentApi(target.environmentId); if (!api) return; const resolved = resolveThreadTarget(target); if (!resolved) return; const { thread, threadRef } = resolved; if (thread.session?.status === "running" && thread.session.activeTurnId != null) { throw new Error("Cannot archive a running thread."); } // Key point: archive only dispatches `thread.archive`. // There is no matching `thread.session.stop` here. await api.orchestration.dispatchCommand({ type: "thread.archive", commandId: newCommandId(), threadId: threadRef.threadId, }); const currentRouteThreadRef = getCurrentRouteThreadRef(); if ( currentRouteThreadRef?.threadId === threadRef.threadId && currentRouteThreadRef.environmentId === threadRef.environmentId ) { await handleNewThreadRef.current(scopeProjectRef(thread.environmentId, thread.projectId)); } }, [getCurrentRouteThreadRef, resolveThreadTarget], );By contrast, delete does stop the session first:
if (thread.session && thread.session.status !== "closed") { // Delete explicitly stops the provider session first. await api.orchestration .dispatchCommand({ type: "thread.session.stop", commandId: newCommandId(), threadId: threadRef.threadId, createdAt: new Date().toISOString(), }) .catch(() => undefined); }That inconsistency is the first strong sign that archive forgot to clean up provider state.
2. The server archive RPC only closes the terminal#
apps/server/src/ws.tsAfter a successful
thread.archivedispatch, the WebSocket layer does one extra cleanup step:terminalManager.close({ threadId })
There is no equivalent provider shutdown here.
[ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) => observeRpcEffect( ORCHESTRATION_WS_METHODS.dispatchCommand, Effect.gen(function* () { const normalizedCommand = yield* normalizeDispatchCommand(command); const result = yield* dispatchNormalizedCommand(normalizedCommand); if (normalizedCommand.type === "thread.archive") { // Key point: archive cleanup only closes the terminal. // It still does not stop the provider session. yield* terminalManager.close({ threadId: normalizedCommand.threadId }).pipe( Effect.catch((error) => Effect.logWarning("failed to close thread terminals after archive", { threadId: normalizedCommand.threadId, error: error.message, }), ), ); } return result; }), );There is also a server test that asserts exactly this behavior and nothing more:
it.effect("closes thread terminals after a successful archive command", () => Effect.gen(function* () { const threadId = ThreadId.make("thread-archive"); const closeInputs: Array<Parameters<TerminalManagerShape["close"]>[0]> = []; yield* buildAppUnderTest({ layers: { terminalManager: { close: (input) => Effect.sync(() => { closeInputs.push(input); }), }, orchestrationEngine: { dispatch: () => Effect.succeed({ sequence: 8 }), }, }, }); // ... // The test only asserts terminal cleanup. // It does not assert provider shutdown. assert.equal(dispatchResult.sequence, 8); assert.deepEqual(closeInputs, [{ threadId }]); }).pipe(Effect.provide(NodeHttpServer.layerTest)), );That test proves archive cleanup currently means "close the terminal", not "stop the provider session".
3. The orchestration decider turns archive into a projection-only thread event#
apps/server/src/orchestration/decider.tsthread.archivebecomesthread.archived, which only updates thread metadata:archivedAtupdatedAt
case "thread.archive": { yield* requireThreadNotArchived({ readModel, command, threadId: command.threadId, }); const occurredAt = nowIso(); return { ...withEventBase({ aggregateKind: "thread", aggregateId: command.threadId, occurredAt, commandId: command.commandId, }), // Key point: archive becomes a thread metadata event. type: "thread.archived", payload: { threadId: command.threadId, // Only archive timestamps are updated here. archivedAt: occurredAt, updatedAt: occurredAt, }, }; }The projection pipeline reflects the same thing:
case "thread.archived": { const existingRow = yield* projectionThreadRepository.getById({ threadId: event.payload.threadId, }); if (Option.isNone(existingRow)) { return; } yield* projectionThreadRepository.upsert({ ...existingRow.value, // Key point: projection only persists archive state. archivedAt: event.payload.archivedAt, updatedAt: event.payload.updatedAt, }); return; }On the web side,
thread.archivedremoves terminal state, but again does not touch provider runtime:case "thread.archived": { threadLifecycleEffects.set(event.payload.threadId, { clearPromotedDraft: false, clearDeletedThread: false, // Key point: archive removes terminal state in the UI. removeTerminalState: true, }); break; }4. The provider reactor never handles
thread.archived#apps/server/src/orchestration/Layers/ProviderCommandReactor.tsThe provider command reactor only reacts to:
thread.runtime-mode-setthread.turn-start-requestedthread.turn-interrupt-requestedthread.approval-response-requestedthread.user-input-response-requestedthread.session-stop-requested
thread.archivedis not in that list.type ProviderIntentEvent = Extract< OrchestrationEvent, { type: // This union includes stop requests... | "thread.runtime-mode-set" | "thread.turn-start-requested" | "thread.turn-interrupt-requested" | "thread.approval-response-requested" | "thread.user-input-response-requested" | "thread.session-stop-requested"; // ...but not `thread.archived`. } >;const processEvent = Effect.fn("processEvent")(function* (event: OrchestrationEvent) { if ( event.type === "thread.runtime-mode-set" || event.type === "thread.turn-start-requested" || event.type === "thread.turn-interrupt-requested" || event.type === "thread.approval-response-requested" || event.type === "thread.user-input-response-requested" || event.type === "thread.session-stop-requested" ) { // Only these events are routed into provider handling. return yield* worker.enqueue(event); } });So once a thread is archived, the provider layer never hears about it, and no shutdown path runs.
Where Claude processes are actually stopped#
The shutdown path exists, but archive never reaches it.
1. Explicit session stop routes through
ProviderService.stopSession#apps/server/src/provider/Layers/ProviderService.tsconst stopSession: ProviderServiceShape["stopSession"] = Effect.fn("stopSession")( function* (rawInput) { const input = yield* decodeInputOrValidationError({ operation: "ProviderService.stopSession", schema: ProviderStopSessionInput, payload: rawInput, }); let metricProvider = "unknown"; return yield* Effect.gen(function* () { const routed = yield* resolveRoutableSession({ threadId: input.threadId, operation: "ProviderService.stopSession", allowRecovery: false, }); metricProvider = routed.adapter.provider; if (routed.isActive) { // This is the shutdown call archive never reaches today. yield* routed.adapter.stopSession(routed.threadId); } // The persisted provider binding is removed only after explicit stop. yield* directory.remove(input.threadId); }); }, );That method calls the provider adapter's
stopSession()and removes the persisted provider binding.2. Claude shutdown calls
query.close()#apps/server/src/provider/Layers/ClaudeAdapter.tsThe Claude adapter's stop flow runs
stopSessionInternal(), which:- shuts down the prompt queue
- interrupts the stream fiber
- calls
context.query.close() - marks the session closed
- removes the session from the in-memory
sessionsmap
if (context.turnState) { yield * completeTurn(context, "interrupted", "Session stopped."); } yield * Queue.shutdown(context.promptQueue); const streamFiber = context.streamFiber; context.streamFiber = undefined; if (streamFiber && streamFiber.pollUnsafe() === undefined) { yield * Fiber.interrupt(streamFiber); } try { // This is the critical Claude SDK shutdown call. context.query.close(); } catch (cause) { yield * emitRuntimeError(context, "Failed to close Claude runtime query.", cause); } const updatedAt = yield * nowIso; context.session = { ...context.session, status: "closed", activeTurnId: undefined, updatedAt, }; if (options?.emitExitEvent !== false) { yield * offerRuntimeEvent({ type: "session.exited", // ... }); } // The in-memory session record is dropped only after the close path runs. sessions.delete(context.session.threadId);Anthropic's TypeScript Agent SDK docs say that
close()will "terminate the underlying process" and "clean up all resources":That is the key reason the archive gap matters: if
close()never runs, the underlying Claude runtime process tree can stay alive.Why this does not look intentional#
I did not find evidence that archived threads are meant to keep provider sessions alive on purpose.
What I did find points the other way:
- Archive is already treated as an inactivity boundary for terminals and UI state.
- Delete explicitly stops sessions before deleting the thread.
- The provider reactor has a dedicated event for session shutdown, but archive never emits or routes to it.
- The test coverage around archive only checks terminal cleanup, which looks more like an incomplete implementation than a deliberate "keep sessions running while archived" policy.
So the safest interpretation is:
- T3 Code intended archived threads to become inactive from the user's perspective.
- Terminal cleanup was wired up.
- Provider cleanup was missed.
Secondary suspect: session restart paths may also leak Claude runtimes#
While investigating the archive bug, I found a second lifecycle risk that may deserve its own issue.
Why it looks risky#
When Claude-specific model options change, the provider command reactor restarts the session by calling
startSession()again:const activeSession = yield * resolveActiveSession(threadId); const existingSessionThreadId = thread.session && thread.session.status !== "stopped" && activeSession ? thread.id : null; if (existingSessionThreadId) { // ... const shouldRestartForModelSelectionChange = currentProvider === "claudeAgent" && requestedModelSelection !== undefined && !Equal.equals(previousModelSelection, requestedModelSelection); if ( !runtimeModeChanged && !providerChanged && !shouldRestartForModelChange && !shouldRestartForModelSelectionChange ) { return existingSessionThreadId; } // Key point: restart goes straight to starting a new session. // There is no stop call immediately before this. const restartedSession = yield * startProviderSession(resumeCursor !== undefined ? { resumeCursor } : undefined); yield * bindSessionToThread(restartedSession); }The tests for that path expect a second
startSession()call and do not expectstopSession()to run first:expect(harness.startSession.mock.calls.length).toBe(1); // Key point: the test explicitly expects no stop call first. expect(harness.stopSession.mock.calls.length).toBe(0);it("restarts claude sessions when claude effort changes", async () => { // ... await waitFor(() => harness.startSession.mock.calls.length === 2); await waitFor(() => harness.sendTurn.mock.calls.length === 2); // Second start call shows the restart path is "start again". expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({ resumeCursor: { opaque: "resume-1" }, modelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6", options: { effort: "max", }, }, }); });But
ClaudeAdapter.startSession()itself does not stop an existing thread session before creating a new query. It creates a new SDK query and overwrites the thread entry in the adapter'ssessionsmap:const startSession: ClaudeAdapterShape["startSession"] = Effect.fn("startSession")( function* (input) { const startedAt = yield* nowIso; const resumeState = readClaudeResumeState(input.resumeCursor); const threadId = input.threadId; const existingResumeSessionId = resumeState?.resume; const newSessionId = existingResumeSessionId === undefined ? yield* Random.nextUUIDv4 : undefined; const promptQueue = yield* Queue.unbounded<PromptQueueItem>(); // ... // A fresh session context is created here. const contextRef = yield* Ref.make<ClaudeSessionContext | undefined>(undefined);const queryRuntime = yield * Effect.try({ try: () => createQuery({ prompt, options: queryOptions, }), // ... }); const context: ClaudeSessionContext = { session, promptQueue, // Key point: this new SDK query becomes the runtime handle for the thread. query: queryRuntime, streamFiber: undefined, startedAt, // ... stopped: false, }; yield * Ref.set(contextRef, context); // The map entry is overwritten with the new session context. sessions.set(threadId, context);That means the previous Claude query is not explicitly closed on restart.
How confident I am#
I am very confident this is a lifecycle smell.
I am less confident calling it the same confirmed leak as the archive bug without a direct repro, because that depends on exactly how the SDK behaves for resumed/restarted sessions at runtime.
Still, from the code alone, it is a plausible additional leak source and should be audited alongside the archive fix.
Likely impact#
The practical impact of the confirmed archive bug is:
- Every archived Claude thread can leave behind at least one long-lived Claude SDK runtime.
- Those runtimes can remain hidden from normal thread lists because the thread is archived.
- Memory usage grows with archived-thread count rather than with visible active-chat count.
- CPU may also remain elevated if those processes keep event loops, watchers, or child processes alive.
So the issue is better described as unbounded process and memory retention rather than a one-off leak.
Most likely place the fix belongs#
The safest fix should be server-side, not only in the web client.
Best candidates:
- Make archive trigger provider shutdown as part of orchestration lifecycle.
- Add a regression test proving that archiving a thread stops its provider session.
- Make provider restarts replace existing sessions safely by shutting down the previous Claude query before starting a new one.
My preferred direction:
- Emit or handle session shutdown in the archive lifecycle on the server.
- Keep the client free of provider-specific cleanup assumptions.
That avoids future bugs where a different client entrypoint archives a thread but forgets to stop the provider session.
Recommended follow-up work#
- Add a regression test around
thread.archivethat asserts provider shutdown, not only terminal shutdown. - Wire archive to
thread.session.stopsemantics or teachProviderCommandReactorto react tothread.archived. - Audit all restart flows so that a thread can never own more than one live Claude query/process tree at a time.
- Add telemetry for:
- active provider sessions
- active Claude sessions
- archived threads with live provider sessions
- Consider a cleanup sweep on startup that force-stops any persisted session bound to an already-archived thread.
Bottom line#
For issue #2007, the current codebase strongly suggests the leak is real and that it resides primarily in the archive lifecycle:
- archive closes terminals
- archive marks the thread archived
- archive does not stop the provider session
- Claude processes therefore remain alive until some other shutdown path runs
That behavior does not look intentional. It looks like an incomplete cleanup path.
- Windows screenshots show many
Note: In MacOS, after command+q inside t3 code, the process still exists , has memory, and still has the 2.1.101 processes. I had to manually kill the t3 process via the terminal for those to dissapear.
juliusmarminge closed this
Sign in to join this conversation.
Claude analysis
Here's the trace through the code:
→ dispatchCommand({ type: "thread.archive", ... }) → decider.ts:194 → emits "thread.archived" event → projector.ts → sets archivedAt timestamp on the thread → DONE The ProviderCommandReactor (ProviderCommandReactor.ts:743-772) handles exactly these event types:
thread.turn-start-requested thread.turn-interrupt-requested thread.approval-response-requested thread.user-input-response-requested thread.session-stop-requested thread.archived is not in that list. It falls through the switch with no handler — the provider layer never hears about it. No stopSession is called; the claude.exe process keeps running.
Delete does stop the process:
await api.orchestration.dispatchCommand({ type: "thread.session.stop", // ← this triggers stopSession ... }); }
Archive only marks the thread with an archivedAt timestamp and cleans up the UI/terminal. The provider session and its underlying claude.exe process are left running. The archive action even has a guard (line 67-69) that prevents archiving if a turn is actively running — but it doesn't stop the session in the non-running case either.
Have archiveThread dispatch a thread.session.stop command before/after the archive (like deleteThread does), or Have the ProviderCommandReactor handle thread.archived events and stop the session there.