@anusornneal/chat-relay 1.3.3 โ†’ 1.3.5

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/README.md CHANGED
@@ -170,6 +170,8 @@ A single account can own multiple computers. Each computer keeps its own agent i
170
170
 
171
171
  Clone the repository only when developing Chat Relay itself. Normal users should use the zero-checkout `npx` flow above.
172
172
 
173
+ Agents must create new WIP backups or Git worktrees only when necessary and only inside the **owning target project's** `workspace/` folder (e.g. `chat-relay/workspace/worktrees/<id>`). Do not create sibling project folders. See [Project workspace policy](docs/PROJECT_WORKSPACE_POLICY.md) and `AGENTS.md`; existing legacy folders remain untouched until verified cleanup.
174
+
173
175
  Common development commands:
174
176
 
175
177
  ```bash
@@ -14,6 +14,7 @@ import {
14
14
  summarizeAgentWork,
15
15
  } from "./lifecycle.mjs";
16
16
  import { humanizeToolCall } from "./toolcall-summary.mjs";
17
+ import { describeToolActivity } from "./toolcall-context.mjs";
17
18
  import { toolErrorGuidance } from "./tool-error-guidance.mjs";
18
19
  import {
19
20
  HeartbeatAckWatchdog,
@@ -83,6 +84,16 @@ const desktop = new DesktopManager({
83
84
  controlQueueTimeoutMs: process.env.AGENT_QUEUE_TIMEOUT_MS,
84
85
  });
85
86
  const recentCalls = [];
87
+ // Correlate asynchronous batch/session output with the project where work began.
88
+ // Local only, bounded and never queried from the Worker.
89
+ const recentToolProjects = new Map();
90
+ function rememberToolProject(id, project) {
91
+ if (!id || !project) return;
92
+ const key = String(id);
93
+ recentToolProjects.delete(key);
94
+ recentToolProjects.set(key, project);
95
+ if (recentToolProjects.size > 96) recentToolProjects.delete(recentToolProjects.keys().next().value);
96
+ }
86
97
  const RECENT_TIMING_KEYS = ["queueWaitMs", "inputMs", "explicitWaitMs", "settleMs", "captureMs", "encodeMs", "workerMs", "managerMs", "totalMs", "requestedActions", "executedActions"];
87
98
  function recentTiming(value) {
88
99
  if (!value || typeof value !== "object") return null;
@@ -518,8 +529,9 @@ function connect() {
518
529
  ? String(message.payload.action ?? "unknown")
519
530
  : "unknown";
520
531
  const callSummary = humanizeToolCall(message.payload);
532
+ const uiActivity = describeToolActivity(message.payload, files.getRoots(), recentToolProjects);
521
533
  const requestBytes = Buffer.byteLength(JSON.stringify(message), "utf8");
522
- emitUi("tool:start", { requestId: message.requestId, action, summary: callSummary, requestBytes });
534
+ emitUi("tool:start", { requestId: message.requestId, action, summary: callSummary, ...uiActivity, requestBytes });
523
535
  let scheduleMeta = { lane: "unknown", queueWaitMs: 0, queueDepthAtStart: 0, activeAtStart: 0 };
524
536
  let handlerDurationMs = 0;
525
537
  try {
@@ -533,6 +545,12 @@ function connect() {
533
545
  }
534
546
  });
535
547
  const timing = recentTiming(result?.timing);
548
+ if (result?.ok !== false) {
549
+ if (action === "terminal.batch.start") rememberToolProject(result?.batchId, uiActivity.project);
550
+ if (action === "terminal.start" || action === "terminal.shell.start" || action === "fs.search.start") {
551
+ rememberToolProject(result?.sessionId, uiActivity.project);
552
+ }
553
+ }
536
554
  recentCalls.push({
537
555
  at: new Date().toISOString(),
538
556
  action,
@@ -0,0 +1,220 @@
1
+ import path from "node:path";
2
+ import { humanizeToolCall } from "./toolcall-summary.mjs";
3
+
4
+ // Derive concise local UI labels, not raw commands or full request payloads.
5
+ const WORKSPACE_DIR = /^(projects?|workspaces?|repos?|repositories|code|src)$/i;
6
+
7
+ function safeLabel(value) {
8
+ const text = String(value ?? "").trim();
9
+ if (!text || text.length > 64 || /[\u0000-\u001f\u007f/\\]/.test(text) || text === "." || text === "..") return null;
10
+ return text;
11
+ }
12
+
13
+ function normalizeLocation(value) {
14
+ if (typeof value !== "string" || !value.trim()) return null;
15
+ const raw = value.trim().replace(/\\/g, "/");
16
+ if (!/^(?:[a-zA-Z]:\/|\/)/.test(raw)) return null;
17
+ const normalized = path.posix.normalize(raw);
18
+ return normalized.length > 1 ? normalized.replace(/\/+$/, "") : normalized;
19
+ }
20
+
21
+ function samePathOrWithin(location, root) {
22
+ const windows = /^[A-Za-z]:\//.test(location) && /^[A-Za-z]:\//.test(root);
23
+ const current = windows ? location.toLowerCase() : location;
24
+ const boundary = windows ? root.toLowerCase() : root;
25
+ return current === boundary || current.startsWith(boundary + "/");
26
+ }
27
+
28
+ function rootsFrom(value) {
29
+ const inputs = Array.isArray(value) ? value : typeof value === "string" ? value.split(";") : [];
30
+ return inputs.map(normalizeLocation).filter(Boolean).sort((a, b) => b.length - a.length);
31
+ }
32
+
33
+ function pathProject(value, roots, { cwd, directory = false } = {}) {
34
+ let location = normalizeLocation(value);
35
+ if (!location && typeof value === "string" && value.trim() && cwd) {
36
+ const base = normalizeLocation(cwd);
37
+ if (base) location = normalizeLocation(path.posix.join(base, value.replace(/\\/g, "/")));
38
+ }
39
+ if (!location) return null;
40
+ for (const root of roots) {
41
+ if (!samePathOrWithin(location, root)) continue;
42
+ const relative = location.slice(root.length).replace(/^\/+/, "");
43
+ const segments = relative.split("/").filter(Boolean);
44
+ const rootName = root.split("/").filter(Boolean).at(-1) || "";
45
+ if (WORKSPACE_DIR.test(rootName)) {
46
+ // A file directly in the workspace root is not a project.
47
+ if (segments.length < 2 && !directory) return null;
48
+ return safeLabel(segments[0]);
49
+ }
50
+ // A configured root can itself be a project, e.g. ~/repo/chat-relay.
51
+ if (segments[0] && WORKSPACE_DIR.test(segments[0])) {
52
+ if (segments.length < 3 && !directory) return null;
53
+ return safeLabel(segments[1]);
54
+ }
55
+ return safeLabel(rootName);
56
+ }
57
+ return null;
58
+ }
59
+
60
+ function candidatePaths(payload) {
61
+ const action = String(payload?.action || "");
62
+ if (action === "terminal.batch.start") {
63
+ const fallbackCwd = payload.cwd;
64
+ return (Array.isArray(payload.jobs) ? payload.jobs : [])
65
+ .map((job) => ({ value: job && typeof job === "object" ? job.cwd || fallbackCwd : fallbackCwd, directory: true }));
66
+ }
67
+ if (action.startsWith("terminal.")) {
68
+ if (action === "terminal.exec" || action === "terminal.start" || action === "terminal.shell.start") {
69
+ return [{ value: payload.cwd, directory: true }];
70
+ }
71
+ return [];
72
+ }
73
+ if (action === "fs.batch") {
74
+ return (Array.isArray(payload.operations) ? payload.operations : [])
75
+ .flatMap((item) => [item?.path, item?.source, item?.destination]
76
+ .filter((value) => typeof value === "string")
77
+ .map((value) => ({ value, cwd: payload.cwd, directory: item?.op === "list" })));
78
+ }
79
+ if (action === "fs.readMany") {
80
+ return (Array.isArray(payload.paths) ? payload.paths : [])
81
+ .map((item) => ({ value: typeof item === "string" ? item : item?.path, cwd: payload.cwd }));
82
+ }
83
+ if (action === "fs.move") {
84
+ return [{ value: payload.source, cwd: payload.cwd }, { value: payload.destination, cwd: payload.cwd }];
85
+ }
86
+ if (action.startsWith("fs.")) {
87
+ return [{ value: payload.path, cwd: payload.cwd, directory: action === "fs.list" || action === "fs.search.start" }];
88
+ }
89
+ if (action === "git.worktree.cleanup") return [{ value: payload.repoPath, directory: true }];
90
+ return [];
91
+ }
92
+
93
+ export function resolveToolProject(payload = {}, allowedRoots = [], linkedContexts = null) {
94
+ payload = payload && typeof payload === "object" ? payload : {};
95
+ const explicit = safeLabel(payload.projectKey);
96
+ if (explicit) return explicit;
97
+ const roots = rootsFrom(allowedRoots);
98
+ const paths = candidatePaths(payload);
99
+ const names = new Set();
100
+ let unresolved = 0;
101
+ for (const candidate of paths) {
102
+ const result = pathProject(candidate.value, roots, candidate);
103
+ if (result) names.add(result);
104
+ else unresolved += 1;
105
+ }
106
+ if (names.size > 1 || (names.size && unresolved)) return "Multiple projects";
107
+ if (names.size === 1) return [...names][0];
108
+ const lookupId = payload.batchId || payload.sessionId;
109
+ const linked = lookupId && linkedContexts?.get?.(String(lookupId));
110
+ return safeLabel(linked);
111
+ }
112
+
113
+ function shortName(value) {
114
+ const filename = String(value ?? "").trim().replace(/\\/g, "/").split("/").filter(Boolean).at(-1);
115
+ return filename ? filename.slice(0, 90) : "file";
116
+ }
117
+
118
+ function relativeLocation(value, project) {
119
+ const normalized = String(value ?? "").trim().replace(/\\/g, "/");
120
+ if (!normalized) return "";
121
+ const parts = normalized.split("/").filter(Boolean);
122
+ const index = parts.findIndex((part) => part.toLowerCase() === String(project || "").toLowerCase());
123
+ if (index >= 0 && index < parts.length - 1) return parts.slice(index + 1).join("/").slice(0, 130);
124
+ return parts.length > 3 ? "โ€ฆ/" + parts.slice(-3).join("/") : normalized.slice(0, 130);
125
+ }
126
+
127
+ function terminalTitle(payload) {
128
+ const command = String(payload.command || "");
129
+ if (/\bGet-Command\s+(?:rg|ripgrep)\b/i.test(command)) return "Check ripgrep availability";
130
+ const toolCheck = command.match(/\bGet-Command\s+([a-z][a-z0-9.-]{0,25})\b/i);
131
+ if (toolCheck?.[1]) return "Check " + toolCheck[1] + " availability";
132
+ if (/\b(?:Select-String|rg)\b/i.test(command) && !/Get-Command/i.test(command)) return "Search project files";
133
+ const npmScript = command.match(/\bnpm\s+run\s+([a-z][a-z0-9:_-]+)/i);
134
+ if (npmScript?.[1]) {
135
+ const script = npmScript[1].toLowerCase();
136
+ if (script === "test:tui") return "Run terminal UI tests";
137
+ if (script === "test:hardening") return "Run hardening tests";
138
+ if (script === "verify:publish") return "Verify release package";
139
+ if (script === "test:learn-bootstrap") return "Run Learn routing tests";
140
+ if (script.startsWith("test:")) return "Run " + script.slice(5).replace(/-/g, " ") + " tests";
141
+ if (script === "build") return "Build project";
142
+ return "Run npm script " + script.slice(0, 40);
143
+ }
144
+ if (/\bnode\s+--test\b/i.test(command)) return "Run unit tests";
145
+ if (/\bgit\s+diff\s+--check\b/i.test(command)) return "Validate Git changes";
146
+ if (/\bgit\s+status\b/i.test(command) && !/\bgit\s+commit\b/i.test(command)) return "Review Git status";
147
+ if (/\bgit\s+commit\b/i.test(command)) return "Commit changes";
148
+ if (/\bGet-ChildItem\b/i.test(command)) return "Inspect project files";
149
+ const translated = humanizeToolCall(payload).replace(/\s+ยท in [^ยท]+$/, "");
150
+ if (translated.startsWith("Run ")) {
151
+ // Do not display arbitrary shell scripts as activity headlines.
152
+ const gitPush = command.match(/\bgit\s+push\s+(?:-u\s+)?origin\s+([a-zA-Z0-9/_-]+)/i);
153
+ if (gitPush?.[1]) return "Push " + gitPush[1].slice(0, 40) + " to origin";
154
+ const getContent = command.match(/\bGet-Content\s+(["']?)([a-zA-Z0-9_./\\:-]+\.[a-z0-9]+)\1/i);
155
+ if (getContent?.[2]) return "Read " + shortName(getContent[2]);
156
+ return "Execute terminal command";
157
+ }
158
+ return translated.slice(0, 160);
159
+ }
160
+
161
+ export function describeToolActivity(payload = {}, allowedRoots = [], linkedContexts = null) {
162
+ payload = payload && typeof payload === "object" ? payload : {};
163
+ const action = String(payload.action || "unknown");
164
+ const project = resolveToolProject(payload, allowedRoots, linkedContexts);
165
+ const filePath = payload.path || payload.source || payload.destination;
166
+ const category = action.startsWith("fs.") ? "Filesystem"
167
+ : action.startsWith("terminal.batch.") ? "Terminal batch"
168
+ : action.startsWith("terminal.") ? "Terminal"
169
+ : action.startsWith("desktop.") ? "Desktop"
170
+ : action.startsWith("process.") ? "Process"
171
+ : action.startsWith("git.") ? "Git"
172
+ : "Agent";
173
+ let operation = humanizeToolCall(payload);
174
+ let detail = "";
175
+ const count = (arr) => Array.isArray(arr) ? arr.length : 0;
176
+ switch (action) {
177
+ case "fs.write":
178
+ operation = (payload.mode === "append" ? "Append " : "Write ") + shortName(payload.path);
179
+ break;
180
+ case "fs.edit":
181
+ operation = "Edit " + shortName(payload.path);
182
+ break;
183
+ case "fs.read":
184
+ operation = "Read " + shortName(payload.path);
185
+ break;
186
+ case "fs.readMany":
187
+ operation = "Read " + count(payload.paths) + " files";
188
+ break;
189
+ case "fs.batch":
190
+ operation = "Inspect " + count(payload.operations) + " filesystem items";
191
+ break;
192
+ case "fs.stat":
193
+ operation = "Inspect " + shortName(payload.path);
194
+ break;
195
+ case "fs.list":
196
+ operation = "Browse " + shortName(payload.path);
197
+ break;
198
+ case "terminal.exec":
199
+ case "terminal.start":
200
+ operation = terminalTitle(payload);
201
+ break;
202
+ case "terminal.batch.start":
203
+ operation = "Run " + count(payload.jobs) + " terminal tasks";
204
+ break;
205
+ case "terminal.batch.read":
206
+ operation = "Review terminal batch results";
207
+ break;
208
+ case "terminal.batch.status":
209
+ operation = "Check terminal batch progress";
210
+ break;
211
+ case "terminal.read":
212
+ operation = "Review terminal output";
213
+ break;
214
+ case "terminal.list":
215
+ operation = "List terminal sessions";
216
+ break;
217
+ }
218
+ if (filePath && category === "Filesystem") detail = relativeLocation(filePath, project);
219
+ return { project, category, operation: String(operation).slice(0, 160), detail };
220
+ }
package/cli/demo.mjs ADDED
@@ -0,0 +1,194 @@
1
+ import { getAgentVersion } from "../agent/protocol.mjs";
2
+ import { describeToolActivity } from "../agent/toolcall-context.mjs";
3
+ import { RemoteTui } from "./tui.mjs";
4
+
5
+ // Demo uses only synthetic inputs. It neither loads credentials nor starts an
6
+ // agent, a child process, a health monitor, or a network request.
7
+ const DEMO_ROOT = "C:\\Projects";
8
+ const DEMO_ROOTS = [DEMO_ROOT];
9
+ const SIMULATED_AGENT = {
10
+ user: { name: "Demo Account" },
11
+ agentName: "DESKTOP-DEMO",
12
+ allowedRoots: DEMO_ROOT,
13
+ relayUrl: "https://demo.invalid",
14
+ terminalEnabled: true,
15
+ desktopEnabled: true,
16
+ };
17
+
18
+ const SAMPLES = [
19
+ {
20
+ action: "fs.write",
21
+ path: "C:\\Projects\\flowly\\apps\\web\\src\\SkillAdminOverview.tsx",
22
+ mode: "rewrite",
23
+ content: "",
24
+ durationMs: 2,
25
+ requestBytes: 6800,
26
+ responseBytes: 330,
27
+ },
28
+ {
29
+ action: "terminal.exec", cwd: "C:\\Projects\\chat-relay",
30
+ command: "git status --short",
31
+ durationMs: 162, requestBytes: 264, responseBytes: 1200,
32
+ },
33
+ {
34
+ action: "terminal.batch.start", cwd: "C:\\Projects\\flowly",
35
+ jobs: [
36
+ { command: "npm run test:tui" },
37
+ { command: "git status --short" },
38
+ { command: "node --check cli/tui.mjs" },
39
+ ],
40
+ concurrency: 3,
41
+ durationMs: 31, requestBytes: 1800, responseBytes: 1100,
42
+ },
43
+ {
44
+ action: "terminal.batch.read", batchId: "demo-batch",
45
+ durationMs: 16, requestBytes: 455, responseBytes: 9800,
46
+ },
47
+ {
48
+ action: "fs.batch",
49
+ operations: [
50
+ { op: "read", path: "C:\\Projects\\flowly\\apps\\web\\src\\App.tsx" },
51
+ { op: "read", path: "C:\\Projects\\chat-relay\\cli\\tui.mjs" },
52
+ ],
53
+ durationMs: 7, requestBytes: 1600, responseBytes: 2600,
54
+ },
55
+ {
56
+ action: "fs.readMany",
57
+ paths: [
58
+ "C:\\Projects\\buddy-android\\app\\src\\main\\java\\NotificationHome.kt",
59
+ "C:\\Projects\\buddy-android\\app\\src\\main\\java\\NewsDetail.kt",
60
+ ],
61
+ durationMs: 12, requestBytes: 1300, responseBytes: 4900,
62
+ },
63
+ {
64
+ action: "terminal.exec", cwd: "C:\\Projects\\chat-relay",
65
+ command: "npm run test:hardening",
66
+ durationMs: 380, requestBytes: 450, responseBytes: 240,
67
+ ok: false, error: "Test failed",
68
+ },
69
+ {
70
+ action: "terminal.start", cwd: "C:\\Projects\\flowly",
71
+ command: "npm run build",
72
+ requestBytes: 310, running: true,
73
+ },
74
+ ];
75
+
76
+ export function buildDemoConfig() {
77
+ return {
78
+ ...SIMULATED_AGENT,
79
+ user: { ...SIMULATED_AGENT.user },
80
+ };
81
+ }
82
+
83
+ function demoTui({ output, input, env, onInterrupt } = {}) {
84
+ return new RemoteTui({
85
+ config: buildDemoConfig(),
86
+ version: getAgentVersion(),
87
+ output, input, env, onInterrupt, demo: true,
88
+ });
89
+ }
90
+
91
+ export function seedDemo(tui, { now = Date.now() } = {}) {
92
+ // Synthetic states: they are deliberately not connected to Relay or a real
93
+ // Agent. The TUI marks this status as DEMO rather than Connected.
94
+ tui.state.status = "connected";
95
+ tui.state.relayHealth = { state: "reachable", code: 200 };
96
+ tui.state.learn = true;
97
+ tui.state.reconnects = 0;
98
+ tui.startedAt = now - (3 * 3600 + 24 * 60 + 7) * 1000;
99
+ const linked = new Map([["demo-batch", "flowly"]]);
100
+
101
+ for (let index = 0; index < SAMPLES.length; index += 1) {
102
+ const sample = SAMPLES[index];
103
+ const { durationMs, requestBytes, responseBytes, running, ok, error, ...payload } = sample;
104
+ const activity = describeToolActivity(payload, DEMO_ROOTS, linked);
105
+ const requestId = "demo-" + (index + 1);
106
+ const at = new Date(now - (SAMPLES.length - index) * 50_000).toISOString();
107
+ tui.handleMessage({
108
+ type: "chat-relay-ui", event: "tool:start", requestId, at,
109
+ action: payload.action, summary: activity.operation, ...activity, requestBytes,
110
+ });
111
+ if (!running) tui.handleMessage({
112
+ type: "chat-relay-ui", event: "tool:end", requestId, at,
113
+ ok: ok !== false, durationMs, responseBytes, ...(error ? { error } : {}),
114
+ });
115
+ }
116
+ // Show the same Learn activity indicator used by the real local agent.
117
+ tui.handleMessage({
118
+ type: "chat-relay-ui", event: "learn",
119
+ activity: {
120
+ eventId: "demo-learn-1", tool: "learn_prepare", projectKey: "chat-relay",
121
+ scopeSummary: "project", durationMs: 24, ok: true,
122
+ at: new Date(now).toISOString(),
123
+ },
124
+ });
125
+ return tui;
126
+ }
127
+
128
+ function boundedDimension(value, fallback, min, max) {
129
+ const parsed = Number(value);
130
+ return Number.isFinite(parsed) ? Math.max(min, Math.min(max, Math.trunc(parsed))) : fallback;
131
+ }
132
+
133
+ export function renderDemoSnapshot({ width = 112, height = 30, now } = {}) {
134
+ const fragments = [];
135
+ const output = {
136
+ isTTY: false,
137
+ columns: boundedDimension(width, 112, 1, 2048),
138
+ rows: boundedDimension(height, 30, 1, 90),
139
+ write: (value) => { fragments.push(String(value)); return true; },
140
+ };
141
+ const tui = demoTui({ output, input: { isTTY: false }, env: { NO_COLOR: "1" } });
142
+ seedDemo(tui, { now });
143
+ tui.render();
144
+ const frame = fragments.at(-1) || "";
145
+ tui.stop();
146
+ return frame.replace(/^\x1b\[2J\x1b\[H/, "");
147
+ }
148
+
149
+ export async function runTuiDemo({
150
+ output = process.stdout,
151
+ input = process.stdin,
152
+ env = process.env,
153
+ snapshot = false,
154
+ width,
155
+ height,
156
+ } = {}) {
157
+ const interactive = output?.isTTY && input?.isTTY && typeof input.setRawMode === "function";
158
+ if (snapshot || !interactive) {
159
+ output.write(renderDemoSnapshot({
160
+ width: width ?? output?.columns ?? 112,
161
+ height: height ?? output?.rows ?? 30,
162
+ }) + "\n");
163
+ return 0;
164
+ }
165
+
166
+ return new Promise((resolve, reject) => {
167
+ let done = false;
168
+ let tui;
169
+ function stop() {
170
+ if (done) return;
171
+ done = true;
172
+ process.removeListener("SIGINT", stop);
173
+ process.removeListener("SIGTERM", stop);
174
+ tui?.stop();
175
+ resolve(0);
176
+ }
177
+ try {
178
+ tui = demoTui({ output, input, env, onInterrupt: stop });
179
+ process.once("SIGINT", stop);
180
+ process.once("SIGTERM", stop);
181
+ tui.start();
182
+ seedDemo(tui);
183
+ tui.render();
184
+ } catch (error) {
185
+ if (!done) {
186
+ done = true;
187
+ process.removeListener("SIGINT", stop);
188
+ process.removeListener("SIGTERM", stop);
189
+ tui?.stop();
190
+ }
191
+ reject(error);
192
+ }
193
+ });
194
+ }
package/cli/index.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import { clearConfig, configPath, loadConfig, saveConfig } from "./config.mjs";
2
+ import { runTuiDemo } from "./demo.mjs";
2
3
  import { login, needsRelayLogin, requestJson } from "./device-login.mjs";
3
4
  import { protocolCompatibility, remote, validateConfig } from "./remote.mjs";
4
5
  import { launchLatestRemote } from "./self-update.mjs";
@@ -15,6 +16,11 @@ function parseOptions(args) {
15
16
  else if (arg === "--no-desktop") options.desktopEnabled = false;
16
17
  else if (arg === "--plain") options.tuiEnabled = false;
17
18
  else if (arg === "--tui") options.tuiEnabled = true;
19
+ else if (arg === "--snapshot") options.snapshot = true;
20
+ else if (arg === "--width") options.width = args[++index];
21
+ else if (arg.startsWith("--width=")) options.width = arg.slice(8);
22
+ else if (arg === "--height") options.height = args[++index];
23
+ else if (arg.startsWith("--height=")) options.height = arg.slice(9);
18
24
  else if (arg === "--relay") options.relayUrl = args[++index];
19
25
  else if (arg.startsWith("--relay=")) options.relayUrl = arg.slice(8);
20
26
  else if (arg === "--root") options.allowedRoot = args[++index];
@@ -33,6 +39,7 @@ function help() {
33
39
 
34
40
  Usage:
35
41
  chat-relay remote [options] Connect this computer to ChatGPT
42
+ chat-relay demo [options] Preview the real TUI offline with sample activity
36
43
  chat-relay login [options] Sign in and register this computer
37
44
  chat-relay status Show account and connection status
38
45
  chat-relay drain Stop accepting new long-running work
@@ -51,11 +58,15 @@ Options:
51
58
  --no-desktop Disable desktop access (default)
52
59
  --plain Use legacy line-by-line logs
53
60
  --tui Force interactive terminal UI
61
+ --snapshot Print demo as plain text and exit
62
+ --width <columns> Demo snapshot width
63
+ --height <rows> Demo snapshot height
54
64
  --no-open Do not open the browser automatically
55
65
  --force Force a new login
56
66
 
57
67
  Examples:
58
68
  npx @anusornneal/chat-relay@latest remote
69
+ node bin/chat-relay.js demo
59
70
  npx @anusornneal/chat-relay@latest login
60
71
  npx @anusornneal/chat-relay@latest status
61
72
  `);
@@ -238,6 +249,8 @@ export async function runCli(argv = process.argv.slice(2)) {
238
249
  return 0;
239
250
  }
240
251
 
252
+ if (command === "demo" || command === "preview") return runTuiDemo(options);
253
+
241
254
  if (command === "login") {
242
255
  const current = loadConfig();
243
256
  if (!options.force && !needsRelayLogin(current, options.relayUrl) && await validateConfig(current)) {
package/cli/tui.mjs CHANGED
@@ -15,7 +15,8 @@ const STYLE = {
15
15
  const LABEL_WIDTH = 12;
16
16
  const GAP = 3;
17
17
  const MIN_FRAME_WIDTH = 60;
18
- const MAX_FRAME_WIDTH = 179;
18
+ const MAX_FRAME_WIDTH = 179; // Legacy fixed-width formatter only.
19
+ const MAX_TUI_VIEWPORT_WIDTH = 2048; // Full-width monitor, bounded for unusual terminals.
19
20
  const FRAME_BOTTOM_MARGIN = 1;
20
21
 
21
22
  function clamp(value, min, max) {
@@ -40,6 +41,9 @@ function codePointCellWidth(codePoint) {
40
41
  || (codePoint >= 0x20d0 && codePoint <= 0x20ff)
41
42
  || (codePoint >= 0xfe20 && codePoint <= 0xfe2f)
42
43
  || codePoint === 0xfe0f
44
+ || codePoint === 0x0e31
45
+ || (codePoint >= 0x0e34 && codePoint <= 0x0e3a)
46
+ || (codePoint >= 0x0e47 && codePoint <= 0x0e4e)
43
47
  || codePoint === 0x200d
44
48
  ) return 0;
45
49
  if (
@@ -234,14 +238,11 @@ function wrapText(value, width, maxLines = 3) {
234
238
  export function formatTransactionRows(item, width = 110, { color = false } = {}) {
235
239
  const requested = Number(width) || 110;
236
240
  const usable = clamp(requested, Math.min(60, Math.max(1, requested)), 180);
237
- const status = item.status === "running" ? "๐ŸŸก" : item.ok === false ? "โŒ" : "โœ…";
238
241
  if (usable < 32) {
239
- const compact = truncateCells(`${clock(item.at)} ${status} ${item.summary || item.action || "Tool call"}`, usable);
240
- if (!color) return [compact];
241
- const glyphStyle = item.status === "running" ? STYLE.yellow : item.ok === false ? STYLE.red : STYLE.green;
242
- return [paint(compact, glyphStyle)];
242
+ const compact = truncateCells(`${clock(item.at)} ${item.summary || item.action || "Tool call"}`, usable);
243
+ return [color && item.ok === false ? paint(compact, STYLE.red) : compact];
243
244
  }
244
- const prefix = `${clock(item.at)} ${status} `;
245
+ const prefix = `${clock(item.at)} `;
245
246
  const prefixWidth = terminalCellWidth(prefix);
246
247
  const continuationPrefix = " ".repeat(prefixWidth);
247
248
  const duration = formatDuration(item.durationMs, item.status);
@@ -259,11 +260,9 @@ export function formatTransactionRows(item, width = 110, { color = false } = {})
259
260
  if (!color) return plainRow;
260
261
  if (item.ok === false) return paint(plainRow, STYLE.red);
261
262
  const time = paint(clock(item.at), STYLE.gray);
262
- const glyphStyle = item.status === "running" ? STYLE.yellow : STYLE.green;
263
- const glyph = paint(status, glyphStyle, STYLE.bold);
264
263
  const summary = item.status === "running" ? paint(line.padEnd(summaryWidth), STYLE.bold) : line.padEnd(summaryWidth);
265
264
  const timing = paint(suffix, STYLE.gray);
266
- return `${time} ${glyph} ${summary}${timing}`;
265
+ return `${time} ${summary}${timing}`;
267
266
  }
268
267
  if (!color) return continuationPrefix + line;
269
268
  if (item.ok === false) return continuationPrefix + paint(line, STYLE.red);
@@ -297,68 +296,181 @@ export function shouldUseColor(stdout = process.stdout, env = process.env) {
297
296
  return true;
298
297
  }
299
298
 
299
+ const MONITOR = {
300
+ accent: "\x1b[38;2;93;218;203m",
301
+ bright: "\x1b[38;2;235;241;248m",
302
+ muted: "\x1b[38;2;128;145;164m",
303
+ dim: "\x1b[38;2;104;121;139m",
304
+ border: "\x1b[38;2;45;60;77m",
305
+ good: "\x1b[38;2;91;218;163m",
306
+ bad: "\x1b[38;2;247;114;114m",
307
+ warning: "\x1b[38;2;243;192;101m",
308
+ liveBg: "\x1b[48;2;20;62;55m",
309
+ };
310
+
311
+ function tint(value, style, enabled) {
312
+ return enabled ? paint(value, style) : value;
313
+ }
314
+
300
315
  function cellPad(value, width) {
301
316
  const clipped = truncateCells(value, Math.max(0, width));
302
317
  return clipped + " ".repeat(Math.max(0, width - terminalCellWidth(clipped)));
303
318
  }
304
319
 
305
- function compactActivityRows(item, width, color = false) {
320
+ function activityCategory(item) {
321
+ if (item.category) return String(item.category);
322
+ const action = String(item.action || "");
323
+ if (action.startsWith("fs.")) return "Filesystem";
324
+ if (action.startsWith("terminal.")) return "Terminal";
325
+ if (action.startsWith("desktop.")) return "Desktop";
326
+ if (action.startsWith("learn")) return "Learn";
327
+ return "Agent";
328
+ }
329
+
330
+ function activityIcon(item) {
331
+ const action = String(item.action || "").toLowerCase();
332
+ const title = String(item.operation || item.summary || "").toLowerCase();
333
+ if (/search/.test(action) || /^(start|search)\b/.test(title)) return "๐Ÿ”Ž";
334
+ if (/(^|\.)(read|readmany|getcontent)(_|$|\.)/.test(action) || /^read\b/.test(title)) return "๐Ÿ“–";
335
+ if (/(^|\.)(write|edit|move|mkdir|delete)(_|$|\.)/.test(action) || /^(write|edit|create|delete|move)\b/.test(title)) return "โœ๏ธ";
336
+ if (activityCategory(item) === "Terminal") return "๐Ÿ“Ÿ";
337
+ if (activityCategory(item) === "Filesystem") return "๐Ÿ“";
338
+ return "";
339
+ }
340
+
341
+ function activitySourceIcon(category) {
342
+ return { Filesystem: "๐Ÿ“", Terminal: "๐Ÿ“Ÿ", Desktop: "๐Ÿ–ฅ๏ธ", Learn: "๐Ÿง " }[category] || "โš™๏ธ";
343
+ }
344
+
345
+ function shortActivityDetail(value, project) {
346
+ const normalized = String(value || "").replace(/\\/g, "/").replace(/\s+/g, " ").trim();
347
+ if (!normalized) return "";
348
+ const projectName = String(project || "").toLowerCase();
349
+ const rootMatch = normalized.match(/(?:[A-Za-z]:)?\/[^\s]*?\/Projects\/([^/\s]+)\//i);
350
+ if (rootMatch) {
351
+ const beginning = normalized.slice(0, rootMatch.index);
352
+ const tail = normalized.slice(rootMatch.index + rootMatch[0].length);
353
+ return beginning + (rootMatch[1].toLowerCase() === projectName ? "" : rootMatch[1] + "/") + tail;
354
+ }
355
+ return normalized.replace(/(?:[A-Za-z]:)?\/[^\s]*?\/Projects\//ig, "");
356
+ }
357
+
358
+ function activityTitle(item) {
359
+ const value = String(item.operation || item.summary || item.action || "Tool call").replace(/\s+/g, " ").trim();
360
+ if (!item.operation && /^Run (?:Write-Output|Get-Command|Get-Content|Set-Variable|Start-Process)\b/i.test(value)) {
361
+ return "Execute terminal command";
362
+ }
363
+ // Preserve the familiar Learn marker even when an operation is humanized.
364
+ if (activityCategory(item) === "Learn") return value.startsWith("๐Ÿง ") ? value : "๐Ÿง  " + value;
365
+ const icon = activityIcon(item);
366
+ const cleaned = value.replace(/^(?:Start Search|Search|Read|Write|Filesystem|Terminal)\b\s*/i, "").trim();
367
+ return icon ? icon + " " + (cleaned || value) : value;
368
+ }
369
+
370
+ function activityRows(item, width, { color = false, twoLines = false } = {}) {
306
371
  const limit = Math.max(1, width);
307
- const isRunning = item.status === "running";
308
- const symbol = isRunning ? "โ—Œ" : item.ok === false ? "ร—" : "โœ“";
309
- const tint = isRunning ? STYLE.yellow : item.ok === false ? STYLE.red : STYLE.green;
372
+ const project = String(item.project || "General");
373
+ const title = activityTitle(item);
310
374
  const time = clock(item.at);
375
+ if (limit < 52) {
376
+ if (limit <= 2) return [tint(truncateCells(title, limit), item.ok === false ? MONITOR.bad : MONITOR.bright, color)];
377
+ const prefix = limit >= 37 ? time.slice(0, 5) + " " : "";
378
+ const bodyWidth = Math.max(0, limit - terminalCellWidth(prefix));
379
+ const projectText = truncateCells(project + " ยท ", bodyWidth);
380
+ const titleText = truncateCells(title, Math.max(0, bodyWidth - terminalCellWidth(projectText)));
381
+ if (!color) return [prefix + projectText + titleText];
382
+ if (item.ok === false) return [tint(prefix + projectText + titleText, MONITOR.bad, true)];
383
+ return [tint(prefix, MONITOR.dim, true) + tint(projectText, MONITOR.muted, true)
384
+ + tint(titleText, MONITOR.bright, true)];
385
+ }
386
+ const opStart = 10;
387
+ const durationWidth = 10;
388
+ const operationWidth = Math.max(1, limit - opStart - durationWidth);
311
389
  const duration = formatDuration(item.durationMs, item.status);
312
- const text = String(item.summary || item.action || "Tool call").replace(/\s+/g, " ").trim();
313
- const traffic = [
314
- Number.isFinite(Number(item.requestBytes)) ? "โ†‘" + formatBytes(item.requestBytes) : null,
315
- Number.isFinite(Number(item.responseBytes)) ? "โ†“" + formatBytes(item.responseBytes) : null,
316
- ].filter(Boolean).join(" ");
317
- // Small viewports keep the operation visible instead of forcing telemetry columns.
318
- if (limit < 43) {
319
- const prefix = limit < 25 ? symbol + " " : time.slice(0, 5) + " " + symbol + " ";
320
- const row = cellPad(prefix + text, limit);
321
- return [color ? paint(symbol, tint) + row.slice(1) : row];
390
+ const operation = cellPad(title, operationWidth);
391
+ const prefix = cellPad(time, 8) + " ";
392
+ const ending = cellPad(duration, durationWidth);
393
+ const headline = item.ok === false
394
+ ? tint(prefix + operation + ending, MONITOR.bad, color)
395
+ : color
396
+ ? tint(prefix, MONITOR.dim, true) + tint(operation, MONITOR.bright, true) + tint(ending, MONITOR.dim, true)
397
+ : prefix + operation + ending;
398
+ if (!twoLines) return [headline];
399
+
400
+ const category = activityCategory(item);
401
+ const secondary = " ยท " + activitySourceIcon(category);
402
+ // Keep request/response telemetry in transaction state but leave it out of
403
+ // the monitoring view, where it competes with operation and project context.
404
+ const textWidth = Math.max(1, limit - opStart);
405
+ const name = truncateCells(project, textWidth);
406
+ const rest = truncateCells(secondary, Math.max(0, textWidth - terminalCellWidth(name)));
407
+ const metadata = " ".repeat(opStart)
408
+ + (color
409
+ ? tint(name, item.ok === false ? MONITOR.bad : item.project ? MONITOR.muted : MONITOR.dim, true)
410
+ + tint(rest, item.ok === false ? MONITOR.bad : MONITOR.dim, true)
411
+ : name + rest);
412
+ const rows = [headline, metadata];
413
+ const extra = item.error && item.ok === false ? "Error: " + shortActivityDetail(item.error, project)
414
+ : shortActivityDetail(item.detail, project);
415
+ if (extra) {
416
+ rows.push(" ".repeat(opStart) + tint(truncateCells(extra, Math.max(1, limit - opStart)), item.ok === false ? MONITOR.bad : MONITOR.dim, color));
322
417
  }
323
- const durationWidth = Math.min(9, Math.max(5, terminalCellWidth(duration)));
324
- const prefix = time + " " + symbol + " ";
325
- const suffix = " " + cellPad(duration, durationWidth);
326
- const trafficText = limit >= 106 && traffic ? " " + traffic : "";
327
- const bodyWidth = Math.max(1, limit - terminalCellWidth(prefix) - terminalCellWidth(suffix) - terminalCellWidth(trafficText));
328
- const readable = truncateCells(text, bodyWidth);
329
- const row = prefix + cellPad(readable, bodyWidth) + trafficText + suffix;
330
- const first = color
331
- ? paint(time, STYLE.gray) + " " + paint(symbol, tint) + " " + cellPad(readable, bodyWidth) + paint(trafficText + suffix, STYLE.gray)
332
- : row;
333
- return [first];
334
- }
335
-
336
- function compactSummary(state, width, rows, color) {
337
- const online = String(state.status || "").toLowerCase() === "connected" && relayIsOnline(state.relayHealth);
338
- const stateText = online ? "โ— ONLINE" : statusText(state.status).replace("WebSocket open", "CONNECTED");
339
- const c = (text, style = STYLE.gray) => color ? paint(text, style) : text;
340
- const capabilities = [
341
- state.terminal ? "โœ“ Terminal" : "ร— Terminal",
342
- state.desktop ? "โœ“ Desktop" : "ร— Desktop",
343
- "Learn " + compactLearnStatus(state.learn),
344
- ].join(" ");
345
- const basic = [
346
- "Agent " + String(state.agent || "-"),
347
- "Uptime " + formatUptime(state.uptimeMs) + " Reconnects " + (state.reconnects ?? 0),
348
- "Root " + String(state.root || "-"),
349
- capabilities,
418
+ return rows;
419
+ }
420
+
421
+ function monitorCapabilities(state, width, color) {
422
+ const parts = [
423
+ { text: (state.terminal ? "โœ“" : "ร—") + " Terminal", color: state.terminal ? MONITOR.good : MONITOR.dim },
424
+ { text: (state.desktop ? "โœ“" : "ร—") + " Desktop", color: state.desktop ? MONITOR.good : MONITOR.dim },
425
+ { text: (state.learn === null ? "โ—Œ" : state.learn ? "โœ“" : "ร—") + " Learn",
426
+ color: state.learn === null ? MONITOR.warning : state.learn ? MONITOR.good : MONITOR.dim },
350
427
  ];
351
- if (rows === 1) return [c(truncateCells(state.agent + " ยท " + stateText, width), online ? STYLE.green : STYLE.yellow)];
352
- if (rows === 2) return [c(truncateCells(basic[0] + " ยท " + basic[1], width), STYLE.bold), c(truncateCells(capabilities, width))];
353
- if (rows === 3) return [c(truncateCells(basic[0] + " " + basic[1], width), STYLE.bold), c(truncateCells(basic[2], width)), c(truncateCells(capabilities, width))];
428
+ const plain = parts.map((part) => part.text).join(" ");
429
+ if (terminalCellWidth(plain) > width) return tint(truncateCells(plain, width), MONITOR.muted, color);
430
+ return parts.map((part) => tint(part.text, part.color, color)).join(" ");
431
+ }
432
+
433
+ function monitoringSummary(state, width, layout, color) {
434
+ if (layout === "tiny") {
435
+ return [tint(truncateCells((state.agent || "Agent") + " ยท " + formatUptime(state.uptimeMs), width), MONITOR.muted, color)];
436
+ }
437
+ if (layout === "medium") {
438
+ const line = "Agent " + String(state.agent || "-") + " Session " + formatUptime(state.uptimeMs)
439
+ + " Reconnects " + (state.reconnects ?? 0);
440
+ return [
441
+ tint(truncateCells(line, width), MONITOR.bright, color),
442
+ tint(truncateCells("Root " + String(state.root || "-"), width), MONITOR.muted, color),
443
+ monitorCapabilities(state, width, color),
444
+ ];
445
+ }
446
+ const w1 = Math.floor(width * 0.49);
447
+ const w2 = Math.floor(width * 0.29);
448
+ const w3 = width - w1 - w2;
449
+ const headings = [
450
+ tint(cellPad("AGENT", w1), MONITOR.muted, color),
451
+ tint(cellPad("SESSION", w2), MONITOR.muted, color),
452
+ tint(cellPad("RECONNECTS", w3), MONITOR.muted, color),
453
+ ].join("");
454
+ const stats = [
455
+ tint(cellPad(state.agent || "-", w1), MONITOR.bright, color),
456
+ tint(cellPad(formatUptime(state.uptimeMs), w2), MONITOR.bright, color),
457
+ tint(cellPad(String(state.reconnects ?? 0), w3), state.reconnects > 0 ? MONITOR.warning : MONITOR.bright, color),
458
+ ].join("");
354
459
  return [
355
- c(truncateCells(basic[0] + " " + basic[1], width), STYLE.bold),
356
- c(truncateCells("Account " + state.account + " Relay " + state.relay, width)),
357
- c(truncateCells(basic[2], width)),
358
- c(truncateCells(capabilities, width), STYLE.green),
460
+ headings,
461
+ stats,
462
+ tint(truncateCells("Root " + String(state.root || "-"), width), MONITOR.muted, color),
463
+ monitorCapabilities(state, width, color),
359
464
  ];
360
465
  }
361
466
 
467
+ function headingRow(width, color) {
468
+ const left = cellPad("TIME", 10);
469
+ const op = cellPad("OPERATION", Math.max(1, width - 20));
470
+ const right = cellPad("DURATION", 10);
471
+ return tint(left + op + right, MONITOR.muted, color);
472
+ }
473
+
362
474
  export class RemoteTui {
363
475
  constructor({
364
476
  config,
@@ -367,6 +479,7 @@ export class RemoteTui {
367
479
  input = process.stdin,
368
480
  env = process.env,
369
481
  onInterrupt = () => process.emit("SIGINT"),
482
+ demo = false,
370
483
  }) {
371
484
  this.output = output;
372
485
  this.input = input;
@@ -386,6 +499,7 @@ export class RemoteTui {
386
499
  };
387
500
  this.version = version || "-";
388
501
  this.colorEnabled = shouldUseColor(output, env);
502
+ this.demoMode = demo === true;
389
503
  this.transactions = [];
390
504
  this.timer = null;
391
505
  this.closed = false;
@@ -449,23 +563,40 @@ export class RemoteTui {
449
563
  }
450
564
 
451
565
  viewportMetrics() {
452
- const terminalWidth = Number(this.output.columns) || 110;
453
- const width = clamp(terminalWidth - 1, Math.min(MIN_FRAME_WIDTH, Math.max(1, terminalWidth - 1)), MAX_FRAME_WIDTH);
566
+ const columns = Math.max(1, Number(this.output.columns) || 110);
567
+ // Fill the actual terminal width; reserve one cell to avoid line wrapping.
568
+ const width = Math.min(Math.max(1, columns - 1), MAX_TUI_VIEWPORT_WIDTH);
454
569
  const height = Math.max(1, Number(this.output.rows) || 30);
455
- const compact = height < 12 || width < 48;
456
- const headerRows = height < 9 ? 1 : compact ? 2 : width < 86 ? 3 : 4;
457
- const fixedRows = 1 + headerRows + 2 + (height >= 14 ? 1 : 0);
458
- const availableRows = Math.max(1, height - fixedRows - FRAME_BOTTOM_MARGIN);
459
- return { width, height, availableRows, compact, headerRows };
570
+ const usableHeight = Math.max(1, height - FRAME_BOTTOM_MARGIN);
571
+ let layout = width >= 88 && usableHeight >= 15 ? "wide"
572
+ : width >= 54 && usableHeight >= 11 ? "medium" : "tiny";
573
+ let topLine = layout === "wide" ? 1 : 0;
574
+ let summaryRows = layout === "wide" ? 4 : layout === "medium" ? 3 : 1;
575
+ let dividerRows = usableHeight >= 6 ? 1 : 0;
576
+ let headingRows = layout === "tiny" ? 0 : 2;
577
+ const footerRows = 0;
578
+ let fixedRows = 1 + topLine + summaryRows + dividerRows + 1 + headingRows + footerRows;
579
+ if (fixedRows >= usableHeight && layout !== "tiny") {
580
+ layout = "tiny";
581
+ topLine = 0;
582
+ summaryRows = 1;
583
+ headingRows = 0;
584
+ fixedRows = 1 + summaryRows + dividerRows + 1 + footerRows;
585
+ }
586
+ return {
587
+ width, height, layout, usableHeight, topLine, dividerRows, headingRows, footerRows,
588
+ availableRows: Math.max(0, usableHeight - fixedRows),
589
+ twoLines: layout !== "tiny" && height >= 17,
590
+ };
460
591
  }
461
592
 
462
- transactionRows(width) {
463
- return this.transactions.flatMap((item) => compactActivityRows(item, width, this.colorEnabled));
593
+ transactionRows(width, twoLines = this.viewportMetrics().twoLines) {
594
+ return this.transactions.flatMap((item) => activityRows(item, width, { color: this.colorEnabled, twoLines }));
464
595
  }
465
596
 
466
597
  maxScrollOffset() {
467
- const { width, availableRows } = this.viewportMetrics();
468
- return Math.max(0, this.transactionRows(width).length - availableRows);
598
+ const { width, twoLines, availableRows } = this.viewportMetrics();
599
+ return Math.max(0, this.transactionRows(width, twoLines).length - availableRows);
469
600
  }
470
601
 
471
602
  scrollBy(lines) {
@@ -515,8 +646,8 @@ export class RemoteTui {
515
646
 
516
647
  appendTransaction(item) {
517
648
  if (this.scrollOffset > 0) {
518
- const { width } = this.viewportMetrics();
519
- this.scrollOffset += compactActivityRows(item, width, false).length;
649
+ const { width, twoLines } = this.viewportMetrics();
650
+ this.scrollOffset += activityRows(item, width, { twoLines }).length;
520
651
  this.unseenTransactions += 1;
521
652
  }
522
653
  this.transactions.push(item);
@@ -534,6 +665,10 @@ export class RemoteTui {
534
665
  at: message.at || new Date().toISOString(),
535
666
  action: message.action,
536
667
  summary: message.summary || humanizeToolCall({ action: message.action }),
668
+ operation: typeof message.operation === "string" ? message.operation : undefined,
669
+ project: typeof message.project === "string" ? message.project : null,
670
+ category: typeof message.category === "string" ? message.category : undefined,
671
+ detail: typeof message.detail === "string" ? message.detail : "",
537
672
  status: "running",
538
673
  ok: null,
539
674
  requestBytes: Number.isFinite(Number(message.requestBytes)) ? Number(message.requestBytes) : undefined,
@@ -545,7 +680,7 @@ export class RemoteTui {
545
680
  item.ok = message.ok !== false;
546
681
  item.durationMs = message.durationMs;
547
682
  if (Number.isFinite(Number(message.responseBytes))) item.responseBytes = Number(message.responseBytes);
548
- if (message.error && message.ok === false) item.summary += ` ยท ${truncate(message.error, 48)}`;
683
+ if (message.error && message.ok === false) item.error = truncate(message.error, 90);
549
684
  }
550
685
  } else if (message.event === "learn") {
551
686
  const activity = message.activity && typeof message.activity === "object" ? message.activity : null;
@@ -584,6 +719,12 @@ export class RemoteTui {
584
719
  at: activity.at || message.at || new Date().toISOString(),
585
720
  action: tool,
586
721
  summary: "๐Ÿง  Learn ยท " + truncate(detail, 120),
722
+ operation: tool === "learn_prepare" ? "Load relevant Learn context"
723
+ : tool === "learn_get" ? "Read Learn memories"
724
+ : tool === "learn_delete" ? "Delete Learn memory" : "Update Learn memory",
725
+ category: "Learn",
726
+ project: typeof activity.projectKey === "string" ? activity.projectKey
727
+ : activity.scope === "project" && typeof activity.scopeKey === "string" ? activity.scopeKey : null,
587
728
  status: "done",
588
729
  ok: activity.ok !== false,
589
730
  ...(Number.isFinite(durationMs) ? { durationMs } : {}),
@@ -603,6 +744,9 @@ export class RemoteTui {
603
744
  at: change.at || message.at || new Date().toISOString(),
604
745
  action: "learn",
605
746
  summary: "Learn " + marker + " " + truncate(detail, 120),
747
+ operation: "Update Learn memory",
748
+ category: "Learn",
749
+ project: typeof change.projectKey === "string" ? change.projectKey : null,
606
750
  status: "done",
607
751
  ok: true,
608
752
  });
@@ -644,32 +788,54 @@ export class RemoteTui {
644
788
 
645
789
  render() {
646
790
  if (this.closed) return;
647
- const { width, height, availableRows, headerRows } = this.viewportMetrics();
791
+ const { width, height, layout, usableHeight, topLine, dividerRows,
792
+ headingRows, footerRows, availableRows, twoLines } = this.viewportMetrics();
648
793
  const state = { ...this.state, uptimeMs: Date.now() - this.startedAt };
649
794
  const online = state.status === "connected" && relayIsOnline(state.relayHealth);
650
- const health = online ? "โ— ONLINE" : state.status === "connected" ? "โ—‹ OFFLINE" : statusText(state.status);
651
- const healthWidth = terminalCellWidth(health);
652
- const label = truncateCells("Chat Relay v" + this.version, Math.max(1, width - healthWidth - 2));
653
- const topGap = " ".repeat(Math.max(1, width - terminalCellWidth(label) - healthWidth));
654
- const top = (this.colorEnabled ? paint(label, STYLE.bold, STYLE.cyan) : label) + topGap
655
- + (this.colorEnabled ? paint(health, online ? STYLE.green : state.status === "connected" ? STYLE.red : STYLE.yellow) : health);
656
- const summary = compactSummary(state, width, headerRows, this.colorEnabled);
657
- const divider = this.colorEnabled ? paint("โ”€".repeat(width), STYLE.gray) : "โ”€".repeat(width);
658
- const mode = this.scrollOffset === 0 ? "โ— LIVE" : this.unseenTransactions ? "+" + this.unseenTransactions + " NEW" : "HISTORY";
659
- const sectionLeft = "Activity " + mode;
660
- const help = "โ†‘โ†“ scroll ยท End live";
661
- const section = truncateCells(sectionLeft + (width > terminalCellWidth(sectionLeft) + terminalCellWidth(help) + 3
662
- ? " ".repeat(width - terminalCellWidth(sectionLeft) - terminalCellWidth(help)) + help : ""), width);
663
- const sectionLine = this.colorEnabled ? paint(section, STYLE.cyan) : section;
664
- const activity = this.transactionRows(width);
665
- this.scrollOffset = clamp(this.scrollOffset, 0, Math.max(0, activity.length - availableRows));
666
- const end = Math.max(0, activity.length - this.scrollOffset);
667
- const start = Math.max(0, end - availableRows);
668
- const events = activity.slice(start, end);
669
- const body = events.length ? events : [this.colorEnabled ? paint(" No recent activity", STYLE.gray) : " No recent activity"];
670
- while (body.length < availableRows) body.unshift("");
671
- const lines = [top, ...summary, divider, sectionLine, ...(height >= 14 ? [divider] : []), ...body];
672
- const screen = lines.slice(0, Math.max(1, height - FRAME_BOTTOM_MARGIN)).join("\n");
673
- this.output.write(ESC + "2J" + ESC + "H" + screen);
795
+ const health = this.demoMode ? "โ—ˆ DEMO" : online ? "โ— ONLINE" : state.status === "connected" ? "โ—‹ OFFLINE" : statusText(state.status);
796
+ const headline = "Chat Relay v" + this.version + (this.demoMode ? " ยท PREVIEW" : "");
797
+ const headlineRoom = width - terminalCellWidth(health) - 2;
798
+ const title = headlineRoom >= 12
799
+ ? tint(truncateCells(headline, headlineRoom), MONITOR.accent, this.colorEnabled)
800
+ + " ".repeat(width - terminalCellWidth(truncateCells(headline, headlineRoom)) - terminalCellWidth(health))
801
+ + tint(health, online ? MONITOR.good : MONITOR.warning, this.colorEnabled)
802
+ : tint(truncateCells(headline, width), MONITOR.accent, this.colorEnabled);
803
+ const divider = tint("โ”€".repeat(width), MONITOR.border, this.colorEnabled);
804
+ const allRows = this.transactionRows(width, twoLines);
805
+ this.scrollOffset = clamp(this.scrollOffset, 0, Math.max(0, allRows.length - availableRows));
806
+ if (this.scrollOffset === 0) this.unseenTransactions = 0;
807
+ const end = Math.max(0, allRows.length - this.scrollOffset);
808
+ const begin = Math.max(0, end - availableRows);
809
+ const visible = allRows.slice(begin, end);
810
+ const badge = this.demoMode ? "โ—ˆ SAMPLE" : this.scrollOffset === 0 ? "โ— LIVE"
811
+ : this.unseenTransactions ? "+" + this.unseenTransactions + " NEW" : "HISTORY";
812
+ const left = "Activity " + badge;
813
+ const count = this.transactions.length + (this.transactions.length === 1 ? " operation" : " operations");
814
+ const showCount = width >= terminalCellWidth(left) + terminalCellWidth(count) + 3;
815
+ const section = terminalCellWidth(left) > width
816
+ ? tint(truncateCells(left, width), MONITOR.accent, this.colorEnabled)
817
+ : this.colorEnabled
818
+ ? tint("Activity", MONITOR.bright, true) + " "
819
+ + (this.scrollOffset === 0 ? paint(badge, MONITOR.good, MONITOR.liveBg) : tint(badge, MONITOR.warning, true))
820
+ + (showCount ? " ".repeat(width - terminalCellWidth(left) - terminalCellWidth(count))
821
+ + tint(count, MONITOR.muted, true) : "")
822
+ : left + (showCount ? " ".repeat(width - terminalCellWidth(left) - terminalCellWidth(count)) + count : "");
823
+ const lines = [title];
824
+ if (topLine) lines.push(divider);
825
+ lines.push(...monitoringSummary(state, width, layout, this.colorEnabled));
826
+ if (dividerRows) lines.push(divider);
827
+ lines.push(section);
828
+ if (headingRows) lines.push(headingRow(width, this.colorEnabled), divider);
829
+ if (availableRows > 0 && visible.length === 0) {
830
+ visible.push(tint(" No recent activity", MONITOR.dim, this.colorEnabled));
831
+ }
832
+ lines.push(...visible);
833
+ while (lines.length < usableHeight - footerRows) lines.push("");
834
+
835
+ const screen = lines.slice(0, Math.max(1, usableHeight)).join("\n");
836
+ if (screen !== this.previousFrame) {
837
+ this.previousFrame = screen;
838
+ this.output.write(ESC + "2J" + ESC + "H" + screen);
839
+ }
674
840
  }
675
841
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anusornneal/chat-relay",
3
- "version": "1.3.3",
3
+ "version": "1.3.5",
4
4
  "description": "Zero-checkout remote MCP agent for ChatGPT with terminal, filesystem, process, multi-user, and multi-agent support.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -13,7 +13,7 @@
13
13
  "README.md"
14
14
  ],
15
15
  "engines": {
16
- "node": ">=20"
16
+ "node": "^22.23.4 || ^24.22.1 || >=26.12.1"
17
17
  },
18
18
  "publishConfig": {
19
19
  "access": "public"
@@ -21,6 +21,7 @@
21
21
  "scripts": {
22
22
  "start": "node bin/chat-relay.js remote",
23
23
  "remote": "node bin/chat-relay.js remote",
24
+ "demo": "node bin/chat-relay.js demo",
24
25
  "login": "node bin/chat-relay.js login",
25
26
  "logout": "node bin/chat-relay.js logout",
26
27
  "status": "node bin/chat-relay.js status",
@@ -53,7 +54,7 @@
53
54
  "test:device-management": "node test/device-management-smoke.mjs",
54
55
  "test:submission": "node test/submission-smoke.mjs",
55
56
  "test:agent-state": "node --experimental-strip-types --test test/agent-state.test.mjs test/reconnect-chaos.test.mjs",
56
- "test:tui": "node --test test/cli-tui.test.mjs",
57
+ "test:tui": "node --test test/cli-tui.test.mjs test/toolcall-context.test.mjs test/cli-demo.test.mjs",
57
58
  "test:config-security": "node --test test/config-security.test.mjs",
58
59
  "test:self-update": "node --test test/self-update.test.mjs test/agent-lifecycle-upgrade.test.mjs",
59
60
  "test:budget": "node --test test/relay-health.test.mjs test/usage-budget.test.mjs",