-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.ts
More file actions
1985 lines (1795 loc) · 65.8 KB
/
Copy pathmain.ts
File metadata and controls
1985 lines (1795 loc) · 65.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
import { App, FileSystemAdapter, ItemView, Menu, Notice, Plugin, PluginSettingTab, Setting, TFile, TFolder, WorkspaceLeaf, parseYaml, setIcon } from "obsidian";
import { spawn, type ChildProcess } from "child_process";
import { randomUUID } from "node:crypto";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import { Terminal } from "@xterm/xterm";
import { FitAddon } from "@xterm/addon-fit";
import {
defaultGenerateRuntimeId,
detectNodeExecutable,
formatActiveFileMention,
formatActiveFolderMention,
isCodexLikeCommand,
mergePathEntries as mergePathEntriesForPlatform,
migrateRuntimeSettings,
resolvePluginDir as resolvePluginDirWithVault,
type CliRuntimeConfig
} from "./runtime-utils";
import {
canOpenSession,
nextSessionLabel,
resolveRuntimeForAutomation,
tabDotClass
} from "./session-utils";
import {
buildPromptPreview,
computeNextRun,
parseAutomationFile,
pushHistory,
type AutomationParseError,
type AutomationRunRecord,
type ParsedAutomation
} from "./automation";
import { AutomationsModal } from "./automations-modal";
// Injected at build time by `esbuild.config.mjs` (see `define`). These hold the
// full source of `pty-proxy.js` and `pty-bridge.py` so the plugin can recreate
// them in the plugin folder when Obsidian's community-store auto-install only
// fetched `main.js`, `manifest.json`, and `styles.css`.
declare const PTY_PROXY_SOURCE: string;
declare const PTY_BRIDGE_SOURCE: string;
const VIEW_TYPE_CLAUDE = "claude-cli-view";
const CODEX_DEFAULT_COMMAND =
"codex --no-alt-screen -c check_for_update_on_startup=false -c hide_full_access_warning=true -c hide_world_writable_warning=true -c hide_rate_limit_model_nudge=true";
const DEFAULT_RUNTIMES: CliRuntimeConfig[] = [
{ id: "claude", name: "Claude", command: "claude" },
{ id: "codex", name: "Codex", command: CODEX_DEFAULT_COMMAND }
];
interface ClaudeCliPluginSettings {
runtimes: CliRuntimeConfig[];
selectedRuntimeId: string;
autoRestartOnRuntimeSwitch: boolean;
autoStart: boolean;
nodeExecutable: string;
automationsFolder: string;
automationsLastRun: Record<string, number>;
automationsHistory: AutomationRunRecord[];
automationsHistoryLimit: number;
autoCloseAutomationSessions: boolean;
autoCloseAutomationSessionsOnIdle: boolean;
idleTimeoutSeconds: number;
maxConcurrentSessions: number;
verboseProxyLogs: boolean;
}
// Default idle threshold (seconds) for the configurable `idleTimeoutSeconds`
// setting. A session is shown as "working" while its CLI emits output, and
// flips back to "idle" once output has been quiet for this long.
const DEFAULT_IDLE_TIMEOUT_SECONDS = 10;
const DEFAULT_SETTINGS: ClaudeCliPluginSettings = {
runtimes: DEFAULT_RUNTIMES.map((runtime) => ({ ...runtime })),
selectedRuntimeId: "claude",
autoRestartOnRuntimeSwitch: true,
autoStart: true,
nodeExecutable: "auto",
automationsFolder: "",
automationsLastRun: {},
automationsHistory: [],
automationsHistoryLimit: 200,
autoCloseAutomationSessions: true,
autoCloseAutomationSessionsOnIdle: false,
idleTimeoutSeconds: DEFAULT_IDLE_TIMEOUT_SECONDS,
maxConcurrentSessions: 8,
verboseProxyLogs: false
};
const AUTOMATION_TICK_MS = 30_000;
const EXAMPLE_AUTOMATION_CONTENT = `---
# ============================================================
# Any AI CLI — automation file. Every available option is shown
# below. The text AFTER the closing "---" is the prompt that gets
# sent to the running CLI.
# ============================================================
# name (string, optional)
# Display name shown in the Automations modal. Defaults to the
# filename (without ".md") when omitted.
name: Hello world
# enabled (true | false, optional, default true)
# When false, the scheduler never auto-fires this automation. It
# still appears in the modal (greyed out) and can be triggered by
# hand with the "Run now" button.
enabled: true
# ----- Schedule: set EXACTLY ONE of "interval" or "cron" -----
# interval (integer minutes, >= 1)
# Fire every N minutes. The first run happens on the next tick
# after the plugin loads; subsequent runs are N minutes apart.
interval: 60
# cron (string, standard 5-field expression)
# Alternative to "interval". To use it: comment out "interval"
# above, then uncomment ONE line below. Fields are:
# minute hour day-of-month month day-of-week
# cron: "*/30 * * * *" # every 30 minutes
# cron: "0 9 * * *" # every day at 09:00
# cron: "0 9 * * 1-5" # weekdays at 09:00
# cron: "0 */2 * * *" # every 2 hours, on the hour
# cron: "0 8 1 * *" # 08:00 on the 1st of each month
# runtime (string, optional)
# Which runtime to spawn for this automation, matched by its id OR its
# display name (case-insensitive). Each run opens its own session tab.
# Remove the line to use the default runtime (set in plugin settings).
# Runs naming an unconfigured runtime are skipped and logged in History.
runtime: Claude
# appendNewline (true | false, optional, default true)
# Append an Enter keystroke after the prompt so the CLI executes it.
# Set false only if you want the text inserted without submitting.
appendNewline: true
---
Say hello and tell me the current date and time.
`;
const AUTOMATION_DOCS_FILENAME = "AUTOMATION-DOCS.md";
const AUTOMATION_DOCS_CONTENT = `# Any AI CLI — Automations reference
This file documents every option an automation file accepts. It is generated by
the **Create example automation** button and is safe to delete — it is regenerated
(overwritten) each time you press that button. It is **not** itself an automation
(it has no frontmatter schedule), so the scheduler ignores it.
## How an automation file works
An automation is a Markdown file in your configured automations folder. It has two
parts:
1. A **YAML frontmatter block** fenced by \`---\` at the very top of the file. It
holds the options below (schedule, runtime, etc.).
2. The **prompt body**: everything after the closing \`---\`. This text is sent to
the CLI when the automation fires.
\`\`\`markdown
---
name: My automation
interval: 60
runtime: Claude
---
Write the prompt that gets sent to the CLI here.
\`\`\`
Each run opens its own session tab for the chosen runtime, waits for the CLI to
finish booting, then types the prompt body (optionally followed by Enter).
## Options
### \`name\` — string, optional
Display name shown in the Automations modal and in the run History.
- **Default:** the filename without its \`.md\` extension.
- **Example:** \`name: Daily standup notes\`
### \`enabled\` — true | false, optional
Master switch for automatic firing.
- **Default:** \`true\`.
- When \`false\`, the scheduler never auto-fires this automation. It still shows in
the modal (greyed out) and can be triggered manually with **Run now**.
- **Example:** \`enabled: false\`
### Schedule — set EXACTLY ONE of \`interval\` or \`cron\`
Every automation needs a schedule. You must provide **either** \`interval\` **or**
\`cron\`, never both and never neither — files that break this rule are reported as
errors in the modal.
#### \`interval\` — integer minutes (>= 1)
Fire every N minutes. The first run happens on the next scheduler tick after the
plugin loads; subsequent runs are N minutes apart.
- Must be a whole number \`>= 1\`.
- **Examples:** \`interval: 15\` (every 15 min), \`interval: 1440\` (once a day).
#### \`cron\` — string, standard 5-field expression
Fire on a calendar schedule. Quote the value so YAML treats it as a string.
The five space-separated fields are:
\`\`\`
minute hour day-of-month month day-of-week
\`\`\`
| Field | Allowed values |
|--------------|-----------------------|
| minute | 0–59 |
| hour | 0–23 |
| day-of-month | 1–31 |
| month | 1–12 |
| day-of-week | 0–7 (0 and 7 = Sunday)|
Common patterns (\`*\` = any, \`*/n\` = every n, \`a-b\` = range, \`a,b\` = list):
| Expression | Meaning |
|---------------------|----------------------------------|
| \`"*/30 * * * *"\` | every 30 minutes |
| \`"0 9 * * *"\` | every day at 09:00 |
| \`"0 9 * * 1-5"\` | weekdays at 09:00 |
| \`"0 */2 * * *"\` | every 2 hours, on the hour |
| \`"30 8,17 * * *"\` | at 08:30 and 17:30 every day |
| \`"0 8 1 * *"\` | 08:00 on the 1st of each month |
- **Example:** \`cron: "0 9 * * 1-5"\`
### \`runtime\` — string, optional
Which configured runtime to spawn for this automation, matched by its **id** OR its
**display name** (case-insensitive).
- **Default:** the default runtime set in plugin settings (when the line is omitted).
- A run naming a runtime that is not configured is **skipped** and logged in History.
- **Example:** \`runtime: Claude\`
### \`appendNewline\` — true | false, optional
Whether to send an Enter keystroke after the prompt so the CLI executes it.
- **Default:** \`true\`.
- Set \`false\` only if you want the text inserted into the input box **without**
submitting (e.g. to let yourself review/edit before pressing Enter).
- **Example:** \`appendNewline: false\`
### Prompt body — required
Everything after the closing \`---\` is the prompt. It must not be empty, otherwise
the file is reported as an error. Multi-line prompts are supported.
## Validation rules (summary)
A file is reported as an error in the modal (and never fires) when:
- the frontmatter block is missing;
- both \`interval\` and \`cron\` are set, or neither is;
- \`interval\` is not an integer \`>= 1\`;
- \`cron\` is not a valid 5-field expression;
- the prompt body is empty.
## Running and history
- The scheduler ticks periodically; due automations fire automatically (unless
\`enabled: false\`).
- The **Automations** modal lists every file with its schedule, last run, next run
and status, plus a per-row **Run now** and **Open file**.
- The **History** tab keeps a capped, chronological log of runs; you can clear it or
export it as a date-stamped Markdown note.
`;
function cloneDefaultRuntimes(): CliRuntimeConfig[] {
return DEFAULT_RUNTIMES.map((runtime) => ({ ...runtime }));
}
interface ProcessAdapter {
write(data: string): void;
resize?(cols: number, rows: number): void;
kill(signal?: string): void;
onData(callback: (data: string) => void): void;
onExit(callback: (exitCode: number, signal: string) => void): void;
}
type SessionOrigin = "manual" | "automation";
// A freshly spawned CLI needs time to render its interactive input box before
// it will accept a typed prompt + Enter. We treat a session as "ready" once its
// output has been quiet for SESSION_READY_QUIET_MS (boot/banner finished), and
// never wait longer than SESSION_READY_MAX_MS as a hard cap.
const SESSION_READY_QUIET_MS = 800;
const SESSION_READY_MAX_MS = 10000;
function createSessionTerminal(): { terminal: Terminal; fitAddon: FitAddon } {
const terminal = new Terminal({
cursorBlink: true,
convertEol: true,
fontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, monospace",
fontSize: 13,
scrollback: 3000,
theme: {
background: "#0f1115",
foreground: "#e6e6e6"
}
});
const fitAddon = new FitAddon();
terminal.loadAddon(fitAddon);
return { terminal, fitAddon };
}
/**
* One independent CLI session: its own PTY process and its own xterm terminal
* rendered into a dedicated host element. The view owns a list of these and
* shows one at a time via tabs.
*/
class CliSession {
readonly id: string;
runtimeId: string;
label: string;
origin: SessionOrigin;
readonly terminal: Terminal;
readonly fitAddon: FitAddon;
readonly hostEl: HTMLDivElement;
processHandle: ProcessAdapter | null = null;
status = "Idle";
pendingRestart = false;
// Live activity: "working" while the CLI emits output, "idle" after it goes
// quiet. Drives the tab dot colour and (for automations) idle auto-close.
activity: "working" | "idle" = "idle";
// Set true once an automation prompt has been sent, so idle auto-close only
// fires after the automation actually ran (not during boot).
closeOnIdleArmed = false;
onActivityChange: (() => void) | null = null;
private activityTimer: number | null = null;
private ready = false;
whenReady!: Promise<void>;
private resolveReady: (() => void) | null = null;
private settleTimer: number | null = null;
private maxWaitTimer: number | null = null;
constructor(params: {
id: string;
runtimeId: string;
label: string;
origin: SessionOrigin;
terminal: Terminal;
fitAddon: FitAddon;
hostEl: HTMLDivElement;
}) {
this.id = params.id;
this.runtimeId = params.runtimeId;
this.label = params.label;
this.origin = params.origin;
this.terminal = params.terminal;
this.fitAddon = params.fitAddon;
this.hostEl = params.hostEl;
this.resetReady();
}
private clearReadyTimers(): void {
if (this.settleTimer !== null) {
activeWindow.clearTimeout(this.settleTimer);
this.settleTimer = null;
}
if (this.maxWaitTimer !== null) {
activeWindow.clearTimeout(this.maxWaitTimer);
this.maxWaitTimer = null;
}
}
/** Arm a fresh readiness promise for a (re)spawn, and reset activity state. */
resetReady(): void {
this.ready = false;
this.clearReadyTimers();
if (this.activityTimer !== null) {
activeWindow.clearTimeout(this.activityTimer);
this.activityTimer = null;
}
this.activity = "idle";
this.closeOnIdleArmed = false;
this.whenReady = new Promise<void>((resolve) => {
this.resolveReady = resolve;
});
}
markReady(): void {
if (this.ready) {
return;
}
this.ready = true;
this.clearReadyTimers();
this.resolveReady?.();
this.resolveReady = null;
}
/** Hard cap so a session never blocks an automation forever. */
armReadyMaxWait(delayMs: number): void {
if (this.maxWaitTimer !== null) {
activeWindow.clearTimeout(this.maxWaitTimer);
}
this.maxWaitTimer = activeWindow.setTimeout(() => this.markReady(), delayMs);
}
/** Each output chunk (re)arms a quiet-period timer; readiness is declared
* once the CLI stops emitting for `quietMs`, i.e. its input box is drawn. */
noteOutputActivity(quietMs: number): void {
if (this.ready) {
return;
}
if (this.settleTimer !== null) {
activeWindow.clearTimeout(this.settleTimer);
}
this.settleTimer = activeWindow.setTimeout(() => this.markReady(), quietMs);
}
/** Each output chunk marks the session "working" and (re)arms a quiet timer
* that flips it back to "idle" after `idleMs` of silence. */
noteActivity(idleMs: number): void {
if (this.activity !== "working") {
this.activity = "working";
this.onActivityChange?.();
}
if (this.activityTimer !== null) {
activeWindow.clearTimeout(this.activityTimer);
}
this.activityTimer = activeWindow.setTimeout(() => {
this.activityTimer = null;
if (this.activity !== "idle") {
this.activity = "idle";
this.onActivityChange?.();
}
}, idleMs);
}
/** Force the idle state immediately (e.g. when the process exits). */
markIdle(): void {
if (this.activityTimer !== null) {
activeWindow.clearTimeout(this.activityTimer);
this.activityTimer = null;
}
if (this.activity !== "idle") {
this.activity = "idle";
this.onActivityChange?.();
}
}
isRunning(): boolean {
return this.processHandle !== null;
}
writeSystemLine(message: string): void {
this.terminal.write("\r[2K");
this.terminal.writeln(message);
}
sendPrompt(text: string, submitWithEnter: boolean): void {
if (!this.processHandle) {
throw new Error("CLI process is not running");
}
this.processHandle.write(text);
if (submitWithEnter) {
// Send Enter as a separate write after a short delay. Some TUIs (notably
// Codex) use bracketed-paste-style heuristics: when text+`\r` arrives in
// a single write they treat the `\r` as a literal newline inside the
// input field, not as the submit key. Splitting the writes lets the
// paste-detection window close, so the `\r` is read as a real Enter.
const handle = this.processHandle;
activeWindow.setTimeout(() => {
try {
handle.write("\r");
} catch {
/* process may have exited between writes */
}
}, 120);
}
// From now on, the next working→idle transition means "automation finished",
// which (if enabled) closes the tab. Driven by the CLI's real output, not a
// timer here, so a slow-to-respond CLI is not closed prematurely.
this.closeOnIdleArmed = true;
this.writeSystemLine(`[Automation prompt injected]`);
}
dispose(): void {
this.clearReadyTimers();
if (this.activityTimer !== null) {
activeWindow.clearTimeout(this.activityTimer);
this.activityTimer = null;
}
try {
this.terminal.dispose();
} catch {
/* ignore disposal errors */
}
this.hostEl.remove();
}
}
class ClaudeCliView extends ItemView {
private plugin: ClaudeCliPlugin;
private sessions: CliSession[] = [];
private activeSessionId: string | null = null;
private tabBarEl: HTMLDivElement | null = null;
private terminalsHostEl: HTMLDivElement | null = null;
private emptyHintEl: HTMLDivElement | null = null;
private statusEl: HTMLDivElement | null = null;
private resizeObserver: ResizeObserver | null = null;
private stopBtn: HTMLButtonElement | null = null;
private restartBtn: HTMLButtonElement | null = null;
private clearBtn: HTMLButtonElement | null = null;
constructor(leaf: WorkspaceLeaf, plugin: ClaudeCliPlugin) {
super(leaf);
this.plugin = plugin;
}
getViewType(): string {
return VIEW_TYPE_CLAUDE;
}
getDisplayText(): string {
return "Any AI CLI";
}
getIcon(): string {
return "bot";
}
onOpen(): Promise<void> {
this.contentEl.empty();
this.contentEl.addClass("claude-cli-view");
this.tabBarEl = this.contentEl.createDiv({ cls: "claude-cli-tabbar" });
const toolbarEl = this.contentEl.createDiv({ cls: "claude-cli-toolbar" });
const primaryRowEl = toolbarEl.createDiv({ cls: "claude-cli-toolbar-row" });
const newBtn = primaryRowEl.createEl("button", { text: "New session" });
const stopBtn = primaryRowEl.createEl("button", { text: "Stop" });
const restartBtn = primaryRowEl.createEl("button", { text: "Restart" });
const clearBtn = primaryRowEl.createEl("button", { text: "Clear" });
this.setButtonIcon(newBtn, "plus", "New session");
this.setButtonIcon(stopBtn, "square", "Stop");
this.setButtonIcon(restartBtn, "refresh-cw", "Restart");
this.setButtonIcon(clearBtn, "eraser", "Clear");
newBtn.addClass("claude-cli-btn-primary");
stopBtn.addClass("claude-cli-btn-danger");
this.stopBtn = stopBtn;
this.restartBtn = restartBtn;
this.clearBtn = clearBtn;
const secondaryRowEl = toolbarEl.createDiv({ cls: "claude-cli-toolbar-row" });
const mentionBtn = secondaryRowEl.createEl("button", { text: "@active file" });
const folderMentionBtn = secondaryRowEl.createEl("button", { text: "@active folder" });
const automationsBtn = secondaryRowEl.createEl("button", { text: "Automations" });
this.setButtonIcon(mentionBtn, "file-plus", "@active file");
this.setButtonIcon(folderMentionBtn, "folder-plus", "@active folder");
this.setButtonIcon(automationsBtn, "calendar-clock", "Automations");
mentionBtn.addClass("claude-cli-btn-info");
folderMentionBtn.addClass("claude-cli-btn-info");
automationsBtn.addClass("claude-cli-btn-info");
this.statusEl = this.contentEl.createDiv({ cls: "claude-cli-status" });
newBtn.addEventListener("click", (evt) => this.openNewSessionMenu(evt));
stopBtn.addEventListener("click", () => this.stopActiveSession());
restartBtn.addEventListener("click", () => this.restartActiveSession());
clearBtn.addEventListener("click", () => this.getActiveSession()?.terminal.clear());
mentionBtn.addEventListener("click", () => this.insertActiveFileMention());
folderMentionBtn.addEventListener("click", () => this.insertActiveFolderMention());
automationsBtn.addEventListener("click", () => {
new AutomationsModal(this.app, this.plugin).open();
});
this.terminalsHostEl = this.contentEl.createDiv({ cls: "claude-cli-terminals" });
this.emptyHintEl = this.terminalsHostEl.createDiv({ cls: "claude-cli-empty-hint" });
this.emptyHintEl.setText("No session running. Use the + button to launch a runtime.");
this.resizeObserver = new ResizeObserver(() => {
const session = this.getActiveSession();
if (!session) {
return;
}
session.fitAddon.fit();
if (session.processHandle) {
session.processHandle.resize?.(
Math.max(20, session.terminal.cols || 120),
Math.max(10, session.terminal.rows || 30)
);
}
});
this.resizeObserver.observe(this.contentEl);
this.renderTabBar();
this.updateEmptyState();
this.updateToolbarState();
if (this.plugin.settings.autoStart) {
const runtime = this.getSelectedRuntime();
if (runtime) {
this.startSession({ runtimeId: runtime.id, origin: "manual" });
} else {
this.setStatus("No runtime configured. Add one in plugin settings.");
}
} else {
this.setStatus("Idle");
}
return Promise.resolve();
}
onClose(): Promise<void> {
for (const session of this.sessions) {
try {
session.processHandle?.kill("SIGTERM");
} catch {
/* ignore */
}
session.dispose();
}
this.sessions = [];
this.activeSessionId = null;
this.resizeObserver?.disconnect();
this.resizeObserver = null;
this.statusEl = null;
this.tabBarEl = null;
this.terminalsHostEl = null;
this.emptyHintEl = null;
return Promise.resolve();
}
getActiveSession(): CliSession | null {
if (!this.activeSessionId) {
return null;
}
return this.findSession(this.activeSessionId);
}
findSession(id: string): CliSession | null {
return this.sessions.find((s) => s.id === id) ?? null;
}
isProcessRunning(): boolean {
return this.sessions.some((s) => s.isRunning());
}
startSession(params: { runtimeId: string; origin: SessionOrigin }): CliSession | null {
if (!this.terminalsHostEl) {
return null;
}
const runtime = this.plugin.settings.runtimes.find((r) => r.id === params.runtimeId);
if (!runtime) {
const message = "Runtime not configured. Add one in plugin settings.";
this.setStatus(message);
new Notice(message, 6000);
return null;
}
if (!canOpenSession(this.sessions.length, this.plugin.settings.maxConcurrentSessions)) {
const message = `Session limit reached (${this.plugin.settings.maxConcurrentSessions}). Close a tab first.`;
this.setStatus(message);
new Notice(message, 6000);
return null;
}
const command = (runtime.command || "").trim();
if (!command) {
const message = `Runtime "${runtime.name || "(Unnamed)"}" has an empty command. Set one in plugin settings.`;
this.setStatus(message);
new Notice(message, 6000);
return null;
}
const hostEl = this.terminalsHostEl.createDiv({ cls: "claude-cli-terminal" });
const { terminal, fitAddon } = createSessionTerminal();
terminal.open(hostEl);
fitAddon.fit();
const label = nextSessionLabel(
this.sessions.map((s) => s.label),
runtime.name || "(Unnamed)"
);
const session = new CliSession({
id: randomUUID(),
runtimeId: runtime.id,
label,
origin: params.origin,
terminal,
fitAddon,
hostEl
});
this.sessions.push(session);
terminal.onData((data) => session.processHandle?.write(data));
session.onActivityChange = () => {
this.renderTabBar();
if (
session.activity === "idle" &&
session.origin === "automation" &&
session.isRunning() &&
session.closeOnIdleArmed &&
this.plugin.settings.autoCloseAutomationSessionsOnIdle
) {
this.closeSession(session.id);
}
};
session.writeSystemLine(`CLI session ready (${label}).`);
// Activate the new tab before spawning so the terminal is visible and sized.
this.setActiveSession(session.id);
this.spawnIntoSession(session, runtime);
this.renderTabBar();
this.updateToolbarState();
return session;
}
closeSession(id: string): void {
const index = this.sessions.findIndex((s) => s.id === id);
if (index < 0) {
return;
}
const session = this.sessions[index];
try {
session.processHandle?.kill("SIGTERM");
} catch {
/* ignore */
}
session.processHandle = null;
session.markReady();
session.dispose();
this.sessions.splice(index, 1);
if (this.activeSessionId === id) {
this.activeSessionId = null;
const next = this.sessions[index] ?? this.sessions[index - 1] ?? null;
if (next) {
this.setActiveSession(next.id);
}
}
this.renderTabBar();
this.updateEmptyState();
this.updateToolbarState();
if (!this.getActiveSession()) {
this.setStatus("Idle");
}
}
setActiveSession(id: string): void {
const session = this.findSession(id);
if (!session) {
return;
}
this.activeSessionId = id;
for (const s of this.sessions) {
s.hostEl.toggleClass("is-hidden", s.id !== id);
}
this.updateEmptyState();
this.renderTabBar();
// A hidden terminal cannot lay out; refit + resize now that it is visible,
// otherwise xterm output degrades to letter-per-line.
session.fitAddon.fit();
session.processHandle?.resize?.(
Math.max(20, session.terminal.cols || 120),
Math.max(10, session.terminal.rows || 30)
);
session.terminal.focus();
this.setStatus(session.status);
this.updateToolbarState();
}
sendAutomationPromptTo(sessionId: string, text: string, submitWithEnter: boolean): void {
const session = this.findSession(sessionId);
if (!session) {
throw new Error("Session no longer exists");
}
session.sendPrompt(text, submitWithEnter);
}
// Called by the plugin when the configured runtimes change in settings.
refreshRuntimeSelect(): void {
this.renderTabBar();
}
private spawnIntoSession(session: CliSession, runtime: CliRuntimeConfig): boolean {
const label = session.label;
const command = (runtime.command || "").trim();
if (!command) {
const message = `Runtime "${runtime.name || "(Unnamed)"}" has an empty command. Set one in plugin settings.`;
session.writeSystemLine(`[${message}]`);
session.status = message;
if (this.activeSessionId === session.id) {
this.setStatus(message);
}
session.markReady();
return false;
}
const codexLike = isCodexLikeCommand(command);
if (codexLike) {
session.terminal.reset();
session.fitAddon.fit();
}
session.resetReady();
session.writeSystemLine(`[Starting: ${command}]`);
session.status = `Starting in vault folder (${process.platform})...`;
if (this.activeSessionId === session.id) {
this.setStatus(session.status);
}
try {
const vaultPath = getVaultBasePath(this.app);
if (!vaultPath) {
const message = `Unable to resolve current vault path. ${label} was not started.`;
session.writeSystemLine(`[${message}]`);
session.status = message;
if (this.activeSessionId === session.id) {
this.setStatus(message);
}
new Notice(message, 6000);
session.markReady();
return false;
}
if (!fs.existsSync(vaultPath)) {
const message = `Vault path does not exist: ${vaultPath}`;
session.writeSystemLine(`[${message}]`);
session.status = message;
if (this.activeSessionId === session.id) {
this.setStatus(message);
}
new Notice(message, 6000);
session.markReady();
return false;
}
const shellEnv = getShellEnv();
if (codexLike) {
// Keep Codex output readable in embedded terminals.
shellEnv.NO_COLOR = "1";
shellEnv.CLICOLOR = "0";
shellEnv.FORCE_COLOR = "0";
}
const helperHandle = spawnPtyProxy({
command,
cwd: vaultPath,
env: shellEnv,
cols: Math.max(20, session.terminal.cols || 120),
rows: Math.max(10, session.terminal.rows || 30),
nodeExecutable: this.plugin.settings.nodeExecutable,
pluginDir: this.plugin.manifest.dir,
vaultPath,
verbose: this.plugin.settings.verboseProxyLogs
});
session.processHandle = makeProxyAdapter(helperHandle);
} catch (error) {
const message = `Failed to start process: ${(error as Error).message}`;
session.writeSystemLine(`[${message}]`);
session.status = message;
if (this.activeSessionId === session.id) {
this.setStatus(message);
}
new Notice(message, 7000);
session.processHandle = null;
session.markReady();
return false;
}
session.status = "Running";
if (this.activeSessionId === session.id) {
this.setStatus("Running");
}
session.armReadyMaxWait(SESSION_READY_MAX_MS);
session.processHandle.onData((data: string) => {
session.terminal.write(data);
// Readiness = first output, then a quiet period (input box rendered).
session.noteOutputActivity(SESSION_READY_QUIET_MS);
// Live activity for the tab dot + automation idle auto-close.
session.noteActivity(this.plugin.settings.idleTimeoutSeconds * 1000);
});
session.processHandle.onExit((exitCode, signal) => {
session.processHandle = null;
session.markReady();
session.markIdle();
if (session.pendingRestart) {
session.pendingRestart = false;
const current = this.plugin.settings.runtimes.find((r) => r.id === session.runtimeId);
if (current) {
this.spawnIntoSession(session, current);
this.renderTabBar();
this.updateToolbarState();
return;
}
}
const message = `Process exited (code=${exitCode}, signal=${signal})`;
session.writeSystemLine(`[${message}]`);
session.status = message;
if (this.activeSessionId === session.id) {
this.setStatus(message);
}
if (session.origin === "automation" && this.plugin.settings.autoCloseAutomationSessions) {
this.closeSession(session.id);
return;
}
this.renderTabBar();
this.updateToolbarState();
});
if (this.activeSessionId === session.id) {
session.fitAddon.fit();
}
return true;
}
private stopActiveSession(): void {
const session = this.getActiveSession();
if (!session || !session.processHandle) {
return;
}
session.writeSystemLine(`[Stopping ${session.label} process...]`);
session.status = "Stopping...";
this.setStatus("Stopping...");
try {
session.processHandle.kill("SIGTERM");
} catch (error) {
const message = `Failed to stop process: ${(error as Error).message}`;
session.writeSystemLine(`[${message}]`);
session.status = message;
this.setStatus(message);
new Notice(message, 6000);
}
}
private restartActiveSession(): void {
const session = this.getActiveSession();
if (!session) {
return;
}
const runtime = this.plugin.settings.runtimes.find((r) => r.id === session.runtimeId);
if (!runtime) {
new Notice("Runtime is no longer configured.", 6000);
return;
}
if (session.processHandle) {
session.pendingRestart = true;
session.writeSystemLine(`[Restart requested: ${session.label}]`);
session.status = "Restarting...";
this.setStatus("Restarting...");
try {
session.processHandle.kill("SIGTERM");
} catch {
session.pendingRestart = false;
}
return;
}
this.spawnIntoSession(session, runtime);
this.renderTabBar();
this.updateToolbarState();
}
private openNewSessionMenu(evt: MouseEvent): void {
const runtimes = this.plugin.settings.runtimes;
if (runtimes.length === 0) {
new Notice("No runtime configured. Add one in plugin settings.", 6000);
return;
}
if (runtimes.length === 1) {
this.startSession({ runtimeId: runtimes[0].id, origin: "manual" });
return;
}
const menu = new Menu();
for (const runtime of runtimes) {
menu.addItem((item) =>
item
.setTitle(runtime.name || "(Unnamed)")
.setIcon("terminal")
.onClick(() => {
this.startSession({ runtimeId: runtime.id, origin: "manual" });
})
);
}
menu.showAtMouseEvent(evt);
}
private renderTabBar(): void {
if (!this.tabBarEl) {
return;
}
this.tabBarEl.empty();
for (const session of this.sessions) {
const tabEl = this.tabBarEl.createDiv({
cls: `claude-cli-tab${session.id === this.activeSessionId ? " is-active" : ""}`
});
const dotCls = tabDotClass({
running: session.isRunning(),
activity: session.activity,
origin: session.origin
});
tabEl.createSpan({ cls: `claude-cli-tab-dot ${dotCls}` });
if (session.origin === "automation") {
const autoIcon = tabEl.createSpan({ cls: "claude-cli-tab-auto" });
setIcon(autoIcon, "calendar-clock");
}
tabEl.createSpan({ text: session.label, cls: "claude-cli-tab-label" });
const closeEl = tabEl.createSpan({ cls: "claude-cli-tab-close" });
setIcon(closeEl, "x");
closeEl.setAttribute("aria-label", "Close session");