townmouse 0.0.0-stage → 0.4.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.
- package/CHANGELOG.md +196 -0
- package/DESIGN.md +153 -0
- package/LICENSE +661 -0
- package/README.md +600 -2
- package/SECURITY.md +60 -0
- package/TOWNMOUSE.md +91 -0
- package/assets/brand/mascot/README.md +23 -0
- package/assets/brand/mascot/townmouse-aristocrat.png +0 -0
- package/assets/brand/mascot/townmouse-icon.svg +1 -0
- package/assets/brand/mascot/townmouse-monocled.png +0 -0
- package/bin/townmouse +68 -0
- package/docs/PACKAGING.md +371 -0
- package/docs/browser-workspace.md +237 -0
- package/docs/panes.md +442 -0
- package/native/TownmouseApp.swift +108 -0
- package/npm-shrinkwrap.json +1282 -0
- package/package.json +93 -4
- package/public/apple-touch-icon.png +0 -0
- package/public/brand/floydslabs-credit.png +0 -0
- package/public/brand/floydslabs-credit.webp +0 -0
- package/public/brand/townmouse-aristocrat.webp +0 -0
- package/public/brand/townmouse-monocled.webp +0 -0
- package/public/browser-picture.mjs +159 -0
- package/public/clipboard-text.mjs +5 -0
- package/public/favicon-16x16.png +0 -0
- package/public/favicon-32x32.png +0 -0
- package/public/favicon.ico +0 -0
- package/public/favicon.svg +1 -0
- package/public/features/app-version.mjs +35 -0
- package/public/features/autosave.mjs +80 -0
- package/public/features/clipboard.mjs +69 -0
- package/public/features/command-palette.mjs +181 -0
- package/public/features/desktop-palette.mjs +19 -0
- package/public/features/export.mjs +37 -0
- package/public/features/file-drop.mjs +77 -0
- package/public/features/floating-palette.mjs +113 -0
- package/public/features/fontsize.mjs +72 -0
- package/public/features/haptic-keys.mjs +42 -0
- package/public/features/history-undo.mjs +102 -0
- package/public/features/keepalive.mjs +36 -0
- package/public/features/keybar-config.mjs +70 -0
- package/public/features/keyboard-shortcuts.mjs +74 -0
- package/public/features/links.mjs +139 -0
- package/public/features/multi-window-sync.mjs +76 -0
- package/public/features/osc-bridge.mjs +64 -0
- package/public/features/phone-landscape-focus.mjs +157 -0
- package/public/features/recent-commands.mjs +100 -0
- package/public/features/search.mjs +134 -0
- package/public/features/session-lock.mjs +96 -0
- package/public/features/session-manager.mjs +251 -0
- package/public/features/settings-sync.mjs +77 -0
- package/public/features/shortcut-help.mjs +85 -0
- package/public/features/smart-completions.mjs +101 -0
- package/public/features/smart-suggest.mjs +124 -0
- package/public/features/snippets.mjs +85 -0
- package/public/features/split-view.mjs +102 -0
- package/public/features/status-metrics.mjs +137 -0
- package/public/features/stylus-support.mjs +124 -0
- package/public/features/swipe-history.mjs +141 -0
- package/public/features/swipe-sessions.mjs +85 -0
- package/public/features/tab-reorder.mjs +70 -0
- package/public/features/theme-system.mjs +51 -0
- package/public/features/toast-status.mjs +118 -0
- package/public/features/two-finger-menu.mjs +87 -0
- package/public/features/voice-input.mjs +244 -0
- package/public/features/wake-fullscreen.mjs +67 -0
- package/public/features/window-title.mjs +47 -0
- package/public/features/zoom.mjs +80 -0
- package/public/icon-128.png +0 -0
- package/public/icon-180.png +0 -0
- package/public/icon-192.png +0 -0
- package/public/icon-48.png +0 -0
- package/public/icon-512-maskable.png +0 -0
- package/public/icon-512.png +0 -0
- package/public/icon.svg +1 -0
- package/public/index.html +2304 -0
- package/public/input-chunks.mjs +22 -0
- package/public/input-guard.mjs +218 -0
- package/public/manifest.json +56 -0
- package/public/panes.css +1433 -0
- package/public/panes.html +211 -0
- package/public/panes.mjs +3183 -0
- package/public/service-worker.js +67 -0
- package/public/workspace.css +1621 -0
- package/public/workspace.mjs +1715 -0
- package/scripts/install-service.sh +303 -0
- package/scripts/node-runtime.sh +138 -0
- package/scripts/panes +568 -0
- package/scripts/prepare-native.sh +35 -0
- package/scripts/retire-legacy-service.sh +76 -0
- package/scripts/run-hooks +69 -0
- package/scripts/townmouse.sh +152 -0
- package/scripts/uninstall-service.sh +65 -0
- package/src/agent-guide.js +329 -0
- package/src/attachments.js +128 -0
- package/src/browser-dom.js +548 -0
- package/src/browser-workspace.js +1733 -0
- package/src/chrome-resolve.js +80 -0
- package/src/owner-page.js +43 -0
- package/src/pty-permissions.js +99 -0
- package/src/regex-worker.js +13 -0
- package/src/replay-text.js +189 -0
- package/src/request-boundary.js +58 -0
- package/src/safe-regex.js +87 -0
- package/src/server.js +1582 -0
- package/src/shell-resolve.js +42 -0
- package/src/static-deps.js +61 -0
- package/src/workspace-panes.js +1431 -0
|
@@ -0,0 +1,1431 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const crypto = require('crypto');
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const os = require('os');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const { spawn } = require('child_process');
|
|
7
|
+
const { StringDecoder } = require('string_decoder');
|
|
8
|
+
const pty = require('node-pty');
|
|
9
|
+
const { resolveShell } = require('./shell-resolve');
|
|
10
|
+
const { replayTranscript } = require('./replay-text');
|
|
11
|
+
const { buildGuide } = require('./agent-guide');
|
|
12
|
+
const { createPatternMatcher } = require('./safe-regex');
|
|
13
|
+
const { ownerPageRefusal } = require('./owner-page');
|
|
14
|
+
|
|
15
|
+
const MAX_PANES_PER_TAB = 4;
|
|
16
|
+
const MAX_TABS = 24;
|
|
17
|
+
const MAX_TERMINAL_PANES = 24;
|
|
18
|
+
const MAX_BUFFER = 200_000;
|
|
19
|
+
// HTTP/1.1 browsers allow six connections per origin. Keep two slots free for
|
|
20
|
+
// input/state/close so terminal streams cannot starve the controls. Panes over
|
|
21
|
+
// this cap fall back to the polling API instead of holding a socket open.
|
|
22
|
+
const MAX_ACTIVE_STREAMS = 4;
|
|
23
|
+
|
|
24
|
+
// Tracked, non-interactive jobs. Bounded so a long session cannot accumulate
|
|
25
|
+
// output forever. Interactive programs still belong in the PTY.
|
|
26
|
+
const MAX_JOBS_PER_PANE = 40;
|
|
27
|
+
const MAX_JOB_OUTPUT = 512 * 1024;
|
|
28
|
+
|
|
29
|
+
// Variables a parent AI harness exports about *its own* process. A pane is an
|
|
30
|
+
// independent session, not a child of whatever launched the TownMouse server,
|
|
31
|
+
// so inheriting these makes a fresh harness believe it is a nested child
|
|
32
|
+
// (which, among other things, disables conversation saving). Credentials and
|
|
33
|
+
// configuration are deliberately kept.
|
|
34
|
+
const INHERITED_SESSION_ENV = new Set([
|
|
35
|
+
'CLAUDECODE',
|
|
36
|
+
'CLAUDE_CODE_CHILD_SESSION',
|
|
37
|
+
'CLAUDE_CODE_SESSION_ID',
|
|
38
|
+
'CLAUDE_CODE_ENTRYPOINT',
|
|
39
|
+
'CLAUDE_CODE_SESSION_ATTENDED',
|
|
40
|
+
'CLAUDE_CODE_MESSAGING_SOCKET',
|
|
41
|
+
'CLAUDE_CODE_MESSAGING_TOKEN',
|
|
42
|
+
'CLAUDE_CODE_AUTO_MODE_SERVER',
|
|
43
|
+
'CLAUDE_PID',
|
|
44
|
+
'CLAUDE_EFFORT'
|
|
45
|
+
]);
|
|
46
|
+
|
|
47
|
+
function paneEnvironment(extra = {}) {
|
|
48
|
+
const env = {};
|
|
49
|
+
const strip = new Set(INHERITED_SESSION_ENV);
|
|
50
|
+
for (const name of String(process.env.TOWNMOUSE_PANE_ENV_STRIP || '').split(',')) {
|
|
51
|
+
const trimmed = name.trim();
|
|
52
|
+
if (trimmed) strip.add(trimmed);
|
|
53
|
+
}
|
|
54
|
+
for (const [key, value] of Object.entries(process.env)) {
|
|
55
|
+
if (strip.has(key)) continue;
|
|
56
|
+
env[key] = value;
|
|
57
|
+
}
|
|
58
|
+
return { ...env, ...extra };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function installWorkspacePanes(app, browserWorkspace, options = {}) {
|
|
62
|
+
const port = options.port || Number(process.env.PORT) || 11357;
|
|
63
|
+
const apiUrl = `http://127.0.0.1:${port}/api/panes`;
|
|
64
|
+
const cliPath = path.join(__dirname, '..', 'scripts', 'panes');
|
|
65
|
+
const epoch = crypto.randomUUID();
|
|
66
|
+
const tokenDir = path.join(os.homedir(), '.townmouse');
|
|
67
|
+
const tokenFile = path.join(tokenDir, 'pane-token');
|
|
68
|
+
let token = '';
|
|
69
|
+
try { token = fs.readFileSync(tokenFile, 'utf8').trim(); } catch (_) { /* first run */ }
|
|
70
|
+
if (!token) {
|
|
71
|
+
token = crypto.randomBytes(32).toString('hex');
|
|
72
|
+
fs.mkdirSync(tokenDir, { recursive: true, mode: 0o700 });
|
|
73
|
+
fs.writeFileSync(tokenFile, token, { mode: 0o600 });
|
|
74
|
+
}
|
|
75
|
+
try { fs.chmodSync(tokenFile, 0o600); } catch (_) { /* best effort */ }
|
|
76
|
+
// Attachment uploads are owner-gated at the page boundary, but a terminal
|
|
77
|
+
// agent inside the workspace presents this scoped pane token instead.
|
|
78
|
+
app.locals.townmousePaneToken = token;
|
|
79
|
+
|
|
80
|
+
// Two keys, two callers. The workspace token is the agents' key: one per
|
|
81
|
+
// machine, kept on disk, handed to every terminal pane and to the CLI. The
|
|
82
|
+
// page key is the owner's: minted per server run, never written anywhere,
|
|
83
|
+
// and handed once, by the cookie-proven bootstrap route, to the person's
|
|
84
|
+
// page. Who is asking is read from the key a request presents, never from a
|
|
85
|
+
// field in its body, so an agent that sends createdBy: "human" stays an agent.
|
|
86
|
+
const pageKey = crypto.randomBytes(32).toString('hex');
|
|
87
|
+
// What an agent has on a pane, lowest first. The words are the terminal
|
|
88
|
+
// surface's: Private, View only, Allow control.
|
|
89
|
+
const ACCESS = { private: 0, view: 1, control: 2 };
|
|
90
|
+
const ACCESS_LABEL = { private: 'Private', view: 'View only', control: 'Allow control' };
|
|
91
|
+
// An unanswered ask clears itself, and one the owner declined may not be
|
|
92
|
+
// repeated at once, so a person who was away does not find a pile of prompts.
|
|
93
|
+
const ACCESS_REQUEST_TTL_MS = 5 * 60 * 1000;
|
|
94
|
+
const ACCESS_DECLINE_TTL_MS = 5 * 60 * 1000;
|
|
95
|
+
|
|
96
|
+
const stateDir = process.env.TOWNMOUSE_STATE_DIR || path.join(os.homedir(), '.townmouse');
|
|
97
|
+
const stateFile = path.join(stateDir, 'workspace.json');
|
|
98
|
+
|
|
99
|
+
const tabs = new Map();
|
|
100
|
+
const panes = new Map();
|
|
101
|
+
let activeTabId = null;
|
|
102
|
+
let activePaneId = null;
|
|
103
|
+
let restored = false;
|
|
104
|
+
let savedWorkspace = false;
|
|
105
|
+
let olderWorkspace = false;
|
|
106
|
+
let restorePromise = null;
|
|
107
|
+
let saveTimer = null;
|
|
108
|
+
let shuttingDown = false;
|
|
109
|
+
let activeStreams = 0;
|
|
110
|
+
// Each state answer is numbered as it is built. A page that has a newer
|
|
111
|
+
// answer ignores an older one still on the wire, so what the person just
|
|
112
|
+
// changed cannot flash back for a moment.
|
|
113
|
+
let stateSeq = 0;
|
|
114
|
+
|
|
115
|
+
const id = (prefix) => prefix + '_' + crypto.randomBytes(6).toString('hex');
|
|
116
|
+
const route = (fn) => async (req, res) => {
|
|
117
|
+
res.set('Cache-Control', 'no-store');
|
|
118
|
+
try { await fn(req, res); }
|
|
119
|
+
catch (error) {
|
|
120
|
+
// Some refusals (a stale target) carry a structured body so the caller can
|
|
121
|
+
// tell "rejected, look again" apart from an ordinary error.
|
|
122
|
+
res.status(error.status || 400).json(error.body || { error: error.message });
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
app.use('/api/panes', (req, res, next) => {
|
|
126
|
+
if (req.body == null) req.body = {};
|
|
127
|
+
next();
|
|
128
|
+
});
|
|
129
|
+
// Length is compared first so a wrong-length guess cannot throw inside the
|
|
130
|
+
// constant-time comparison; both keys are fixed-length hex.
|
|
131
|
+
const sameSecret = (supplied, secret) => {
|
|
132
|
+
if (typeof supplied !== 'string') return false;
|
|
133
|
+
const given = Buffer.from(supplied);
|
|
134
|
+
const held = Buffer.from(secret);
|
|
135
|
+
return given.length === held.length && crypto.timingSafeEqual(given, held);
|
|
136
|
+
};
|
|
137
|
+
// 'owner' is the person's page. 'agent' is anything holding the workspace token.
|
|
138
|
+
const callerOf = (req) => {
|
|
139
|
+
if (sameSecret(req.get('X-Townmouse-Owner'), pageKey)) return 'owner';
|
|
140
|
+
const supplied = req.get('X-Townmouse-Token') || (req.get('Authorization') || '').replace(/^Bearer\s+/i, '');
|
|
141
|
+
return sameSecret(supplied, token) ? 'agent' : null;
|
|
142
|
+
};
|
|
143
|
+
const auth = (req, res, next) => {
|
|
144
|
+
const caller = callerOf(req);
|
|
145
|
+
// The code lets the page tell a stale key (the server restarted) from any
|
|
146
|
+
// other refusal, and renew its session without bothering the person.
|
|
147
|
+
if (!caller) { res.status(403).json({ error: 'Workspace token required.', code: 'UNKNOWN_KEY' }); return; }
|
|
148
|
+
req.caller = caller;
|
|
149
|
+
next();
|
|
150
|
+
};
|
|
151
|
+
const tabOf = (pane) => tabs.get(pane.tabId) || null;
|
|
152
|
+
|
|
153
|
+
// ── Who may do what on a pane ─────────────────────────────────────────────
|
|
154
|
+
//
|
|
155
|
+
// A pane belongs to whoever asked for it: the owner's page, or an agent
|
|
156
|
+
// through the CLI or the API. The owner may do anything. An agent has
|
|
157
|
+
// control of a pane an agent opened, and exactly the grant the owner has
|
|
158
|
+
// given on one of the owner's own panes: nothing (Private), reading (View
|
|
159
|
+
// only), or reading and driving (Allow control). Everything below is
|
|
160
|
+
// enforced here, in the routes, so hiding a control in a page changes
|
|
161
|
+
// nothing about what a request can do.
|
|
162
|
+
|
|
163
|
+
function refuse(status, code, message, extra = {}) {
|
|
164
|
+
throw Object.assign(new Error(message), { status, body: { error: message, code, ...extra } });
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// What an agent currently has on a pane. The same object is put on every
|
|
168
|
+
// pane in every state response, so the page and the CLI cannot disagree
|
|
169
|
+
// with the routes.
|
|
170
|
+
function agentAccess(pane) {
|
|
171
|
+
const level = pane.createdBy === 'agent' ? 'control' : pane.grant;
|
|
172
|
+
return { level, label: ACCESS_LABEL[level] };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function hasAccess(pane, caller, need) {
|
|
176
|
+
if (!pane) return false;
|
|
177
|
+
if (caller === 'owner') return true;
|
|
178
|
+
return ACCESS[agentAccess(pane).level] >= ACCESS[need];
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// A refusal names the pane's level and the one command that asks the owner
|
|
182
|
+
// for more, so an agent's next step is never a guess.
|
|
183
|
+
function requireAccess(pane, caller, need) {
|
|
184
|
+
if (hasAccess(pane, caller, need)) return;
|
|
185
|
+
const access = agentAccess(pane);
|
|
186
|
+
const ask = `panes pane request ${pane.id} --level ${need}`;
|
|
187
|
+
if (access.level === 'private') {
|
|
188
|
+
refuse(403, 'PANE_PRIVATE',
|
|
189
|
+
`This pane is Private: the owner has not given an agent access. Ask for it: ${ask}`, { paneId: pane.id, agentAccess: access });
|
|
190
|
+
}
|
|
191
|
+
refuse(403, 'PANE_VIEW_ONLY',
|
|
192
|
+
`The owner gave an agent View only on this pane. Ask for control: ${ask}`, { paneId: pane.id, agentAccess: access });
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// Some things are the owner's alone on the owner's own panes, whatever an
|
|
196
|
+
// agent has been given: ending the pane, resizing it, and changing the grant.
|
|
197
|
+
function requireOwner(pane, caller, verb) {
|
|
198
|
+
if (caller === 'owner' || pane.createdBy === 'agent') return;
|
|
199
|
+
refuse(403, 'OWNER_ONLY', `Only the owner can ${verb} one of the owner's panes.`, { paneId: pane.id, agentAccess: agentAccess(pane) });
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function paneOr404(paneId) {
|
|
203
|
+
const pane = panes.get(paneId);
|
|
204
|
+
if (!pane) refuse(404, 'PANE_NOT_FOUND', 'Pane not found.');
|
|
205
|
+
return pane;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function tabOr404(tabId) {
|
|
209
|
+
const tab = tabs.get(tabId);
|
|
210
|
+
if (!tab) refuse(404, 'TAB_NOT_FOUND', 'Workspace tab not found.');
|
|
211
|
+
return tab;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// A pending ask, or null once it has waited long enough for an answer.
|
|
215
|
+
function currentRequest(pane) {
|
|
216
|
+
const request = pane.accessRequest;
|
|
217
|
+
if (!request) return null;
|
|
218
|
+
if (Date.now() - request.at > ACCESS_REQUEST_TTL_MS) {
|
|
219
|
+
pane.accessRequest = null;
|
|
220
|
+
return null;
|
|
221
|
+
}
|
|
222
|
+
return {
|
|
223
|
+
level: request.level,
|
|
224
|
+
label: ACCESS_LABEL[request.level],
|
|
225
|
+
message: request.message,
|
|
226
|
+
at: request.at,
|
|
227
|
+
expiresAt: request.at + ACCESS_REQUEST_TTL_MS
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// "Not now" means the owner does not want to be asked about this pane for a
|
|
232
|
+
// while, whatever the level: a smaller or a larger ask both wait.
|
|
233
|
+
function recentlyDeclined(pane) {
|
|
234
|
+
const declined = pane.accessDeclined;
|
|
235
|
+
return Boolean(declined && Date.now() - declined.at <= ACCESS_DECLINE_TTL_MS);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// Changing the grant ends what an agent already holds on the pane, the way
|
|
239
|
+
// the terminal surface rotates a connection token: an output stream an agent
|
|
240
|
+
// is reading closes, and the long routes (waits, a queued action, a job that
|
|
241
|
+
// is being waited on) look again before they answer.
|
|
242
|
+
function setGrant(pane, level) {
|
|
243
|
+
const wasControl = ACCESS[agentAccess(pane).level];
|
|
244
|
+
pane.grant = level;
|
|
245
|
+
pane.accessRequest = null;
|
|
246
|
+
if (pane.kind === 'browser' && pane.browserId) browserWorkspace.grant(pane.browserId, level);
|
|
247
|
+
if (ACCESS[level] < wasControl) {
|
|
248
|
+
for (const stream of [...pane.streams]) if (stream.paneViewer === 'agent') stream.endPaneStream?.();
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function createTab(title, createdBy = 'human') {
|
|
253
|
+
if (tabs.size >= MAX_TABS) {
|
|
254
|
+
throw Object.assign(new Error('Close a workspace tab before opening another.'), { status: 409 });
|
|
255
|
+
}
|
|
256
|
+
const tab = { id: id('t'), title: title || `Workspace ${tabs.size + 1}`, createdBy, panes: [] };
|
|
257
|
+
tabs.set(tab.id, tab);
|
|
258
|
+
if (!activeTabId) activeTabId = tab.id;
|
|
259
|
+
scheduleSave();
|
|
260
|
+
return tab;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const clampCols = (value) => Math.max(20, Math.min(400, Math.round(Number(value) || 100)));
|
|
264
|
+
const clampRows = (value) => Math.max(5, Math.min(200, Math.round(Number(value) || 30)));
|
|
265
|
+
const KEY_SEQUENCES = {
|
|
266
|
+
enter: '\r', return: '\r', esc: '\x1b', escape: '\x1b', tab: '\t',
|
|
267
|
+
backspace: '\x7f', delete: '\x1b[3~', space: ' ',
|
|
268
|
+
up: '\x1b[A', down: '\x1b[B', right: '\x1b[C', left: '\x1b[D',
|
|
269
|
+
home: '\x1b[H', end: '\x1b[F', pgup: '\x1b[5~', pgdn: '\x1b[6~',
|
|
270
|
+
pageup: '\x1b[5~', pagedown: '\x1b[6~'
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
function keySequence(name) {
|
|
274
|
+
const raw = String(name || '').trim();
|
|
275
|
+
if (!raw || raw.length > 40) throw Object.assign(new Error('Invalid key name.'), { status: 400 });
|
|
276
|
+
const parts = raw.toLowerCase().split('+').filter(Boolean);
|
|
277
|
+
const key = parts.pop();
|
|
278
|
+
let sequence = KEY_SEQUENCES[key];
|
|
279
|
+
if (!sequence && key.length === 1) sequence = key;
|
|
280
|
+
if (!sequence) throw Object.assign(new Error(`Unknown key: ${raw}`), { status: 400 });
|
|
281
|
+
const ctrl = parts.includes('ctrl') || parts.includes('control');
|
|
282
|
+
const alt = parts.includes('alt') || parts.includes('option');
|
|
283
|
+
const shift = parts.includes('shift');
|
|
284
|
+
if (key === 'tab' && shift) sequence = '\x1b[Z';
|
|
285
|
+
else if (ctrl && key.length === 1) sequence = String.fromCharCode(key.charCodeAt(0) & 0x1f);
|
|
286
|
+
if (alt) sequence = '\x1b' + sequence;
|
|
287
|
+
return sequence;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// A terminal can outrun a slow SSE reader. Honor write backpressure instead
|
|
291
|
+
// of letting Node queue every chunk in memory. Once a reader falls behind we
|
|
292
|
+
// end its stream; the client's polling fallback catches up from /read.
|
|
293
|
+
function sendStreamEvent(stream, event) {
|
|
294
|
+
if (stream._sseBlocked) {
|
|
295
|
+
stream._sseDropped = true;
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
try {
|
|
299
|
+
if (!stream.write(event)) {
|
|
300
|
+
stream._sseBlocked = true;
|
|
301
|
+
stream.once('drain', () => {
|
|
302
|
+
stream._sseBlocked = false;
|
|
303
|
+
if (stream._sseDropped) {
|
|
304
|
+
try { stream.end(); } catch (_) { /* already gone */ }
|
|
305
|
+
}
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
} catch (_) {
|
|
309
|
+
stream._sseDropped = true;
|
|
310
|
+
try { stream.end(); } catch (_) { /* already gone */ }
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
function startPanePty(pane) {
|
|
315
|
+
const env = paneEnvironment({
|
|
316
|
+
TERM: 'xterm-256color',
|
|
317
|
+
TOWNMOUSE_API: apiUrl,
|
|
318
|
+
TOWNMOUSE_TOKEN: token,
|
|
319
|
+
TOWNMOUSE_TAB_ID: pane.tabId,
|
|
320
|
+
TOWNMOUSE_PANE_ID: pane.id,
|
|
321
|
+
TOWNMOUSE_PANES_CLI: cliPath
|
|
322
|
+
});
|
|
323
|
+
pane.cwd = pane.cwd || os.homedir();
|
|
324
|
+
const shell = resolveShell();
|
|
325
|
+
// A fresh program is not the previous task. Drop the old agent-reported
|
|
326
|
+
// "done"/"working" label rather than presenting it as a report about this
|
|
327
|
+
// program.
|
|
328
|
+
pane.agentState = null;
|
|
329
|
+
pane.agentMessage = '';
|
|
330
|
+
pane.agentStateAt = null;
|
|
331
|
+
pane.exited = false;
|
|
332
|
+
pane.exitCode = null;
|
|
333
|
+
pane.exitSignal = null;
|
|
334
|
+
pane.startedAt = Date.now();
|
|
335
|
+
// The widest the shell has been. What it printed was laid out for that many
|
|
336
|
+
// columns, and a viewer that is narrower must be told, so it can show the
|
|
337
|
+
// output at that width first (see the terminal mounting in public/panes.mjs).
|
|
338
|
+
pane.maxCols = Math.max(pane.maxCols || 0, pane.cols);
|
|
339
|
+
const child = pty.spawn(shell, ['-l'], {
|
|
340
|
+
name: 'xterm-256color', cols: pane.cols, rows: pane.rows,
|
|
341
|
+
cwd: pane.cwd, env
|
|
342
|
+
});
|
|
343
|
+
pane.pty = child;
|
|
344
|
+
child.onData((data) => {
|
|
345
|
+
pane.lastOutputAt = Date.now();
|
|
346
|
+
pane.buffer += data;
|
|
347
|
+
pane.totalOffset += data.length;
|
|
348
|
+
if (pane.buffer.length > MAX_BUFFER) pane.buffer = pane.buffer.slice(-MAX_BUFFER);
|
|
349
|
+
pane.bufferStart = pane.totalOffset - pane.buffer.length;
|
|
350
|
+
const event = `data: ${JSON.stringify({ data, offset: pane.totalOffset })}\n\n`;
|
|
351
|
+
for (const stream of pane.streams) sendStreamEvent(stream, event);
|
|
352
|
+
});
|
|
353
|
+
child.onExit((event = {}) => {
|
|
354
|
+
// Program status only. Whether the *agent* finished is its own report,
|
|
355
|
+
// and a quiet or exited program is not that report.
|
|
356
|
+
pane.exited = true;
|
|
357
|
+
pane.exitCode = Number.isFinite(Number(event.exitCode)) ? Number(event.exitCode) : null;
|
|
358
|
+
pane.exitSignal = event.signal ?? null;
|
|
359
|
+
pane.exitedAt = Date.now();
|
|
360
|
+
pane.lastOutputAt = Date.now();
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
async function createPane(tabId, kind, opts = {}) {
|
|
365
|
+
let tab = tabs.get(tabId);
|
|
366
|
+
if (!tab) throw Object.assign(new Error('Workspace tab not found.'), { status: 404 });
|
|
367
|
+
if (tab.panes.length >= MAX_PANES_PER_TAB) {
|
|
368
|
+
throw Object.assign(new Error('A workspace tab holds at most four panes.'), { status: 409 });
|
|
369
|
+
}
|
|
370
|
+
if (kind !== 'browser' && [...panes.values()].filter((pane) => pane.kind === 'terminal').length >= MAX_TERMINAL_PANES) {
|
|
371
|
+
throw Object.assign(new Error('Close a terminal pane before opening another.'), { status: 409 });
|
|
372
|
+
}
|
|
373
|
+
// createdBy is decided by the caller of this function from who asked, and
|
|
374
|
+
// is never taken from a request body: the routes pass the key's owner.
|
|
375
|
+
const pane = {
|
|
376
|
+
id: id('p'), tabId, kind: kind === 'browser' ? 'browser' : 'terminal',
|
|
377
|
+
title: opts.title || '', titleLocked: Boolean(opts.title), url: '', browserId: null, pty: null,
|
|
378
|
+
createdBy: opts.createdBy === 'agent' ? 'agent' : 'human',
|
|
379
|
+
// The owner's panes start Private. A grant lives in memory only: after a
|
|
380
|
+
// restart the panes come back empty, so an agent asks again rather than
|
|
381
|
+
// inheriting access given to something that no longer exists.
|
|
382
|
+
grant: 'private', accessRequest: null, accessDeclined: null,
|
|
383
|
+
cwd: opts.cwd || null,
|
|
384
|
+
buffer: '', bufferStart: 0, totalOffset: 0, streams: new Set(),
|
|
385
|
+
cols: clampCols(opts.cols), rows: clampRows(opts.rows), maxCols: 0, exited: false,
|
|
386
|
+
exitCode: null, exitSignal: null, lastOutputAt: Date.now(), createdAt: Date.now(),
|
|
387
|
+
startedAt: null, exitedAt: null, jobs: [], liveJobs: 0,
|
|
388
|
+
agentState: null, agentMessage: '', agentStateAt: null
|
|
389
|
+
};
|
|
390
|
+
if (pane.kind === 'browser') {
|
|
391
|
+
// The page session records the same truth: an agent's pane is an agent
|
|
392
|
+
// context; one of the owner's panes is the owner's, and takes the grant.
|
|
393
|
+
const browser = await browserWorkspace.create(pane.createdBy === 'agent' ? 'agent' : 'human', opts.url);
|
|
394
|
+
tab = tabs.get(tabId);
|
|
395
|
+
if (!tab) {
|
|
396
|
+
await browserWorkspace.close(browser.id).catch(() => {});
|
|
397
|
+
throw Object.assign(new Error('Workspace tab was closed while the browser opened.'), { status: 404 });
|
|
398
|
+
}
|
|
399
|
+
if (tab.panes.length >= MAX_PANES_PER_TAB) {
|
|
400
|
+
await browserWorkspace.close(browser.id).catch(() => {});
|
|
401
|
+
throw Object.assign(new Error('A workspace tab holds at most four panes.'), { status: 409 });
|
|
402
|
+
}
|
|
403
|
+
pane.browserId = browser.id;
|
|
404
|
+
pane.url = browser.url && browser.url !== 'about:blank' ? browser.url : (opts.url || '');
|
|
405
|
+
pane.title = opts.title || browser.title || 'Browser';
|
|
406
|
+
} else {
|
|
407
|
+
pane.title = opts.title || `Terminal ${tab.panes.length + 1}`;
|
|
408
|
+
pane.cwd = opts.cwd || os.homedir();
|
|
409
|
+
// UI-created panes defer the PTY until the client has measured the pane,
|
|
410
|
+
// so the first prompt wraps at the width the user can actually see.
|
|
411
|
+
if (opts.start !== false) startPanePty(pane);
|
|
412
|
+
}
|
|
413
|
+
tab.panes.push(pane);
|
|
414
|
+
panes.set(pane.id, pane);
|
|
415
|
+
scheduleSave();
|
|
416
|
+
return pane;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function scheduleSave() {
|
|
420
|
+
if (!restored || shuttingDown) return;
|
|
421
|
+
if (saveTimer) clearTimeout(saveTimer);
|
|
422
|
+
saveTimer = setTimeout(() => {
|
|
423
|
+
saveTimer = null;
|
|
424
|
+
saveState().catch(() => { /* the next mutation retries */ });
|
|
425
|
+
}, 150).unref?.();
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
async function saveState() {
|
|
429
|
+
const list = [...tabs.values()];
|
|
430
|
+
const activeIndex = Math.max(0, list.findIndex((tab) => tab.id === activeTabId));
|
|
431
|
+
const activeTab = list[activeIndex];
|
|
432
|
+
const activePaneIndex = activeTab
|
|
433
|
+
? Math.max(0, activeTab.panes.findIndex((pane) => pane.id === activePaneId))
|
|
434
|
+
: 0;
|
|
435
|
+
const payload = {
|
|
436
|
+
// Version 2 is the first that can be trusted for ownership: it records
|
|
437
|
+
// who asked for each pane, as the server decided it.
|
|
438
|
+
version: 2,
|
|
439
|
+
savedAt: new Date().toISOString(),
|
|
440
|
+
activeTabIndex: activeIndex,
|
|
441
|
+
activePaneIndex,
|
|
442
|
+
tabs: list.map((tab) => ({
|
|
443
|
+
title: tab.title,
|
|
444
|
+
createdBy: tab.createdBy,
|
|
445
|
+
panes: tab.panes.map((pane) => ({
|
|
446
|
+
kind: pane.kind,
|
|
447
|
+
title: pane.titleLocked ? pane.title : undefined,
|
|
448
|
+
url: pane.kind === 'browser' ? pane.url : undefined,
|
|
449
|
+
cwd: pane.kind === 'terminal' ? pane.cwd : undefined,
|
|
450
|
+
cols: pane.kind === 'terminal' ? pane.cols : undefined,
|
|
451
|
+
rows: pane.kind === 'terminal' ? pane.rows : undefined,
|
|
452
|
+
createdBy: pane.createdBy
|
|
453
|
+
}))
|
|
454
|
+
}))
|
|
455
|
+
};
|
|
456
|
+
await fs.promises.mkdir(stateDir, { recursive: true, mode: 0o700 });
|
|
457
|
+
const temp = stateFile + '.tmp';
|
|
458
|
+
await fs.promises.writeFile(temp, JSON.stringify(payload, null, 2), { mode: 0o600 });
|
|
459
|
+
await fs.promises.rename(temp, stateFile);
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
async function restoreState() {
|
|
463
|
+
let saved;
|
|
464
|
+
try { saved = JSON.parse(await fs.promises.readFile(stateFile, 'utf8')); }
|
|
465
|
+
catch (_) { return; }
|
|
466
|
+
if (!saved || !Array.isArray(saved.tabs)) return;
|
|
467
|
+
savedWorkspace = true;
|
|
468
|
+
// Written before ownership could be trusted; it is saved again in the
|
|
469
|
+
// current form once it has been read, so the migration happens once.
|
|
470
|
+
olderWorkspace = Number(saved.version || 1) < 2;
|
|
471
|
+
for (const savedTab of saved.tabs.slice(0, MAX_TABS)) {
|
|
472
|
+
const tab = createTab(
|
|
473
|
+
typeof savedTab.title === 'string' ? savedTab.title : 'Workspace',
|
|
474
|
+
savedTab.createdBy === 'agent' ? 'agent' : 'human'
|
|
475
|
+
);
|
|
476
|
+
for (const savedPane of (savedTab.panes || []).slice(0, MAX_PANES_PER_TAB)) {
|
|
477
|
+
try {
|
|
478
|
+
// A browser pane that was never navigated saves about:blank, which
|
|
479
|
+
// the address validator correctly rejects. Omitting it creates a
|
|
480
|
+
// fresh blank browser pane instead of silently dropping the pane.
|
|
481
|
+
const savedUrl = typeof savedPane.url === 'string' && savedPane.url !== 'about:blank'
|
|
482
|
+
? savedPane.url
|
|
483
|
+
: undefined;
|
|
484
|
+
// Whose pane it is comes back with it. An agent's pane stays the
|
|
485
|
+
// agents' to use after a restart; one of the owner's comes back
|
|
486
|
+
// Private, because its grant was given to a pane that no longer
|
|
487
|
+
// exists. Before version 2 the seeded Orchestrator pane was recorded
|
|
488
|
+
// as the owner's, since nothing told the two apart: it is the place
|
|
489
|
+
// the agents work in, so an older workspace gets it back as theirs.
|
|
490
|
+
const legacyOrchestrator = Number(saved.version || 1) < 2 &&
|
|
491
|
+
savedPane.title === 'Orchestrator' && savedPane.kind !== 'browser' &&
|
|
492
|
+
savedPane.createdBy !== 'agent';
|
|
493
|
+
await createPane(tab.id, savedPane.kind === 'browser' ? 'browser' : 'terminal', {
|
|
494
|
+
title: typeof savedPane.title === 'string' ? savedPane.title : undefined,
|
|
495
|
+
url: savedUrl,
|
|
496
|
+
cwd: typeof savedPane.cwd === 'string' ? savedPane.cwd : undefined,
|
|
497
|
+
cols: savedPane.cols,
|
|
498
|
+
rows: savedPane.rows,
|
|
499
|
+
createdBy: legacyOrchestrator || savedPane.createdBy === 'agent' ? 'agent' : 'human'
|
|
500
|
+
});
|
|
501
|
+
} catch (_) { /* one bad pane must not lose the rest of the workspace */ }
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
const list = [...tabs.values()];
|
|
505
|
+
if (!list.length) return;
|
|
506
|
+
const active = list[Math.min(Math.max(0, Number(saved.activeTabIndex) || 0), list.length - 1)];
|
|
507
|
+
if (!active) return;
|
|
508
|
+
activeTabId = active.id;
|
|
509
|
+
const pane = active.panes[Math.min(Math.max(0, Number(saved.activePaneIndex) || 0), Math.max(0, active.panes.length - 1))];
|
|
510
|
+
activePaneId = pane ? pane.id : (active.panes[0]?.id || null);
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
// A pane as a caller may see it. The owner sees everything. An agent is
|
|
514
|
+
// shown the shape of a Private pane, and nothing in it: no title, address,
|
|
515
|
+
// working directory or status, only what an agent has and whether an ask of
|
|
516
|
+
// its own is waiting. So the agent can count the panes and ask about one,
|
|
517
|
+
// and cannot learn what the person is doing there.
|
|
518
|
+
function serializePane(pane, viewer = 'owner') {
|
|
519
|
+
const access = agentAccess(pane);
|
|
520
|
+
const request = currentRequest(pane);
|
|
521
|
+
if (viewer === 'agent' && pane.createdBy === 'human' && access.level === 'private') {
|
|
522
|
+
return {
|
|
523
|
+
id: pane.id, tabId: pane.tabId, kind: pane.kind, createdBy: 'human',
|
|
524
|
+
agentAccess: access, accessRequest: request, redacted: true
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
if (pane.kind === 'browser' && pane.browserId) {
|
|
528
|
+
const browser = browserWorkspace.get(pane.browserId);
|
|
529
|
+
if (browser) {
|
|
530
|
+
const liveUrl = browser.page.url();
|
|
531
|
+
if (liveUrl && liveUrl !== 'about:blank') pane.url = liveUrl;
|
|
532
|
+
if (!pane.titleLocked) pane.title = browser.title || pane.title;
|
|
533
|
+
pane.sizing = browser.sizing;
|
|
534
|
+
} else {
|
|
535
|
+
pane.url = '';
|
|
536
|
+
if (!pane.titleLocked) pane.title = 'Browser unavailable';
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
const programStatus = pane.exited ? 'exited' : (pane.kind === 'terminal' && !pane.pty ? 'starting' : 'running');
|
|
540
|
+
const latestJob = pane.jobs.length ? serializeJob(pane.jobs[pane.jobs.length - 1], false) : null;
|
|
541
|
+
return {
|
|
542
|
+
id: pane.id, tabId: pane.tabId, kind: pane.kind, title: pane.title,
|
|
543
|
+
url: pane.url, browserId: pane.browserId,
|
|
544
|
+
sizing: pane.kind === 'browser' ? pane.sizing : undefined,
|
|
545
|
+
cwd: pane.kind === 'terminal' ? pane.cwd : undefined,
|
|
546
|
+
cols: pane.cols, rows: pane.rows,
|
|
547
|
+
// The widest the shell has been; its output was laid out for at most this.
|
|
548
|
+
maxCols: pane.kind === 'terminal' ? Math.max(pane.maxCols || 0, pane.cols) : undefined,
|
|
549
|
+
// Kept flat for existing callers; the three meanings are also exposed
|
|
550
|
+
// separately below so they cannot be confused with one another.
|
|
551
|
+
status: programStatus,
|
|
552
|
+
programStatus,
|
|
553
|
+
program: {
|
|
554
|
+
status: programStatus,
|
|
555
|
+
startedAt: pane.startedAt,
|
|
556
|
+
exitedAt: pane.exitedAt,
|
|
557
|
+
exitCode: pane.exitCode,
|
|
558
|
+
exitSignal: pane.exitSignal
|
|
559
|
+
},
|
|
560
|
+
lastOutputAt: pane.lastOutputAt,
|
|
561
|
+
idleMs: Math.max(0, Date.now() - pane.lastOutputAt),
|
|
562
|
+
exitCode: pane.exitCode,
|
|
563
|
+
exitSignal: pane.exitSignal,
|
|
564
|
+
// Agent-reported status: what the AI last said about its own work.
|
|
565
|
+
agentState: pane.agentState,
|
|
566
|
+
agentMessage: pane.agentMessage,
|
|
567
|
+
agentStateAt: pane.agentStateAt,
|
|
568
|
+
agentStateAgeMs: pane.agentStateAt ? Math.max(0, Date.now() - pane.agentStateAt) : null,
|
|
569
|
+
agent: {
|
|
570
|
+
state: pane.agentState,
|
|
571
|
+
message: pane.agentMessage,
|
|
572
|
+
reportedAt: pane.agentStateAt,
|
|
573
|
+
ageMs: pane.agentStateAt ? Math.max(0, Date.now() - pane.agentStateAt) : null
|
|
574
|
+
},
|
|
575
|
+
// Command status: the most recent tracked job, if any.
|
|
576
|
+
command: latestJob ? {
|
|
577
|
+
jobId: latestJob.id,
|
|
578
|
+
status: latestJob.status,
|
|
579
|
+
exitCode: latestJob.exitCode,
|
|
580
|
+
startedAt: latestJob.startedAt,
|
|
581
|
+
endedAt: latestJob.endedAt
|
|
582
|
+
} : null,
|
|
583
|
+
// createdBy says whose pane it is; agentAccess says what an agent has on
|
|
584
|
+
// it now; accessRequest is an agent's unanswered ask.
|
|
585
|
+
createdBy: pane.createdBy,
|
|
586
|
+
agentAccess: access,
|
|
587
|
+
accessRequest: request,
|
|
588
|
+
active: pane.id === activePaneId
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
function serializeJob(job, includeOutput = true) {
|
|
593
|
+
const payload = {
|
|
594
|
+
id: job.id,
|
|
595
|
+
paneId: job.paneId,
|
|
596
|
+
command: job.command,
|
|
597
|
+
status: job.status,
|
|
598
|
+
startedAt: job.startedAt,
|
|
599
|
+
endedAt: job.endedAt,
|
|
600
|
+
elapsedMs: (job.endedAt || Date.now()) - job.startedAt,
|
|
601
|
+
exitCode: job.exitCode,
|
|
602
|
+
signal: job.signal,
|
|
603
|
+
timedOut: job.timedOut
|
|
604
|
+
};
|
|
605
|
+
if (includeOutput) {
|
|
606
|
+
payload.stdout = job.stdout;
|
|
607
|
+
payload.stderr = job.stderr;
|
|
608
|
+
payload.stdoutTruncated = job.stdoutTruncated;
|
|
609
|
+
payload.stderrTruncated = job.stderrTruncated;
|
|
610
|
+
}
|
|
611
|
+
return payload;
|
|
612
|
+
}
|
|
613
|
+
function serializeTab(tab, viewer = 'owner') {
|
|
614
|
+
return { id: tab.id, title: tab.title, createdBy: tab.createdBy || 'human', active: tab.id === activeTabId, panes: tab.panes.map((pane) => serializePane(pane, viewer)) };
|
|
615
|
+
}
|
|
616
|
+
// viewer tells the caller how the server sees it, so a page whose key has
|
|
617
|
+
// gone stale (the server restarted) knows to renew it instead of quietly
|
|
618
|
+
// drawing an agent's view of the person's own panes.
|
|
619
|
+
function state(viewer = 'owner') {
|
|
620
|
+
return {
|
|
621
|
+
host: os.hostname().replace(/\.local$/i, '').toLowerCase(),
|
|
622
|
+
epoch,
|
|
623
|
+
seq: ++stateSeq,
|
|
624
|
+
restored,
|
|
625
|
+
viewer,
|
|
626
|
+
tabs: [...tabs.values()].map((tab) => serializeTab(tab, viewer)),
|
|
627
|
+
activeTabId, activePaneId,
|
|
628
|
+
limits: { maxTabs: MAX_TABS, maxPanesPerTab: MAX_PANES_PER_TAB, maxTerminalPanes: MAX_TERMINAL_PANES }
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
function ensureInitial() {
|
|
632
|
+
if (!restorePromise) {
|
|
633
|
+
// Seed exactly once. An intentionally empty workspace (the user closed
|
|
634
|
+
// the last tab) must stay empty across state polls.
|
|
635
|
+
restorePromise = restoreState()
|
|
636
|
+
.catch(() => { /* corrupt state is not fatal */ })
|
|
637
|
+
.then(async () => {
|
|
638
|
+
restored = true;
|
|
639
|
+
if (olderWorkspace) {
|
|
640
|
+
olderWorkspace = false;
|
|
641
|
+
await saveState().catch(() => { /* the next change retries */ });
|
|
642
|
+
}
|
|
643
|
+
if (savedWorkspace || tabs.size) return;
|
|
644
|
+
const tab = createTab('Workspace 1');
|
|
645
|
+
// The Orchestrator pane is the place an agent works in: the person
|
|
646
|
+
// starts one there, and it reports and runs from inside it. It is
|
|
647
|
+
// the agents' pane from the first moment; what the person adds is
|
|
648
|
+
// theirs.
|
|
649
|
+
const pane = await createPane(tab.id, 'terminal', { title: 'Orchestrator', createdBy: 'agent' });
|
|
650
|
+
activeTabId = tab.id;
|
|
651
|
+
activePaneId = pane.id;
|
|
652
|
+
});
|
|
653
|
+
}
|
|
654
|
+
return restorePromise;
|
|
655
|
+
}
|
|
656
|
+
function killPty(pane) {
|
|
657
|
+
if (!pane.pty) return;
|
|
658
|
+
try { pane.pty.kill('SIGTERM'); } catch (_) { /* already gone */ }
|
|
659
|
+
setTimeout(() => {
|
|
660
|
+
try { pane.pty.kill('SIGKILL'); } catch (_) { /* exited cleanly */ }
|
|
661
|
+
}, 1000).unref?.();
|
|
662
|
+
}
|
|
663
|
+
function closePane(pane) {
|
|
664
|
+
if (!pane) return;
|
|
665
|
+
const tab = tabOf(pane);
|
|
666
|
+
if (tab) tab.panes = tab.panes.filter((candidate) => candidate.id !== pane.id);
|
|
667
|
+
panes.delete(pane.id);
|
|
668
|
+
for (const stream of pane.streams) { try { stream.end(); } catch (_) { /* already closed */ } }
|
|
669
|
+
pane.streams.clear();
|
|
670
|
+
for (const job of pane.jobs || []) cancelJob(job);
|
|
671
|
+
killPty(pane);
|
|
672
|
+
if (pane.kind === 'browser' && pane.browserId) browserWorkspace.close(pane.browserId).catch(() => {});
|
|
673
|
+
if (activePaneId === pane.id) {
|
|
674
|
+
const next = tab && tab.panes[0];
|
|
675
|
+
activePaneId = next ? next.id : null;
|
|
676
|
+
}
|
|
677
|
+
scheduleSave();
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
// ── Tracked jobs ─────────────────────────────────────────────────────────
|
|
681
|
+
//
|
|
682
|
+
// An ordinary, non-interactive command gets a real process with a pid, an
|
|
683
|
+
// exit code, and output attributed to it. Typing into the interactive shell
|
|
684
|
+
// and reading back recent output does not prove anything finished, and the
|
|
685
|
+
// two operations are kept separate on purpose.
|
|
686
|
+
|
|
687
|
+
function pruneJobs(pane) {
|
|
688
|
+
while (pane.jobs.length > MAX_JOBS_PER_PANE) {
|
|
689
|
+
const index = pane.jobs.findIndex((job) => job.status !== 'running');
|
|
690
|
+
if (index < 0) break;
|
|
691
|
+
pane.jobs.splice(index, 1);
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
function startJob(pane, command) {
|
|
696
|
+
const job = {
|
|
697
|
+
id: 'j_' + crypto.randomBytes(6).toString('hex'),
|
|
698
|
+
paneId: pane.id,
|
|
699
|
+
command,
|
|
700
|
+
status: 'running',
|
|
701
|
+
startedAt: Date.now(),
|
|
702
|
+
endedAt: null,
|
|
703
|
+
exitCode: null,
|
|
704
|
+
signal: null,
|
|
705
|
+
timedOut: false,
|
|
706
|
+
stdout: '',
|
|
707
|
+
stderr: '',
|
|
708
|
+
stdoutTruncated: false,
|
|
709
|
+
stderrTruncated: false,
|
|
710
|
+
child: null,
|
|
711
|
+
cancelled: false,
|
|
712
|
+
waiters: []
|
|
713
|
+
};
|
|
714
|
+
const env = paneEnvironment({
|
|
715
|
+
TERM: 'dumb',
|
|
716
|
+
TOWNMOUSE_API: apiUrl,
|
|
717
|
+
TOWNMOUSE_TOKEN: token,
|
|
718
|
+
TOWNMOUSE_TAB_ID: pane.tabId,
|
|
719
|
+
TOWNMOUSE_PANE_ID: pane.id,
|
|
720
|
+
TOWNMOUSE_PANES_CLI: cliPath
|
|
721
|
+
});
|
|
722
|
+
const shell = resolveShell();
|
|
723
|
+
// A compound command's children are not killed by signalling only the
|
|
724
|
+
// shell. Run the job in its own process group so cancellation and pane
|
|
725
|
+
// close can terminate the whole workload.
|
|
726
|
+
const child = spawn(shell, ['-lc', command], {
|
|
727
|
+
cwd: pane.cwd || os.homedir(),
|
|
728
|
+
env,
|
|
729
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
730
|
+
detached: process.platform !== 'win32'
|
|
731
|
+
});
|
|
732
|
+
job.child = child;
|
|
733
|
+
// Pipe chunks split multi-byte characters at arbitrary byte boundaries.
|
|
734
|
+
// Decode per stream so `é` is not turned into two replacement characters.
|
|
735
|
+
const decoders = { stdout: new StringDecoder('utf8'), stderr: new StringDecoder('utf8') };
|
|
736
|
+
const append = (key, text) => {
|
|
737
|
+
if (!text) return;
|
|
738
|
+
if (job[key].length < MAX_JOB_OUTPUT) {
|
|
739
|
+
job[key] += text.slice(0, MAX_JOB_OUTPUT - job[key].length);
|
|
740
|
+
}
|
|
741
|
+
if (job[key].length >= MAX_JOB_OUTPUT || text.length > MAX_JOB_OUTPUT) job[key + 'Truncated'] = true;
|
|
742
|
+
};
|
|
743
|
+
const collect = (channel) => (chunk) => append(channel, decoders[channel].write(chunk));
|
|
744
|
+
child.stdout.on('data', collect('stdout'));
|
|
745
|
+
child.stderr.on('data', collect('stderr'));
|
|
746
|
+
const finish = (status, detail = {}) => {
|
|
747
|
+
if (job.status !== 'running') return;
|
|
748
|
+
append('stdout', decoders.stdout.end());
|
|
749
|
+
append('stderr', decoders.stderr.end());
|
|
750
|
+
job.status = status;
|
|
751
|
+
job.endedAt = Date.now();
|
|
752
|
+
job.exitCode = detail.exitCode ?? null;
|
|
753
|
+
job.signal = detail.signal ?? null;
|
|
754
|
+
if (detail.timedOut) job.timedOut = true;
|
|
755
|
+
delete job.child;
|
|
756
|
+
for (const waiter of job.waiters.splice(0)) waiter();
|
|
757
|
+
};
|
|
758
|
+
child.on('error', (error) => {
|
|
759
|
+
job.stderr += (job.stderr ? '\n' : '') + String(error.message || error);
|
|
760
|
+
finish('failed', { exitCode: null });
|
|
761
|
+
});
|
|
762
|
+
child.on('close', (code, signal) => {
|
|
763
|
+
finish(job.cancelled ? 'cancelled' : (code === 0 ? 'completed' : 'failed'), { exitCode: code, signal });
|
|
764
|
+
});
|
|
765
|
+
pane.jobs.push(job);
|
|
766
|
+
pane.liveJobs += 1;
|
|
767
|
+
pruneJobs(pane);
|
|
768
|
+
return job;
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
function waitForJob(job, timeoutMs) {
|
|
772
|
+
if (job.status !== 'running') return Promise.resolve(job);
|
|
773
|
+
return new Promise((resolve) => {
|
|
774
|
+
let settled = false;
|
|
775
|
+
const done = () => {
|
|
776
|
+
if (settled) return;
|
|
777
|
+
settled = true;
|
|
778
|
+
clearTimeout(timer);
|
|
779
|
+
resolve(job);
|
|
780
|
+
};
|
|
781
|
+
const timer = setTimeout(() => {
|
|
782
|
+
// The job keeps running; the caller simply learns it is not done yet.
|
|
783
|
+
done();
|
|
784
|
+
}, Math.max(50, Math.min(120000, Number(timeoutMs) || 30000)));
|
|
785
|
+
job.waiters.push(done);
|
|
786
|
+
timer.unref?.();
|
|
787
|
+
});
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
function cancelJob(job) {
|
|
791
|
+
if (job.status !== 'running' || !job.child) return false;
|
|
792
|
+
job.cancelled = true;
|
|
793
|
+
const child = job.child;
|
|
794
|
+
const pid = child.pid;
|
|
795
|
+
const signalGroup = (signal) => {
|
|
796
|
+
if (process.platform !== 'win32' && pid) {
|
|
797
|
+
try { process.kill(-pid, signal); return true; } catch (_) { /* fall through */ }
|
|
798
|
+
}
|
|
799
|
+
try { child.kill(signal); return true; } catch (_) { return false; }
|
|
800
|
+
};
|
|
801
|
+
signalGroup('SIGTERM');
|
|
802
|
+
const escalate = setTimeout(() => { signalGroup('SIGKILL'); }, 1000);
|
|
803
|
+
escalate.unref?.();
|
|
804
|
+
if (typeof child.once === 'function') child.once('exit', () => clearTimeout(escalate));
|
|
805
|
+
return true;
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
// ── Clean terminal text ──────────────────────────────────────────────────
|
|
809
|
+
|
|
810
|
+
function cleanPaneText(pane, since) {
|
|
811
|
+
const start = Math.max(pane.bufferStart, Number(since) || pane.bufferStart);
|
|
812
|
+
const raw = pane.buffer.slice(start - pane.bufferStart);
|
|
813
|
+
// Render at the width the output was produced at where possible; the
|
|
814
|
+
// transcript renderer is what resume already uses for the same reason.
|
|
815
|
+
const text = replayTranscript(raw, Math.max(20, Math.min(400, pane.cols || 120)));
|
|
816
|
+
return {
|
|
817
|
+
text,
|
|
818
|
+
raw,
|
|
819
|
+
mode: 'clean',
|
|
820
|
+
cols: pane.cols,
|
|
821
|
+
bufferStart: pane.bufferStart,
|
|
822
|
+
offset: pane.totalOffset,
|
|
823
|
+
// The ring buffer is bounded; when the requested position predates what
|
|
824
|
+
// is still held, say so rather than quietly returning less.
|
|
825
|
+
truncated: Number(since) > 0 && Number(since) < pane.bufferStart,
|
|
826
|
+
evicted: pane.bufferStart
|
|
827
|
+
};
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
// The owner's key leaves only with the owner's page. The proof and its
|
|
831
|
+
// refusals are shared with the single-browser workspace's bootstrap.
|
|
832
|
+
app.get('/api/panes/bootstrap', route(async (req, res) => {
|
|
833
|
+
const refused = ownerPageRefusal(req);
|
|
834
|
+
if (refused) throw Object.assign(new Error(refused.body.error), { status: refused.status, body: refused.body });
|
|
835
|
+
await ensureInitial();
|
|
836
|
+
// ownerKey is the page's own key for this server run. The page sends it
|
|
837
|
+
// from here on; it never needs the agents' token.
|
|
838
|
+
res.json({ token, ownerKey: pageKey, state: state('owner'), api: apiUrl });
|
|
839
|
+
}));
|
|
840
|
+
app.get('/api/panes/state', auth, route(async (req, res) => { await ensureInitial(); res.json(state(req.caller)); }));
|
|
841
|
+
|
|
842
|
+
// The instruction sheet an agent gets when it connects. It describes the
|
|
843
|
+
// tools and this connection's permissions; it never enlarges them.
|
|
844
|
+
app.get('/api/panes/guide', auth, route(async (req, res) => {
|
|
845
|
+
const cli = {
|
|
846
|
+
available: fs.existsSync(cliPath),
|
|
847
|
+
path: cliPath,
|
|
848
|
+
env: {
|
|
849
|
+
api: 'TOWNMOUSE_API',
|
|
850
|
+
token: 'TOWNMOUSE_TOKEN',
|
|
851
|
+
tab: 'TOWNMOUSE_TAB_ID',
|
|
852
|
+
pane: 'TOWNMOUSE_PANE_ID'
|
|
853
|
+
}
|
|
854
|
+
};
|
|
855
|
+
res.json(buildGuide({ cli }));
|
|
856
|
+
}));
|
|
857
|
+
app.post('/api/panes/tabs', auth, route(async (req, res) => {
|
|
858
|
+
await ensureInitial();
|
|
859
|
+
// The key that asks decides whose tab it is. createdBy in the body is
|
|
860
|
+
// ignored: it was how a client described itself, and trusting it let an
|
|
861
|
+
// agent label a tab as the owner's.
|
|
862
|
+
const createdBy = req.caller === 'owner' ? 'human' : 'agent';
|
|
863
|
+
const tab = createTab(typeof req.body.title === 'string' ? req.body.title.slice(0, 80) : '', createdBy);
|
|
864
|
+
const activate = req.body.activate === true || (createdBy === 'human' && req.body.activate !== false);
|
|
865
|
+
if (activate) {
|
|
866
|
+
activeTabId = tab.id;
|
|
867
|
+
activePaneId = tab.panes[0]?.id || null;
|
|
868
|
+
scheduleSave();
|
|
869
|
+
}
|
|
870
|
+
res.json(serializeTab(tab, req.caller));
|
|
871
|
+
}));
|
|
872
|
+
app.delete('/api/panes/tabs/:id', auth, route(async (req, res) => {
|
|
873
|
+
const tab = tabOr404(req.params.id);
|
|
874
|
+
// Closing a tab ends every pane in it, and one of the owner's panes is
|
|
875
|
+
// the owner's to end however much an agent has been given on it.
|
|
876
|
+
if (req.caller !== 'owner' && tab.panes.some((pane) => pane.createdBy === 'human')) {
|
|
877
|
+
refuse(403, 'OWNER_ONLY', "This tab holds one of the owner's panes, so only the owner can close it.", { tabId: tab.id });
|
|
878
|
+
}
|
|
879
|
+
for (const pane of [...tab.panes]) closePane(pane);
|
|
880
|
+
tabs.delete(tab.id);
|
|
881
|
+
if (activeTabId === tab.id) {
|
|
882
|
+
const next = [...tabs.values()][0];
|
|
883
|
+
activeTabId = next ? next.id : null;
|
|
884
|
+
activePaneId = next?.panes[0]?.id || null;
|
|
885
|
+
}
|
|
886
|
+
scheduleSave();
|
|
887
|
+
res.json({ closed: true, state: state(req.caller) });
|
|
888
|
+
}));
|
|
889
|
+
app.post('/api/panes/tabs/:id/panes', auth, route(async (req, res) => {
|
|
890
|
+
await ensureInitial();
|
|
891
|
+
// A pane belongs to whoever opens it: the owner's page or an agent's key.
|
|
892
|
+
// An agent may add a pane of its own beside the owner's; it reads nothing
|
|
893
|
+
// by doing so.
|
|
894
|
+
const pane = await createPane(req.params.id, req.body.kind, {
|
|
895
|
+
url: req.body.url, cwd: req.body.cwd, title: req.body.title,
|
|
896
|
+
cols: req.body.cols, rows: req.body.rows, start: req.body.start,
|
|
897
|
+
createdBy: req.caller === 'owner' ? 'human' : 'agent'
|
|
898
|
+
});
|
|
899
|
+
res.json(serializePane(pane, req.caller));
|
|
900
|
+
}));
|
|
901
|
+
app.post('/api/panes/panes/:id/status', auth, route(async (req, res) => {
|
|
902
|
+
const pane = terminalPane(req.params.id, req.caller, 'control');
|
|
903
|
+
const state = String(req.body.state || '').toLowerCase();
|
|
904
|
+
if (!['working', 'blocked', 'idle', 'done', 'unknown'].includes(state)) {
|
|
905
|
+
res.status(400).json({ error: 'State must be working, blocked, idle, done, or unknown.' });
|
|
906
|
+
return;
|
|
907
|
+
}
|
|
908
|
+
pane.agentState = state === 'unknown' ? null : state;
|
|
909
|
+
pane.agentMessage = String(req.body.message || '').slice(0, 1000);
|
|
910
|
+
pane.agentStateAt = Date.now();
|
|
911
|
+
scheduleSave();
|
|
912
|
+
res.json(serializePane(pane, req.caller));
|
|
913
|
+
}));
|
|
914
|
+
app.post('/api/panes/panes/:id/start', auth, route(async (req, res) => {
|
|
915
|
+
const pane = terminalPane(req.params.id, req.caller, 'control');
|
|
916
|
+
if (pane.exited) { res.status(409).json({ error: 'Terminal pane has exited.' }); return; }
|
|
917
|
+
if (!pane.pty) {
|
|
918
|
+
pane.cols = clampCols(req.body.cols);
|
|
919
|
+
pane.rows = clampRows(req.body.rows);
|
|
920
|
+
startPanePty(pane);
|
|
921
|
+
scheduleSave();
|
|
922
|
+
}
|
|
923
|
+
res.json(serializePane(pane, req.caller));
|
|
924
|
+
}));
|
|
925
|
+
app.post('/api/panes/tabs/:id/reorder', auth, route(async (req, res) => {
|
|
926
|
+
const tab = tabOr404(req.params.id);
|
|
927
|
+
const from = tab.panes.findIndex((pane) => pane.id === req.body.paneId);
|
|
928
|
+
if (from < 0) { res.status(404).json({ error: 'Pane not found in this tab.' }); return; }
|
|
929
|
+
// An agent may arrange its own panes, not the owner's.
|
|
930
|
+
requireOwner(tab.panes[from], req.caller, 'move');
|
|
931
|
+
const to = Math.max(0, Math.min(tab.panes.length - 1, Math.round(Number(req.body.index))));
|
|
932
|
+
if (!Number.isFinite(to) || to === from) { res.json(state(req.caller)); return; }
|
|
933
|
+
const [pane] = tab.panes.splice(from, 1);
|
|
934
|
+
tab.panes.splice(to, 0, pane);
|
|
935
|
+
scheduleSave();
|
|
936
|
+
res.json(state(req.caller));
|
|
937
|
+
}));
|
|
938
|
+
app.delete('/api/panes/panes/:id', auth, route(async (req, res) => {
|
|
939
|
+
const pane = paneOr404(req.params.id);
|
|
940
|
+
requireOwner(pane, req.caller, 'close');
|
|
941
|
+
closePane(pane);
|
|
942
|
+
res.json({ closed: true, state: state(req.caller) });
|
|
943
|
+
}));
|
|
944
|
+
app.post('/api/panes/active', auth, route(async (req, res) => {
|
|
945
|
+
// What is active is what the person is looking at and typing into. An
|
|
946
|
+
// agent may bring one of its own panes forward to show it; it may not
|
|
947
|
+
// move the person onto one of the owner's panes.
|
|
948
|
+
const pane = req.body.paneId ? panes.get(req.body.paneId) : null;
|
|
949
|
+
const tab = req.body.tabId ? tabs.get(req.body.tabId) : null;
|
|
950
|
+
if (req.caller !== 'owner') {
|
|
951
|
+
if (pane && pane.createdBy === 'human') requireOwner(pane, req.caller, 'bring');
|
|
952
|
+
if (tab && !tab.panes.some((candidate) => candidate.createdBy === 'agent')) {
|
|
953
|
+
refuse(403, 'OWNER_ONLY', "This tab holds only the owner's panes, so only the owner can switch to it.", { tabId: tab.id });
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
if (req.body.tabId && tabs.has(req.body.tabId)) activeTabId = req.body.tabId;
|
|
957
|
+
if (req.body.paneId && panes.has(req.body.paneId)) activePaneId = req.body.paneId;
|
|
958
|
+
scheduleSave();
|
|
959
|
+
res.json(state(req.caller));
|
|
960
|
+
}));
|
|
961
|
+
|
|
962
|
+
// ── The grant, and the one way an agent asks for it ──────────────────────
|
|
963
|
+
|
|
964
|
+
// Only the owner changes what an agent may do on one of the owner's panes.
|
|
965
|
+
// Setting a level also answers any pending ask, and lowering one ends what
|
|
966
|
+
// agents already hold on the pane (see setGrant).
|
|
967
|
+
app.post('/api/panes/panes/:id/permission', auth, route(async (req, res) => {
|
|
968
|
+
const pane = paneOr404(req.params.id);
|
|
969
|
+
if (req.caller !== 'owner') refuse(403, 'OWNER_ONLY', 'Only the owner can change what an agent may do on a pane.', { paneId: pane.id, agentAccess: agentAccess(pane) });
|
|
970
|
+
if (pane.createdBy === 'agent') refuse(409, 'AGENT_PANE', 'An agent opened this pane, so agents always have control of it. To keep a pane private, open one of your own.', { paneId: pane.id });
|
|
971
|
+
const level = String(req.body.permission || '');
|
|
972
|
+
if (!Object.hasOwn(ACCESS, level)) { res.status(400).json({ error: 'Agent access must be private, view, or control.' }); return; }
|
|
973
|
+
setGrant(pane, level);
|
|
974
|
+
res.json(state(req.caller));
|
|
975
|
+
}));
|
|
976
|
+
|
|
977
|
+
// An agent asks for access to one of the owner's panes. The ask appears on
|
|
978
|
+
// that pane for the owner to answer. It clears itself unanswered, and a pane
|
|
979
|
+
// the owner just said not now to cannot be asked about for a while.
|
|
980
|
+
app.post('/api/panes/panes/:id/request-access', auth, route(async (req, res) => {
|
|
981
|
+
const pane = paneOr404(req.params.id);
|
|
982
|
+
if (req.caller === 'owner') refuse(403, 'AGENT_ONLY', 'The owner does not ask: set the pane\'s agent access instead.', { paneId: pane.id });
|
|
983
|
+
if (pane.createdBy === 'agent') refuse(409, 'AGENT_PANE', 'Agents already have control of this pane; there is nothing to ask for.', { paneId: pane.id });
|
|
984
|
+
const level = String(req.body.level || '');
|
|
985
|
+
if (!Object.hasOwn(ACCESS, level) || level === 'private') { res.status(400).json({ error: 'Ask for view or control.' }); return; }
|
|
986
|
+
const access = agentAccess(pane);
|
|
987
|
+
if (ACCESS[access.level] >= ACCESS[level]) {
|
|
988
|
+
refuse(409, 'ALREADY_GRANTED', `Agents already have ${access.label} on this pane; there is nothing to ask for.`, { paneId: pane.id, agentAccess: access });
|
|
989
|
+
}
|
|
990
|
+
const pending = currentRequest(pane);
|
|
991
|
+
if (pending && ACCESS[pending.level] >= ACCESS[level]) {
|
|
992
|
+
// The same ask, or a smaller one, is already waiting: one prompt per pane.
|
|
993
|
+
res.json(serializePane(pane, req.caller));
|
|
994
|
+
return;
|
|
995
|
+
}
|
|
996
|
+
if (recentlyDeclined(pane)) {
|
|
997
|
+
refuse(409, 'DECLINED', `The owner said not now to ${ACCESS_LABEL[pane.accessDeclined.level]} on this pane a moment ago, so this pane cannot be asked about yet. Finish without it, or wait for the owner to change what an agent may do there.`, { paneId: pane.id, agentAccess: access });
|
|
998
|
+
}
|
|
999
|
+
const message = String(req.body.message || '').replace(/\s+/g, ' ').trim().slice(0, 300);
|
|
1000
|
+
pane.accessRequest = { level, message, at: Date.now() };
|
|
1001
|
+
res.json(serializePane(pane, req.caller));
|
|
1002
|
+
}));
|
|
1003
|
+
|
|
1004
|
+
// The owner dismisses an ask ("not now": the grant is left as it is), or an
|
|
1005
|
+
// agent withdraws its own.
|
|
1006
|
+
app.delete('/api/panes/panes/:id/request-access', auth, route(async (req, res) => {
|
|
1007
|
+
const pane = paneOr404(req.params.id);
|
|
1008
|
+
if (req.caller === 'owner' && pane.accessRequest) {
|
|
1009
|
+
pane.accessDeclined = { level: pane.accessRequest.level, at: Date.now() };
|
|
1010
|
+
}
|
|
1011
|
+
pane.accessRequest = null;
|
|
1012
|
+
res.json(serializePane(pane, req.caller));
|
|
1013
|
+
}));
|
|
1014
|
+
|
|
1015
|
+
// ── Browser panes ────────────────────────────────────────────────────────
|
|
1016
|
+
//
|
|
1017
|
+
// Reading a page (the picture, the catalog, the text, a wait) needs View
|
|
1018
|
+
// only. Moving it (an address, an action, a dialog, its size) needs Allow
|
|
1019
|
+
// control. Each route checks before the work and again after it, because a
|
|
1020
|
+
// grant can be lowered while a capture or a wait is running.
|
|
1021
|
+
|
|
1022
|
+
// Lookup in the order that tells an agent least: a missing pane, then
|
|
1023
|
+
// whether this caller may use it, and only then whether it is a browser.
|
|
1024
|
+
function browserPane(paneId, caller, need) {
|
|
1025
|
+
const pane = paneOr404(paneId);
|
|
1026
|
+
requireAccess(pane, caller, need);
|
|
1027
|
+
if (pane.kind !== 'browser') throw Object.assign(new Error('Browser pane required.'), { status: 400 });
|
|
1028
|
+
return pane;
|
|
1029
|
+
}
|
|
1030
|
+
function terminalPane(paneId, caller, need) {
|
|
1031
|
+
const pane = paneOr404(paneId);
|
|
1032
|
+
requireAccess(pane, caller, need);
|
|
1033
|
+
if (pane.kind !== 'terminal') throw Object.assign(new Error('Terminal pane required.'), { status: 400 });
|
|
1034
|
+
return pane;
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
app.post('/api/panes/panes/:id/url', auth, route(async (req, res) => {
|
|
1038
|
+
const pane = browserPane(req.params.id, req.caller, 'control');
|
|
1039
|
+
const browser = await browserWorkspace.navigate(pane.browserId, req.body.url);
|
|
1040
|
+
requireAccess(pane, req.caller, 'control');
|
|
1041
|
+
pane.url = browser.url;
|
|
1042
|
+
if (!pane.titleLocked) pane.title = browser.title || pane.title;
|
|
1043
|
+
scheduleSave();
|
|
1044
|
+
res.json(serializePane(pane, req.caller));
|
|
1045
|
+
}));
|
|
1046
|
+
app.post('/api/panes/panes/:id/browser/action', auth, route(async (req, res) => {
|
|
1047
|
+
const pane = browserPane(req.params.id, req.caller, 'control');
|
|
1048
|
+
const outcome = await browserWorkspace.action(pane.browserId, req.body.action, req.body, {
|
|
1049
|
+
// Actions queue behind captures and navigations. This is checked again
|
|
1050
|
+
// inside the queue, so a grant lowered a moment ago stops the action.
|
|
1051
|
+
authorize: () => requireAccess(pane, req.caller, 'control')
|
|
1052
|
+
});
|
|
1053
|
+
requireAccess(pane, req.caller, 'control');
|
|
1054
|
+
pane.url = outcome.url;
|
|
1055
|
+
if (!pane.titleLocked) pane.title = outcome.title || pane.title;
|
|
1056
|
+
if (!['click', 'type', 'key', 'scroll', 'select', 'setValue', 'selectAt', 'setValueAt', 'hover', 'drag'].includes(req.body.action)) scheduleSave();
|
|
1057
|
+
// The action result is nested so it cannot be mistaken for the pane's
|
|
1058
|
+
// program status; those are three different meanings of "status".
|
|
1059
|
+
res.status(outcome.httpStatus || 200).json({
|
|
1060
|
+
...serializePane(pane, req.caller),
|
|
1061
|
+
// Flat `control` stays for the human viewer's picker overlay.
|
|
1062
|
+
control: outcome.control || null,
|
|
1063
|
+
action: {
|
|
1064
|
+
ok: outcome.ok,
|
|
1065
|
+
status: outcome.status,
|
|
1066
|
+
message: outcome.message || null,
|
|
1067
|
+
warning: outcome.warning || null,
|
|
1068
|
+
target: outcome.target || null,
|
|
1069
|
+
control: outcome.control || null,
|
|
1070
|
+
observationId: outcome.observationId || null
|
|
1071
|
+
}
|
|
1072
|
+
});
|
|
1073
|
+
}));
|
|
1074
|
+
app.post('/api/panes/panes/:id/browser/reopen', auth, route(async (req, res) => {
|
|
1075
|
+
const pane = browserPane(req.params.id, req.caller, 'control');
|
|
1076
|
+
const previous = pane.browserId;
|
|
1077
|
+
const browser = await browserWorkspace.create(pane.createdBy === 'agent' ? 'agent' : 'human', req.body.url);
|
|
1078
|
+
browserWorkspace.grant(browser.id, agentAccess(pane).level);
|
|
1079
|
+
pane.browserId = browser.id;
|
|
1080
|
+
pane.url = browser.url && browser.url !== 'about:blank' ? browser.url : 'about:blank';
|
|
1081
|
+
if (!pane.titleLocked) pane.title = browser.title || 'Browser';
|
|
1082
|
+
if (previous) await browserWorkspace.close(previous).catch(() => {});
|
|
1083
|
+
scheduleSave();
|
|
1084
|
+
res.json(serializePane(pane, req.caller));
|
|
1085
|
+
}));
|
|
1086
|
+
app.post('/api/panes/panes/:id/browser/dialog', auth, route(async (req, res) => {
|
|
1087
|
+
const pane = browserPane(req.params.id, req.caller, 'control');
|
|
1088
|
+
const browser = await browserWorkspace.respondDialog(pane.browserId, req.body.action, req.body.text);
|
|
1089
|
+
requireAccess(pane, req.caller, 'view');
|
|
1090
|
+
res.json(browser);
|
|
1091
|
+
}));
|
|
1092
|
+
// A viewer sends `watch`: `watch=1` while its pane is on screen (the request
|
|
1093
|
+
// waits for the next picture, up to `wait` ms), `watch=0` for its title,
|
|
1094
|
+
// address and page prompt only. Without `watch` a picture is taken for the
|
|
1095
|
+
// caller there and then; an agent's `observe` takes its own, separately.
|
|
1096
|
+
app.get('/api/panes/panes/:id/browser/snapshot', auth, route(async (req, res) => {
|
|
1097
|
+
const pane = browserPane(req.params.id, req.caller, 'view');
|
|
1098
|
+
const snap = await browserWorkspace.snapshot(pane.browserId, browserWorkspace.viewerRequest(req, res));
|
|
1099
|
+
if (!snap) return; // The viewer went away while its request waited.
|
|
1100
|
+
requireAccess(pane, req.caller, 'view');
|
|
1101
|
+
pane.url = snap.url;
|
|
1102
|
+
if (!pane.titleLocked) pane.title = snap.title || pane.title;
|
|
1103
|
+
res.json(snap);
|
|
1104
|
+
}));
|
|
1105
|
+
app.get('/api/panes/panes/:id/browser/observe', auth, route(async (req, res) => {
|
|
1106
|
+
const pane = browserPane(req.params.id, req.caller, 'view');
|
|
1107
|
+
const observed = await browserWorkspace.observe(pane.browserId, {
|
|
1108
|
+
elements: req.query.elements === '1' || req.query.elements === 'true',
|
|
1109
|
+
max: req.query.max
|
|
1110
|
+
});
|
|
1111
|
+
requireAccess(pane, req.caller, 'view');
|
|
1112
|
+
pane.url = observed.url;
|
|
1113
|
+
if (!pane.titleLocked) pane.title = observed.title || pane.title;
|
|
1114
|
+
res.json(observed);
|
|
1115
|
+
}));
|
|
1116
|
+
app.get('/api/panes/panes/:id/browser/elements', auth, route(async (req, res) => {
|
|
1117
|
+
const pane = browserPane(req.params.id, req.caller, 'view');
|
|
1118
|
+
const catalogued = await browserWorkspace.elements(pane.browserId, { max: req.query.max });
|
|
1119
|
+
requireAccess(pane, req.caller, 'view');
|
|
1120
|
+
pane.url = catalogued.url;
|
|
1121
|
+
if (!pane.titleLocked) pane.title = catalogued.title || pane.title;
|
|
1122
|
+
res.json(catalogued);
|
|
1123
|
+
}));
|
|
1124
|
+
app.post('/api/panes/panes/:id/browser/wait', auth, route(async (req, res) => {
|
|
1125
|
+
const pane = browserPane(req.params.id, req.caller, 'view');
|
|
1126
|
+
const waited = await browserWorkspace.wait(pane.browserId, req.body || {}, {
|
|
1127
|
+
interrupted: () => !hasAccess(pane, req.caller, 'view')
|
|
1128
|
+
});
|
|
1129
|
+
requireAccess(pane, req.caller, 'view');
|
|
1130
|
+
res.json(waited);
|
|
1131
|
+
}));
|
|
1132
|
+
app.post('/api/panes/panes/:id/browser/sizing', auth, route(async (req, res) => {
|
|
1133
|
+
const pane = browserPane(req.params.id, req.caller, 'control');
|
|
1134
|
+
const size = await browserWorkspace.sizing(pane.browserId, req.body.mode, req.body);
|
|
1135
|
+
requireAccess(pane, req.caller, 'view');
|
|
1136
|
+
res.json(size);
|
|
1137
|
+
}));
|
|
1138
|
+
app.get('/api/panes/panes/:id/browser/content', auth, route(async (req, res) => {
|
|
1139
|
+
const pane = browserPane(req.params.id, req.caller, 'view');
|
|
1140
|
+
const browser = browserWorkspace.get(pane.browserId);
|
|
1141
|
+
if (!browser) { res.status(404).json({ error: 'Browser pane no longer exists.' }); return; }
|
|
1142
|
+
const info = await browserWorkspace.content(pane.browserId, { limit: req.query.limit });
|
|
1143
|
+
requireAccess(pane, req.caller, 'view');
|
|
1144
|
+
res.json({
|
|
1145
|
+
url: info.url,
|
|
1146
|
+
title: info.title || browser.title || pane.title,
|
|
1147
|
+
text: info.text,
|
|
1148
|
+
totalLength: info.totalLength,
|
|
1149
|
+
truncated: info.truncated,
|
|
1150
|
+
frameCount: info.frameCount,
|
|
1151
|
+
frames: info.frames
|
|
1152
|
+
});
|
|
1153
|
+
}));
|
|
1154
|
+
// ── Terminal panes ────────────────────────────────────────────────────────
|
|
1155
|
+
//
|
|
1156
|
+
// Reading a terminal (the stream, the buffer, screen text, a wait, a job's
|
|
1157
|
+
// output) needs View only. Writing to it (input, keys, a typed line, a job,
|
|
1158
|
+
// a status) needs Allow control. Resizing and closing stay the owner's.
|
|
1159
|
+
|
|
1160
|
+
app.get('/api/panes/panes/:id/stream', auth, (req, res) => {
|
|
1161
|
+
let pane;
|
|
1162
|
+
try { pane = terminalPane(req.params.id, req.caller, 'view'); }
|
|
1163
|
+
catch (error) {
|
|
1164
|
+
// This route writes its own response, so the refusal is written here.
|
|
1165
|
+
res.status(error.status || 400).json(error.body || { error: error.message });
|
|
1166
|
+
return;
|
|
1167
|
+
}
|
|
1168
|
+
if (activeStreams >= MAX_ACTIVE_STREAMS) {
|
|
1169
|
+
res.status(429).json({ error: 'Terminal stream capacity reached; polling this pane.' });
|
|
1170
|
+
return;
|
|
1171
|
+
}
|
|
1172
|
+
activeStreams++;
|
|
1173
|
+
let ping = null;
|
|
1174
|
+
let closed = false;
|
|
1175
|
+
const end = () => {
|
|
1176
|
+
if (closed) return;
|
|
1177
|
+
closed = true;
|
|
1178
|
+
if (ping) clearInterval(ping);
|
|
1179
|
+
pane.streams.delete(res);
|
|
1180
|
+
activeStreams = Math.max(0, activeStreams - 1);
|
|
1181
|
+
};
|
|
1182
|
+
// Register cleanup before the first write so a client that vanishes during
|
|
1183
|
+
// the handshake cannot leak a stream slot forever.
|
|
1184
|
+
req.on('close', end);
|
|
1185
|
+
res.on('close', end);
|
|
1186
|
+
// Lowering the grant ends the streams agents are reading on this pane.
|
|
1187
|
+
res.paneViewer = req.caller;
|
|
1188
|
+
res.endPaneStream = () => { try { res.end(); } catch (_) { /* already gone */ } end(); };
|
|
1189
|
+
res.writeHead(200, {
|
|
1190
|
+
'Content-Type': 'text/event-stream',
|
|
1191
|
+
'Cache-Control': 'no-store',
|
|
1192
|
+
Connection: 'keep-alive',
|
|
1193
|
+
'X-Accel-Buffering': 'no'
|
|
1194
|
+
});
|
|
1195
|
+
let since = Math.max(0, Number(req.query.since) || 0);
|
|
1196
|
+
if (since < pane.bufferStart) since = pane.bufferStart;
|
|
1197
|
+
sendStreamEvent(res, `data: ${JSON.stringify({ data: pane.buffer.slice(since - pane.bufferStart), offset: pane.totalOffset, exited: pane.exited })}\n\n`);
|
|
1198
|
+
pane.streams.add(res);
|
|
1199
|
+
ping = setInterval(() => {
|
|
1200
|
+
if (!res._sseBlocked) {
|
|
1201
|
+
try { res.write(': ping\n\n'); } catch (_) { /* client vanished */ }
|
|
1202
|
+
}
|
|
1203
|
+
}, 15000);
|
|
1204
|
+
ping.unref?.();
|
|
1205
|
+
});
|
|
1206
|
+
app.get('/api/panes/panes/:id/read', auth, route(async (req, res) => {
|
|
1207
|
+
const pane = terminalPane(req.params.id, req.caller, 'view');
|
|
1208
|
+
let since = Math.max(0, Number(req.query.since) || 0);
|
|
1209
|
+
if (since < pane.bufferStart) since = pane.bufferStart;
|
|
1210
|
+
res.json({ data: pane.buffer.slice(since - pane.bufferStart), offset: pane.totalOffset, exited: pane.exited });
|
|
1211
|
+
}));
|
|
1212
|
+
app.post('/api/panes/panes/:id/input', auth, route(async (req, res) => {
|
|
1213
|
+
const pane = terminalPane(req.params.id, req.caller, 'control');
|
|
1214
|
+
if (!pane.pty) { res.status(400).json({ error: 'Terminal pane required.' }); return; }
|
|
1215
|
+
pane.pty.write(String(req.body.data ?? ''));
|
|
1216
|
+
res.json({ ok: true });
|
|
1217
|
+
}));
|
|
1218
|
+
app.post('/api/panes/panes/:id/keys', auth, route(async (req, res) => {
|
|
1219
|
+
const pane = terminalPane(req.params.id, req.caller, 'control');
|
|
1220
|
+
if (!pane.pty) { res.status(400).json({ error: 'Terminal pane required.' }); return; }
|
|
1221
|
+
const keys = Array.isArray(req.body.keys) ? req.body.keys : [req.body.key];
|
|
1222
|
+
if (!keys.length || keys.length > 32) { res.status(400).json({ error: 'Send between 1 and 32 keys.' }); return; }
|
|
1223
|
+
const sequence = keys.map(keySequence).join('');
|
|
1224
|
+
if (sequence.length > 4096) { res.status(400).json({ error: 'Key sequence is too large.' }); return; }
|
|
1225
|
+
pane.pty.write(sequence);
|
|
1226
|
+
res.json({ ok: true, bytes: sequence.length });
|
|
1227
|
+
}));
|
|
1228
|
+
app.get('/api/panes/panes/:id/wait', auth, route(async (req, res) => {
|
|
1229
|
+
const pane = terminalPane(req.params.id, req.caller, 'view');
|
|
1230
|
+
const timeout = Math.max(100, Math.min(120000, Number(req.query.timeout) || 30000));
|
|
1231
|
+
const since = req.query.since === undefined ? pane.totalOffset : Math.max(0, Number(req.query.since) || 0);
|
|
1232
|
+
const match = typeof req.query.match === 'string' ? req.query.match : '';
|
|
1233
|
+
const pattern = typeof req.query.regex === 'string' ? req.query.regex : '';
|
|
1234
|
+
const idleMs = Math.max(0, Math.min(120000, Number(req.query.idleMs) || 0));
|
|
1235
|
+
const state = typeof req.query.state === 'string' ? req.query.state.toLowerCase() : '';
|
|
1236
|
+
if (state && !['working', 'blocked', 'idle', 'done', 'unknown'].includes(state)) {
|
|
1237
|
+
res.status(400).json({ error: 'Unknown agent state.' });
|
|
1238
|
+
return;
|
|
1239
|
+
}
|
|
1240
|
+
if (!match && !pattern && !idleMs && !state) {
|
|
1241
|
+
res.status(400).json({ error: 'Provide match, regex, idleMs, or state.' });
|
|
1242
|
+
return;
|
|
1243
|
+
}
|
|
1244
|
+
// A client-supplied regex is evaluated in a worker thread so a pattern with
|
|
1245
|
+
// catastrophic backtracking can be terminated instead of freezing the
|
|
1246
|
+
// event loop every other request shares.
|
|
1247
|
+
let matcher = null;
|
|
1248
|
+
if (pattern) {
|
|
1249
|
+
const created = createPatternMatcher(pattern);
|
|
1250
|
+
if (created.error) { res.status(400).json({ error: created.error }); return; }
|
|
1251
|
+
matcher = created;
|
|
1252
|
+
}
|
|
1253
|
+
const started = Date.now();
|
|
1254
|
+
let result;
|
|
1255
|
+
try {
|
|
1256
|
+
result = await new Promise((resolve) => {
|
|
1257
|
+
let finished = false;
|
|
1258
|
+
const finish = (payload) => {
|
|
1259
|
+
if (finished) return;
|
|
1260
|
+
finished = true;
|
|
1261
|
+
resolve(payload);
|
|
1262
|
+
};
|
|
1263
|
+
const snapshot = (matched, reason) => {
|
|
1264
|
+
const data = pane.buffer.slice(Math.max(0, since - pane.bufferStart));
|
|
1265
|
+
finish({
|
|
1266
|
+
matched, reason,
|
|
1267
|
+
data: data.slice(-100000),
|
|
1268
|
+
offset: pane.totalOffset,
|
|
1269
|
+
idleMs: Math.max(0, Date.now() - pane.lastOutputAt),
|
|
1270
|
+
agentState: pane.agentState,
|
|
1271
|
+
agentMessage: pane.agentMessage,
|
|
1272
|
+
elapsedMs: Date.now() - started
|
|
1273
|
+
});
|
|
1274
|
+
};
|
|
1275
|
+
res.on('close', () => finish({ aborted: true }));
|
|
1276
|
+
const run = async () => {
|
|
1277
|
+
while (!finished) {
|
|
1278
|
+
// A wait can hold a caller for two minutes. If the owner takes
|
|
1279
|
+
// the pane back in that time, the wait ends with nothing rather
|
|
1280
|
+
// than answering a question about a pane it may no longer read.
|
|
1281
|
+
if (!hasAccess(pane, req.caller, 'view')) return finish({ aborted: true });
|
|
1282
|
+
const data = pane.buffer.slice(Math.max(0, since - pane.bufferStart));
|
|
1283
|
+
if (state && pane.agentState === (state === 'unknown' ? null : state)) return snapshot(true, 'state');
|
|
1284
|
+
if (match && data.includes(match)) return snapshot(true, 'match');
|
|
1285
|
+
if (matcher) {
|
|
1286
|
+
try {
|
|
1287
|
+
if (await matcher.test(data)) return snapshot(true, 'match');
|
|
1288
|
+
} catch (error) {
|
|
1289
|
+
return finish({ error: error.message, status: error.status || 400 });
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
if (idleMs && Date.now() - pane.lastOutputAt >= idleMs) return snapshot(true, 'idle');
|
|
1293
|
+
if (Date.now() - started >= timeout) return snapshot(false, 'timeout');
|
|
1294
|
+
await new Promise((next) => setTimeout(next, 100));
|
|
1295
|
+
}
|
|
1296
|
+
};
|
|
1297
|
+
void run();
|
|
1298
|
+
});
|
|
1299
|
+
} finally {
|
|
1300
|
+
if (matcher) matcher.close();
|
|
1301
|
+
}
|
|
1302
|
+
if (result && result.error) {
|
|
1303
|
+
if (!res.writableEnded) res.status(result.status || 400).json({ error: result.error });
|
|
1304
|
+
return;
|
|
1305
|
+
}
|
|
1306
|
+
requireAccess(pane, req.caller, 'view');
|
|
1307
|
+
if (!res.writableEnded) res.json(result);
|
|
1308
|
+
}));
|
|
1309
|
+
app.post('/api/panes/panes/:id/resize', auth, route(async (req, res) => {
|
|
1310
|
+
// A pane's size is how the owner's viewer lays it out; an agent does not
|
|
1311
|
+
// rearrange what the person is looking at.
|
|
1312
|
+
const pane = paneOr404(req.params.id);
|
|
1313
|
+
requireOwner(pane, req.caller, 'resize');
|
|
1314
|
+
if (pane.kind === 'browser') {
|
|
1315
|
+
const size = await browserWorkspace.setViewport(pane.browserId, req.body.width, req.body.height);
|
|
1316
|
+
res.json(size);
|
|
1317
|
+
return;
|
|
1318
|
+
}
|
|
1319
|
+
pane.cols = clampCols(req.body.cols);
|
|
1320
|
+
pane.rows = clampRows(req.body.rows);
|
|
1321
|
+
if (!pane.pty) {
|
|
1322
|
+
// A deferred pane is about to start at these measured dimensions.
|
|
1323
|
+
res.json({ cols: pane.cols, rows: pane.rows });
|
|
1324
|
+
return;
|
|
1325
|
+
}
|
|
1326
|
+
// Let output the shell wrote before this request be read first, so that the
|
|
1327
|
+
// point named below is exact. A viewer shows what came before that point at
|
|
1328
|
+
// the width the shell had (see public/panes.mjs, a terminal that opened at
|
|
1329
|
+
// the shell's width), and is fitted to its pane afterwards.
|
|
1330
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
1331
|
+
pane.maxCols = Math.max(pane.maxCols || 0, pane.cols);
|
|
1332
|
+
pane.pty.resize(pane.cols, pane.rows);
|
|
1333
|
+
res.json({ cols: pane.cols, rows: pane.rows, offset: pane.totalOffset });
|
|
1334
|
+
}));
|
|
1335
|
+
app.get('/api/panes/panes/:id/text', auth, route(async (req, res) => {
|
|
1336
|
+
const pane = terminalPane(req.params.id, req.caller, 'view');
|
|
1337
|
+
const mode = req.query.mode === 'raw' ? 'raw' : 'clean';
|
|
1338
|
+
const since = req.query.since === undefined ? pane.bufferStart : Number(req.query.since);
|
|
1339
|
+
if (mode === 'raw') {
|
|
1340
|
+
const start = Math.max(pane.bufferStart, Number(since) || pane.bufferStart);
|
|
1341
|
+
res.json({
|
|
1342
|
+
mode: 'raw',
|
|
1343
|
+
text: pane.buffer.slice(start - pane.bufferStart),
|
|
1344
|
+
offset: pane.totalOffset,
|
|
1345
|
+
bufferStart: pane.bufferStart,
|
|
1346
|
+
truncated: Number(since) > 0 && Number(since) < pane.bufferStart
|
|
1347
|
+
});
|
|
1348
|
+
return;
|
|
1349
|
+
}
|
|
1350
|
+
const clean = cleanPaneText(pane, since);
|
|
1351
|
+
res.json({
|
|
1352
|
+
mode: 'clean',
|
|
1353
|
+
text: clean.text,
|
|
1354
|
+
cols: clean.cols,
|
|
1355
|
+
offset: clean.offset,
|
|
1356
|
+
bufferStart: clean.bufferStart,
|
|
1357
|
+
truncated: clean.truncated
|
|
1358
|
+
});
|
|
1359
|
+
}));
|
|
1360
|
+
|
|
1361
|
+
app.post('/api/panes/panes/:id/jobs', auth, route(async (req, res) => {
|
|
1362
|
+
const pane = terminalPane(req.params.id, req.caller, 'control');
|
|
1363
|
+
const command = String(req.body.command || '').replace(/\r?\n$/, '');
|
|
1364
|
+
if (!command.trim()) { res.status(400).json({ error: 'command must not be empty.' }); return; }
|
|
1365
|
+
if (command.length > 10000) { res.status(400).json({ error: 'command is too long.' }); return; }
|
|
1366
|
+
const job = startJob(pane, command);
|
|
1367
|
+
const wait = req.body.wait !== false;
|
|
1368
|
+
if (wait) await waitForJob(job, req.body.timeoutMs);
|
|
1369
|
+
// The wait can last two minutes. The command was started with the grant
|
|
1370
|
+
// the agent had; its output leaves only if the agent may still read.
|
|
1371
|
+
requireAccess(pane, req.caller, 'view');
|
|
1372
|
+
scheduleSave();
|
|
1373
|
+
res.status(202).json(serializeJob(job));
|
|
1374
|
+
}));
|
|
1375
|
+
|
|
1376
|
+
app.get('/api/panes/panes/:id/jobs/:jobId', auth, route(async (req, res) => {
|
|
1377
|
+
const pane = terminalPane(req.params.id, req.caller, 'view');
|
|
1378
|
+
const job = pane.jobs.find((candidate) => candidate.id === req.params.jobId);
|
|
1379
|
+
if (!job) { res.status(404).json({ error: 'Job not found.' }); return; }
|
|
1380
|
+
res.json(serializeJob(job));
|
|
1381
|
+
}));
|
|
1382
|
+
|
|
1383
|
+
app.delete('/api/panes/panes/:id/jobs/:jobId', auth, route(async (req, res) => {
|
|
1384
|
+
const pane = terminalPane(req.params.id, req.caller, 'control');
|
|
1385
|
+
const job = pane.jobs.find((candidate) => candidate.id === req.params.jobId);
|
|
1386
|
+
if (!job) { res.status(404).json({ error: 'Job not found.' }); return; }
|
|
1387
|
+
const cancelled = cancelJob(job);
|
|
1388
|
+
res.json({ cancelled, job: serializeJob(job) });
|
|
1389
|
+
}));
|
|
1390
|
+
|
|
1391
|
+
app.post('/api/panes/panes/:id/command', auth, route(async (req, res) => {
|
|
1392
|
+
const pane = terminalPane(req.params.id, req.caller, 'control');
|
|
1393
|
+
if (!pane.pty) { res.status(400).json({ error: 'Terminal pane required.' }); return; }
|
|
1394
|
+
const command = String(req.body.command || '').replace(/\r?\n$/, '');
|
|
1395
|
+
pane.pty.write(command + '\n');
|
|
1396
|
+
await new Promise((resolve) => setTimeout(resolve, Number(req.body.waitMs) || 300));
|
|
1397
|
+
requireAccess(pane, req.caller, 'view');
|
|
1398
|
+
// This proves the line was written and shows recent output. It does not
|
|
1399
|
+
// prove the command finished; use POST /jobs for that.
|
|
1400
|
+
res.json({
|
|
1401
|
+
ok: true,
|
|
1402
|
+
confirmed: false,
|
|
1403
|
+
note: 'The line was typed into the interactive terminal. For a tracked completion and exit code, use POST /api/panes/panes/<id>/jobs.',
|
|
1404
|
+
output: pane.buffer.slice(-4000),
|
|
1405
|
+
offset: pane.totalOffset
|
|
1406
|
+
});
|
|
1407
|
+
}));
|
|
1408
|
+
|
|
1409
|
+
async function closeAll() {
|
|
1410
|
+
// Stop new debounced writes before the final snapshot. saveState itself
|
|
1411
|
+
// does not schedule, so the explicit save below still lands.
|
|
1412
|
+
shuttingDown = true;
|
|
1413
|
+
if (saveTimer) { clearTimeout(saveTimer); saveTimer = null; }
|
|
1414
|
+
if (restored) await saveState().catch(() => { /* best effort on shutdown */ });
|
|
1415
|
+
for (const pane of [...panes.values()]) {
|
|
1416
|
+
for (const job of pane.jobs || []) cancelJob(job);
|
|
1417
|
+
killPty(pane);
|
|
1418
|
+
if (pane.kind === 'browser' && pane.browserId) {
|
|
1419
|
+
await browserWorkspace.close(pane.browserId).catch(() => {});
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
panes.clear();
|
|
1423
|
+
tabs.clear();
|
|
1424
|
+
}
|
|
1425
|
+
|
|
1426
|
+
// auth and route are shared with the shell-session API in server.js, so
|
|
1427
|
+
// every workspace route has one definition of "who may call" and of errors.
|
|
1428
|
+
return { closeAll, state, auth, route };
|
|
1429
|
+
}
|
|
1430
|
+
|
|
1431
|
+
module.exports = { installWorkspacePanes };
|