@wherever-dev/client 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/client.ts ADDED
@@ -0,0 +1,888 @@
1
+ import { writable, get, type Writable } from "sveltore";
2
+ import { type ChatMessage, type WhereverState } from "./types.js";
3
+
4
+ export interface WhereverClientConfig {
5
+ host: string;
6
+ port: number | string;
7
+ token?: string;
8
+ secure?: boolean;
9
+ WebSocketCtor?: any;
10
+ hideThinking?: boolean;
11
+ hideTools?: boolean;
12
+ }
13
+
14
+ const defaultState: WhereverState = {
15
+ connected: false,
16
+ connecting: false,
17
+ creatingSession: false,
18
+ error: null,
19
+ session: null,
20
+ sessionId: null,
21
+ isStreaming: false,
22
+ messages: [],
23
+ clientId: null,
24
+ conflict: null,
25
+ isInterrupted: false,
26
+ sessionError: null,
27
+ readOnly: false,
28
+ activeSessionFile: null,
29
+ activeCwd: null,
30
+ activeModel: null,
31
+ hideThinking: false,
32
+ hideTools: false,
33
+ historyTotalCount: 0,
34
+ historyOffset: 0,
35
+ loadingMoreHistory: false,
36
+ };
37
+
38
+ export class WhereverClient {
39
+ private ws: any = null;
40
+ private config: WhereverClientConfig;
41
+ public stateStore: Writable<WhereverState>;
42
+ private reconnectTimer: any = null;
43
+ private agentEndTimeout: any = null;
44
+ private reconnectAttempts = 0;
45
+ private reconnectDelay = 2000;
46
+ private maxReconnectDelay = 15000;
47
+ private isInitialConnect = true;
48
+ private listeners = new Set<(msg: any) => void>();
49
+ private pendingUploads = new Map<string, {resolve: (val: any) => void, reject: (err: any) => void}>();
50
+
51
+ constructor(config: WhereverClientConfig) {
52
+ this.config = {
53
+ secure: true,
54
+ ...config
55
+ };
56
+ this.stateStore = writable<WhereverState>({
57
+ ...defaultState,
58
+ hideThinking: !!this.config.hideThinking,
59
+ hideTools: !!this.config.hideTools,
60
+ });
61
+ }
62
+
63
+ public connect(newConfig?: Partial<WhereverClientConfig>) {
64
+ if (newConfig) {
65
+ this.config = {
66
+ ...this.config,
67
+ ...newConfig
68
+ };
69
+ }
70
+
71
+ this.disconnect(false);
72
+
73
+ this.stateStore.update(s => ({
74
+ ...defaultState,
75
+ connecting: true,
76
+ hideThinking: !!this.config.hideThinking,
77
+ hideTools: !!this.config.hideTools,
78
+ }));
79
+
80
+ const protocol = this.config.secure ? "wss" : "ws";
81
+ const host = this.config.host.startsWith('http')
82
+ ? this.config.host.replace(/^https?:\/\//, '')
83
+ : this.config.host;
84
+ const tokenQuery = this.config.token ? `?token=${encodeURIComponent(this.config.token)}` : "";
85
+ const wsUrl = `${protocol}://${host}:${this.config.port}/ws${tokenQuery}`;
86
+
87
+ const WebSocketImpl = this.config.WebSocketCtor || (typeof globalThis !== 'undefined' ? (globalThis as any).WebSocket : null);
88
+
89
+ if (!WebSocketImpl) {
90
+ this.stateStore.update(s => ({
91
+ ...s,
92
+ connecting: false,
93
+ error: "No WebSocket implementation found. Please pass custom WebSocketCtor."
94
+ }));
95
+ return;
96
+ }
97
+
98
+ try {
99
+ const wsOptions = this.config.secure && this.config.WebSocketCtor ? { rejectUnauthorized: false } : undefined;
100
+ this.ws = wsOptions ? new WebSocketImpl(wsUrl, wsOptions) : new WebSocketImpl(wsUrl);
101
+ } catch (err) {
102
+ this.stateStore.update(s => ({
103
+ ...s,
104
+ connecting: false,
105
+ error: `Failed to connect: ${err}`
106
+ }));
107
+ this.scheduleReconnect();
108
+ return;
109
+ }
110
+
111
+ const currentWs = this.ws;
112
+
113
+ const onOpen = () => {
114
+ if (this.ws !== currentWs) return;
115
+ this.reconnectAttempts = 0;
116
+ this.reconnectDelay = 2000;
117
+ this.isInitialConnect = false;
118
+ this.stateStore.update(s => ({
119
+ ...s,
120
+ connected: true,
121
+ connecting: false,
122
+ error: null
123
+ }));
124
+ };
125
+
126
+ const onMessage = (event: any) => {
127
+ if (this.ws !== currentWs) return;
128
+ try {
129
+ const rawData = typeof event.data === 'string' ? event.data : event.data.toString();
130
+ const msg = JSON.parse(rawData);
131
+ this.handleMessage(msg);
132
+ } catch (err) {
133
+ console.error("Failed to parse WebSocket message:", err);
134
+ }
135
+ };
136
+
137
+ const onClose = () => {
138
+ if (this.ws !== currentWs) return;
139
+ this.ws = null;
140
+ this.stateStore.update(s => ({
141
+ ...s,
142
+ connected: false,
143
+ connecting: false,
144
+ }));
145
+ this.scheduleReconnect();
146
+ };
147
+
148
+ const onError = (err: any) => {
149
+ if (this.ws !== currentWs) return;
150
+ this.stateStore.update(s => ({
151
+ ...s,
152
+ error: s.error || 'Connection error occurred'
153
+ }));
154
+ };
155
+
156
+ if (typeof currentWs.addEventListener === 'function') {
157
+ currentWs.addEventListener('open', onOpen);
158
+ currentWs.addEventListener('message', onMessage);
159
+ currentWs.addEventListener('close', onClose);
160
+ currentWs.addEventListener('error', onError);
161
+ } else if (typeof currentWs.on === 'function') {
162
+ currentWs.on('open', onOpen);
163
+ currentWs.on('message', (data: any) => onMessage({ data }));
164
+ currentWs.on('close', onClose);
165
+ currentWs.on('error', onError);
166
+ }
167
+ }
168
+
169
+ public disconnect(resetState = true) {
170
+ if (this.reconnectTimer) {
171
+ clearTimeout(this.reconnectTimer);
172
+ this.reconnectTimer = null;
173
+ }
174
+
175
+ if (this.ws) {
176
+ try {
177
+ if (typeof this.ws.removeAllListeners === 'function') {
178
+ this.ws.removeAllListeners();
179
+ }
180
+ this.ws.close();
181
+ } catch (err) {}
182
+ this.ws = null;
183
+ }
184
+
185
+ if (resetState) {
186
+ this.stateStore.set({
187
+ ...defaultState,
188
+ hideThinking: !!this.config.hideThinking,
189
+ hideTools: !!this.config.hideTools,
190
+ });
191
+ }
192
+ }
193
+
194
+ private scheduleReconnect() {
195
+ if (this.reconnectTimer) return;
196
+
197
+ this.reconnectTimer = setTimeout(() => {
198
+ this.reconnectTimer = null;
199
+ this.reconnectDelay = Math.min(this.reconnectDelay * 1.5, this.maxReconnectDelay);
200
+
201
+ this.stateStore.update(s => ({
202
+ ...s,
203
+ connecting: true,
204
+ error: 'Reconnecting...',
205
+ }));
206
+
207
+ this.connect();
208
+ }, this.reconnectDelay);
209
+ }
210
+
211
+ private handleMessage(msg: any) {
212
+ for (const listener of this.listeners) {
213
+ try {
214
+ listener(msg);
215
+ } catch (err) {
216
+ console.error("Error in message listener:", err);
217
+ }
218
+ }
219
+
220
+ switch (msg.type) {
221
+ case 'connected':
222
+ this.stateStore.update((s: WhereverState) => ({
223
+ ...s,
224
+ connected: true,
225
+ connecting: false,
226
+ clientId: msg.clientId,
227
+ error: null,
228
+ }));
229
+ break;
230
+
231
+ case 'file_uploaded': {
232
+ const pending = this.pendingUploads.get(msg.uploadId);
233
+ if (pending) {
234
+ pending.resolve({savedPath: msg.savedPath, filename: msg.filename});
235
+ this.pendingUploads.delete(msg.uploadId);
236
+ }
237
+ break;
238
+ }
239
+
240
+ case 'file_upload_error': {
241
+ const pending = this.pendingUploads.get(msg.uploadId);
242
+ if (pending) {
243
+ pending.reject(new Error(msg.error));
244
+ this.pendingUploads.delete(msg.uploadId);
245
+ }
246
+ break;
247
+ }
248
+
249
+ case 'agent_start':
250
+ if (this.agentEndTimeout) {
251
+ clearTimeout(this.agentEndTimeout);
252
+ this.agentEndTimeout = null;
253
+ }
254
+ this.stateStore.update((s: WhereverState) => ({...s, isStreaming: true}));
255
+ break;
256
+
257
+ case 'thinking_update':
258
+ this.stateStore.update((s: WhereverState) => {
259
+ let lastThinking = [...s.messages]
260
+ .reverse()
261
+ .find((m: ChatMessage) => m.role === 'thinking' && m.isStreaming);
262
+ if (!lastThinking) {
263
+ const newMsg: ChatMessage = {
264
+ id: this.generateId(),
265
+ role: 'thinking',
266
+ content: msg.delta,
267
+ timestamp: Date.now(),
268
+ isStreaming: true,
269
+ };
270
+ return {...s, messages: [...s.messages, newMsg]};
271
+ }
272
+ return {
273
+ ...s,
274
+ messages: s.messages.map((m: ChatMessage) =>
275
+ m.id === lastThinking.id
276
+ ? {...m, content: m.content + msg.delta, isStreaming: true}
277
+ : m,
278
+ ),
279
+ };
280
+ });
281
+ break;
282
+
283
+ case 'message_update':
284
+ this.stateStore.update((s: WhereverState) => {
285
+ let lastAssistant = [...s.messages]
286
+ .reverse()
287
+ .find(
288
+ (m: ChatMessage) => m.role === 'assistant' && m.isStreaming,
289
+ );
290
+ if (!lastAssistant) {
291
+ const newMsg: ChatMessage = {
292
+ id: this.generateId(),
293
+ role: 'assistant',
294
+ content: msg.delta,
295
+ timestamp: Date.now(),
296
+ isStreaming: true,
297
+ };
298
+ return {...s, messages: [...s.messages, newMsg]};
299
+ }
300
+ return {
301
+ ...s,
302
+ messages: s.messages.map((m: ChatMessage) =>
303
+ m.id === lastAssistant.id
304
+ ? {...m, content: m.content + msg.delta, isStreaming: true}
305
+ : m,
306
+ ),
307
+ };
308
+ });
309
+ break;
310
+
311
+ case 'message_end':
312
+ this.stateStore.update((s: WhereverState) => {
313
+ let newMessages = s.messages;
314
+
315
+ const lastThinking = [...newMessages]
316
+ .reverse()
317
+ .find((m: ChatMessage) => m.role === 'thinking' && m.isStreaming);
318
+ if (lastThinking) {
319
+ newMessages = newMessages.map((m: ChatMessage) =>
320
+ m.id === lastThinking.id ? {...m, isStreaming: false} : m,
321
+ );
322
+ }
323
+
324
+ const lastAssistant = [...newMessages]
325
+ .reverse()
326
+ .find(
327
+ (m: ChatMessage) => m.role === 'assistant' && m.isStreaming,
328
+ );
329
+ if (lastAssistant) {
330
+ newMessages = newMessages.map((m: ChatMessage) =>
331
+ m.id === lastAssistant.id
332
+ ? {
333
+ ...m,
334
+ content: msg.content || m.content,
335
+ isStreaming: false,
336
+ }
337
+ : m,
338
+ );
339
+ } else if (msg.content) {
340
+ const lastUserMessage = [...newMessages]
341
+ .reverse()
342
+ .find((m) => m.role === 'user');
343
+ const isDuplicateUserMsg =
344
+ msg.role === 'user' &&
345
+ lastUserMessage &&
346
+ lastUserMessage.content === msg.content;
347
+
348
+ if (!isDuplicateUserMsg) {
349
+ newMessages = [
350
+ ...newMessages,
351
+ {
352
+ id: this.generateId(),
353
+ role: msg.role || 'assistant',
354
+ content: msg.content,
355
+ timestamp: Date.now(),
356
+ isStreaming: false,
357
+ },
358
+ ];
359
+ }
360
+ }
361
+
362
+ return {...s, messages: newMessages};
363
+ });
364
+ break;
365
+
366
+ case 'agent_end':
367
+ if (this.agentEndTimeout) {
368
+ clearTimeout(this.agentEndTimeout);
369
+ this.agentEndTimeout = null;
370
+ }
371
+ this.agentEndTimeout = setTimeout(() => {
372
+ this.stateStore.update((s: WhereverState) => ({
373
+ ...s,
374
+ isStreaming: false,
375
+ messages: s.messages.map((m: ChatMessage) =>
376
+ m.isStreaming ? {...m, isStreaming: false} : m,
377
+ ),
378
+ }));
379
+ this.agentEndTimeout = null;
380
+ }, 300);
381
+ break;
382
+
383
+ case 'tool_start':
384
+ if (this.agentEndTimeout) {
385
+ clearTimeout(this.agentEndTimeout);
386
+ this.agentEndTimeout = null;
387
+ }
388
+ const toolArgs = msg.args
389
+ ? Object.entries(msg.args)
390
+ .filter(([k, v]) => v !== undefined && v !== '')
391
+ .map(([k, v]) => `${k}=${JSON.stringify(v)}`)
392
+ .join(' ')
393
+ : '';
394
+ this.stateStore.update((s: WhereverState) => {
395
+ const finalizedMessages = s.messages.map((m: ChatMessage) =>
396
+ m.isStreaming && (m.role === 'assistant' || m.role === 'thinking')
397
+ ? {...m, isStreaming: false}
398
+ : m,
399
+ );
400
+ const newMsg: ChatMessage = {
401
+ id: this.generateId(),
402
+ role: 'tool',
403
+ content: toolArgs
404
+ ? `$ ${msg.toolName} ${toolArgs}`
405
+ : `$ ${msg.toolName}`,
406
+ timestamp: Date.now(),
407
+ isStreaming: true,
408
+ toolName: msg.toolName,
409
+ toolArgs: toolArgs,
410
+ toolOutput: '',
411
+ };
412
+ return {
413
+ ...s,
414
+ messages: [...finalizedMessages, newMsg],
415
+ };
416
+ });
417
+ break;
418
+
419
+ case 'tool_update': {
420
+ this.stateStore.update((s: WhereverState) => {
421
+ const toolMsg = [...s.messages]
422
+ .reverse()
423
+ .find(
424
+ (m: ChatMessage) =>
425
+ m.role === 'tool' &&
426
+ m.toolName === msg.toolName &&
427
+ m.isStreaming,
428
+ );
429
+ if (toolMsg) {
430
+ return {
431
+ ...s,
432
+ messages: s.messages.map((m: ChatMessage) =>
433
+ m.id === toolMsg.id
434
+ ? {
435
+ ...m,
436
+ content: m.content.includes('\n')
437
+ ? m.content + msg.delta
438
+ : `${m.content}\n${msg.delta}`,
439
+ toolOutput: `${m.toolOutput}${msg.delta}`,
440
+ }
441
+ : m,
442
+ ),
443
+ };
444
+ }
445
+ return s;
446
+ });
447
+ break;
448
+ }
449
+
450
+ case 'tool_end': {
451
+ const result = msg.result ? `${msg.result}` : '';
452
+ this.stateStore.update((s: WhereverState) => {
453
+ const toolMsg = [...s.messages]
454
+ .reverse()
455
+ .find(
456
+ (m: ChatMessage) =>
457
+ m.role === 'tool' &&
458
+ m.toolName === msg.toolName &&
459
+ !m.content.startsWith('Tool error:'),
460
+ );
461
+ if (toolMsg) {
462
+ const errorPrefix = msg.isError ? 'Error: ' : '';
463
+ return {
464
+ ...s,
465
+ messages: s.messages.map((m: ChatMessage) =>
466
+ m.id === toolMsg.id
467
+ ? {
468
+ ...m,
469
+ content: `${errorPrefix}${m.content}\n${result}`,
470
+ isStreaming: false,
471
+ isError: msg.isError,
472
+ toolOutput: result,
473
+ }
474
+ : m,
475
+ ),
476
+ };
477
+ } else {
478
+ const content = msg.isError
479
+ ? `Tool error: ${msg.toolName}\n${result}`
480
+ : `${msg.toolName}\n${result}`;
481
+ const message: ChatMessage = {
482
+ id: this.generateId(),
483
+ role: 'tool',
484
+ content,
485
+ timestamp: Date.now(),
486
+ isStreaming: false,
487
+ toolName: msg.toolName,
488
+ toolArgs: '',
489
+ toolOutput: result,
490
+ isError: msg.isError,
491
+ };
492
+ return {
493
+ ...s,
494
+ messages: [...s.messages, message],
495
+ };
496
+ }
497
+ });
498
+ break;
499
+ }
500
+
501
+ case 'aborted':
502
+ this.stateStore.update((s: WhereverState) => ({
503
+ ...s,
504
+ isStreaming: false,
505
+ messages: s.messages.map((m: ChatMessage) =>
506
+ m.isStreaming ? {...m, isStreaming: false} : m,
507
+ ),
508
+ }));
509
+ break;
510
+
511
+ case 'session_created':
512
+ this.stateStore.update((s: WhereverState) => ({
513
+ ...s,
514
+ session: msg.sessionFile,
515
+ sessionId: msg.sessionId,
516
+ activeSessionFile: msg.sessionFile,
517
+ activeCwd: msg.cwd,
518
+ activeModel: msg.model,
519
+ isStreaming: msg.isStreaming ?? false,
520
+ creatingSession: false,
521
+ }));
522
+ break;
523
+
524
+ case 'session_destroyed':
525
+ this.stateStore.update((s: WhereverState) => {
526
+ if (s.sessionId === msg.sessionId) {
527
+ return {
528
+ ...s,
529
+ messages: [],
530
+ session: null,
531
+ sessionId: null,
532
+ activeSessionFile: null,
533
+ activeCwd: null,
534
+ activeModel: null,
535
+ };
536
+ }
537
+ return s;
538
+ });
539
+ break;
540
+
541
+ case 'session_error':
542
+ this.stateStore.update((s: WhereverState) => ({
543
+ ...s,
544
+ sessionError: msg.error,
545
+ isStreaming: false,
546
+ creatingSession: false,
547
+ }));
548
+ break;
549
+
550
+ case 'session_conflict':
551
+ this.stateStore.update((s: WhereverState) => ({
552
+ ...s,
553
+ conflict: {
554
+ targetSessionId: msg.sessionId,
555
+ conflictingSessionId: msg.conflictingSession,
556
+ conflictingCwd: msg.conflictingCwd,
557
+ },
558
+ creatingSession: false,
559
+ }));
560
+ break;
561
+
562
+ case 'session_interrupted':
563
+ this.stateStore.update((s: WhereverState) => ({
564
+ ...s,
565
+ isInterrupted: true,
566
+ readOnly: true,
567
+ messages: [],
568
+ session: null,
569
+ sessionId: null,
570
+ activeSessionFile: null,
571
+ activeCwd: null,
572
+ activeModel: null,
573
+ creatingSession: false,
574
+ }));
575
+ break;
576
+
577
+ case 'message_history':
578
+ this.stateStore.update((s: WhereverState) => {
579
+ const mapped = this.mapHistory(msg.messages, msg.sessionId, s.isStreaming);
580
+ const totalCount =
581
+ typeof msg.totalCount === 'number' ? msg.totalCount : mapped.length;
582
+ const offset = typeof msg.offset === 'number' ? msg.offset : 0;
583
+ return {
584
+ ...s,
585
+ messages: mapped,
586
+ historyTotalCount: totalCount,
587
+ historyOffset: offset,
588
+ loadingMoreHistory: false,
589
+ };
590
+ });
591
+ break;
592
+
593
+ case 'message_history_prepend':
594
+ this.stateStore.update((s: WhereverState) => {
595
+ // Older window prepended ahead of currently-loaded messages. No
596
+ // streaming-tail handling here (those messages are historical).
597
+ const older = this.mapHistory(msg.messages, msg.sessionId, false);
598
+ const offset = typeof msg.offset === 'number' ? msg.offset : 0;
599
+ if (older.length === 0) {
600
+ return {...s, loadingMoreHistory: false, historyOffset: offset};
601
+ }
602
+ return {
603
+ ...s,
604
+ messages: [...older, ...s.messages],
605
+ historyOffset: offset,
606
+ loadingMoreHistory: false,
607
+ };
608
+ });
609
+ break;
610
+
611
+ case 'model_changed':
612
+ this.stateStore.update((s: WhereverState) => ({
613
+ ...s,
614
+ activeModel: msg.model,
615
+ }));
616
+ break;
617
+ }
618
+ }
619
+
620
+ /**
621
+ * Map a server `HistoryMessage[]` window into UI `ChatMessage[]`. When
622
+ * `applyStreamingTail` is true, the last assistant/thinking message and any
623
+ * unmatched tool-call placeholders are marked streaming (used only for the
624
+ * live tail window, not for prepended older history).
625
+ */
626
+ private mapHistory(
627
+ rawMessages: any[],
628
+ sessionId: string,
629
+ applyStreamingTail: boolean,
630
+ ): ChatMessage[] {
631
+ const mapped: ChatMessage[] = [];
632
+ const pendingCalls: Record<string, string[]> = {};
633
+
634
+ for (const m of rawMessages) {
635
+ if (m.role === 'tool_call') {
636
+ const tName = m.toolName || 'unknown';
637
+ if (!pendingCalls[tName]) {
638
+ pendingCalls[tName] = [];
639
+ }
640
+ pendingCalls[tName].push(m.content || '');
641
+ } else if (m.role === 'tool_result') {
642
+ const tName = m.toolName || 'unknown';
643
+ const tArgs =
644
+ pendingCalls[tName] && pendingCalls[tName].length > 0
645
+ ? pendingCalls[tName].shift()!
646
+ : '';
647
+ mapped.push({
648
+ id: this.generateId(),
649
+ role: 'tool',
650
+ content: tArgs
651
+ ? `$ ${tName} ${tArgs}\n${m.content}`
652
+ : `$ ${tName}\n${m.content}`,
653
+ timestamp: m.timestamp,
654
+ isStreaming: false,
655
+ toolName: tName,
656
+ toolArgs: tArgs,
657
+ toolOutput: m.content,
658
+ isError: m.isError,
659
+ sessionId,
660
+ });
661
+ } else {
662
+ mapped.push({
663
+ id: this.generateId(),
664
+ role: m.role,
665
+ content: m.content,
666
+ timestamp: m.timestamp,
667
+ isStreaming: false,
668
+ toolName: m.toolName,
669
+ sessionId,
670
+ });
671
+ }
672
+ }
673
+
674
+ for (const [tName, argsList] of Object.entries(pendingCalls)) {
675
+ for (const args of argsList) {
676
+ mapped.push({
677
+ id: this.generateId(),
678
+ role: 'tool',
679
+ content: args ? `$ ${tName} ${args}` : `$ ${tName}`,
680
+ timestamp:
681
+ mapped.length > 0
682
+ ? mapped[mapped.length - 1].timestamp + 1
683
+ : Date.now(),
684
+ isStreaming: applyStreamingTail,
685
+ toolName: tName,
686
+ toolArgs: args,
687
+ toolOutput: '',
688
+ sessionId,
689
+ });
690
+ }
691
+ }
692
+
693
+ if (applyStreamingTail && mapped.length > 0) {
694
+ const lastIndex = mapped.length - 1;
695
+ const lastMsg = mapped[lastIndex];
696
+ if (lastMsg.role === 'assistant' || lastMsg.role === 'thinking') {
697
+ mapped[lastIndex] = {
698
+ ...lastMsg,
699
+ isStreaming: true,
700
+ };
701
+ }
702
+ }
703
+
704
+ return mapped;
705
+ }
706
+
707
+ /**
708
+ * Request the previous window of older history for the active session.
709
+ * No-op when there is nothing older to load or a request is already in
710
+ * flight.
711
+ */
712
+ public loadMoreHistory() {
713
+ const s = get(this.stateStore);
714
+ if (!s.sessionId) return;
715
+ if (s.loadingMoreHistory) return;
716
+ if (s.historyOffset <= 0) return;
717
+ this.stateStore.update((st: WhereverState) => ({
718
+ ...st,
719
+ loadingMoreHistory: true,
720
+ }));
721
+ this.send({
722
+ type: 'history_load_more',
723
+ sessionId: s.sessionId,
724
+ beforeOffset: s.historyOffset,
725
+ });
726
+ }
727
+
728
+ public send(msg: any) {
729
+ if (this.ws && this.ws.readyState === 1 /* OPEN */) {
730
+ this.ws.send(JSON.stringify(msg));
731
+ }
732
+ }
733
+
734
+ public sendMessage(text: string) {
735
+ const s = get(this.stateStore);
736
+ if (!s.sessionId) return;
737
+
738
+ this.stateStore.update((s: WhereverState) => ({...s, sessionError: null}));
739
+
740
+ const message: ChatMessage = {
741
+ id: this.generateId(),
742
+ role: 'user',
743
+ content: text,
744
+ timestamp: Date.now(),
745
+ isStreaming: false,
746
+ sessionId: s.sessionId,
747
+ };
748
+ this.stateStore.update((s: WhereverState) => ({
749
+ ...s,
750
+ messages: [...s.messages, message],
751
+ }));
752
+
753
+ this.send({type: 'message', message: text, sessionId: s.sessionId});
754
+ }
755
+
756
+ public abort() {
757
+ const s = get(this.stateStore);
758
+ if (!s.sessionId) return;
759
+ this.send({type: 'abort', sessionId: s.sessionId});
760
+ }
761
+
762
+ public joinSession(sessionFile: string, cwd?: string, model?: string) {
763
+ this.stateStore.update((s: WhereverState) => ({
764
+ ...s,
765
+ conflict: null,
766
+ sessionError: null,
767
+ }));
768
+ this.send({type: 'session_load', sessionFile, cwd, model});
769
+ }
770
+
771
+ public createSession(
772
+ cwd: string,
773
+ model?: string,
774
+ gitInit?: boolean,
775
+ createRemote?: boolean,
776
+ repoVisibility?: 'private' | 'public',
777
+ ) {
778
+ this.stateStore.update((s: WhereverState) => ({
779
+ ...s,
780
+ conflict: null,
781
+ sessionError: null,
782
+ creatingSession: true,
783
+ }));
784
+ this.send({
785
+ type: 'session_new',
786
+ cwd,
787
+ model,
788
+ gitInit,
789
+ createRemote,
790
+ repoVisibility,
791
+ });
792
+ }
793
+
794
+ public leaveSession() {
795
+ const s = get(this.stateStore);
796
+ if (!s.sessionId) return;
797
+ this.send({type: 'session_leave', sessionId: s.sessionId});
798
+ this.stateStore.update((s: WhereverState) => ({
799
+ ...s,
800
+ messages: [],
801
+ session: null,
802
+ sessionId: null,
803
+ activeSessionFile: null,
804
+ activeCwd: null,
805
+ activeModel: null,
806
+ readOnly: false,
807
+ creatingSession: false,
808
+ }));
809
+ }
810
+
811
+ public resolveConflict(action: 'take_over' | 'read_only', cwd?: string) {
812
+ const s = get(this.stateStore);
813
+ if (!s.conflict) return;
814
+
815
+ this.send({
816
+ type: 'session_resolve_conflict',
817
+ action,
818
+ sessionId: s.conflict.targetSessionId,
819
+ cwd: cwd || s.conflict.conflictingCwd,
820
+ });
821
+
822
+ this.stateStore.update((s: WhereverState) => ({
823
+ ...s,
824
+ conflict: null,
825
+ readOnly: action === 'read_only',
826
+ }));
827
+ }
828
+
829
+ public ping() {
830
+ this.send({type: 'ping'});
831
+ }
832
+
833
+ public clearMessages() {
834
+ this.stateStore.update((s: WhereverState) => ({...s, messages: []}));
835
+ }
836
+
837
+ public dismissSessionError() {
838
+ this.stateStore.update((s: WhereverState) => ({...s, sessionError: null}));
839
+ }
840
+
841
+ public changeModel(model: string) {
842
+ this.send({type: 'model_change', model});
843
+ }
844
+
845
+ public setConfig(updates: Partial<WhereverClientConfig>) {
846
+ this.config = {
847
+ ...this.config,
848
+ ...updates,
849
+ };
850
+ this.stateStore.update((s: WhereverState) => {
851
+ const next = {...s};
852
+ if (updates.hideThinking !== undefined)
853
+ next.hideThinking = !!updates.hideThinking;
854
+ if (updates.hideTools !== undefined)
855
+ next.hideTools = !!updates.hideTools;
856
+ return next;
857
+ });
858
+ }
859
+
860
+ public onMessage(cb: (msg: any) => void) {
861
+ this.listeners.add(cb);
862
+ return () => {
863
+ this.listeners.delete(cb);
864
+ };
865
+ }
866
+
867
+ public uploadFileViaWebSocket(sessionId: string, filename: string, base64Data: string): Promise<{savedPath: string; filename: string}> {
868
+ return new Promise((resolve, reject) => {
869
+ const uploadId = this.generateId();
870
+ this.pendingUploads.set(uploadId, {resolve, reject});
871
+ this.send({
872
+ type: 'file_upload',
873
+ uploadId,
874
+ sessionId,
875
+ filename,
876
+ data: base64Data
877
+ });
878
+ });
879
+ }
880
+
881
+ private generateId() {
882
+ return Math.random().toString(36).substring(2) + Date.now().toString(36);
883
+ }
884
+
885
+ public getIsConnected() {
886
+ return this.ws && this.ws.readyState === 1;
887
+ }
888
+ }