-
Notifications
You must be signed in to change notification settings - Fork 597
Expand file tree
/
Copy pathclaude.ts
More file actions
2500 lines (2249 loc) · 103 KB
/
claude.ts
File metadata and controls
2500 lines (2249 loc) · 103 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { observable } from "@trpc/server/observable"
import { eq } from "drizzle-orm"
import { app, BrowserWindow, safeStorage } from "electron"
import * as fs from "fs/promises"
import * as os from "os"
import path from "path"
import { z } from "zod"
import { setConnectionMethod } from "../../analytics"
import {
buildClaudeEnv,
checkOfflineFallback,
createTransformer,
getBundledClaudeBinaryPath,
logClaudeEnv,
logRawClaudeMessage,
type UIMessageChunk,
} from "../../claude"
import { getProjectMcpServers, GLOBAL_MCP_PATH, readClaudeConfig, removeMcpServerConfig, resolveProjectPathFromWorktree, updateClaudeConfigAtomic, updateMcpServerConfig, writeClaudeConfig, type McpServerConfig } from "../../claude-config"
import { discoverPluginMcpServers } from "../../plugins"
import { getEnabledPlugins, getApprovedPluginMcpServers } from "./claude-settings"
import { chats, claudeCodeCredentials, getDatabase, subChats } from "../../db"
import { createRollbackStash } from "../../git/stash"
import { ensureMcpTokensFresh, fetchMcpTools, fetchMcpToolsStdio, getMcpAuthStatus, startMcpOAuth, type McpToolInfo } from "../../mcp-auth"
import { fetchOAuthMetadata, getMcpBaseUrl } from "../../oauth"
import { publicProcedure, router } from "../index"
import { buildAgentsOption } from "./agent-utils"
/**
* Parse @[agent:name], @[skill:name], and @[tool:servername] mentions from prompt text
* Returns the cleaned prompt and lists of mentioned agents/skills/MCP servers
*
* File mention formats:
* - @[file:local:relative/path] - file inside project (relative path)
* - @[file:external:/absolute/path] - file outside project (absolute path)
* - @[file:owner/repo:path] - legacy web format (repo:path)
* - @[folder:local:path] or @[folder:external:path] - folder mentions
*/
function parseMentions(prompt: string): {
cleanedPrompt: string
agentMentions: string[]
skillMentions: string[]
fileMentions: string[]
folderMentions: string[]
toolMentions: string[]
} {
const agentMentions: string[] = []
const skillMentions: string[] = []
const fileMentions: string[] = []
const folderMentions: string[] = []
const toolMentions: string[] = []
// Match @[prefix:name] pattern
const mentionRegex = /@\[(file|folder|skill|agent|tool):([^\]]+)\]/g
let match
while ((match = mentionRegex.exec(prompt)) !== null) {
const [, type, name] = match
switch (type) {
case "agent":
agentMentions.push(name)
break
case "skill":
skillMentions.push(name)
break
case "file":
fileMentions.push(name)
break
case "folder":
folderMentions.push(name)
break
case "tool":
// Validate: server name (alphanumeric, underscore, hyphen) or full tool id (mcp__server__tool)
if (/^[a-zA-Z0-9_-]+$/.test(name) || /^mcp__[a-zA-Z0-9_-]+__[a-zA-Z0-9_-]+$/.test(name)) {
toolMentions.push(name)
}
break
}
}
// Clean agent/skill/tool mentions from prompt (they will be added as context or hints)
// Keep file/folder mentions as they are useful context
let cleanedPrompt = prompt
.replace(/@\[agent:[^\]]+\]/g, "")
.replace(/@\[skill:[^\]]+\]/g, "")
.replace(/@\[tool:[^\]]+\]/g, "")
.trim()
// Transform file mentions to readable paths for the agent
// @[file:local:path] -> path (relative to project)
// @[file:external:/abs/path] -> /abs/path (absolute)
cleanedPrompt = cleanedPrompt
.replace(/@\[file:local:([^\]]+)\]/g, "$1")
.replace(/@\[file:external:([^\]]+)\]/g, "$1")
.replace(/@\[folder:local:([^\]]+)\]/g, "$1")
.replace(/@\[folder:external:([^\]]+)\]/g, "$1")
// Add usage hints for mentioned MCP servers or individual tools
// Names are already validated to contain only safe characters
if (toolMentions.length > 0) {
const toolHints = toolMentions
.map((t) => {
if (t.startsWith("mcp__")) {
// Individual tool mention (from MCP widget): "Use the mcp__server__tool tool"
return `Use the ${t} tool for this request.`
}
// Server mention (from @ dropdown): "Use tools from the X MCP server"
return `Use tools from the ${t} MCP server for this request.`
})
.join(" ")
cleanedPrompt = `${toolHints}\n\n${cleanedPrompt}`
}
return { cleanedPrompt, agentMentions, skillMentions, fileMentions, folderMentions, toolMentions }
}
/**
* Decrypt token using Electron's safeStorage
*/
function decryptToken(encrypted: string): string {
if (!safeStorage.isEncryptionAvailable()) {
return Buffer.from(encrypted, "base64").toString("utf-8")
}
const buffer = Buffer.from(encrypted, "base64")
return safeStorage.decryptString(buffer)
}
function decryptIfNeeded(token: string): string {
if (!token) return token
if (!token.startsWith("enc:")) return token
return decryptToken(token.slice(4))
}
/**
* Get Claude Code OAuth token from local SQLite
* Returns null if not connected
*/
function getClaudeCodeToken(): string | null {
try {
const db = getDatabase()
const cred = db
.select()
.from(claudeCodeCredentials)
.where(eq(claudeCodeCredentials.id, "default"))
.get()
if (!cred?.oauthToken) {
console.log("[claude] No Claude Code credentials found")
return null
}
return decryptToken(cred.oauthToken)
} catch (error) {
console.error("[claude] Error getting Claude Code token:", error)
return null
}
}
// Dynamic import for ESM module - CACHED to avoid re-importing on every message
let cachedClaudeQuery: typeof import("@anthropic-ai/claude-agent-sdk").query | null = null
const getClaudeQuery = async () => {
if (cachedClaudeQuery) {
return cachedClaudeQuery
}
const sdk = await import("@anthropic-ai/claude-agent-sdk")
cachedClaudeQuery = sdk.query
return cachedClaudeQuery
}
// Active sessions for cancellation (onAbort handles stash + abort + restore)
// Active sessions for cancellation
const activeSessions = new Map<string, AbortController>()
// In-memory cache of working MCP server names (resets on app restart)
// Key: "scope::serverName" where scope is "__global__" or projectPath
// Value: true if working (has tools), false if failed
export const workingMcpServers = new Map<string, boolean>()
// Helper to build scoped cache key
const GLOBAL_SCOPE = "__global__"
function mcpCacheKey(scope: string | null, serverName: string): string {
return `${scope ?? GLOBAL_SCOPE}::${serverName}`
}
// Cache for symlinks (track which subChatIds have already set up symlinks)
const symlinksCreated = new Set<string>()
// Cache for MCP config (avoid re-reading ~/.claude.json on every message)
const mcpConfigCache = new Map<string, {
config: Record<string, any> | undefined
mtime: number
}>()
const pendingToolApprovals = new Map<
string,
{
subChatId: string
resolve: (decision: {
approved: boolean
message?: string
updatedInput?: unknown
}) => void
}
>()
const PLAN_MODE_BLOCKED_TOOLS = new Set([
"Bash",
"NotebookEdit",
])
const clearPendingApprovals = (message: string, subChatId?: string) => {
for (const [toolUseId, pending] of pendingToolApprovals) {
if (subChatId && pending.subChatId !== subChatId) continue
pending.resolve({ approved: false, message })
pendingToolApprovals.delete(toolUseId)
}
}
// Image attachment schema
const imageAttachmentSchema = z.object({
base64Data: z.string(),
mediaType: z.string(), // e.g. "image/png", "image/jpeg"
filename: z.string().optional(),
})
export type ImageAttachment = z.infer<typeof imageAttachmentSchema>
/**
* Clear all performance caches (for testing/debugging)
*/
export function clearClaudeCaches() {
cachedClaudeQuery = null
symlinksCreated.clear()
mcpConfigCache.clear()
console.log("[claude] All caches cleared")
}
/**
* Determine server status based on config
* - If authType is "none" -> "connected" (no auth required)
* - If has Authorization header -> "connected" (OAuth completed, SDK can use it)
* - If has _oauth but no headers -> "needs-auth" (legacy config, needs re-auth to migrate)
* - If HTTP server (has URL) with explicit authType -> "needs-auth"
* - HTTP server without authType -> "connected" (assume public)
* - Local stdio server -> "connected"
*/
function getServerStatusFromConfig(serverConfig: McpServerConfig): string {
const headers = serverConfig.headers as Record<string, string> | undefined
const { _oauth: oauth, authType } = serverConfig
// If authType is explicitly "none", no auth required
if (authType === "none") {
return "connected"
}
// If has Authorization header, it's ready for SDK to use
if (headers?.Authorization) {
return "connected"
}
// If has _oauth but no headers, this is a legacy config that needs re-auth
// (old format that SDK can't use)
if (oauth?.accessToken && !headers?.Authorization) {
return "needs-auth"
}
// If HTTP server with explicit authType (oauth/bearer), needs auth
if (serverConfig.url && (["oauth", "bearer"].includes(authType ?? ""))) {
return "needs-auth"
}
// HTTP server without authType - assume no auth required (public endpoint)
// Local stdio server - also connected
return "connected"
}
const MCP_FETCH_TIMEOUT_MS = 10_000
/**
* Fetch tools from an MCP server (HTTP or stdio transport)
* Times out after 10 seconds to prevent slow MCPs from blocking the cache update
*/
async function fetchToolsForServer(serverConfig: McpServerConfig): Promise<McpToolInfo[]> {
const timeoutPromise = new Promise<McpToolInfo[]>((_, reject) =>
setTimeout(() => reject(new Error('Timeout')), MCP_FETCH_TIMEOUT_MS)
)
const fetchPromise = (async () => {
// HTTP transport
if (serverConfig.url) {
const headers = serverConfig.headers as Record<string, string> | undefined
try {
return await fetchMcpTools(serverConfig.url, headers)
} catch {
return []
}
}
// Stdio transport
const command = (serverConfig as any).command as string | undefined
if (command) {
try {
return await fetchMcpToolsStdio({
command,
args: (serverConfig as any).args,
env: (serverConfig as any).env,
})
} catch {
return []
}
}
return []
})()
try {
return await Promise.race([fetchPromise, timeoutPromise])
} catch {
return []
}
}
/**
* Handler for getAllMcpConfig - exported so it can be called on app startup
*/
export async function getAllMcpConfigHandler() {
try {
const totalStart = Date.now()
// Clear cache before repopulating
workingMcpServers.clear()
const config = await readClaudeConfig()
const convertServers = async (servers: Record<string, McpServerConfig> | undefined, scope: string | null) => {
if (!servers) return []
const results = await Promise.all(
Object.entries(servers).map(async ([name, serverConfig]) => {
const configObj = serverConfig as Record<string, unknown>
let status = getServerStatusFromConfig(serverConfig)
const headers = serverConfig.headers as Record<string, string> | undefined
let tools: McpToolInfo[] = []
let needsAuth = false
try {
tools = await fetchToolsForServer(serverConfig)
} catch (error) {
console.error(`[MCP] Failed to fetch tools for ${name}:`, error)
}
const cacheKey = mcpCacheKey(scope, name)
if (tools.length > 0) {
status = "connected"
workingMcpServers.set(cacheKey, true)
} else {
workingMcpServers.set(cacheKey, false)
if (serverConfig.url) {
try {
const baseUrl = getMcpBaseUrl(serverConfig.url)
const metadata = await fetchOAuthMetadata(baseUrl)
needsAuth = !!metadata && !!metadata.authorization_endpoint
} catch {
// If probe fails, assume no auth needed
}
} else if (serverConfig.authType === "oauth" || serverConfig.authType === "bearer") {
needsAuth = true
}
if (needsAuth && !headers?.Authorization) {
status = "needs-auth"
} else {
// No tools and doesn't need auth - server failed to connect or has no tools
status = "failed"
}
}
return { name, status, tools, needsAuth, config: configObj }
})
)
return results
}
// Build list of all groups to process with timing
const groupTasks: Array<{
groupName: string
projectPath: string | null
promise: Promise<{
mcpServers: Array<{ name: string; status: string; tools: McpToolInfo[]; needsAuth: boolean; config: Record<string, unknown> }>
duration: number
}>
}> = []
// Global MCPs
if (config.mcpServers) {
groupTasks.push({
groupName: "Global",
projectPath: null,
promise: (async () => {
const start = Date.now()
const freshServers = await ensureMcpTokensFresh(config.mcpServers!, GLOBAL_MCP_PATH)
const mcpServers = await convertServers(freshServers, null) // null = global scope
return { mcpServers, duration: Date.now() - start }
})()
})
} else {
groupTasks.push({
groupName: "Global",
projectPath: null,
promise: Promise.resolve({ mcpServers: [], duration: 0 })
})
}
// Project MCPs
if (config.projects) {
for (const [projectPath, projectConfig] of Object.entries(config.projects)) {
if (projectConfig.mcpServers && Object.keys(projectConfig.mcpServers).length > 0) {
const groupName = path.basename(projectPath) || projectPath
groupTasks.push({
groupName,
projectPath,
promise: (async () => {
const start = Date.now()
const freshServers = await ensureMcpTokensFresh(projectConfig.mcpServers!, projectPath)
const mcpServers = await convertServers(freshServers, projectPath) // projectPath = scope
return { mcpServers, duration: Date.now() - start }
})()
})
}
}
}
// Process all groups in parallel
const results = await Promise.all(groupTasks.map(t => t.promise))
// Build groups with timing info
const groupsWithTiming = groupTasks.map((task, i) => ({
groupName: task.groupName,
projectPath: task.projectPath,
mcpServers: results[i].mcpServers,
duration: results[i].duration
}))
// Log performance (sorted by duration DESC)
const totalDuration = Date.now() - totalStart
const workingCount = [...workingMcpServers.values()].filter(v => v).length
const sortedByDuration = [...groupsWithTiming].sort((a, b) => b.duration - a.duration)
console.log(`[MCP] Cache updated in ${totalDuration}ms. Working: ${workingCount}/${workingMcpServers.size}`)
for (const g of sortedByDuration) {
if (g.mcpServers.length > 0) {
console.log(`[MCP] ${g.groupName}: ${g.duration}ms (${g.mcpServers.length} servers)`)
}
}
// Return groups without timing info
const groups = groupsWithTiming.map(({ groupName, projectPath, mcpServers }) => ({
groupName,
projectPath,
mcpServers
}))
// Plugin MCPs (from installed plugins)
const [enabledPluginSources, pluginMcpConfigs, approvedServers] = await Promise.all([
getEnabledPlugins(),
discoverPluginMcpServers(),
getApprovedPluginMcpServers(),
])
for (const pluginConfig of pluginMcpConfigs) {
// Only show MCP servers from enabled plugins
if (!enabledPluginSources.includes(pluginConfig.pluginSource)) continue
const globalServerNames = config.mcpServers ? Object.keys(config.mcpServers) : []
if (Object.keys(pluginConfig.mcpServers).length > 0) {
const pluginMcpServers = (await Promise.all(
Object.entries(pluginConfig.mcpServers).map(async ([name, serverConfig]) => {
// Skip servers that have been promoted to ~/.claude.json (e.g., after OAuth)
if (globalServerNames.includes(name)) return null
const configObj = serverConfig as Record<string, unknown>
const identifier = `${pluginConfig.pluginSource}:${name}`
const isApproved = approvedServers.includes(identifier)
if (!isApproved) {
return { name, status: "pending-approval", tools: [] as McpToolInfo[], needsAuth: false, config: configObj, isApproved }
}
// Try to get status and tools for approved servers
let status = getServerStatusFromConfig(serverConfig)
const headers = serverConfig.headers as Record<string, string> | undefined
let tools: McpToolInfo[] = []
let needsAuth = false
try {
tools = await fetchToolsForServer(serverConfig)
} catch (error) {
console.error(`[MCP] Failed to fetch tools for plugin ${name}:`, error)
}
if (tools.length > 0) {
status = "connected"
} else {
// Same OAuth detection logic as regular MCP servers
if (serverConfig.url) {
try {
const baseUrl = getMcpBaseUrl(serverConfig.url)
const metadata = await fetchOAuthMetadata(baseUrl)
needsAuth = !!metadata && !!metadata.authorization_endpoint
} catch {
// If probe fails, assume no auth needed
}
} else if (serverConfig.authType === "oauth" || serverConfig.authType === "bearer") {
needsAuth = true
}
if (needsAuth && !headers?.Authorization) {
status = "needs-auth"
} else {
status = "failed"
}
}
return { name, status, tools, needsAuth, config: configObj, isApproved }
})
)).filter((s): s is NonNullable<typeof s> => s !== null)
groups.push({
groupName: `Plugin: ${pluginConfig.pluginSource}`,
projectPath: null,
mcpServers: pluginMcpServers,
})
}
}
return { groups }
} catch (error) {
console.error("[getAllMcpConfig] Error:", error)
return { groups: [], error: String(error) }
}
}
export const claudeRouter = router({
/**
* Stream chat with Claude - single subscription handles everything
*/
chat: publicProcedure
.input(
z.object({
subChatId: z.string(),
chatId: z.string(),
prompt: z.string(),
cwd: z.string(),
projectPath: z.string().optional(), // Original project path for MCP config lookup
mode: z.enum(["plan", "agent"]).default("agent"),
sessionId: z.string().optional(),
model: z.string().optional(),
customConfig: z
.object({
model: z.string().min(1),
token: z.string(),
baseUrl: z.string().min(1),
})
.optional(),
maxThinkingTokens: z.number().optional(), // Enable extended thinking
images: z.array(imageAttachmentSchema).optional(), // Image attachments
historyEnabled: z.boolean().optional(),
offlineModeEnabled: z.boolean().optional(), // Whether offline mode (Ollama) is enabled in settings
enableTasks: z.boolean().optional(), // Enable task management tools (TodoWrite, Task agents)
}),
)
.subscription(({ input }) => {
return observable<UIMessageChunk>((emit) => {
// Abort any existing session for this subChatId before starting a new one
// This prevents race conditions if two messages are sent in quick succession
const existingController = activeSessions.get(input.subChatId)
if (existingController) {
existingController.abort()
}
const abortController = new AbortController()
const streamId = crypto.randomUUID()
activeSessions.set(input.subChatId, abortController)
// Stream debug logging
const subId = input.subChatId.slice(-8) // Short ID for logs
const streamStart = Date.now()
let chunkCount = 0
let lastChunkType = ""
// Shared sessionId for cleanup to save on abort
let currentSessionId: string | null = null
console.log(`[SD] M:START sub=${subId} stream=${streamId.slice(-8)} mode=${input.mode}`)
// Track if observable is still active (not unsubscribed)
let isObservableActive = true
// Helper to safely emit (no-op if already unsubscribed)
const safeEmit = (chunk: UIMessageChunk) => {
if (!isObservableActive) return false
try {
emit.next(chunk)
return true
} catch {
isObservableActive = false
return false
}
}
// Helper to safely complete (no-op if already closed)
const safeComplete = () => {
try {
emit.complete()
} catch {
// Already completed or closed
}
}
// Helper to emit error to frontend
const emitError = (error: unknown, context: string) => {
const errorMessage =
error instanceof Error ? error.message : String(error)
const errorStack = error instanceof Error ? error.stack : undefined
console.error(`[claude] ${context}:`, errorMessage)
if (errorStack) console.error("[claude] Stack:", errorStack)
// Send detailed error to frontend (safely)
safeEmit({
type: "error",
errorText: `${context}: ${errorMessage}`,
// Include extra debug info
...(process.env.NODE_ENV !== "production" && {
debugInfo: {
context,
cwd: input.cwd,
mode: input.mode,
PATH: process.env.PATH?.slice(0, 200),
},
}),
} as UIMessageChunk)
}
;(async () => {
try {
const db = getDatabase()
// 1. Get existing messages from DB
const existing = db
.select()
.from(subChats)
.where(eq(subChats.id, input.subChatId))
.get()
const existingMessages = JSON.parse(existing?.messages || "[]")
const existingSessionId = existing?.sessionId || null
// Get resumeSessionAt UUID only if shouldResume flag was set (by rollbackToMessage)
const lastAssistantMsg = [...existingMessages].reverse().find(
(m: any) => m.role === "assistant"
)
const resumeAtUuid = lastAssistantMsg?.metadata?.shouldResume
? (lastAssistantMsg?.metadata?.sdkMessageUuid || null)
: null
const historyEnabled = input.historyEnabled === true
// Check if last message is already this user message (avoid duplicate)
const lastMsg = existingMessages[existingMessages.length - 1]
const isDuplicate =
lastMsg?.role === "user" &&
lastMsg?.parts?.[0]?.text === input.prompt
// 2. Create user message and save BEFORE streaming (skip if duplicate)
let userMessage: any
let messagesToSave: any[]
if (isDuplicate) {
userMessage = lastMsg
messagesToSave = existingMessages
} else {
userMessage = {
id: crypto.randomUUID(),
role: "user",
parts: [{ type: "text", text: input.prompt }],
}
messagesToSave = [...existingMessages, userMessage]
db.update(subChats)
.set({
messages: JSON.stringify(messagesToSave),
streamId,
updatedAt: new Date(),
})
.where(eq(subChats.id, input.subChatId))
.run()
}
// 2.5. AUTO-FALLBACK: Check internet and switch to Ollama if offline
// Only check if offline mode is enabled in settings
const claudeCodeToken = getClaudeCodeToken()
const offlineResult = await checkOfflineFallback(
input.customConfig,
claudeCodeToken,
undefined, // selectedOllamaModel - will be read from customConfig if present
input.offlineModeEnabled ?? false, // Pass offline mode setting
)
if (offlineResult.error) {
emitError(new Error(offlineResult.error), 'Offline mode unavailable')
safeEmit({ type: 'finish' } as UIMessageChunk)
safeComplete()
return
}
// Use offline config if available
const finalCustomConfig = offlineResult.config || input.customConfig
const isUsingOllama = offlineResult.isUsingOllama
const resolvedCustomConfig = finalCustomConfig
? {
...finalCustomConfig,
token: decryptIfNeeded(finalCustomConfig.token),
}
: undefined
// Track connection method for analytics
let connectionMethod = "claude-subscription" // default (Claude Code OAuth)
if (isUsingOllama) {
connectionMethod = "offline-ollama"
} else if (resolvedCustomConfig) {
// Has custom config = either API key or custom model
const isDefaultAnthropicUrl = !resolvedCustomConfig.baseUrl ||
resolvedCustomConfig.baseUrl.includes("anthropic.com")
connectionMethod = isDefaultAnthropicUrl ? "api-key" : "custom-model"
}
setConnectionMethod(connectionMethod)
// Offline status is shown in sidebar, no need to emit message here
// (emitting text-delta without text-start breaks UI text rendering)
// 3. Get Claude SDK
let claudeQuery
try {
claudeQuery = await getClaudeQuery()
} catch (sdkError) {
emitError(sdkError, "Failed to load Claude SDK")
console.log(`[SD] M:END sub=${subId} reason=sdk_load_error n=${chunkCount}`)
safeEmit({ type: "finish" } as UIMessageChunk)
safeComplete()
return
}
const transform = createTransformer({
emitSdkMessageUuid: historyEnabled,
isUsingOllama,
})
// 4. Setup accumulation state
const parts: any[] = []
let currentText = ""
let metadata: any = {}
// Capture stderr from Claude process for debugging
const stderrLines: string[] = []
// Parse mentions from prompt (agents, skills, files, folders)
const { cleanedPrompt, agentMentions, skillMentions } = parseMentions(input.prompt)
// Build agents option for SDK (proper registration via options.agents)
const agentsOption = await buildAgentsOption(agentMentions, input.cwd)
// Log if agents were mentioned
if (agentMentions.length > 0) {
console.log(`[claude] Registering agents via SDK:`, Object.keys(agentsOption))
}
// Log if skills were mentioned
if (skillMentions.length > 0) {
console.log(`[claude] Skills mentioned:`, skillMentions)
}
// Build final prompt with skill instructions if needed
let finalPrompt = cleanedPrompt
// Handle empty prompt when only mentions are present
if (!finalPrompt.trim()) {
if (agentMentions.length > 0 && skillMentions.length > 0) {
finalPrompt = `Use the ${agentMentions.join(", ")} agent(s) and invoke the "${skillMentions.join('", "')}" skill(s) using the Skill tool for this task.`
} else if (agentMentions.length > 0) {
finalPrompt = `Use the ${agentMentions.join(", ")} agent(s) for this task.`
} else if (skillMentions.length > 0) {
finalPrompt = `Invoke the "${skillMentions.join('", "')}" skill(s) using the Skill tool for this task.`
}
} else if (skillMentions.length > 0) {
// Append skill instruction to existing prompt
finalPrompt = `${finalPrompt}\n\nUse the "${skillMentions.join('", "')}" skill(s) for this task.`
}
// Build prompt: if there are images, create an AsyncIterable<SDKUserMessage>
// Otherwise use simple string prompt
let prompt: string | AsyncIterable<any> = finalPrompt
if (input.images && input.images.length > 0) {
// Create message content array with images first, then text
const messageContent: any[] = [
...input.images.map((img) => ({
type: "image" as const,
source: {
type: "base64" as const,
media_type: img.mediaType,
data: img.base64Data,
},
})),
]
// Add text if present
if (finalPrompt.trim()) {
messageContent.push({
type: "text" as const,
text: finalPrompt,
})
}
// Create an async generator that yields a single SDKUserMessage
async function* createPromptWithImages() {
yield {
type: "user" as const,
message: {
role: "user" as const,
content: messageContent,
},
parent_tool_use_id: null,
}
}
prompt = createPromptWithImages()
}
// Build full environment for Claude SDK (includes HOME, PATH, etc.)
const claudeEnv = buildClaudeEnv({
...(resolvedCustomConfig && {
customEnv: {
...(resolvedCustomConfig.token && {
ANTHROPIC_AUTH_TOKEN: resolvedCustomConfig.token,
}),
ANTHROPIC_BASE_URL: resolvedCustomConfig.baseUrl,
},
}),
enableTasks: input.enableTasks ?? true,
})
// Debug logging in dev
if (process.env.NODE_ENV !== "production") {
logClaudeEnv(claudeEnv, `[${input.subChatId}] `)
}
// Create isolated config directory per subChat to prevent session contamination
// The Claude binary stores sessions in ~/.claude/ based on cwd, which causes
// cross-chat contamination when multiple chats use the same project folder
// For Ollama: use chatId instead of subChatId so all messages in the same chat share history
const isolatedConfigDir = path.join(
app.getPath("userData"),
"claude-sessions",
isUsingOllama ? input.chatId : input.subChatId
)
// MCP servers to pass to SDK (read from ~/.claude.json)
let mcpServersForSdk: Record<string, any> | undefined
// Ensure isolated config dir exists and symlink skills/agents from ~/.claude/
// This is needed because SDK looks for skills at $CLAUDE_CONFIG_DIR/skills/
// OPTIMIZATION: Only create symlinks once per subChatId (cached)
try {
await fs.mkdir(isolatedConfigDir, { recursive: true })
// Only create symlinks if not already created for this config dir
const cacheKey = isUsingOllama ? input.chatId : input.subChatId
if (!symlinksCreated.has(cacheKey)) {
const homeClaudeDir = path.join(os.homedir(), ".claude")
const skillsSource = path.join(homeClaudeDir, "skills")
const skillsTarget = path.join(isolatedConfigDir, "skills")
const agentsSource = path.join(homeClaudeDir, "agents")
const agentsTarget = path.join(isolatedConfigDir, "agents")
// Symlink skills directory if source exists and target doesn't
try {
const skillsSourceExists = await fs.stat(skillsSource).then(() => true).catch(() => false)
const skillsTargetExists = await fs.lstat(skillsTarget).then(() => true).catch(() => false)
if (skillsSourceExists && !skillsTargetExists) {
await fs.symlink(skillsSource, skillsTarget, "dir")
}
} catch (symlinkErr) {
// Ignore symlink errors (might already exist or permission issues)
}
// Symlink agents directory if source exists and target doesn't
try {
const agentsSourceExists = await fs.stat(agentsSource).then(() => true).catch(() => false)
const agentsTargetExists = await fs.lstat(agentsTarget).then(() => true).catch(() => false)
if (agentsSourceExists && !agentsTargetExists) {
await fs.symlink(agentsSource, agentsTarget, "dir")
}
} catch (symlinkErr) {
// Ignore symlink errors (might already exist or permission issues)
}
symlinksCreated.add(cacheKey)
}
// Read MCP servers from ~/.claude.json for the original project path
// These will be passed directly to the SDK via options.mcpServers
// OPTIMIZATION: Cache MCP config by file mtime to avoid re-parsing on every message
const claudeJsonSource = path.join(os.homedir(), ".claude.json")
try {
const stats = await fs.stat(claudeJsonSource).catch(() => null)
if (stats) {
const currentMtime = stats.mtimeMs
const cached = mcpConfigCache.get(claudeJsonSource)
const lookupPath = input.projectPath || input.cwd
// Get or refresh cached config
let claudeConfig: any
if (cached && cached.mtime === currentMtime) {
claudeConfig = cached.config
} else {
claudeConfig = JSON.parse(await fs.readFile(claudeJsonSource, "utf-8"))
mcpConfigCache.set(claudeJsonSource, { config: claudeConfig, mtime: currentMtime })
}
// Merge global + project servers (project overrides global)
// getProjectMcpServers resolves worktree paths internally
const globalServers = claudeConfig.mcpServers || {}
const projectServers = getProjectMcpServers(claudeConfig, lookupPath) || {}
// Load plugin MCP servers (filtered by enabled plugins and approval)
const [enabledPluginSources, pluginMcpConfigs, approvedServers] = await Promise.all([
getEnabledPlugins(),
discoverPluginMcpServers(),
getApprovedPluginMcpServers(),
])
const pluginServers: Record<string, McpServerConfig> = {}
for (const config of pluginMcpConfigs) {
if (enabledPluginSources.includes(config.pluginSource)) {
for (const [name, serverConfig] of Object.entries(config.mcpServers)) {
if (!globalServers[name] && !projectServers[name]) {
const identifier = `${config.pluginSource}:${name}`
if (approvedServers.includes(identifier)) {
pluginServers[name] = serverConfig
}
}
}
}
}
// Priority: project > global > plugin
const allServers = { ...pluginServers, ...globalServers, ...projectServers }
// Filter to only working MCPs using scoped cache keys
if (workingMcpServers.size > 0) {
const filtered: Record<string, any> = {}
// Resolve worktree path to original project path to match cache keys
const resolvedProjectPath = resolveProjectPathFromWorktree(lookupPath) || lookupPath
for (const [name, config] of Object.entries(allServers)) {
// Use resolved project scope if server is from project, otherwise global
const scope = name in projectServers ? resolvedProjectPath : null
const cacheKey = mcpCacheKey(scope, name)
// Include server if it's marked working, or if it's not in cache at all
// (plugin servers won't be in the cache yet)
if (workingMcpServers.get(cacheKey) === true || !workingMcpServers.has(cacheKey)) {
filtered[name] = config
}
}
mcpServersForSdk = filtered
const skipped = Object.keys(allServers).length - Object.keys(filtered).length
if (skipped > 0) {
console.log(`[claude] Filtered out ${skipped} non-working MCP(s)`)
}
} else {
mcpServersForSdk = allServers
}
}
} catch (configErr) {
console.error(`[claude] Failed to read MCP config:`, configErr)
}
} catch (mkdirErr) {
console.error(`[claude] Failed to setup isolated config dir:`, mkdirErr)
}
// Check if user has existing API key or proxy configured in their shell environment
// If so, use that instead of OAuth (allows using custom API proxies)
// Based on PR #29 by @sa4hnd
const hasExistingApiConfig = !!(claudeEnv.ANTHROPIC_API_KEY || claudeEnv.ANTHROPIC_BASE_URL)
if (hasExistingApiConfig) {
console.log(`[claude] Using existing CLI config - API_KEY: ${claudeEnv.ANTHROPIC_API_KEY ? "set" : "not set"}, BASE_URL: ${claudeEnv.ANTHROPIC_BASE_URL || "default"}`)
}
// Build final env - only add OAuth token if we have one AND no existing API config
// Existing CLI config takes precedence over OAuth
const finalEnv: {