-
Notifications
You must be signed in to change notification settings - Fork 103
Expand file tree
/
Copy pathchatCommands.ts
More file actions
1064 lines (944 loc) · 33.8 KB
/
chatCommands.ts
File metadata and controls
1064 lines (944 loc) · 33.8 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
/**
* Chat command execution utilities
* Handles executing workspace operations from slash commands
*
* These utilities are shared between ChatInput command handlers and UI components
* to ensure consistent behavior and avoid duplication.
*/
import type { RouterClient } from "@orpc/server";
import type { AppRouter } from "@/node/orpc/router";
import type { SendMessageOptions, ImagePart } from "@/common/orpc/types";
import type {
MuxFrontendMetadata,
CompactionRequestData,
ContinueMessage,
} from "@/common/types/message";
import type { FrontendWorkspaceMetadata } from "@/common/types/workspace";
import type { RuntimeConfig } from "@/common/types/runtime";
import { RUNTIME_MODE, SSH_RUNTIME_PREFIX } from "@/common/types/runtime";
import { CUSTOM_EVENTS, createCustomEvent } from "@/common/constants/events";
import { WORKSPACE_ONLY_COMMANDS } from "@/constants/slashCommands";
import type { Toast } from "@/browser/components/ChatInputToast";
import type { ParsedCommand } from "@/browser/utils/slashCommands/types";
import { applyCompactionOverrides } from "@/browser/utils/messages/compactionOptions";
import {
resolveCompactionModel,
isValidModelFormat,
} from "@/browser/utils/messages/compactionModelPreference";
import type { ImageAttachment } from "../components/ImageAttachments";
import { dispatchWorkspaceSwitch } from "./workspaceEvents";
import { getRuntimeKey, copyWorkspaceStorage } from "@/common/constants/storage";
import {
DEFAULT_COMPACTION_WORD_TARGET,
WORDS_TO_TOKENS_RATIO,
buildCompactionPrompt,
} from "@/common/constants/ui";
import { openInEditor } from "@/browser/utils/openInEditor";
// ============================================================================
// Workspace Creation
// ============================================================================
import {
createCommandToast,
createInvalidCompactModelToast,
} from "@/browser/components/ChatInputToasts";
import { trackCommandUsed, trackProviderConfigured } from "@/common/telemetry";
import { addEphemeralMessage } from "@/browser/stores/WorkspaceStore";
export interface ForkOptions {
client: RouterClient<AppRouter>;
sourceWorkspaceId: string;
newName: string;
startMessage?: string;
sendMessageOptions?: SendMessageOptions;
}
export interface ForkResult {
success: boolean;
workspaceInfo?: FrontendWorkspaceMetadata;
error?: string;
}
/**
* Fork a workspace and switch to it
* Handles copying storage, dispatching switch event, and optionally sending start message
*
* Caller is responsible for error handling, logging, and showing toasts
*/
export async function forkWorkspace(options: ForkOptions): Promise<ForkResult> {
const { client } = options;
const result = await client.workspace.fork({
sourceWorkspaceId: options.sourceWorkspaceId,
newName: options.newName,
});
if (!result.success) {
return { success: false, error: result.error ?? "Failed to fork workspace" };
}
// Copy UI state to the new workspace
copyWorkspaceStorage(options.sourceWorkspaceId, result.metadata.id);
// Get workspace info for switching
const workspaceInfo = await client.workspace.getInfo({ workspaceId: result.metadata.id });
if (!workspaceInfo) {
return { success: false, error: "Failed to get workspace info after fork" };
}
// Dispatch event to switch workspace
dispatchWorkspaceSwitch(workspaceInfo);
// If there's a start message, defer until React finishes rendering and WorkspaceStore subscribes
// Using requestAnimationFrame ensures we wait for:
// 1. React to process the workspace switch and update state
// 2. Effects to run (workspaceStore.syncWorkspaces in App.tsx)
// 3. WorkspaceStore to subscribe to the new workspace's IPC channel
if (options.startMessage && options.sendMessageOptions) {
requestAnimationFrame(() => {
void client.workspace.sendMessage({
workspaceId: result.metadata.id,
message: options.startMessage!,
options: options.sendMessageOptions,
});
});
}
return { success: true, workspaceInfo };
}
export interface SlashCommandContext extends Omit<CommandHandlerContext, "workspaceId"> {
workspaceId?: string;
variant: "workspace" | "creation";
// Global Actions
onProviderConfig?: (provider: string, keyPath: string[], value: string) => Promise<void>;
onModelChange?: (model: string) => void;
setPreferredModel: (model: string) => void;
setVimEnabled: (cb: (prev: boolean) => boolean) => void;
// Workspace Actions
onTruncateHistory?: (percentage?: number) => Promise<void>;
resetInputHeight: () => void;
}
// ============================================================================
// Command Dispatcher
// ============================================================================
/**
* Process any slash command
* Returns true if the command was handled (even if it failed)
* Returns false if it's not a command (should be sent as message) - though parsed usually implies it is a command
*/
export async function processSlashCommand(
parsed: ParsedCommand,
context: SlashCommandContext
): Promise<CommandHandlerResult> {
if (!parsed) return { clearInput: false, toastShown: false };
const {
api: client,
setInput,
setIsSending,
setToast,
variant,
setVimEnabled,
setPreferredModel,
onModelChange,
} = context;
// 1. Global Commands
if (parsed.type === "providers-set") {
if (context.onProviderConfig) {
setIsSending(true);
setInput(""); // Clear input immediately
try {
await context.onProviderConfig(parsed.provider, parsed.keyPath, parsed.value);
// Track successful provider configuration
trackCommandUsed("providers");
trackProviderConfigured(parsed.provider, parsed.keyPath[0] ?? "unknown");
setToast({
id: Date.now().toString(),
type: "success",
message: `Provider ${parsed.provider} updated`,
});
} catch (error) {
console.error("Failed to update provider config:", error);
setToast({
id: Date.now().toString(),
type: "error",
message: error instanceof Error ? error.message : "Failed to update provider",
});
return { clearInput: false, toastShown: true }; // Input restored by caller if clearInput is false?
// Actually caller restores if we return clearInput: false.
// But here we cleared it proactively?
// The caller (ChatInput) pattern is: if (!result.clearInput) setInput(original).
// So we should return clearInput: false on error.
} finally {
setIsSending(false);
}
return { clearInput: true, toastShown: true };
}
return { clearInput: false, toastShown: false };
}
if (parsed.type === "model-set") {
const modelString = parsed.modelString;
// Validate provider:model format
if (!modelString.includes(":")) {
setToast({
id: Date.now().toString(),
type: "error",
message: `Invalid model format: expected "provider:model"`,
});
return { clearInput: false, toastShown: true };
}
const [provider, modelId] = modelString.split(":", 2);
if (!provider || !modelId) {
setToast({
id: Date.now().toString(),
type: "error",
message: `Invalid model format: expected "provider:model"`,
});
return { clearInput: false, toastShown: true };
}
// Validate provider is supported
const { isValidProvider } = await import("@/common/constants/providers");
if (!isValidProvider(provider)) {
setToast({
id: Date.now().toString(),
type: "error",
message: `Unknown provider "${provider}"`,
});
return { clearInput: false, toastShown: true };
}
// Check if model needs to be added to provider's custom models
const config = await client.providers.getConfig();
const existingModels = config[provider]?.models ?? [];
if (!existingModels.includes(modelId)) {
// Add model via the same API as settings
await client.providers.setModels({ provider, models: [...existingModels, modelId] });
}
setInput("");
setPreferredModel(modelString);
onModelChange?.(modelString);
trackCommandUsed("model");
setToast({
id: Date.now().toString(),
type: "success",
message: `Model changed to ${modelString}`,
});
return { clearInput: true, toastShown: true };
}
if (parsed.type === "vim-toggle") {
setInput("");
setVimEnabled((prev) => !prev);
trackCommandUsed("vim");
return { clearInput: true, toastShown: false };
}
// 2. Workspace Commands
const isWorkspaceCommand = WORKSPACE_ONLY_COMMANDS.has(parsed.type);
if (isWorkspaceCommand) {
if (variant !== "workspace") {
setToast({
id: Date.now().toString(),
type: "error",
message: "Command not available during workspace creation",
});
return { clearInput: false, toastShown: true };
}
// Dispatch workspace commands
switch (parsed.type) {
case "clear":
return handleClearCommand(parsed, context);
case "truncate":
return handleTruncateCommand(parsed, context);
case "compact":
// handleCompactCommand expects workspaceId in context
if (!context.workspaceId) throw new Error("Workspace ID required");
return handleCompactCommand(parsed, {
...context,
workspaceId: context.workspaceId,
} as CommandHandlerContext);
case "fork":
return handleForkCommand(parsed, context);
case "new":
if (!context.workspaceId) throw new Error("Workspace ID required");
return handleNewCommand(parsed, {
...context,
workspaceId: context.workspaceId,
} as CommandHandlerContext);
case "plan-show":
if (!context.workspaceId) throw new Error("Workspace ID required");
return handlePlanShowCommand({
...context,
workspaceId: context.workspaceId,
} as CommandHandlerContext);
case "plan-open":
if (!context.workspaceId) throw new Error("Workspace ID required");
return handlePlanOpenCommand({
...context,
workspaceId: context.workspaceId,
} as CommandHandlerContext);
}
}
// 3. Fallback / Help / Unknown
const commandToast = createCommandToast(parsed);
if (commandToast) {
setToast(commandToast);
return { clearInput: false, toastShown: true };
}
return { clearInput: false, toastShown: false };
}
// ============================================================================
// Command Handlers
// ============================================================================
async function handleClearCommand(
_parsed: Extract<ParsedCommand, { type: "clear" }>,
context: SlashCommandContext
): Promise<CommandHandlerResult> {
const { setInput, onTruncateHistory, resetInputHeight, setToast } = context;
setInput("");
resetInputHeight();
if (!onTruncateHistory) return { clearInput: true, toastShown: false };
try {
await onTruncateHistory(1.0);
trackCommandUsed("clear");
setToast({
id: Date.now().toString(),
type: "success",
message: "Chat history cleared",
});
return { clearInput: true, toastShown: true };
} catch (error) {
const normalized = error instanceof Error ? error : new Error("Failed to clear history");
console.error("Failed to clear history:", normalized);
setToast({
id: Date.now().toString(),
type: "error",
message: normalized.message,
});
return { clearInput: false, toastShown: true };
}
}
async function handleTruncateCommand(
parsed: Extract<ParsedCommand, { type: "truncate" }>,
context: SlashCommandContext
): Promise<CommandHandlerResult> {
const { setInput, onTruncateHistory, resetInputHeight, setToast } = context;
setInput("");
resetInputHeight();
if (!onTruncateHistory) return { clearInput: true, toastShown: false };
try {
await onTruncateHistory(parsed.percentage);
setToast({
id: Date.now().toString(),
type: "success",
message: `Chat history truncated by ${Math.round(parsed.percentage * 100)}%`,
});
return { clearInput: true, toastShown: true };
} catch (error) {
const normalized = error instanceof Error ? error : new Error("Failed to truncate history");
console.error("Failed to truncate history:", normalized);
setToast({
id: Date.now().toString(),
type: "error",
message: normalized.message,
});
return { clearInput: false, toastShown: true };
}
}
async function handleForkCommand(
parsed: Extract<ParsedCommand, { type: "fork" }>,
context: SlashCommandContext
): Promise<CommandHandlerResult> {
const {
api: client,
workspaceId,
sendMessageOptions,
setInput,
setIsSending,
setToast,
} = context;
setInput(""); // Clear input immediately
setIsSending(true);
try {
// Note: workspaceId is required for fork, but SlashCommandContext allows undefined workspaceId.
// If we are here, variant === "workspace", so workspaceId should be defined.
if (!workspaceId) throw new Error("Workspace ID required for fork");
if (!client) throw new Error("Client required for fork");
const forkResult = await forkWorkspace({
client,
sourceWorkspaceId: workspaceId,
newName: parsed.newName,
startMessage: parsed.startMessage,
sendMessageOptions,
});
if (!forkResult.success) {
const errorMsg = forkResult.error ?? "Failed to fork workspace";
console.error("Failed to fork workspace:", errorMsg);
setToast({
id: Date.now().toString(),
type: "error",
title: "Fork Failed",
message: errorMsg,
});
return { clearInput: false, toastShown: true };
} else {
trackCommandUsed("fork");
setToast({
id: Date.now().toString(),
type: "success",
message: `Forked to workspace "${parsed.newName}"`,
});
return { clearInput: true, toastShown: true };
}
} catch (error) {
const normalized = error instanceof Error ? error : new Error("Failed to fork workspace");
console.error("Fork error:", normalized);
setToast({
id: Date.now().toString(),
type: "error",
title: "Fork Failed",
message: normalized.message,
});
return { clearInput: false, toastShown: true };
} finally {
setIsSending(false);
}
}
/**
* Parse runtime string from -r flag into RuntimeConfig for backend
* Supports formats:
* - "ssh <host>" or "ssh <user@host>" -> SSH runtime
* - "worktree" -> Worktree runtime (git worktrees)
* - "local" -> Local runtime (project-dir, no isolation)
* - undefined -> Worktree runtime (default)
*/
export function parseRuntimeString(
runtime: string | undefined,
_workspaceName: string
): RuntimeConfig | undefined {
if (!runtime) {
return undefined; // Default to worktree (backend decides)
}
const trimmed = runtime.trim();
const lowerTrimmed = trimmed.toLowerCase();
// Worktree runtime (explicit or default)
if (lowerTrimmed === RUNTIME_MODE.WORKTREE) {
return undefined; // Explicit worktree - let backend use default
}
// Local runtime (project-dir, no isolation)
if (lowerTrimmed === RUNTIME_MODE.LOCAL) {
// Return "local" type without srcBaseDir to indicate project-dir runtime
return { type: RUNTIME_MODE.LOCAL };
}
// Parse "ssh <host>" or "ssh <user@host>" format
if (lowerTrimmed === RUNTIME_MODE.SSH || lowerTrimmed.startsWith(SSH_RUNTIME_PREFIX)) {
const hostPart = trimmed.slice(SSH_RUNTIME_PREFIX.length - 1).trim(); // Preserve original case for host
if (!hostPart) {
throw new Error("SSH runtime requires host (e.g., 'ssh hostname' or 'ssh user@host')");
}
// Accept both "hostname" and "user@hostname" formats
// SSH will use current user or ~/.ssh/config if user not specified
// Use tilde path - backend will resolve it via runtime.resolvePath()
return {
type: RUNTIME_MODE.SSH,
host: hostPart,
srcBaseDir: "~/mux", // Default remote base directory (tilde will be resolved by backend)
};
}
throw new Error(`Unknown runtime type: '${runtime}'. Use 'ssh <host>', 'worktree', or 'local'`);
}
export interface CreateWorkspaceOptions {
client: RouterClient<AppRouter>;
projectPath: string;
workspaceName: string;
trunkBranch?: string;
runtime?: string;
startMessage?: string;
sendMessageOptions?: SendMessageOptions;
}
export interface CreateWorkspaceResult {
success: boolean;
workspaceInfo?: FrontendWorkspaceMetadata;
error?: string;
}
/**
* Create a new workspace and switch to it
* Handles backend creation, dispatching switch event, and optionally sending start message
*
* Shared between /new command and NewWorkspaceModal
*/
export async function createNewWorkspace(
options: CreateWorkspaceOptions
): Promise<CreateWorkspaceResult> {
// Get recommended trunk if not provided
let effectiveTrunk = options.trunkBranch;
if (!effectiveTrunk) {
const { recommendedTrunk } = await options.client.projects.listBranches({
projectPath: options.projectPath,
});
effectiveTrunk = recommendedTrunk ?? "main";
}
// Use saved default runtime preference if not explicitly provided
let effectiveRuntime = options.runtime;
if (effectiveRuntime === undefined) {
const runtimeKey = getRuntimeKey(options.projectPath);
const savedRuntime = localStorage.getItem(runtimeKey);
if (savedRuntime) {
effectiveRuntime = savedRuntime;
}
}
// Parse runtime config if provided
const runtimeConfig = parseRuntimeString(effectiveRuntime, options.workspaceName);
const result = await options.client.workspace.create({
projectPath: options.projectPath,
branchName: options.workspaceName,
trunkBranch: effectiveTrunk,
runtimeConfig,
});
if (!result.success) {
return { success: false, error: result.error ?? "Failed to create workspace" };
}
// Get workspace info for switching
const workspaceInfo = await options.client.workspace.getInfo({ workspaceId: result.metadata.id });
if (!workspaceInfo) {
return { success: false, error: "Failed to get workspace info after creation" };
}
// Dispatch event to switch workspace
dispatchWorkspaceSwitch(workspaceInfo);
// If there's a start message, defer until React finishes rendering and WorkspaceStore subscribes
if (options.startMessage && options.sendMessageOptions) {
requestAnimationFrame(() => {
void options.client.workspace.sendMessage({
workspaceId: result.metadata.id,
message: options.startMessage!,
options: options.sendMessageOptions,
});
});
}
return { success: true, workspaceInfo };
}
/**
* Format /new command string for display
*/
export function formatNewCommand(
workspaceName: string,
trunkBranch?: string,
runtime?: string,
startMessage?: string
): string {
let cmd = `/new ${workspaceName}`;
if (trunkBranch) {
cmd += ` -t ${trunkBranch}`;
}
if (runtime) {
cmd += ` -r '${runtime}'`;
}
if (startMessage) {
cmd += `\n${startMessage}`;
}
return cmd;
}
// ============================================================================
// Workspace Forking (Inline implementation)
// ============================================================================
// ============================================================================
// Compaction
// ============================================================================
export interface CompactionOptions {
api?: RouterClient<AppRouter>;
workspaceId: string;
maxOutputTokens?: number;
continueMessage?: ContinueMessage;
model?: string;
sendMessageOptions: SendMessageOptions;
editMessageId?: string;
/** Source of compaction request (e.g., "idle-compaction" for auto-triggered) */
source?: "idle-compaction";
}
export interface CompactionResult {
success: boolean;
error?: string;
}
/**
* Prepare compaction message from options
* Returns the actual message text (summarization request), metadata, and options
*/
export function prepareCompactionMessage(options: CompactionOptions): {
messageText: string;
metadata: MuxFrontendMetadata;
sendOptions: SendMessageOptions;
} {
const targetWords = options.maxOutputTokens
? Math.round(options.maxOutputTokens / WORDS_TO_TOKENS_RATIO)
: DEFAULT_COMPACTION_WORD_TARGET;
// Build compaction message with optional continue context
let messageText = buildCompactionPrompt(targetWords);
const continueText = options.continueMessage?.text;
const hasImages =
options.continueMessage?.imageParts && options.continueMessage.imageParts.length > 0;
const hasReviews = options.continueMessage?.reviews && options.continueMessage.reviews.length > 0;
// continueMessage is a follow-up user message that will be auto-sent after compaction.
// For forced compaction (no explicit follow-up), we inject a short resume sentinel ("Continue").
// Keep that sentinel out of the *compaction prompt* (summarization request), otherwise the model can
// misread it as a competing instruction. We still keep it in metadata so the backend resumes.
// Only treat it as the default resume when there's no other queued content (images/reviews).
const isDefaultResume =
typeof continueText === "string" &&
continueText.trim() === "Continue" &&
!hasImages &&
!hasReviews;
if (options.continueMessage && !isDefaultResume) {
messageText += `\n\nThe user wants to continue with: ${options.continueMessage.text}`;
}
// Handle model preference (sticky globally)
const effectiveModel = resolveCompactionModel(options.model);
// Create compaction metadata (will be stored in user message)
// Only include continueMessage if there's text, images, or reviews to queue after compaction
const hasText = continueText;
// Determine mode for continue message - use mode from sendMessageOptions if it's exec/plan, otherwise default to exec
const continueMode = options.sendMessageOptions.mode === "plan" ? "plan" : "exec";
const compactData: CompactionRequestData = {
model: effectiveModel,
maxOutputTokens: options.maxOutputTokens,
continueMessage:
hasText || hasImages || hasReviews
? {
text: options.continueMessage?.text ?? "",
imageParts: options.continueMessage?.imageParts,
model: options.continueMessage?.model ?? options.sendMessageOptions.model,
mode: continueMode,
reviews: options.continueMessage?.reviews,
}
: undefined,
};
const metadata: MuxFrontendMetadata = {
type: "compaction-request",
rawCommand: formatCompactionCommandLine(options),
parsed: compactData,
...(options.source === "idle-compaction" && {
source: options.source,
displayStatus: { emoji: "💤", message: "Compacting idle workspace..." },
}),
};
// Apply compaction overrides
const sendOptions = applyCompactionOverrides(options.sendMessageOptions, compactData);
return { messageText, metadata, sendOptions };
}
/**
* Execute a compaction command via the control-plane endpoint.
* This ensures compaction cannot be dropped or treated as a normal message.
*/
export async function executeCompaction(
options: CompactionOptions & { api: RouterClient<AppRouter> }
): Promise<CompactionResult> {
// Resolve compaction model preference
const effectiveModel = resolveCompactionModel(options.model);
// Map source to control-plane format
const source: "user" | "force-compaction" | "idle-compaction" =
options.source === "idle-compaction" ? "idle-compaction" : "user";
// Build continue message if provided
const continueMode = options.continueMessage?.mode ?? "exec";
const continueMessage = options.continueMessage
? {
text: options.continueMessage.text,
imageParts: options.continueMessage.imageParts,
model: options.continueMessage.model ?? options.sendMessageOptions.model,
mode: continueMode,
}
: undefined;
// Call the control-plane compactHistory endpoint
const result = await options.api.workspace.compactHistory({
workspaceId: options.workspaceId,
model: effectiveModel,
maxOutputTokens: options.maxOutputTokens,
continueMessage,
source,
// For edits, interrupt any active stream before compacting.
// We preserve partial output; compaction will commit partial.json before summarizing.
interrupt: options.editMessageId ? "abort" : undefined,
sendMessageOptions: {
model: options.sendMessageOptions.model,
thinkingLevel: options.sendMessageOptions.thinkingLevel,
providerOptions: options.sendMessageOptions.providerOptions,
experiments: options.sendMessageOptions.experiments,
},
});
if (!result.success) {
// Convert SendMessageError to string for error display
const errorString = result.error
? typeof result.error === "string"
? result.error
: "type" in result.error
? result.error.type
: "Failed to compact"
: undefined;
return { success: false, error: errorString };
}
return { success: true };
}
/**
* Format compaction command *line* for display.
*
* Intentionally excludes the multiline continue payload; that content is stored in
* `muxMetadata.parsed.continueMessage` and is shown/edited separately.
*/
function formatCompactionCommandLine(options: CompactionOptions): string {
let cmd = "/compact";
if (options.maxOutputTokens) {
cmd += ` -t ${options.maxOutputTokens}`;
}
if (options.model) {
cmd += ` -m ${options.model}`;
}
return cmd;
}
// ============================================================================
// Command Handler Types
// ============================================================================
export interface CommandHandlerContext {
api: RouterClient<AppRouter>;
workspaceId: string;
sendMessageOptions: SendMessageOptions;
imageParts?: ImagePart[];
editMessageId?: string;
setInput: (value: string) => void;
setImageAttachments: (images: ImageAttachment[]) => void;
setIsSending: (value: boolean) => void;
setToast: (toast: Toast) => void;
onCancelEdit?: () => void;
}
export interface CommandHandlerResult {
/** Whether the input should be cleared */
clearInput: boolean;
/** Whether to show a toast (already set via context.setToast) */
toastShown: boolean;
}
/**
* Handle /new command execution
*/
export async function handleNewCommand(
parsed: Extract<ParsedCommand, { type: "new" }>,
context: CommandHandlerContext
): Promise<CommandHandlerResult> {
const {
api: client,
workspaceId,
sendMessageOptions,
setInput,
setIsSending,
setToast,
} = context;
// Open modal if no workspace name provided
if (!parsed.workspaceName) {
setInput("");
// Get workspace info to extract projectPath for the modal
const workspaceInfo = await client.workspace.getInfo({ workspaceId });
if (!workspaceInfo) {
setToast({
id: Date.now().toString(),
type: "error",
title: "Error",
message: "Failed to get workspace info",
});
return { clearInput: false, toastShown: true };
}
// Dispatch event with start message, model, and optional preferences
const event = createCustomEvent(CUSTOM_EVENTS.START_WORKSPACE_CREATION, {
projectPath: workspaceInfo.projectPath,
startMessage: parsed.startMessage ?? "",
model: sendMessageOptions.model,
trunkBranch: parsed.trunkBranch,
runtime: parsed.runtime,
});
window.dispatchEvent(event);
return { clearInput: true, toastShown: false };
}
setInput("");
setIsSending(true);
try {
// Get workspace info to extract projectPath
const workspaceInfo = await client.workspace.getInfo({ workspaceId });
if (!workspaceInfo) {
throw new Error("Failed to get workspace info");
}
const createResult = await createNewWorkspace({
client,
projectPath: workspaceInfo.projectPath,
workspaceName: parsed.workspaceName,
trunkBranch: parsed.trunkBranch,
runtime: parsed.runtime,
startMessage: parsed.startMessage,
sendMessageOptions,
});
if (!createResult.success) {
const errorMsg = createResult.error ?? "Failed to create workspace";
console.error("Failed to create workspace:", errorMsg);
setToast({
id: Date.now().toString(),
type: "error",
title: "Create Failed",
message: errorMsg,
});
return { clearInput: false, toastShown: true };
}
trackCommandUsed("new");
setToast({
id: Date.now().toString(),
type: "success",
message: `Created workspace "${parsed.workspaceName}"`,
});
return { clearInput: true, toastShown: true };
} catch (error) {
const errorMsg = error instanceof Error ? error.message : "Failed to create workspace";
console.error("Create error:", error);
setToast({
id: Date.now().toString(),
type: "error",
title: "Create Failed",
message: errorMsg,
});
return { clearInput: false, toastShown: true };
} finally {
setIsSending(false);
}
}
/**
* Handle /compact command execution
*/
export async function handleCompactCommand(
parsed: Extract<ParsedCommand, { type: "compact" }>,
context: CommandHandlerContext
): Promise<CommandHandlerResult> {
const {
api,
workspaceId,
sendMessageOptions,
editMessageId,
setInput,
setImageAttachments,
setIsSending,
setToast,
onCancelEdit,
} = context;
// Validate model format early - fail fast before sending to backend
if (parsed.model && !isValidModelFormat(parsed.model)) {
setToast(createInvalidCompactModelToast(parsed.model));
return { clearInput: false, toastShown: true };
}
setInput("");
setImageAttachments([]);
setIsSending(true);
try {
const result = await executeCompaction({
api,
workspaceId,
maxOutputTokens: parsed.maxOutputTokens,
continueMessage:
parsed.continueMessage || (context.imageParts && context.imageParts.length > 0)
? {
text: parsed.continueMessage ?? "",
imageParts: context.imageParts,
model: sendMessageOptions.model,
}
: undefined,
model: parsed.model,
sendMessageOptions,
editMessageId,
});
if (!result.success) {
console.error("Failed to initiate compaction:", result.error);
const errorMsg = result.error ?? "Failed to start compaction";
setToast({
id: Date.now().toString(),
type: "error",
message: errorMsg,
});
return { clearInput: false, toastShown: true };
}
trackCommandUsed("compact");
setToast({
id: Date.now().toString(),
type: "success",
message: parsed.continueMessage
? "Compaction started. Will continue automatically after completion."
: "Compaction started. AI will summarize the conversation.",
});
// Clear editing state on success
if (editMessageId && onCancelEdit) {
onCancelEdit();
}
return { clearInput: true, toastShown: true };
} catch (error) {
console.error("Compaction error:", error);
setToast({
id: Date.now().toString(),
type: "error",
message: error instanceof Error ? error.message : "Failed to start compaction",
});
return { clearInput: false, toastShown: true };
} finally {
setIsSending(false);
}
}
// ============================================================================
// Plan Command Handlers
// ============================================================================
export async function handlePlanShowCommand(
context: CommandHandlerContext
): Promise<CommandHandlerResult> {
const { api, workspaceId, setInput, setToast } = context;
setInput("");
const result = await api.workspace.getPlanContent({ workspaceId });
if (!result.success) {
setToast({
id: Date.now().toString(),
type: "error",
message: "No plan found for this workspace",
});
return { clearInput: true, toastShown: true };
}
// Create ephemeral plan-display message (not persisted to history)
// Uses addEphemeralMessage to properly trigger React re-render via store bump
// Use a very high historySequence so it appears at the end of the chat
const planMessage = {
id: `plan-display-${Date.now()}`,