-
Notifications
You must be signed in to change notification settings - Fork 965
fix(streams): streaming correctness, reliability, and performance overhaul #1391
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
38 commits
Select commit
Hold shift + click to select a range
93b7541
Reduce stream latency
Kitenite 2c2434c
Smooth stream
Kitenite e4ff696
Smooth stream
Kitenite d0c47b4
fix(streams): fail /generations/finish when producer had background e…
Kitenite 380e509
refactor(streams): extract producer error helpers for clarity
Kitenite 27d421c
fix(desktop): check res.ok for /generations/finish and send messageId
Kitenite 1d1bd45
fix(streams): await producer flush and detach in deleteSession
Kitenite 01ce87c
fix(streams): flush producer before reset control event
Kitenite 87a7994
fix(streams): route all writes through producer for global ordering
Kitenite d5858bc
fix(desktop): add abort signal to chunk POSTs for fast interrupt
Kitenite be91b6c
fix(desktop): emit error event when generation finish fails
Kitenite 99493d2
fix(streams): guard session delete/reset with per-session mutex
Kitenite 1a21243
fix(streams): write user messages directly to stream for txid immediacy
Kitenite 7481c20
perf(desktop): remove /generations/start round trip
Kitenite 4378d16
perf: batch chunk sends to reduce per-chunk HTTP overhead
Kitenite d89b779
Update docs
Kitenite 28347db
perf(streams): tune producer lingerMs and add flush timeout
Kitenite 00c5e61
perf: skip Zod on batch endpoint, add bounded queue to ChunkBatcher
Kitenite af42487
Add retry with exponential backoff for batch sends (#21)
Kitenite aeb1aed
Add producer health tracking with sync fallback (#23, #24)
Kitenite fc6197e
Track active generation per session for single-writer enforcement (#2…
Kitenite ab271f9
Add sessionId and messageId to all route responses (#34)
Kitenite 056af58
Add structured error codes to all route responses (#32)
Kitenite 2050c5a
Add structured error codes and sessionId to auth routes (#32, #34)
Kitenite cbe05da
Format: lint fixes across streams and desktop
Kitenite 1679647
Update recommendations doc: mark completed items
Kitenite 60b9f0c
Add perf
Kitenite a891e1a
Chunks
Kitenite 963475c
Remove /generations/start endpoint (#29)
Kitenite 1075c38
Document terminal semantics convention (#31)
Kitenite 329d6c1
Fix restore
Kitenite e9d0ac5
Refactor
Kitenite 417dadc
More splitting
Kitenite 88172aa
More split
Kitenite edf0bea
Fixed feedback
Kitenite e526c47
Chunk
Kitenite 838c515
Fixed comments
Kitenite b3f660c
Update CI env
Kitenite File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
123 changes: 123 additions & 0 deletions
123
apps/desktop/src/lib/trpc/routers/ai-chat/utils/session-manager/agent-execution.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,123 @@ | ||
| import { join } from "node:path"; | ||
| import { | ||
| createPermissionRequest, | ||
| executeAgent, | ||
| resolvePendingPermission, | ||
| } from "@superset/agent"; | ||
| import { app } from "electron"; | ||
| import { buildClaudeEnv } from "../auth"; | ||
| import type { SessionStore } from "../session-store"; | ||
| import type { PermissionRequestEvent } from "./session-events"; | ||
| import type { ActiveSession } from "./session-types"; | ||
|
|
||
| function getClaudeBinaryPath(): string { | ||
| if (app.isPackaged) { | ||
| return join(process.resourcesPath, "bin", "claude"); | ||
| } | ||
| const platform = process.platform; | ||
| const arch = process.arch; | ||
| return join( | ||
| app.getAppPath(), | ||
| "resources", | ||
| "bin", | ||
| `${platform}-${arch}`, | ||
| "claude", | ||
| ); | ||
| } | ||
|
|
||
| export interface ResolvePermissionInput { | ||
| sessionId: string; | ||
| toolUseId: string; | ||
| approved: boolean; | ||
| updatedInput?: Record<string, unknown>; | ||
| } | ||
|
|
||
| export interface ExecuteAgentInput { | ||
| session: ActiveSession; | ||
| sessionId: string; | ||
| prompt: string; | ||
| abortController: AbortController; | ||
| onChunk: (chunk: unknown) => void; | ||
| } | ||
|
|
||
| interface AgentExecutionDeps { | ||
| store: SessionStore; | ||
| emitPermissionRequest: (event: PermissionRequestEvent) => void; | ||
| } | ||
|
|
||
| export class AgentExecution { | ||
| constructor(private readonly deps: AgentExecutionDeps) {} | ||
|
|
||
| async execute({ | ||
| session, | ||
| sessionId, | ||
| prompt, | ||
| abortController, | ||
| onChunk, | ||
| }: ExecuteAgentInput): Promise<void> { | ||
| const agentEnv = buildClaudeEnv(); | ||
|
|
||
| await executeAgent({ | ||
| sessionId, | ||
| prompt, | ||
| cwd: session.cwd, | ||
| pathToClaudeCodeExecutable: getClaudeBinaryPath(), | ||
| env: agentEnv, | ||
| model: session.model, | ||
| permissionMode: session.permissionMode ?? "default", | ||
| maxThinkingTokens: session.maxThinkingTokens, | ||
| signal: abortController.signal, | ||
| onChunk, | ||
| onPermissionRequest: async (params) => { | ||
| this.deps.emitPermissionRequest({ | ||
| type: "permission_request", | ||
| sessionId, | ||
| toolUseId: params.toolUseId, | ||
| toolName: params.toolName, | ||
| input: params.input, | ||
| }); | ||
|
|
||
| return createPermissionRequest({ | ||
| toolUseId: params.toolUseId, | ||
| signal: params.signal, | ||
| }); | ||
| }, | ||
| onEvent: (event) => { | ||
| if (event.type === "session_initialized") { | ||
| this.deps.store | ||
| .update(sessionId, { | ||
| providerSessionId: event.claudeSessionId, | ||
| lastActiveAt: Date.now(), | ||
| }) | ||
| .catch((err: unknown) => { | ||
| console.error( | ||
| `[chat/session] Failed to update providerSessionId:`, | ||
| err, | ||
| ); | ||
| }); | ||
| } | ||
| }, | ||
| }); | ||
| } | ||
|
|
||
| resolvePermission({ | ||
| sessionId, | ||
| toolUseId, | ||
| approved, | ||
| updatedInput, | ||
| }: ResolvePermissionInput): void { | ||
| const result = approved | ||
| ? { | ||
| behavior: "allow" as const, | ||
| updatedInput: updatedInput ?? {}, | ||
| } | ||
| : { behavior: "deny" as const, message: "User denied permission" }; | ||
|
|
||
| const resolved = resolvePendingPermission({ toolUseId, result }); | ||
| if (!resolved) { | ||
| console.warn( | ||
| `[chat/session] No pending permission for toolUseId=${toolUseId} in session ${sessionId}`, | ||
| ); | ||
| } | ||
| } | ||
| } |
137 changes: 137 additions & 0 deletions
137
apps/desktop/src/lib/trpc/routers/ai-chat/utils/session-manager/agent-runner.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,137 @@ | ||
| import type { SessionStore } from "../session-store"; | ||
| import type { ResolvePermissionInput } from "./agent-execution"; | ||
| import { AgentExecution } from "./agent-execution"; | ||
| import { AgentStreamWriter } from "./agent-stream-writer"; | ||
| import type { ChunkBatcher } from "./chunk-batcher"; | ||
| import type { GenerationWatchdog } from "./generation-watchdog"; | ||
| import type { PermissionRequestEvent } from "./session-events"; | ||
| import type { ActiveSession, EnsureSessionReadyInput } from "./session-types"; | ||
|
|
||
| export type { ResolvePermissionInput } from "./agent-execution"; | ||
|
|
||
| export interface StartAgentInput { | ||
| sessionId: string; | ||
| prompt: string; | ||
| } | ||
|
|
||
| interface AgentRunnerDeps { | ||
| store: SessionStore; | ||
| sessions: Map<string, ActiveSession>; | ||
| runningAgents: Map<string, AbortController>; | ||
| proxyUrl: string; | ||
| emitSessionError: (params: { sessionId: string; error: string }) => void; | ||
| emitPermissionRequest: (event: PermissionRequestEvent) => void; | ||
| ensureSessionReady: (input: EnsureSessionReadyInput) => Promise<void>; | ||
| } | ||
|
|
||
| export class AgentRunner { | ||
| private readonly execution: AgentExecution; | ||
| private readonly streamWriter: AgentStreamWriter; | ||
|
|
||
| constructor(private readonly deps: AgentRunnerDeps) { | ||
| this.execution = new AgentExecution({ | ||
| store: deps.store, | ||
| emitPermissionRequest: deps.emitPermissionRequest, | ||
| }); | ||
| this.streamWriter = new AgentStreamWriter({ | ||
| proxyUrl: deps.proxyUrl, | ||
| emitSessionError: deps.emitSessionError, | ||
| ensureSessionReady: deps.ensureSessionReady, | ||
| isSessionActive: (sessionId) => this.deps.sessions.has(sessionId), | ||
| }); | ||
| } | ||
|
|
||
| private abortExistingAgent({ sessionId }: { sessionId: string }): void { | ||
| const existingController = this.deps.runningAgents.get(sessionId); | ||
| if (!existingController) return; | ||
| console.warn(`[chat/session] Aborting previous agent run for ${sessionId}`); | ||
| existingController.abort(); | ||
| if (this.deps.runningAgents.get(sessionId) === existingController) { | ||
| this.deps.runningAgents.delete(sessionId); | ||
| } | ||
| } | ||
|
|
||
| async startAgent({ sessionId, prompt }: StartAgentInput): Promise<void> { | ||
| const session = this.deps.sessions.get(sessionId); | ||
| if (!session) { | ||
| console.error( | ||
| `[chat/session] Session ${sessionId} not found for startAgent`, | ||
| ); | ||
| this.deps.emitSessionError({ | ||
| sessionId, | ||
| error: "Session not active", | ||
| }); | ||
| return; | ||
| } | ||
|
|
||
| this.abortExistingAgent({ sessionId }); | ||
|
|
||
| const abortController = new AbortController(); | ||
| this.deps.runningAgents.set(sessionId, abortController); | ||
|
|
||
| const messageId = crypto.randomUUID(); | ||
| let headers: Record<string, string> | null = null; | ||
| let batcher: ChunkBatcher | null = null; | ||
| let watchdog: GenerationWatchdog | null = null; | ||
|
|
||
| try { | ||
| const prepared = await this.streamWriter.prepareStream({ | ||
| sessionId, | ||
| session, | ||
| abortController, | ||
| }); | ||
| headers = prepared.headers; | ||
| batcher = prepared.batcher; | ||
| watchdog = prepared.watchdog; | ||
|
|
||
| await this.execution.execute({ | ||
| session, | ||
| sessionId, | ||
| prompt, | ||
| abortController, | ||
| onChunk: (chunk) => { | ||
| this.streamWriter.onAssistantChunk({ | ||
| watchdog: watchdog as GenerationWatchdog, | ||
| batcher: batcher as ChunkBatcher, | ||
| messageId, | ||
| chunk, | ||
| }); | ||
| }, | ||
| }); | ||
| } catch (error) { | ||
| const message = error instanceof Error ? error.message : String(error); | ||
| if (!abortController.signal.aborted) { | ||
| console.error( | ||
| `[chat/session] Agent execution failed for ${sessionId}:`, | ||
| message, | ||
| ); | ||
| this.deps.emitSessionError({ sessionId, error: message }); | ||
| } else if (watchdog?.wasTriggered) { | ||
| console.warn( | ||
| `[chat/session] Agent aborted by watchdog for ${sessionId}:`, | ||
| message, | ||
| ); | ||
| } | ||
| } finally { | ||
| watchdog?.clear(); | ||
| await this.streamWriter.drainChunkBatcher({ | ||
| sessionId, | ||
| batcher, | ||
| abortController, | ||
| }); | ||
| await this.streamWriter.finalizeGeneration({ | ||
| sessionId, | ||
| session, | ||
| messageId, | ||
| headers, | ||
| }); | ||
| if (this.deps.runningAgents.get(sessionId) === abortController) { | ||
| this.deps.runningAgents.delete(sessionId); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| resolvePermission(input: ResolvePermissionInput): void { | ||
| this.execution.resolvePermission(input); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.