tabherd 0.0.1 → 0.6.0

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.
Files changed (68) hide show
  1. package/CHANGELOG.md +166 -0
  2. package/LICENSE +674 -0
  3. package/README.md +538 -2
  4. package/launcher/npm.js +9 -0
  5. package/lib/agents.js +324 -0
  6. package/lib/codex-client.js +306 -0
  7. package/lib/codex-rollout.js +251 -0
  8. package/lib/codex.js +424 -0
  9. package/lib/comfy.js +479 -0
  10. package/lib/completed.js +55 -0
  11. package/lib/copilot.js +359 -0
  12. package/lib/cursor.js +516 -0
  13. package/lib/dismissed.js +30 -0
  14. package/lib/filters.js +120 -0
  15. package/lib/groups.js +144 -0
  16. package/lib/history.js +253 -0
  17. package/lib/llamacpp.js +159 -0
  18. package/lib/lmstudio.js +134 -0
  19. package/lib/localai.js +291 -0
  20. package/lib/memory.js +55 -0
  21. package/lib/ollama.js +124 -0
  22. package/lib/open-dashboard.js +39 -0
  23. package/lib/opencode.js +371 -0
  24. package/lib/repos.js +81 -0
  25. package/lib/saved.js +33 -0
  26. package/lib/secrets.js +196 -0
  27. package/lib/session-id.js +9 -0
  28. package/lib/settings.js +231 -0
  29. package/lib/store.js +44 -0
  30. package/lib/terminals/index.js +62 -0
  31. package/lib/terminals/kitty.js +126 -0
  32. package/lib/terminals/linux.js +310 -0
  33. package/lib/terminals/macos.js +468 -0
  34. package/lib/terminals/tmux.js +89 -0
  35. package/lib/terminals/unix-driver.js +172 -0
  36. package/lib/terminals/unix.js +204 -0
  37. package/lib/terminals/unsupported.js +22 -0
  38. package/lib/terminals/wezterm.js +103 -0
  39. package/lib/terminals/windows-close.ps1 +125 -0
  40. package/lib/terminals/windows-focus.ps1 +235 -0
  41. package/lib/terminals/windows-pick-folder.ps1 +57 -0
  42. package/lib/terminals/windows-titles.js +124 -0
  43. package/lib/terminals/windows-titles.ps1 +95 -0
  44. package/lib/terminals/windows.js +166 -0
  45. package/lib/ticket-refs.js +184 -0
  46. package/lib/tickets.js +437 -0
  47. package/lib/todos.js +166 -0
  48. package/lib/trackers.js +541 -0
  49. package/lib/transcript.js +314 -0
  50. package/lib/updates.js +186 -0
  51. package/package.json +35 -7
  52. package/public/app.js +4077 -0
  53. package/public/favicon.svg +1 -0
  54. package/public/icons/tabherd-128.png +0 -0
  55. package/public/icons/tabherd-16.png +0 -0
  56. package/public/icons/tabherd-20.png +0 -0
  57. package/public/icons/tabherd-24.png +0 -0
  58. package/public/icons/tabherd-256.png +0 -0
  59. package/public/icons/tabherd-32.png +0 -0
  60. package/public/icons/tabherd-40.png +0 -0
  61. package/public/icons/tabherd-48.png +0 -0
  62. package/public/icons/tabherd-512.png +0 -0
  63. package/public/icons/tabherd-64.png +0 -0
  64. package/public/index.html +655 -0
  65. package/public/lang/es.js +742 -0
  66. package/public/style.css +1443 -0
  67. package/server.js +814 -0
  68. package/placeholder.js +0 -3
@@ -0,0 +1,235 @@
1
+ param([int]$TargetPid, [switch]$DryRun, [string]$Send, [string]$StatusFile)
2
+
3
+ # Brings the window hosting a console process to the front. In Windows Terminal
4
+ # it also selects the tab and focuses the pane that the process runs in.
5
+ # -Send then types a prompt into that session and presses Enter.
6
+ # Prints one line of JSON. -DryRun reports how the tab would be found and
7
+ # changes nothing.
8
+
9
+ $ErrorActionPreference = 'Stop'
10
+ $ProgressPreference = 'SilentlyContinue'
11
+ [Console]::OutputEncoding = [Text.Encoding]::UTF8
12
+ Add-Type -AssemblyName UIAutomationClient, UIAutomationTypes
13
+ Add-Type @"
14
+ using System; using System.Text; using System.Collections.Generic; using System.Runtime.InteropServices;
15
+
16
+ // An INPUT_RECORD holding a KEY_EVENT_RECORD, flattened.
17
+ [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)]
18
+ public struct KeyRecord {
19
+ [FieldOffset(0)] public ushort EventType;
20
+ [FieldOffset(4)] public int KeyDown;
21
+ [FieldOffset(8)] public ushort RepeatCount;
22
+ [FieldOffset(10)] public ushort VirtualKeyCode;
23
+ [FieldOffset(12)] public ushort VirtualScanCode;
24
+ [FieldOffset(14)] public char UnicodeChar;
25
+ [FieldOffset(16)] public uint ControlKeyState;
26
+ }
27
+
28
+ public static class W {
29
+ [DllImport("kernel32.dll")] public static extern bool FreeConsole();
30
+ [DllImport("kernel32.dll")] public static extern bool AttachConsole(uint pid);
31
+ [DllImport("kernel32.dll")] public static extern IntPtr GetConsoleWindow();
32
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] public static extern uint GetConsoleTitle(StringBuilder sb, uint size);
33
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr CreateFile(string name, uint access, uint share, IntPtr security, uint disposition, uint flags, IntPtr template);
34
+ [DllImport("kernel32.dll")] public static extern bool CloseHandle(IntPtr handle);
35
+ [DllImport("kernel32.dll", EntryPoint = "WriteConsoleInputW")] public static extern bool WriteConsoleInput(IntPtr input, KeyRecord[] records, uint count, out uint written);
36
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern short VkKeyScan(char c);
37
+ [DllImport("user32.dll")] public static extern uint MapVirtualKey(uint code, uint type);
38
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetClassName(IntPtr hwnd, StringBuilder sb, int max);
39
+ [DllImport("user32.dll")] public static extern IntPtr GetAncestor(IntPtr hwnd, uint flags);
40
+ [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hwnd);
41
+ [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr hwnd);
42
+ [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hwnd, int cmd);
43
+ [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hwnd);
44
+ [DllImport("user32.dll")] public static extern void keybd_event(byte vk, byte scan, uint flags, UIntPtr extra);
45
+
46
+ public static string ClassOf(IntPtr hwnd) {
47
+ var sb = new StringBuilder(256);
48
+ GetClassName(hwnd, sb, sb.Capacity);
49
+ return sb.ToString();
50
+ }
51
+
52
+ // The input buffer of whichever console this process is attached to.
53
+ public static IntPtr OpenConsoleInput() {
54
+ return CreateFile("CONIN$", 0xC0000000, 3, IntPtr.Zero, 3, 0, IntPtr.Zero);
55
+ }
56
+
57
+ // Key-down and key-up records for each character, as if typed.
58
+ public static bool Type(IntPtr input, string text) {
59
+ var records = new List<KeyRecord>();
60
+ foreach (char c in text) {
61
+ short scan = VkKeyScan(c);
62
+ ushort vk = (ushort)(scan == -1 ? 0 : scan & 0xff);
63
+ uint shift = scan != -1 && (scan & 0x100) != 0 ? 0x10u : 0u;
64
+ for (int down = 1; down >= 0; down--) {
65
+ records.Add(new KeyRecord { EventType = 1, KeyDown = down, RepeatCount = 1, VirtualKeyCode = vk,
66
+ VirtualScanCode = (ushort)MapVirtualKey(vk, 0), UnicodeChar = c, ControlKeyState = shift });
67
+ }
68
+ }
69
+ uint written;
70
+ return WriteConsoleInput(input, records.ToArray(), (uint)records.Count, out written) && written == records.Count;
71
+ }
72
+ }
73
+ "@
74
+
75
+ $AE = [Windows.Automation.AutomationElement]
76
+ $Scope = [Windows.Automation.TreeScope]
77
+
78
+ function Out-Result($ok, $props) {
79
+ $props.ok = $ok
80
+ [Console]::Out.WriteLine(($props | ConvertTo-Json -Compress))
81
+ exit 0
82
+ }
83
+
84
+ # Claude Code prefixes its title with a spinner or status glyph that changes.
85
+ function Get-TitleKey([string]$title) {
86
+ return ($title -replace '^[^\p{L}\p{N}]+', '').Trim()
87
+ }
88
+
89
+ # A newly selected tab's panes take a moment to appear, hence the retries.
90
+ function Find-Pane($window, [string]$key, [int]$attempts = 1) {
91
+ $cond = New-Object Windows.Automation.PropertyCondition($AE::ClassNameProperty, 'TermControl')
92
+ foreach ($attempt in 1..$attempts) {
93
+ foreach ($pane in $window.FindAll($Scope::Descendants, $cond)) {
94
+ if ((Get-TitleKey $pane.Current.HelpText) -eq $key) { return $pane }
95
+ }
96
+ if ($attempt -lt $attempts) { Start-Sleep -Milliseconds 60 }
97
+ }
98
+ return $null
99
+ }
100
+
101
+ function Select-Tab($tab) {
102
+ $tab.GetCurrentPattern([Windows.Automation.SelectionItemPattern]::Pattern).Select()
103
+ }
104
+
105
+ function Get-SelectedTabName($window) {
106
+ $tabCond = New-Object Windows.Automation.PropertyCondition($AE::ControlTypeProperty, [Windows.Automation.ControlType]::TabItem)
107
+ foreach ($tab in $window.FindAll($Scope::Descendants, $tabCond)) {
108
+ if ($tab.GetCurrentPattern([Windows.Automation.SelectionItemPattern]::Pattern).Current.IsSelected) { return $tab.Current.Name }
109
+ }
110
+ return $null
111
+ }
112
+
113
+ function Get-WindowFromAncestors([int]$id) {
114
+ for ($i = 0; $i -lt 10 -and $id -gt 0; $i++) {
115
+ $p = Get-Process -Id $id -ErrorAction SilentlyContinue
116
+ if ($p -and $p.MainWindowHandle -ne [IntPtr]::Zero) { return $p.MainWindowHandle }
117
+ $cim = Get-CimInstance Win32_Process -Filter "ProcessId=$id" -ErrorAction SilentlyContinue
118
+ if (-not $cim) { break }
119
+ $id = [int]$cim.ParentProcessId
120
+ }
121
+ return [IntPtr]::Zero
122
+ }
123
+
124
+ # Writes straight into the session's console input, so the text reaches that
125
+ # session even if its window couldn't be brought forward. Returns a problem
126
+ # description, or nothing on success.
127
+ function Send-Prompt([string]$text) {
128
+ # Typing into an open permission prompt or dialog could answer it.
129
+ if ($StatusFile -and (Test-Path -LiteralPath $StatusFile)) {
130
+ if ((Get-Content -Raw -LiteralPath $StatusFile | ConvertFrom-Json).status -eq 'waiting') { return 'waiting' }
131
+ }
132
+ [void][W]::FreeConsole()
133
+ if (-not [W]::AttachConsole([uint32]$TargetPid)) { return "couldn't attach to its console" }
134
+ try {
135
+ $conIn = [W]::OpenConsoleInput()
136
+ if ($conIn -eq [IntPtr]-1) { return "couldn't open its console input" }
137
+ try {
138
+ if (-not [W]::Type($conIn, $text)) { return "couldn't type into its console" }
139
+ # Sent on its own, Enter submits the prompt; in the same burst Claude Code
140
+ # would take it as part of a paste.
141
+ Start-Sleep -Milliseconds 250
142
+ if (-not [W]::Type($conIn, "`r")) { return "couldn't press Enter in its console" }
143
+ } finally {
144
+ [void][W]::CloseHandle($conIn)
145
+ }
146
+ } finally {
147
+ [void][W]::FreeConsole()
148
+ }
149
+ }
150
+
151
+ # 1. The console tells us both the app's title and, through the owner of its
152
+ # window, which top-level window hosts it.
153
+ $top = [IntPtr]::Zero
154
+ $key = ''
155
+ $hiddenConsole = $false
156
+ [void][W]::FreeConsole()
157
+ if ([W]::AttachConsole([uint32]$TargetPid)) {
158
+ $con = [W]::GetConsoleWindow()
159
+ $sb = New-Object Text.StringBuilder 1024
160
+ [void][W]::GetConsoleTitle($sb, 1024)
161
+ [void][W]::FreeConsole()
162
+ $key = Get-TitleKey $sb.ToString()
163
+ if ($con -ne [IntPtr]::Zero) {
164
+ $root = [W]::GetAncestor($con, 3)
165
+ if ($root -ne $con) { $top = $root }
166
+ elseif ([W]::IsWindowVisible($con)) { $top = $con }
167
+ # A hidden classic console belongs to a background process. Its ancestors'
168
+ # windows, such as the terminal that launched it, aren't its window.
169
+ elseif ([W]::ClassOf($con) -eq 'ConsoleWindowClass') { $hiddenConsole = $true }
170
+ }
171
+ }
172
+ # VS Code, Claude Desktop and similar hosts give the session a pseudoconsole
173
+ # with no owner, or no console at all; the host app's window is the answer.
174
+ if ($top -eq [IntPtr]::Zero -and -not $hiddenConsole) { $top = Get-WindowFromAncestors $TargetPid }
175
+ if ($top -eq [IntPtr]::Zero -and -not $Send) {
176
+ Out-Result $false @{ error = 'No window found for this session. It may be running in the background.' }
177
+ }
178
+
179
+ $windowName = $null
180
+ $terminal = $false
181
+ $tabFound = $false
182
+ $tabName = $null
183
+ $raised = $false
184
+ if ($top -ne [IntPtr]::Zero) {
185
+ # 2. In Windows Terminal, find the tab. Only the selected tab's panes are
186
+ # visible to UI Automation, and a renamed tab hides the app's title, so
187
+ # step through the tabs when the name doesn't give it away.
188
+ $window = $AE::FromHandle($top)
189
+ $windowName = $window.Current.Name
190
+ $terminal = $window.Current.ClassName -eq 'CASCADIA_HOSTING_WINDOW_CLASS'
191
+ $pane = $null
192
+ if ($terminal -and $key) {
193
+ $pane = Find-Pane $window $key
194
+ if (-not $pane) {
195
+ $tabCond = New-Object Windows.Automation.PropertyCondition($AE::ControlTypeProperty, [Windows.Automation.ControlType]::TabItem)
196
+ $tabs = @($window.FindAll($Scope::Descendants, $tabCond))
197
+ $original = $tabs | Where-Object { $_.GetCurrentPattern([Windows.Automation.SelectionItemPattern]::Pattern).Current.IsSelected } | Select-Object -First 1
198
+ $named = @($tabs | Where-Object { (Get-TitleKey $_.Current.Name) -eq $key })
199
+ if ($DryRun) {
200
+ Out-Result $true @{ window = $windowName; terminal = $true; key = $key; tab = $(if ($named.Count) { "named: $($named[0].Current.Name)" } else { "search $($tabs.Count) tabs" }) }
201
+ }
202
+ $candidates = $named + @($tabs | Where-Object { $named -notcontains $_ })
203
+ foreach ($tab in $candidates) {
204
+ Select-Tab $tab
205
+ $pane = Find-Pane $window $key 8
206
+ if ($pane) { break }
207
+ }
208
+ if (-not $pane -and $original) { Select-Tab $original }
209
+ }
210
+ $tabFound = [bool]$pane
211
+ if ($pane) { $tabName = Get-SelectedTabName $window }
212
+ }
213
+ if ($DryRun) { Out-Result $true @{ window = $windowName; terminal = $terminal; key = $key; tab = $(if ($pane) { 'already selected' } else { 'none' }) } }
214
+
215
+ # 3. Raise the window. Windows only lets the foreground app hand over focus;
216
+ # a synthetic Alt press gives this process that right.
217
+ if ([W]::IsIconic($top)) { [void][W]::ShowWindow($top, 9) }
218
+ [W]::keybd_event(0x12, 0, 0, [UIntPtr]::Zero)
219
+ $raised = [W]::SetForegroundWindow($top)
220
+ [W]::keybd_event(0x12, 0, 2, [UIntPtr]::Zero)
221
+ if ($pane) { try { $pane.SetFocus() } catch {} }
222
+ }
223
+
224
+ # 4. Optionally ask the session something.
225
+ $sent = $false
226
+ if ($Send) {
227
+ $problem = Send-Prompt $Send
228
+ if ($problem -eq 'waiting') {
229
+ Out-Result $false @{ error = 'It started waiting on a prompt or dialog, so nothing was typed. Answer that first.'; window = $windowName }
230
+ }
231
+ if ($problem) { Out-Result $false @{ error = "Couldn't send the question: $problem."; window = $windowName } }
232
+ $sent = $true
233
+ }
234
+
235
+ Out-Result $true @{ window = $windowName; hwnd = [string][int64]$top; tab = $tabFound; tabName = $tabName; raised = $raised; terminal = $terminal; sent = $sent }
@@ -0,0 +1,57 @@
1
+ # Shows a Windows folder picker and prints the result as one line of JSON:
2
+ # {"ok":true,"path":"..."} or {"ok":true,"cancelled":true}. The server runs it
3
+ # for a to-do's folder. The folder to start in and the dialog's title come in
4
+ # as environment variables, so nothing in them is ever read as code.
5
+ $ErrorActionPreference = 'Stop'
6
+ [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false
7
+ Add-Type -AssemblyName System.Windows.Forms
8
+ Add-Type -Namespace Picker -Name W -MemberDefinition @'
9
+ [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hwnd, int cmd);
10
+ [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hwnd);
11
+ [DllImport("user32.dll")] public static extern void keybd_event(byte vk, byte scan, uint flags, UIntPtr extra);
12
+ '@
13
+
14
+ $start = $env:AGENTS_PICK_START
15
+ $title = $env:AGENTS_PICK_TITLE
16
+
17
+ try {
18
+ # The server runs in the background, and Windows doesn't let a background
19
+ # process put its windows in front. The dialog's owner is a topmost window,
20
+ # invisible, brought forward with a synthetic Alt press as in
21
+ # windows-focus.ps1, so the dialog opens in front of the dashboard.
22
+ $owner = New-Object System.Windows.Forms.Form -Property @{
23
+ TopMost = $true
24
+ ShowInTaskbar = $false
25
+ FormBorderStyle = 'None'
26
+ Opacity = 0
27
+ StartPosition = 'CenterScreen'
28
+ Size = New-Object System.Drawing.Size 1, 1
29
+ }
30
+ $owner.Show()
31
+ # The server starts this hidden, and Windows applies that to the first
32
+ # window the process shows, so the owner stayed hidden and the dialog
33
+ # returned at once without showing. Showing it a second time works; it has
34
+ # no size or opacity, so nothing appears.
35
+ [void][Picker.W]::ShowWindow($owner.Handle, 5)
36
+ [Picker.W]::keybd_event(0x12, 0, 0, [UIntPtr]::Zero)
37
+ [void][Picker.W]::SetForegroundWindow($owner.Handle)
38
+ [Picker.W]::keybd_event(0x12, 0, 2, [UIntPtr]::Zero)
39
+
40
+ $dialog = New-Object System.Windows.Forms.FolderBrowserDialog
41
+ $dialog.Description = if ($title) { $title } else { 'Choose a folder' }
42
+ # Windows PowerShell's .NET has the older dialog, without these.
43
+ $modern = [bool]($dialog | Get-Member -Name InitialDirectory)
44
+ if ($modern) { $dialog.UseDescriptionForTitle = $true }
45
+ if ($start -and (Test-Path -LiteralPath $start -PathType Container)) {
46
+ if ($modern) { $dialog.InitialDirectory = $start } else { $dialog.SelectedPath = $start }
47
+ }
48
+ $result = $dialog.ShowDialog($owner)
49
+ $owner.Close()
50
+ if ($result -eq [System.Windows.Forms.DialogResult]::OK -and $dialog.SelectedPath) {
51
+ ConvertTo-Json -Compress @{ ok = $true; path = $dialog.SelectedPath }
52
+ } else {
53
+ '{"ok":true,"cancelled":true}'
54
+ }
55
+ } catch {
56
+ ConvertTo-Json -Compress @{ ok = $false; error = "The folder picker failed: $($_.Exception.Message)" }
57
+ }
@@ -0,0 +1,124 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const { spawn } = require('child_process');
6
+
7
+ const SCRIPT = path.join(__dirname, 'windows-titles.ps1');
8
+ const REFRESH_MS = 3000;
9
+ const TIMEOUT_MS = 15000;
10
+
11
+ // pid -> { title, window, tab }. A renamed tab only shows whose it is while
12
+ // selected, so what was learned is kept until the tab or session goes away.
13
+ const known = new Map();
14
+ let worker = null;
15
+ let pending = null;
16
+ let lastScanAt = 0;
17
+
18
+ const titleKey = (title) => String(title || '').replace(/^[^\p{L}\p{N}]+/u, '').trim();
19
+
20
+ function startWorker() {
21
+ const script = fs.readFileSync(SCRIPT, 'utf8');
22
+ // An encoded command isn't subject to the script execution policy.
23
+ const args = ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')];
24
+ const child = spawn('powershell.exe', args, { windowsHide: true, stdio: ['pipe', 'pipe', 'ignore'] });
25
+ // It doesn't keep Node running by itself: the server does that, and a
26
+ // one-off run, such as --once, can exit.
27
+ child.unref();
28
+ child.stdin.unref?.();
29
+ child.stdout.unref?.();
30
+ let buffer = '';
31
+ child.stdout.setEncoding('utf8');
32
+ child.stdout.on('data', (chunk) => {
33
+ buffer += chunk;
34
+ let end;
35
+ while ((end = buffer.indexOf('\n')) >= 0) {
36
+ const line = buffer.slice(0, end).trim();
37
+ buffer = buffer.slice(end + 1);
38
+ if (!pending) continue;
39
+ const { resolve, timer } = pending;
40
+ pending = null;
41
+ clearTimeout(timer);
42
+ try {
43
+ resolve(JSON.parse(line));
44
+ } catch {
45
+ resolve(null);
46
+ }
47
+ }
48
+ });
49
+ const reset = () => {
50
+ if (worker === child) worker = null;
51
+ if (pending) {
52
+ clearTimeout(pending.timer);
53
+ pending.resolve(null);
54
+ pending = null;
55
+ }
56
+ };
57
+ child.on('exit', reset);
58
+ child.on('error', reset);
59
+ child.stdin.on('error', reset);
60
+ return child;
61
+ }
62
+
63
+ function scan(pids) {
64
+ if (!worker) worker = startWorker();
65
+ const child = worker;
66
+ return new Promise((resolve) => {
67
+ const timer = setTimeout(() => child.kill(), TIMEOUT_MS);
68
+ pending = { resolve, timer };
69
+ child.stdin.write(`${pids.join(' ')}\n`);
70
+ });
71
+ }
72
+
73
+ function merge(result, pids) {
74
+ const live = new Set(pids.map(String));
75
+ for (const pid of known.keys()) if (!live.has(pid)) known.delete(pid);
76
+ const windows = result.windows || {};
77
+ for (const [pid, s] of Object.entries(result.sessions || {})) {
78
+ const prev = known.get(pid);
79
+ const entry = { title: s.title || '', window: s.window || null, tab: s.tab || null };
80
+ if (!entry.tab && prev?.tab && prev.window === entry.window && windows[entry.window]?.includes(prev.tab)) {
81
+ entry.tab = prev.tab;
82
+ }
83
+ known.set(pid, entry);
84
+ }
85
+ // In a window where one session's tab is unknown and exactly one tab isn't
86
+ // claimed by another session, that tab must be the one.
87
+ for (const [win, tabs] of Object.entries(windows)) {
88
+ const entries = [...known.values()].filter((e) => e.window === win);
89
+ const unknown = entries.filter((e) => !e.tab);
90
+ const claimed = new Set(entries.filter((e) => e.tab).map((e) => e.tab));
91
+ const free = tabs.filter((t) => !claimed.has(t));
92
+ if (unknown.length === 1 && free.length === 1) unknown[0].tab = free[0];
93
+ }
94
+ }
95
+
96
+ // Starts a background scan when the last one is stale. Never waits for it;
97
+ // the next snapshot picks up the result.
98
+ function refresh(pids) {
99
+ if (process.platform !== 'win32' || pending || Date.now() - lastScanAt < REFRESH_MS || !pids.length) return;
100
+ lastScanAt = Date.now();
101
+ scan(pids).then((result) => {
102
+ if (result) merge(result, pids);
103
+ });
104
+ }
105
+
106
+ // Records the tab that Go to window found.
107
+ function remember(pid, window, tab) {
108
+ const entry = known.get(String(pid));
109
+ if (entry && tab && (!entry.window || entry.window === String(window))) {
110
+ entry.window = String(window);
111
+ entry.tab = tab;
112
+ }
113
+ }
114
+
115
+ // What the terminal shows for this session: a renamed tab's name, otherwise
116
+ // the session's own title without Claude Code's spinner glyph.
117
+ function titleFor(pid) {
118
+ const entry = known.get(String(pid));
119
+ if (!entry) return null;
120
+ if (entry.tab && titleKey(entry.tab) !== entry.title) return entry.tab;
121
+ return entry.title || null;
122
+ }
123
+
124
+ module.exports = { refresh, remember, titleFor };
@@ -0,0 +1,95 @@
1
+ # Long-running helper. For each line of space-separated PIDs read from stdin,
2
+ # prints one line of JSON: each process's console title and, when it runs in
3
+ # Windows Terminal, the window and the name of its tab if that can be told
4
+ # without switching tabs. Also lists every tab in those windows.
5
+
6
+ $ErrorActionPreference = 'Stop'
7
+ $ProgressPreference = 'SilentlyContinue'
8
+ [Console]::OutputEncoding = [Text.Encoding]::UTF8
9
+ Add-Type -AssemblyName UIAutomationClient, UIAutomationTypes
10
+ Add-Type @"
11
+ using System; using System.Text; using System.Runtime.InteropServices;
12
+ public static class T {
13
+ [DllImport("kernel32.dll")] public static extern bool FreeConsole();
14
+ [DllImport("kernel32.dll")] public static extern bool AttachConsole(uint pid);
15
+ [DllImport("kernel32.dll")] public static extern IntPtr GetConsoleWindow();
16
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] public static extern uint GetConsoleTitle(StringBuilder sb, uint size);
17
+ [DllImport("kernel32.dll")] public static extern bool SetConsoleCtrlHandler(IntPtr handler, bool add);
18
+ [DllImport("user32.dll")] public static extern IntPtr GetAncestor(IntPtr hwnd, uint flags);
19
+ }
20
+ "@
21
+
22
+ # While attached to a session's console, a Ctrl+C typed there would otherwise
23
+ # end this process too.
24
+ [void][T]::SetConsoleCtrlHandler([IntPtr]::Zero, $true)
25
+
26
+ $AE = [Windows.Automation.AutomationElement]
27
+ $Descendants = [Windows.Automation.TreeScope]::Descendants
28
+ $SelectionItem = [Windows.Automation.SelectionItemPattern]::Pattern
29
+ $TabCond = New-Object Windows.Automation.PropertyCondition($AE::ControlTypeProperty, [Windows.Automation.ControlType]::TabItem)
30
+ $PaneCond = New-Object Windows.Automation.PropertyCondition($AE::ClassNameProperty, 'TermControl')
31
+
32
+ function Get-TitleKey([string]$title) {
33
+ return ($title -replace '^[^\p{L}\p{N}]+', '').Trim()
34
+ }
35
+
36
+ # Tab names, which one is selected, and the app titles of the selected tab's
37
+ # panes (the only panes UI Automation can see).
38
+ function Get-Tabs([IntPtr]$hwnd) {
39
+ $window = $AE::FromHandle($hwnd)
40
+ if ($window.Current.ClassName -ne 'CASCADIA_HOSTING_WINDOW_CLASS') { return $null }
41
+ $tabs = @()
42
+ $selected = $null
43
+ foreach ($t in $window.FindAll($Descendants, $TabCond)) {
44
+ $tabs += $t.Current.Name
45
+ if ($t.GetCurrentPattern($SelectionItem).Current.IsSelected) { $selected = $t.Current.Name }
46
+ }
47
+ $panes = @(foreach ($p in $window.FindAll($Descendants, $PaneCond)) { Get-TitleKey $p.Current.HelpText })
48
+ return @{ tabs = $tabs; selected = $selected; panes = $panes }
49
+ }
50
+
51
+ [void][T]::FreeConsole()
52
+ while ($null -ne ($line = [Console]::In.ReadLine())) {
53
+ $sessions = @{}
54
+ $windows = @{}
55
+ foreach ($id in ($line -split '\s+' | Where-Object { $_ })) {
56
+ try {
57
+ if (-not [T]::AttachConsole([uint32]$id)) {
58
+ # An app with a window and no console, such as Comfy Desktop: the
59
+ # title of its main window stands in.
60
+ $p = Get-Process -Id $id -ErrorAction SilentlyContinue
61
+ if ($p -and $p.MainWindowTitle) { $sessions[[string]$id] = @{ title = $p.MainWindowTitle } }
62
+ continue
63
+ }
64
+ try {
65
+ $con = [T]::GetConsoleWindow()
66
+ $sb = New-Object Text.StringBuilder 1024
67
+ [void][T]::GetConsoleTitle($sb, 1024)
68
+ } finally {
69
+ [void][T]::FreeConsole()
70
+ }
71
+ $session = @{ title = Get-TitleKey $sb.ToString() }
72
+ $root = if ($con -ne [IntPtr]::Zero) { [T]::GetAncestor($con, 3) } else { [IntPtr]::Zero }
73
+ if ($root -ne [IntPtr]::Zero -and $root -ne $con) {
74
+ $hwnd = [string][int64]$root
75
+ if (-not $windows.ContainsKey($hwnd)) { $windows[$hwnd] = Get-Tabs $root }
76
+ $w = $windows[$hwnd]
77
+ if ($w) {
78
+ $session.window = $hwnd
79
+ if ($session.title -and $w.selected -and $w.panes -contains $session.title) {
80
+ $session.tab = $w.selected
81
+ } else {
82
+ $named = $w.tabs | Where-Object { $session.title -and (Get-TitleKey $_) -eq $session.title } | Select-Object -First 1
83
+ if ($named) { $session.tab = $named }
84
+ }
85
+ }
86
+ }
87
+ $sessions[[string]$id] = $session
88
+ } catch {
89
+ # The process exited or its window closed mid-scan; skip it this round.
90
+ }
91
+ }
92
+ $tabLists = @{}
93
+ foreach ($k in $windows.Keys) { if ($windows[$k]) { $tabLists[$k] = @($windows[$k].tabs) } }
94
+ [Console]::Out.WriteLine((@{ sessions = $sessions; windows = $tabLists } | ConvertTo-Json -Compress -Depth 5))
95
+ }
@@ -0,0 +1,166 @@
1
+ 'use strict';
2
+
3
+ // Windows: sessions run in Windows Terminal (or VS Code, or a classic
4
+ // console). PowerShell scripts beside this file do the work that needs the
5
+ // Windows API: finding and focusing a session's tab, typing into its console,
6
+ // reading tab titles and showing the folder picker.
7
+
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+ const { spawn, execFile } = require('child_process');
11
+ const titles = require('./windows-titles');
12
+
13
+ const FOCUS_SCRIPT = path.join(__dirname, 'windows-focus.ps1');
14
+ const CLOSE_SCRIPT = path.join(__dirname, 'windows-close.ps1');
15
+ const PICK_SCRIPT = path.join(__dirname, 'windows-pick-folder.ps1');
16
+
17
+ const psQuote = (s) => `'${String(s).replace(/'/g, "''")}'`;
18
+
19
+ // pwsh from the Microsoft Store is an app execution alias, a link that
20
+ // fs.existsSync can't follow, so check for the link itself.
21
+ function onPath(exe) {
22
+ return (process.env.PATH || '').split(path.delimiter).some((dir) => {
23
+ try {
24
+ return Boolean(dir) && Boolean(fs.lstatSync(path.join(dir, exe)));
25
+ } catch {
26
+ return false;
27
+ }
28
+ });
29
+ }
30
+
31
+ // The script's last line of output is its JSON result.
32
+ function lastJsonLine(stdout, stderr, err, fallback) {
33
+ try {
34
+ return JSON.parse(String(stdout).trim().split(/\r?\n/).pop());
35
+ } catch {
36
+ const detail = String(stderr || err?.message || '').trim().split(/\r?\n/)[0];
37
+ return { ok: false, error: detail || fallback };
38
+ }
39
+ }
40
+
41
+ // Goes to the session's window and, with `send`, also types that prompt into
42
+ // it. `statusFile` is the session's registry file: nothing is typed while it
43
+ // says the session is waiting on a prompt or dialog.
44
+ function focus(pid, { send, statusFile } = {}) {
45
+ return new Promise((resolve) => {
46
+ const extra = send ? ` -Send ${psQuote(send)} -StatusFile ${psQuote(statusFile)}` : '';
47
+ // An encoded command isn't subject to the script execution policy.
48
+ const script = `& {\n${fs.readFileSync(FOCUS_SCRIPT, 'utf8')}\n} ${Number(pid)}${extra}`;
49
+ const args = ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')];
50
+ execFile('powershell.exe', args, { windowsHide: true, timeout: 20000 }, (err, stdout, stderr) => {
51
+ const result = lastJsonLine(stdout, stderr, err, 'Could not find the window.');
52
+ if (result.tabName) titles.remember(pid, result.hwnd, result.tabName);
53
+ resolve(result);
54
+ });
55
+ });
56
+ }
57
+
58
+ const TERMINAL_SETTINGS = [
59
+ ['Packages', 'Microsoft.WindowsTerminal_8wekyb3d8bbwe', 'LocalState', 'settings.json'],
60
+ ['Packages', 'Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe', 'LocalState', 'settings.json'],
61
+ ['Microsoft', 'Windows Terminal', 'settings.json'],
62
+ ];
63
+
64
+ // Windows Terminal's profile defaults can say to run tabs as administrator. A
65
+ // tab opened with just a command line gets those defaults, so it opened in a
66
+ // separate administrator instance that also mangled the command. Naming the
67
+ // default profile gives the tab the settings the user's own new tabs get.
68
+ function defaultTerminalProfile() {
69
+ for (const parts of TERMINAL_SETTINGS) {
70
+ try {
71
+ const text = fs.readFileSync(path.join(process.env.LOCALAPPDATA || '', ...parts), 'utf8');
72
+ const match = text.match(/"defaultProfile"\s*:\s*"([^"]+)"/);
73
+ if (match) return match[1];
74
+ } catch {}
75
+ }
76
+ return null;
77
+ }
78
+
79
+ // Opens a tab in the most recently used Windows Terminal window, running
80
+ // `command` in `dir`. It runs inside a shell, so the tab stays open at a
81
+ // prompt in that folder after it exits.
82
+ function open(dir, command) {
83
+ return new Promise((resolve) => {
84
+ // Windows Terminal reads a semicolon anywhere in its arguments as the start
85
+ // of another command.
86
+ if (dir.includes(';')) {
87
+ resolve({ ok: false, error: "Windows Terminal can't open a folder with a semicolon in its path." });
88
+ return;
89
+ }
90
+ const shell = onPath('pwsh.exe') ? 'pwsh.exe' : 'powershell.exe';
91
+ const profile = defaultTerminalProfile();
92
+ // Encoded, the command can't be split up or have its flags read by
93
+ // Windows Terminal as its own.
94
+ const encoded = Buffer.from(command, 'utf16le').toString('base64');
95
+ const args = ['-w', '0', 'new-tab', ...(profile ? ['-p', profile] : []), '-d', dir, shell, '-NoExit', '-EncodedCommand', encoded];
96
+ const child = spawn('wt.exe', args, { detached: true, stdio: 'ignore' });
97
+ child.on('error', (err) => resolve({ ok: false, error: `Couldn't start Windows Terminal: ${err.message}` }));
98
+ child.on('spawn', () => {
99
+ child.unref();
100
+ resolve({ ok: true });
101
+ });
102
+ });
103
+ }
104
+
105
+ // Shows Windows' folder picker, in front of the other windows, and resolves to
106
+ // { ok, path } or { ok, cancelled }.
107
+ function pickFolder(start, title) {
108
+ return new Promise((resolve) => {
109
+ // pwsh has the newer dialog, with the address bar and the folder to start in.
110
+ const shell = onPath('pwsh.exe') ? 'pwsh.exe' : 'powershell.exe';
111
+ const script = `& {\n${fs.readFileSync(PICK_SCRIPT, 'utf8')}\n}`;
112
+ const args = ['-NoProfile', '-NonInteractive', '-STA', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')];
113
+ const env = { ...process.env, AGENTS_PICK_START: start || '', AGENTS_PICK_TITLE: title || '' };
114
+ execFile(shell, args, { windowsHide: true, env, timeout: 30 * 60 * 1000 }, (err, stdout, stderr) => {
115
+ resolve(lastJsonLine(stdout, stderr, err, "The folder picker didn't open."));
116
+ });
117
+ });
118
+ }
119
+
120
+ // /T also ends the session's shells and MCP servers; a console app ignores a
121
+ // polite close request, so /F is needed.
122
+ function stop(pid) {
123
+ return new Promise((resolve) => {
124
+ const child = spawn('taskkill.exe', ['/PID', String(pid), '/T', '/F'], { windowsHide: true });
125
+ let out = '';
126
+ child.stdout.on('data', (d) => (out += d));
127
+ child.stderr.on('data', (d) => (out += d));
128
+ child.on('error', (err) => resolve({ ok: false, error: err.message }));
129
+ child.on('close', (code) => resolve(code === 0 ? { ok: true } : { ok: false, error: out.trim() || `taskkill exited ${code}` }));
130
+ });
131
+ }
132
+
133
+ // Ends the session and its tab (windows-close.ps1).
134
+ function close(pid) {
135
+ return new Promise((resolve) => {
136
+ const script = `& {\n${fs.readFileSync(CLOSE_SCRIPT, 'utf8')}\n} ${Number(pid)}`;
137
+ const args = ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')];
138
+ execFile('powershell.exe', args, { windowsHide: true, timeout: 20000 }, (err, stdout, stderr) => {
139
+ resolve(lastJsonLine(stdout, stderr, err, "Couldn't close it."));
140
+ });
141
+ });
142
+ }
143
+
144
+ function openFolder(dir) {
145
+ const child = spawn('explorer.exe', [dir], { detached: true, stdio: 'ignore' });
146
+ child.on('error', () => {});
147
+ child.unref();
148
+ }
149
+
150
+ // Only Windows Terminal, for now.
151
+ const TERMINALS = [{ id: 'windows-terminal', name: 'Windows Terminal' }];
152
+
153
+ module.exports = {
154
+ name: 'windows',
155
+ terminals: () => TERMINALS.map((t) => ({ ...t, available: true })),
156
+ // Commands run in PowerShell.
157
+ quote: psQuote,
158
+ open,
159
+ focus,
160
+ pickFolder,
161
+ stop,
162
+ close,
163
+ openFolder,
164
+ refreshTitles: titles.refresh,
165
+ titleFor: titles.titleFor,
166
+ };