Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions apps/desktop/src/lib/trpc/routers/ai-chat/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,17 @@ export const createAiChatRouter = () => {
sessionId: z.string(),
workspaceId: z.string(),
cwd: z.string(),
paneId: z.string().optional(),
tabId: z.string().optional(),
}),
)
.mutation(async ({ input }) => {
await chatSessionManager.startSession({
sessionId: input.sessionId,
workspaceId: input.workspaceId,
cwd: input.cwd,
paneId: input.paneId,
tabId: input.tabId,
});
return { success: true };
}),
Expand All @@ -43,12 +47,16 @@ export const createAiChatRouter = () => {
z.object({
sessionId: z.string(),
cwd: z.string(),
paneId: z.string().optional(),
tabId: z.string().optional(),
}),
)
.mutation(async ({ input }) => {
await chatSessionManager.restoreSession({
sessionId: input.sessionId,
cwd: input.cwd,
paneId: input.paneId,
tabId: input.tabId,
});
return { success: true };
}),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { PORTS } from "shared/constants";
import { env } from "shared/env.shared";
import { buildClaudeEnv } from "../auth";
import type {
AgentProvider,
Expand All @@ -17,11 +19,17 @@ export class ClaudeSdkProvider implements AgentProvider {
getAgentRegistration({
sessionId,
cwd,
paneId,
tabId,
workspaceId,
}: {
sessionId: string;
cwd: string;
paneId?: string;
tabId?: string;
workspaceId?: string;
}): AgentRegistration {
const env = buildClaudeEnv();
const claudeEnv = buildClaudeEnv();

return {
id: "claude",
Expand All @@ -30,7 +38,14 @@ export class ClaudeSdkProvider implements AgentProvider {
bodyTemplate: {
sessionId,
cwd,
env,
env: claudeEnv,
notification: {
port: PORTS.NOTIFICATIONS,
paneId,
tabId,
workspaceId,
env: env.NODE_ENV === "development" ? "development" : "production",
},
},
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ export interface AgentProvider {
getAgentRegistration(opts: {
sessionId: string;
cwd: string;
paneId?: string;
tabId?: string;
workspaceId?: string;
}): AgentRegistration;

getProviderSessionId(sessionId: string): Promise<string | undefined>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,14 @@ export class ChatSessionManager extends EventEmitter {
sessionId,
workspaceId,
cwd,
paneId,
tabId,
}: {
sessionId: string;
workspaceId: string;
cwd: string;
paneId?: string;
tabId?: string;
}): Promise<void> {
if (this.sessions.has(sessionId)) {
console.warn(`[chat/session] Session ${sessionId} already active`);
Expand All @@ -84,6 +88,9 @@ export class ChatSessionManager extends EventEmitter {
const registration = this.provider.getAgentRegistration({
sessionId,
cwd,
paneId,
tabId,
workspaceId,
});
const registerRes = await fetch(
`${PROXY_URL}/v1/sessions/${sessionId}/agents`,
Expand Down Expand Up @@ -131,9 +138,13 @@ export class ChatSessionManager extends EventEmitter {
async restoreSession({
sessionId,
cwd,
paneId,
tabId,
}: {
sessionId: string;
cwd: string;
paneId?: string;
tabId?: string;
}): Promise<void> {
if (this.sessions.has(sessionId)) {
return;
Expand All @@ -156,6 +167,8 @@ export class ChatSessionManager extends EventEmitter {
const registration = this.provider.getAgentRegistration({
sessionId,
cwd,
paneId,
tabId,
});
const registerRes = await fetch(
`${PROXY_URL}/v1/sessions/${sessionId}/agents`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,16 @@ interface ChatInterfaceProps {
sessionId: string;
workspaceId: string;
cwd: string;
paneId: string;
tabId: string;
}

export function ChatInterface({
sessionId,
workspaceId,
cwd,
paneId,
tabId,
}: ChatInterfaceProps) {
const [selectedModel, setSelectedModel] = useState<ModelOption>(MODELS[1]);
const [modelSelectorOpen, setModelSelectorOpen] = useState(false);
Expand Down Expand Up @@ -124,19 +128,21 @@ export function ChatInterface({
setSessionReady(false);

if (existingSession) {
restoreSessionRef.current.mutate({ sessionId, cwd });
restoreSessionRef.current.mutate({ sessionId, cwd, paneId, tabId });
} else {
startSessionRef.current.mutate({
sessionId,
workspaceId,
cwd,
paneId,
tabId,
});
}

return () => {
stopSessionRef.current.mutate({ sessionId });
};
}, [sessionId, cwd, workspaceId, existingSession]);
}, [sessionId, cwd, workspaceId, existingSession, paneId, tabId]);

useEffect(() => {
if (sessionReady && config?.proxyUrl) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ export function ChatPane({
sessionId={sessionId}
workspaceId={workspaceId}
cwd={workspace?.worktreePath ?? ""}
paneId={paneId}
tabId={tabId}
/>
</BasePaneWindow>
);
Expand Down
61 changes: 59 additions & 2 deletions apps/streams/src/claude-agent.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { query } from "@anthropic-ai/claude-agent-sdk";
import {
type HookCallbackMatcher,
type HookEvent,
query,
} from "@anthropic-ai/claude-agent-sdk";
import { Hono } from "hono";
import { z } from "zod";
import { createConverter } from "./sdk-to-ai-chunks";
Expand All @@ -11,6 +15,14 @@ const MAX_AGENT_TURNS = 25;
const SESSION_MAX_SIZE = 1000;
const SESSION_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours

const notificationSchema = z.object({
port: z.number(),
paneId: z.string().optional(),
tabId: z.string().optional(),
workspaceId: z.string().optional(),
env: z.string().optional(),
});

const agentRequestSchema = z.object({
messages: z
.array(z.object({ role: z.string(), content: z.string() }))
Expand All @@ -19,6 +31,7 @@ const agentRequestSchema = z.object({
sessionId: z.string().optional(),
cwd: z.string().optional(),
env: z.record(z.string(), z.string()).optional(),
notification: notificationSchema.optional(),
});

interface SessionEntry {
Expand Down Expand Up @@ -98,6 +111,45 @@ function setClaudeSessionId(sessionId: string, claudeSessionId: string): void {
persistSessions();
}

type NotificationContext = z.infer<typeof notificationSchema>;

// Mirrors the terminal shell wrapper hooks that call GET /hook/complete
function buildNotificationHooks({
notification,
}: {
notification: NotificationContext;
}): Partial<Record<HookEvent, HookCallbackMatcher[]>> {
const baseUrl = `http://localhost:${notification.port}/hook/complete`;

const buildUrl = (eventType: string): string => {
const params = new URLSearchParams({ eventType });
if (notification.paneId) params.set("paneId", notification.paneId);
if (notification.tabId) params.set("tabId", notification.tabId);
if (notification.workspaceId)
params.set("workspaceId", notification.workspaceId);
if (notification.env) params.set("env", notification.env);
return `${baseUrl}?${params.toString()}`;
};

const createHookMatcher = (eventType: string): HookCallbackMatcher => ({
hooks: [
async () => {
try {
await fetch(buildUrl(eventType));
} catch (err) {
console.warn(`[claude-agent] Failed to notify ${eventType}:`, err);
}
return { continue: true };
},
],
});

return {
UserPromptSubmit: [createHookMatcher("UserPromptSubmit")],
Stop: [createHookMatcher("Stop")],
};
}

const app = new Hono();

app.post("/", async (c) => {
Expand All @@ -117,7 +169,7 @@ app.post("/", async (c) => {
);
}

const { messages, sessionId, cwd, env: agentEnv } = parsed.data;
const { messages, sessionId, cwd, env: agentEnv, notification } = parsed.data;

const latestUserMessage = messages?.filter((m) => m.role === "user").pop();

Expand All @@ -135,6 +187,10 @@ app.post("/", async (c) => {

const binaryPath = process.env.CLAUDE_BINARY_PATH;

const hooks = notification
? buildNotificationHooks({ notification })
: undefined;

const abortController = new AbortController();
const result = query({
prompt,
Expand All @@ -148,6 +204,7 @@ app.post("/", async (c) => {
...(binaryPath && { pathToClaudeCodeExecutable: binaryPath }),
env: queryEnv,
abortController,
...(hooks && { hooks }),
},
});

Expand Down
2 changes: 1 addition & 1 deletion apps/streams/src/sdk-to-ai-chunks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
* - RUN_ERROR — error during execution
*/

import type { StreamChunk } from "@tanstack/ai";
import { createTextSegmentEnricher } from "@superset/durable-session";
import type { StreamChunk } from "@tanstack/ai";

// ============================================================================
// Claude SDK Types (subset used for conversion)
Expand Down
Loading