-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathservice.ts
More file actions
2195 lines (1954 loc) · 65.9 KB
/
service.ts
File metadata and controls
2195 lines (1954 loc) · 65.9 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 type {
ContentBlock,
RequestPermissionRequest,
SessionConfigOption,
} from "@agentclientprotocol/sdk";
import {
setSessionResetCallback,
useAuthStore,
} from "@features/auth/stores/authStore";
import { useSessionAdapterStore } from "@features/sessions/stores/sessionAdapterStore";
import {
getPersistedConfigOptions,
removePersistedConfigOptions,
setPersistedConfigOptions,
updatePersistedConfigOptionValue,
} from "@features/sessions/stores/sessionConfigStore";
import type {
Adapter,
AgentSession,
} from "@features/sessions/stores/sessionStore";
import {
getConfigOptionByCategory,
mergeConfigOptions,
sessionStoreSetters,
} from "@features/sessions/stores/sessionStore";
import { useSettingsStore } from "@features/settings/stores/settingsStore";
import { taskViewedApi } from "@features/sidebar/hooks/useTaskViewed";
import { DEFAULT_GATEWAY_MODEL } from "@posthog/agent/gateway-models";
import { getIsOnline } from "@renderer/stores/connectivityStore";
import { trpcClient } from "@renderer/trpc/client";
import { toast } from "@renderer/utils/toast";
import { getCloudUrlFromRegion } from "@shared/constants/oauth";
import type {
CloudTaskUpdatePayload,
ExecutionMode,
Task,
} from "@shared/types";
import { ANALYTICS_EVENTS } from "@shared/types/analytics";
import type { AcpMessage, StoredLogEntry } from "@shared/types/session-events";
import { isJsonRpcRequest } from "@shared/types/session-events";
import { track } from "@utils/analytics";
import { logger } from "@utils/logger";
import {
notifyPermissionRequest,
notifyPromptComplete,
} from "@utils/notifications";
import { queryClient } from "@utils/queryClient";
import {
convertStoredEntriesToEvents,
createUserMessageEvent,
createUserShellExecuteEvent,
extractPromptText,
getUserShellExecutesSinceLastPrompt,
isFatalSessionError,
normalizePromptToBlocks,
shellExecutesToContextBlocks,
} from "@utils/session";
const log = logger.scope("session-service");
export const PREVIEW_TASK_ID = "__preview__";
interface AuthCredentials {
apiKey: string;
apiHost: string;
projectId: number;
client: ReturnType<typeof useAuthStore.getState>["client"];
}
export interface ConnectParams {
task: Task;
repoPath: string;
initialPrompt?: ContentBlock[];
executionMode?: ExecutionMode;
adapter?: "claude" | "codex";
model?: string;
reasoningLevel?: string;
}
// --- Singleton Service Instance ---
let serviceInstance: SessionService | null = null;
export function getSessionService(): SessionService {
if (!serviceInstance) {
serviceInstance = new SessionService();
}
return serviceInstance;
}
export function resetSessionService(): void {
if (serviceInstance) {
serviceInstance.reset();
serviceInstance = null;
}
sessionStoreSetters.clearAll();
trpcClient.agent.resetAll.mutate().catch((err) => {
log.error("Failed to reset all sessions on main process", err);
});
}
setSessionResetCallback(resetSessionService);
export class SessionService {
private connectingTasks = new Map<string, Promise<void>>();
private subscriptions = new Map<
string,
{
event: { unsubscribe: () => void };
permission?: { unsubscribe: () => void };
}
>();
/** AbortController for the current in-flight preview session start */
private previewAbort: AbortController | null = null;
/** Active cloud task watchers, keyed by taskId */
private cloudTaskWatchers = new Map<
string,
{
runId: string;
subscription: { unsubscribe: () => void };
onStatusChange?: () => void;
}
>();
private idleKilledSubscription: { unsubscribe: () => void } | null = null;
constructor() {
this.idleKilledSubscription =
trpcClient.agent.onSessionIdleKilled.subscribe(undefined, {
onData: (event: { taskRunId: string }) => {
const { taskRunId } = event;
log.info("Session idle-killed by main process", { taskRunId });
this.teardownSession(taskRunId);
},
onError: (err: unknown) => {
log.debug("Idle-killed subscription error", { error: err });
},
});
}
/**
* Connect to a task session.
* Uses locking to prevent duplicate concurrent connections.
*/
async connectToTask(params: ConnectParams): Promise<void> {
const { task } = params;
const taskId = task.id;
log.info("Connecting to task", { taskId });
// Return existing connection promise if already connecting
const existingPromise = this.connectingTasks.get(taskId);
if (existingPromise) {
log.info("Already connecting to task, returning existing promise", {
taskId,
});
return existingPromise;
}
// Check for existing connected session
const existingSession = sessionStoreSetters.getSessionByTaskId(taskId);
if (existingSession?.status === "connected") {
log.info("Already connected to task", { taskId });
return;
}
if (existingSession?.status === "connecting") {
log.info("Session already in connecting state", { taskId });
return;
}
// Create and store the connection promise
const connectPromise = this.doConnect(params).finally(() => {
this.connectingTasks.delete(taskId);
});
this.connectingTasks.set(taskId, connectPromise);
return connectPromise;
}
private async doConnect(params: ConnectParams): Promise<void> {
const {
task,
repoPath,
initialPrompt,
executionMode,
adapter,
model,
reasoningLevel,
} = params;
const { id: taskId, latest_run: latestRun } = task;
const taskTitle = task.title || task.description || "Task";
try {
const auth = this.getAuthCredentials();
if (!auth) {
log.error("Missing auth credentials");
const taskRunId = latestRun?.id ?? `error-${taskId}`;
const session = this.createBaseSession(taskRunId, taskId, taskTitle);
session.status = "error";
session.errorMessage =
"Authentication required. Please sign in to continue.";
sessionStoreSetters.setSession(session);
return;
}
if (latestRun?.id && latestRun?.log_url) {
if (!getIsOnline()) {
log.info("Skipping connection attempt - offline", { taskId });
const { rawEntries } = await this.fetchSessionLogs(
latestRun.log_url,
latestRun.id,
);
const events = convertStoredEntriesToEvents(rawEntries);
const session = this.createBaseSession(
latestRun.id,
taskId,
taskTitle,
);
session.events = events;
session.logUrl = latestRun.log_url;
session.status = "disconnected";
session.errorMessage =
"No internet connection. Connect when you're back online.";
sessionStoreSetters.setSession(session);
return;
}
const [workspaceResult, logResult] = await Promise.all([
trpcClient.workspace.verify.query({ taskId }),
this.fetchSessionLogs(latestRun.log_url, latestRun.id),
]);
if (!workspaceResult.exists) {
log.warn("Workspace no longer exists, showing error state", {
taskId,
missingPath: workspaceResult.missingPath,
});
const events = convertStoredEntriesToEvents(logResult.rawEntries);
const session = this.createBaseSession(
latestRun.id,
taskId,
taskTitle,
);
session.events = events;
session.logUrl = latestRun.log_url;
session.status = "error";
session.errorMessage = workspaceResult.missingPath
? `Working directory no longer exists: ${workspaceResult.missingPath}`
: "The working directory for this task no longer exists. Please start a new session.";
sessionStoreSetters.setSession(session);
return;
}
await this.reconnectToLocalSession(
taskId,
latestRun.id,
taskTitle,
latestRun.log_url,
repoPath,
auth,
logResult,
);
} else {
if (!getIsOnline()) {
log.info("Skipping connection attempt - offline", { taskId });
const taskRunId = latestRun?.id ?? `offline-${taskId}`;
const session = this.createBaseSession(taskRunId, taskId, taskTitle);
session.status = "disconnected";
session.errorMessage =
"No internet connection. Connect when you're back online.";
sessionStoreSetters.setSession(session);
return;
}
await this.createNewLocalSession(
taskId,
taskTitle,
repoPath,
auth,
initialPrompt,
executionMode,
adapter,
model,
reasoningLevel,
);
}
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
log.error("Failed to connect to task", { message });
const taskRunId = latestRun?.id ?? `error-${taskId}`;
const session = this.createBaseSession(taskRunId, taskId, taskTitle);
session.status = "error";
session.errorTitle = "Failed to connect";
session.errorMessage = message;
if (latestRun?.log_url) {
try {
const { rawEntries } = await this.fetchSessionLogs(
latestRun.log_url,
latestRun.id,
);
session.events = convertStoredEntriesToEvents(rawEntries);
session.logUrl = latestRun.log_url;
} catch {
// Ignore log fetch errors
}
}
sessionStoreSetters.setSession(session);
}
}
private async reconnectToLocalSession(
taskId: string,
taskRunId: string,
taskTitle: string,
logUrl: string | undefined,
repoPath: string,
auth: AuthCredentials,
prefetchedLogs?: {
rawEntries: StoredLogEntry[];
sessionId?: string;
adapter?: Adapter;
},
): Promise<void> {
const { rawEntries, sessionId, adapter } =
prefetchedLogs ?? (await this.fetchSessionLogs(logUrl, taskRunId));
const events = convertStoredEntriesToEvents(rawEntries);
const storedAdapter = useSessionAdapterStore
.getState()
.getAdapter(taskRunId);
const resolvedAdapter = adapter ?? storedAdapter;
const persistedConfigOptions = getPersistedConfigOptions(taskRunId);
const session = this.createBaseSession(taskRunId, taskId, taskTitle);
session.events = events;
if (logUrl) {
session.logUrl = logUrl;
}
if (persistedConfigOptions) {
session.configOptions = persistedConfigOptions;
}
if (resolvedAdapter) {
session.adapter = resolvedAdapter;
useSessionAdapterStore.getState().setAdapter(taskRunId, resolvedAdapter);
}
sessionStoreSetters.setSession(session);
this.subscribeToChannel(taskRunId);
try {
const persistedMode = getConfigOptionByCategory(
persistedConfigOptions,
"mode",
)?.currentValue;
trpcClient.workspace.verify
.query({ taskId })
.then((workspaceResult) => {
if (!workspaceResult.exists) {
log.warn("Workspace no longer exists", {
taskId,
missingPath: workspaceResult.missingPath,
});
sessionStoreSetters.updateSession(taskRunId, {
status: "error",
errorMessage: workspaceResult.missingPath
? `Working directory no longer exists: ${workspaceResult.missingPath}`
: "The working directory for this task no longer exists. Please start a new session.",
});
}
})
.catch((err) => {
log.warn("Failed to verify workspace", { taskId, err });
});
const { customInstructions } = useSettingsStore.getState();
const result = await trpcClient.agent.reconnect.mutate({
taskId,
taskRunId,
repoPath,
apiKey: auth.apiKey,
apiHost: auth.apiHost,
projectId: auth.projectId,
logUrl,
sessionId,
adapter: resolvedAdapter,
permissionMode: persistedMode,
customInstructions: customInstructions || undefined,
});
if (result) {
// Cast and merge live configOptions with persisted values.
// Fall back to persisted options if the agent doesn't return any
// (e.g. after session compaction).
let configOptions = result.configOptions as
| SessionConfigOption[]
| undefined;
if (configOptions && persistedConfigOptions) {
configOptions = mergeConfigOptions(
configOptions,
persistedConfigOptions,
);
} else if (!configOptions) {
configOptions = persistedConfigOptions ?? undefined;
}
sessionStoreSetters.updateSession(taskRunId, {
status: "connected",
configOptions,
});
// Persist the merged config options
if (configOptions) {
setPersistedConfigOptions(taskRunId, configOptions);
}
// Restore persisted config options to server in parallel
if (persistedConfigOptions) {
await Promise.all(
persistedConfigOptions.map((opt) =>
trpcClient.agent.setConfigOption
.mutate({
sessionId: taskRunId,
configId: opt.id,
value: opt.currentValue,
})
.catch((error) => {
log.warn(
"Failed to restore persisted config option after reconnect",
{
taskId,
configId: opt.id,
error,
},
);
}),
),
);
}
} else {
log.warn("Reconnect returned null", { taskId, taskRunId });
this.setErrorSession(
taskId,
taskRunId,
taskTitle,
"Session could not be resumed. Please retry or start a new session.",
);
}
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : String(error);
log.warn("Reconnect failed", { taskId, error: errorMessage });
this.setErrorSession(
taskId,
taskRunId,
taskTitle,
errorMessage ||
"Failed to reconnect. Please retry or start a new session.",
);
}
}
private async teardownSession(taskRunId: string): Promise<void> {
try {
await trpcClient.agent.cancel.mutate({ sessionId: taskRunId });
} catch (error) {
log.debug("Cancel during teardown failed (session may already be gone)", {
taskRunId,
error: error instanceof Error ? error.message : String(error),
});
}
this.unsubscribeFromChannel(taskRunId);
sessionStoreSetters.removeSession(taskRunId);
useSessionAdapterStore.getState().removeAdapter(taskRunId);
removePersistedConfigOptions(taskRunId);
}
private setErrorSession(
taskId: string,
taskRunId: string,
taskTitle: string,
errorMessage: string,
errorTitle?: string,
): void {
// Preserve events and logUrl from the existing session so the
// retry / reset flows can re-hydrate without a fresh log fetch.
// Note: the error overlay is opaque, so these events aren't visible
// to the user — they're carried forward for the next reconnect attempt.
const existing = sessionStoreSetters.getSessionByTaskId(taskId);
const session = this.createBaseSession(taskRunId, taskId, taskTitle);
session.status = "error";
session.errorTitle = errorTitle;
session.errorMessage = errorMessage;
if (existing?.events?.length) {
session.events = existing.events;
}
if (existing?.logUrl) {
session.logUrl = existing.logUrl;
}
sessionStoreSetters.setSession(session);
}
private async createNewLocalSession(
taskId: string,
taskTitle: string,
repoPath: string,
auth: AuthCredentials,
initialPrompt?: ContentBlock[],
executionMode?: ExecutionMode,
adapter?: "claude" | "codex",
model?: string,
reasoningLevel?: string,
): Promise<void> {
const { client } = auth;
if (!client) {
throw new Error("Unable to reach server. Please check your connection.");
}
const taskRun = await client.createTaskRun(taskId);
if (!taskRun?.id) {
throw new Error("Failed to create task run. Please try again.");
}
const { customInstructions: startCustomInstructions } =
useSettingsStore.getState();
const result = await trpcClient.agent.start.mutate({
taskId,
taskRunId: taskRun.id,
repoPath,
apiKey: auth.apiKey,
apiHost: auth.apiHost,
projectId: auth.projectId,
permissionMode: executionMode,
adapter,
customInstructions: startCustomInstructions || undefined,
});
const session = this.createBaseSession(taskRun.id, taskId, taskTitle);
session.channel = result.channel;
session.status = "connected";
session.adapter = adapter;
const configOptions = result.configOptions as
| SessionConfigOption[]
| undefined;
session.configOptions = configOptions;
// Persist the config options
if (configOptions) {
setPersistedConfigOptions(taskRun.id, configOptions);
}
// Persist the adapter
if (adapter) {
useSessionAdapterStore.getState().setAdapter(taskRun.id, adapter);
}
sessionStoreSetters.setSession(session);
this.subscribeToChannel(taskRun.id);
track(ANALYTICS_EVENTS.TASK_RUN_STARTED, {
task_id: taskId,
execution_type: "local",
});
const preferredModel = model ?? DEFAULT_GATEWAY_MODEL;
const configPromises: Promise<void>[] = [];
if (preferredModel) {
configPromises.push(
this.setSessionConfigOptionByCategory(
taskId,
"model",
preferredModel,
).catch((err) => log.warn("Failed to set model", { taskId, err })),
);
}
if (reasoningLevel) {
configPromises.push(
this.setSessionConfigOptionByCategory(
taskId,
"thought_level",
reasoningLevel,
).catch((err) =>
log.warn("Failed to set reasoning level", { taskId, err }),
),
);
}
if (configPromises.length > 0) {
await Promise.all(configPromises);
}
if (initialPrompt?.length) {
await this.sendPrompt(taskId, initialPrompt);
}
}
async disconnectFromTask(taskId: string): Promise<void> {
const session = sessionStoreSetters.getSessionByTaskId(taskId);
if (!session) return;
await this.teardownSession(session.taskRunId);
}
// --- Preview Session Management ---
async startPreviewSession(params: {
adapter: "claude" | "codex";
}): Promise<void> {
this.previewAbort?.abort();
const abort = new AbortController();
this.previewAbort = abort;
await this.cleanupPreviewSession();
if (abort.signal.aborted) return;
const auth = this.getAuthCredentials();
if (!auth) {
log.info("Skipping preview session - not authenticated");
return;
}
const taskRunId = `preview-${crypto.randomUUID()}`;
const session = this.createBaseSession(
taskRunId,
PREVIEW_TASK_ID,
"Preview",
);
session.adapter = params.adapter;
sessionStoreSetters.setSession(session);
try {
const { customInstructions: previewCustomInstructions } =
useSettingsStore.getState();
const result = await trpcClient.agent.start.mutate({
taskId: PREVIEW_TASK_ID,
taskRunId,
repoPath: "__preview__",
apiKey: auth.apiKey,
apiHost: auth.apiHost,
projectId: auth.projectId,
adapter: params.adapter,
permissionMode: "plan",
customInstructions: previewCustomInstructions || undefined,
});
if (abort.signal.aborted) {
trpcClient.agent.cancel
.mutate({ sessionId: taskRunId })
.catch((err) => {
log.warn("Failed to cancel stale preview session", {
taskRunId,
error: err,
});
});
sessionStoreSetters.removeSession(taskRunId);
return;
}
const configOptions = result.configOptions as
| SessionConfigOption[]
| undefined;
sessionStoreSetters.updateSession(taskRunId, {
status: "connected",
channel: result.channel,
configOptions,
});
this.subscribeToChannel(taskRunId);
log.info("Preview session started", {
taskRunId,
adapter: params.adapter,
configOptionsCount: configOptions?.length ?? 0,
});
} catch (error) {
if (abort.signal.aborted) return;
log.error("Failed to start preview session", { error });
sessionStoreSetters.removeSession(taskRunId);
}
}
async cancelPreviewSession(): Promise<void> {
this.previewAbort?.abort();
this.previewAbort = null;
await this.cleanupPreviewSession();
}
private async cleanupPreviewSession(): Promise<void> {
const session = sessionStoreSetters.getSessionByTaskId(PREVIEW_TASK_ID);
if (!session) return;
const { taskRunId } = session;
this.unsubscribeFromChannel(taskRunId);
sessionStoreSetters.removeSession(taskRunId);
try {
await trpcClient.agent.cancel.mutate({ sessionId: taskRunId });
} catch (error) {
log.warn("Failed to cancel preview session", { taskRunId, error });
}
}
// --- Subscription Management ---
private subscribeToChannel(taskRunId: string): void {
if (this.subscriptions.has(taskRunId)) {
return;
}
const eventSubscription = trpcClient.agent.onSessionEvent.subscribe(
{ taskRunId },
{
onData: (payload: unknown) => {
this.handleSessionEvent(taskRunId, payload as AcpMessage);
},
onError: (err) => {
log.error("Session subscription error", { taskRunId, error: err });
sessionStoreSetters.updateSession(taskRunId, {
status: "error",
errorMessage:
"Lost connection to the agent. Please restart the task.",
});
},
},
);
const permissionSubscription =
trpcClient.agent.onPermissionRequest.subscribe(
{ taskRunId },
{
onData: async (payload) => {
this.handlePermissionRequest(taskRunId, payload);
},
onError: (err) => {
log.error("Permission subscription error", {
taskRunId,
error: err,
});
},
},
);
this.subscriptions.set(taskRunId, {
event: eventSubscription,
permission: permissionSubscription,
});
}
private unsubscribeFromChannel(taskRunId: string): void {
const subscription = this.subscriptions.get(taskRunId);
subscription?.event.unsubscribe();
subscription?.permission?.unsubscribe();
this.subscriptions.delete(taskRunId);
}
/**
* Reset all service state and clean up subscriptions.
* Called on logout or app reset.
*/
reset(): void {
log.info("Resetting session service", {
subscriptionCount: this.subscriptions.size,
connectingCount: this.connectingTasks.size,
cloudWatcherCount: this.cloudTaskWatchers.size,
});
// Unsubscribe from all active subscriptions
for (const taskRunId of this.subscriptions.keys()) {
this.unsubscribeFromChannel(taskRunId);
}
// Clean up all cloud task watchers
for (const taskId of [...this.cloudTaskWatchers.keys()]) {
this.stopCloudTaskWatch(taskId);
}
this.connectingTasks.clear();
this.previewAbort?.abort();
this.previewAbort = null;
this.idleKilledSubscription?.unsubscribe();
this.idleKilledSubscription = null;
}
private updatePromptStateFromEvents(
taskRunId: string,
events: AcpMessage[],
): void {
for (const acpMsg of events) {
const msg = acpMsg.message;
if (isJsonRpcRequest(msg) && msg.method === "session/prompt") {
sessionStoreSetters.updateSession(taskRunId, {
isPromptPending: true,
promptStartedAt: acpMsg.ts,
});
}
if (
"id" in msg &&
"result" in msg &&
typeof msg.result === "object" &&
msg.result !== null &&
"stopReason" in msg.result
) {
sessionStoreSetters.updateSession(taskRunId, {
isPromptPending: false,
promptStartedAt: null,
});
}
}
}
private handleSessionEvent(taskRunId: string, acpMsg: AcpMessage): void {
const session = sessionStoreSetters.getSessions()[taskRunId];
if (!session) return;
const isUserPromptEcho =
isJsonRpcRequest(acpMsg.message) &&
acpMsg.message.method === "session/prompt";
if (isUserPromptEcho) {
sessionStoreSetters.replaceOptimisticWithEvent(taskRunId, acpMsg);
} else {
sessionStoreSetters.appendEvents(taskRunId, [acpMsg]);
}
this.updatePromptStateFromEvents(taskRunId, [acpMsg]);
const msg = acpMsg.message;
if (
"id" in msg &&
"result" in msg &&
typeof msg.result === "object" &&
msg.result !== null &&
"stopReason" in msg.result
) {
const stopReason = (msg.result as { stopReason?: string }).stopReason;
const hasQueuedMessages =
session.messageQueue.length > 0 && session.status === "connected";
// Only notify when queue is empty - queued messages will start a new turn
if (stopReason && !hasQueuedMessages) {
notifyPromptComplete(session.taskTitle, stopReason, session.taskId);
}
taskViewedApi.markActivity(session.taskId);
// Process queued messages after turn completes - send all as one prompt
if (hasQueuedMessages) {
setTimeout(() => {
this.sendQueuedMessages(session.taskId).catch((err) => {
log.error("Failed to send queued messages", {
taskId: session.taskId,
error: err,
});
});
}, 0);
}
}
if ("method" in msg && msg.method === "session/update" && "params" in msg) {
const params = msg.params as {
update?: {
sessionUpdate?: string;
configOptions?: SessionConfigOption[];
};
};
// Handle config option updates (replaces current_mode_update)
if (
params?.update?.sessionUpdate === "config_option_update" &&
params.update.configOptions
) {
const configOptions = params.update.configOptions;
sessionStoreSetters.updateSession(taskRunId, {
configOptions,
});
// Persist the updated config options
setPersistedConfigOptions(taskRunId, configOptions);
log.info("Session config options updated", { taskRunId });
}
}
// Handle _posthog/sdk_session notifications for adapter info
if (
"method" in msg &&
msg.method === "_posthog/sdk_session" &&
"params" in msg
) {
const params = msg.params as {
adapter?: Adapter;
};
if (params?.adapter) {
sessionStoreSetters.updateSession(taskRunId, {
adapter: params.adapter,
});
useSessionAdapterStore.getState().setAdapter(taskRunId, params.adapter);
log.info("Session adapter updated", {
taskRunId,
adapter: params.adapter,
});
}
}
}
private handlePermissionRequest(
taskRunId: string,
payload: Omit<RequestPermissionRequest, "sessionId"> & {
taskRunId: string;
},
): void {
log.info("Permission request received in renderer", {
taskRunId,
toolCallId: payload.toolCall.toolCallId,
title: payload.toolCall.title,
});
// Get fresh session state
const session = sessionStoreSetters.getSessions()[taskRunId];
if (!session) {
log.warn("Session not found for permission request", {
taskRunId,
});
return;
}
const newPermissions = new Map(session.pendingPermissions);
// Add receivedAt to create PermissionRequest
newPermissions.set(payload.toolCall.toolCallId, {
...payload,
receivedAt: Date.now(),
});
sessionStoreSetters.setPendingPermissions(taskRunId, newPermissions);
taskViewedApi.markActivity(session.taskId);
notifyPermissionRequest(session.taskTitle, session.taskId);
}
// --- Prompt Handling ---
/**
* Send a prompt to the agent.
* Queues if a prompt is already pending.
*/
async sendPrompt(
taskId: string,
prompt: string | ContentBlock[],
): Promise<{ stopReason: string }> {
if (!getIsOnline()) {
throw new Error(
"No internet connection. Please check your connection and try again.",
);
}
const session = sessionStoreSetters.getSessionByTaskId(taskId);
if (!session) throw new Error("No active session for task");
if (session.isCloud) {
return this.sendCloudPrompt(session, prompt);
}
if (session.status !== "connected") {
if (session.status === "error") {
throw new Error(
session.errorMessage ||
"Session is in error state. Please retry or start a new session.",
);
}
if (session.status === "connecting") {
throw new Error(
"Session is still connecting. Please wait and try again.",
);
}
throw new Error(`Session is not ready (status: ${session.status})`);
}
if (session.isPromptPending) {
const promptText = extractPromptText(prompt);
sessionStoreSetters.enqueueMessage(taskId, promptText);
log.info("Message queued", {
taskId,
queueLength: session.messageQueue.length + 1,
});
return { stopReason: "queued" };
}
let blocks = normalizePromptToBlocks(prompt);
const shellExecutes = getUserShellExecutesSinceLastPrompt(session.events);
if (shellExecutes.length > 0) {
const contextBlocks = shellExecutesToContextBlocks(shellExecutes);
blocks = [...contextBlocks, ...blocks];
}
const promptText = extractPromptText(prompt);