xonecas.io
64875
Mc

mini-coder / commit 38ffdbd

fix: align prompt reload and ui behavior

xonecas2026-04-08 38ffdbd0c0d1aa71f2b442bf9c970a3592101cf0 parent 3b4fa39

14 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

TODO.md+0−15
@@ -5,21 +5,6 @@ Don't keep completed items bloating the file.
55 Keep the file structured and minimal.
66 The spec.md and code are the sources of truth, not this file, don't assume anything because it's documented here.
77
8-## Spec alignment
9-
10-### Prompt and session context
11-
12-- [ ] **Reload AGENTS.md, skills, and plugins on `/new`** (`index.ts`, `ui/commands.ts`) — they are only loaded at startup right now, but the spec says prompt context can change on `/new` or CWD change.
13-- [ ] **Honor `MC_AGENTS_ROOT=/`** (`index.ts`, `prompt.ts`) — only walk AGENTS.md discovery to filesystem root when this env var is explicitly set.
14-- [ ] **Fix OAuth credential refresh comparison** (`index.ts`) — avoid reference-based comparison when deciding whether refreshed OAuth credentials should be written back to disk.
15-
16-### UI mismatches
17-
18-- [ ] **Implement `Ctrl+Z` suspend/background** (`ui.ts`)
19-- [ ] **Show shell exit codes in the UI** (`tools.ts`, `ui.ts`) — shell tool rendering should display the numeric exit code.
20-- [ ] **Render a real diff for new-file `edit` results** (`ui/conversation.ts`) — the spec calls for a unified diff, but the current UI only shows `(new file)`.
21-- [ ] **Left-truncate CWD on narrow terminals** (`ui.ts`) — status bar path should truncate from the left (`…/mini-coder`).
22-
238 ## Plugins and API drift (deferred until core/spec alignment is done)
249
2510 - [ ] **Reconcile the plugin tool execution API with the spec/docs** (`plugins.ts`, `index.ts`, `spec.md`) — the implementation currently needs an undocumented `toolHandlers` map in addition to `tools`, so plugin tools are not actually self-describing the way the spec says.
src/index.test.ts+203−1
@@ -1,9 +1,79 @@
1-import { expect, test } from "bun:test";
1+import { afterEach, expect, test } from "bun:test";
2+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3+import { tmpdir } from "node:os";
24 import { join } from "node:path";
35 import { pathToFileURL } from "node:url";
6+import {
7+ type AppState,
8+ didOAuthCredentialsChange,
9+ loadPromptContext,
10+ reloadPromptContext,
11+} from "./index.ts";
12+import type { LoadedPlugin } from "./plugins.ts";
13+import { openDatabase } from "./session.ts";
14+import { DEFAULT_THEME } from "./theme.ts";
415
516 const REPO_ROOT = join(import.meta.dir, "..");
617 const INDEX_MODULE_URL = pathToFileURL(join(import.meta.dir, "index.ts")).href;
18+const tempDirs: string[] = [];
19+
20+function createTempDir(): string {
21+ const dir = mkdtempSync(join(tmpdir(), "mc-index-test-"));
22+ tempDirs.push(dir);
23+ return dir;
24+}
25+
26+function createTestState(plugins: LoadedPlugin[] = []): AppState {
27+ const cwd = createTempDir();
28+ return {
29+ db: openDatabase(":memory:"),
30+ session: null,
31+ model: null,
32+ effort: "medium",
33+ messages: [],
34+ stats: { totalInput: 0, totalOutput: 0, totalCost: 0 },
35+ agentsMd: [],
36+ skills: [],
37+ plugins,
38+ theme: DEFAULT_THEME,
39+ git: null,
40+ providers: new Map(),
41+ oauthCredentials: {},
42+ settings: {},
43+ settingsPath: join(cwd, "settings.json"),
44+ cwd,
45+ canonicalCwd: cwd,
46+ running: false,
47+ abortController: null,
48+ activeTurnPromise: null,
49+ showReasoning: true,
50+ verbose: false,
51+ };
52+}
53+
54+function createLoadedPlugin(name: string): LoadedPlugin {
55+ return {
56+ entry: { name, module: `${name}.ts` },
57+ plugin: {
58+ name,
59+ description: `${name} plugin`,
60+ async init() {
61+ return {};
62+ },
63+ async destroy() {},
64+ },
65+ result: {
66+ systemPromptSuffix: `${name} suffix`,
67+ theme: { accentText: "color03" },
68+ },
69+ };
70+}
71+
72+afterEach(() => {
73+ for (const dir of tempDirs.splice(0)) {
74+ rmSync(dir, { recursive: true, force: true });
75+ }
76+});
777
878 async function importIndexInChild(): Promise<{
979 exitCode: number;
@@ -55,3 +125,135 @@ test("importing index.ts does not start the CLI", async () => {
55125 expect(result.stdout).toBe("imported\n");
56126 expect(result.stderr).toBe("");
57127 });
128+
129+test("didOAuthCredentialsChange compares refreshed credentials structurally", () => {
130+ const current = {
131+ refresh: "refresh-token",
132+ access: "access-token",
133+ expires: 123,
134+ };
135+ const refreshedWithSameValues = {
136+ access: "access-token",
137+ expires: 123,
138+ refresh: "refresh-token",
139+ };
140+
141+ expect(didOAuthCredentialsChange(current, refreshedWithSameValues)).toBe(
142+ false,
143+ );
144+ expect(
145+ didOAuthCredentialsChange(current, {
146+ ...refreshedWithSameValues,
147+ access: "new-access-token",
148+ }),
149+ ).toBe(true);
150+});
151+
152+test("loadPromptContext loads AGENTS.md, skills, plugins, and theme overrides", async () => {
153+ const project = createTempDir();
154+ const pluginPath = join(project, "plugin.ts");
155+
156+ writeFileSync(join(project, "AGENTS.md"), "Project instructions");
157+ mkdirSync(join(project, ".agents", "skills", "example-skill"), {
158+ recursive: true,
159+ });
160+ writeFileSync(
161+ join(project, ".agents", "skills", "example-skill", "SKILL.md"),
162+ [
163+ "---",
164+ "name: example-skill",
165+ 'description: "Example skill."',
166+ "---",
167+ "",
168+ "# Example Skill",
169+ ].join("\n"),
170+ );
171+ writeFileSync(
172+ pluginPath,
173+ [
174+ "export default {",
175+ ' name: "test-plugin",',
176+ ' description: "Adds prompt context.",',
177+ " async init(agent) {",
178+ " return {",
179+ ` systemPromptSuffix: \`Plugin cwd: \${agent.cwd}\` ,`,
180+ ' theme: { accentText: "color03" },',
181+ " };",
182+ " },",
183+ "};",
184+ ].join("\n"),
185+ );
186+
187+ const context = await loadPromptContext([], {
188+ cwd: project,
189+ pluginEntries: [{ name: "test-plugin", module: pluginPath }],
190+ });
191+
192+ expect(context.cwd).toBe(project);
193+ expect(context.agentsMd.at(-1)?.content).toBe("Project instructions");
194+ expect(context.skills.map((skill) => skill.name)).toContain("example-skill");
195+ expect(context.plugins).toHaveLength(1);
196+ expect(context.plugins[0]?.result.systemPromptSuffix).toBe(
197+ `Plugin cwd: ${project}`,
198+ );
199+ expect(context.theme.accentText).toBe("color03");
200+});
201+
202+test("reloadPromptContext keeps the current plugin state when loading the replacement context fails", async () => {
203+ const plugin = createLoadedPlugin("existing");
204+ const state = createTestState([plugin]);
205+ let destroyed = false;
206+
207+ try {
208+ await expect(
209+ reloadPromptContext(state, {
210+ loadPromptContext: async () => {
211+ throw new Error("reload failed");
212+ },
213+ destroyPlugins: async () => {
214+ destroyed = true;
215+ },
216+ }),
217+ ).rejects.toThrow("reload failed");
218+
219+ expect(destroyed).toBe(false);
220+ expect(state.plugins).toEqual([plugin]);
221+ expect(state.theme).toBe(DEFAULT_THEME);
222+ } finally {
223+ state.db.close();
224+ }
225+});
226+
227+test("reloadPromptContext swaps in the new context before destroying the old plugins", async () => {
228+ const previousPlugin = createLoadedPlugin("previous");
229+ const nextPlugin = createLoadedPlugin("next");
230+ const state = createTestState([previousPlugin]);
231+ let destroyedPlugins: LoadedPlugin[] = [];
232+
233+ try {
234+ await reloadPromptContext(state, {
235+ loadPromptContext: async () => ({
236+ cwd: state.cwd,
237+ canonicalCwd: state.canonicalCwd,
238+ git: null,
239+ agentsMd: [{ path: "/tmp/AGENTS.md", content: "next agents" }],
240+ skills: [],
241+ plugins: [nextPlugin],
242+ theme: { ...DEFAULT_THEME, accentText: "color05" },
243+ }),
244+ destroyPlugins: async (plugins) => {
245+ destroyedPlugins = [...plugins];
246+ expect(state.plugins).toEqual([nextPlugin]);
247+ expect(state.theme.accentText).toBe("color05");
248+ },
249+ });
250+
251+ expect(destroyedPlugins).toEqual([previousPlugin]);
252+ expect(state.plugins).toEqual([nextPlugin]);
253+ expect(state.agentsMd).toEqual([
254+ { path: "/tmp/AGENTS.md", content: "next agents" },
255+ ]);
256+ } finally {
257+ state.db.close();
258+ }
259+});
src/index.ts+108−36
@@ -11,8 +11,10 @@
1111 import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
1212 import { homedir } from "node:os";
1313 import { join } from "node:path";
14+import { isDeepStrictEqual } from "node:util";
1415 import type {
1516 KnownProvider,
17+ Message,
1618 Model,
1719 OAuthCredentials,
1820 ThinkingLevel,
@@ -29,11 +31,13 @@ import {
2931 initPlugins,
3032 type LoadedPlugin,
3133 loadPluginConfig,
34+ type PluginEntry,
3235 } from "./plugins.ts";
3336 import {
3437 type AgentsMdFile,
3538 buildSystemPrompt,
3639 discoverAgentsMd,
40+ resolveAgentsScanRoot,
3741 } from "./prompt.ts";
3842 import {
3943 computeStats,
@@ -106,6 +110,14 @@ function saveOAuthCredentials(creds: Record<string, OAuthCredentials>): void {
106110 writeFileSync(AUTH_PATH, JSON.stringify(creds, null, 2), "utf-8");
107111 }
108112
113+/** Return whether refreshed OAuth credentials differ from the persisted value. */
114+export function didOAuthCredentialsChange(
115+ current: OAuthCredentials | undefined,
116+ next: OAuthCredentials,
117+): boolean {
118+ return !isDeepStrictEqual(current, next);
119+}
120+
109121 // ---------------------------------------------------------------------------
110122 // Provider discovery
111123 // ---------------------------------------------------------------------------
@@ -148,7 +160,12 @@ async function discoverProviders(): Promise<DiscoveryResult> {
148160 if (result) {
149161 providers.set(oauthProvider.id, result.apiKey);
150162 // Update credentials if they were refreshed
151- if (result.newCredentials !== oauthCredentials[oauthProvider.id]) {
163+ if (
164+ didOAuthCredentialsChange(
165+ oauthCredentials[oauthProvider.id],
166+ result.newCredentials,
167+ )
168+ ) {
152169 oauthCredentials[oauthProvider.id] = result.newCredentials;
153170 credsModified = true;
154171 }
@@ -286,6 +303,88 @@ function getSkillScanPaths(cwd: string, gitRoot: string | null): string[] {
286303 ];
287304 }
288305
306+/** Load AGENTS.md files, skills, plugins, git state, and the merged theme. */
307+export async function loadPromptContext(
308+ messages: readonly Message[],
309+ opts?: {
310+ cwd?: string;
311+ pluginEntries?: PluginEntry[];
312+ pluginConfigPath?: string;
313+ },
314+): Promise<{
315+ cwd: string;
316+ canonicalCwd: string;
317+ git: GitState | null;
318+ agentsMd: AgentsMdFile[];
319+ skills: Skill[];
320+ plugins: LoadedPlugin[];
321+ theme: Theme;
322+}> {
323+ const cwd = opts?.cwd ?? process.cwd();
324+ const canonicalCwd = canonicalizePath(cwd);
325+ const git = await getGitState(cwd);
326+ const gitRoot = git?.root ?? null;
327+ const home = homedir();
328+ const scanRoot = resolveAgentsScanRoot(
329+ cwd,
330+ gitRoot,
331+ home,
332+ process.env.MC_AGENTS_ROOT,
333+ );
334+ const agentsMd = discoverAgentsMd(cwd, scanRoot, join(home, ".agents"));
335+ const skills = discoverSkills(getSkillScanPaths(canonicalCwd, gitRoot));
336+ const pluginEntries =
337+ opts?.pluginEntries ??
338+ loadPluginConfig(opts?.pluginConfigPath ?? PLUGIN_CONFIG_PATH);
339+ const context: AgentContext = {
340+ cwd,
341+ messages,
342+ dataDir: DATA_DIR,
343+ };
344+ const plugins = await initPlugins(pluginEntries, context, (entry, err) => {
345+ console.error(`Plugin "${entry.name}" failed to init: ${err.message}`);
346+ });
347+ const themeOverrides = plugins
348+ .map((plugin) => plugin.result.theme)
349+ .filter((theme): theme is Partial<Theme> => theme != null);
350+
351+ return {
352+ cwd,
353+ canonicalCwd,
354+ git,
355+ agentsMd,
356+ skills,
357+ plugins,
358+ theme: mergeThemes(DEFAULT_THEME, ...themeOverrides),
359+ };
360+}
361+
362+/** Refresh the current prompt/session context at a reload boundary like `/new`. */
363+export async function reloadPromptContext(
364+ state: AppState,
365+ runtime?: {
366+ loadPromptContext?: typeof loadPromptContext;
367+ destroyPlugins?: typeof destroyPlugins;
368+ },
369+): Promise<void> {
370+ const loadContext = runtime?.loadPromptContext ?? loadPromptContext;
371+ const destroyLoadedPlugins = runtime?.destroyPlugins ?? destroyPlugins;
372+ const previousPlugins = state.plugins;
373+ const context = await loadContext(filterModelMessages(state.messages));
374+
375+ state.cwd = context.cwd;
376+ state.canonicalCwd = context.canonicalCwd;
377+ state.git = context.git;
378+ state.agentsMd = context.agentsMd;
379+ state.skills = context.skills;
380+ state.plugins = context.plugins;
381+ state.theme = context.theme;
382+
383+ await destroyLoadedPlugins(previousPlugins, (entry, err) => {
384+ console.error(`Plugin "${entry.name}" failed to destroy: ${err.message}`);
385+ });
386+}
387+
289388 // ---------------------------------------------------------------------------
290389 // App state
291390 // ---------------------------------------------------------------------------
@@ -345,7 +444,6 @@ export interface AppState {
345444 /** Initialize and return the full app state. */
346445 export async function init(): Promise<AppState> {
347446 const cwd = process.cwd();
348- const canonicalCwd = canonicalizePath(cwd);
349447
350448 // Ensure data directory exists
351449 mkdirSync(DATA_DIR, { recursive: true });
@@ -362,41 +460,15 @@ export async function init(): Promise<AppState> {
362460 );
363461 const model = selectModel(availableModels, startup.modelId);
364462
365- // Gather git state
366- const git = await getGitState(cwd);
367- const gitRoot = git?.root ?? null;
368-
369- // Discover context
370- const home = homedir();
371- const scanRoot = gitRoot ?? home;
372- const agentsMd = discoverAgentsMd(cwd, scanRoot, join(home, ".agents"));
373- const skills = discoverSkills(getSkillScanPaths(canonicalCwd, gitRoot));
374-
375- // Load plugins
376- const pluginEntries = loadPluginConfig(PLUGIN_CONFIG_PATH);
377-
378463 // Open database. Sessions are created lazily on the first user message.
379464 const db = openDatabase(DB_PATH);
380465 const effort = startup.effort;
381466 const messages: ReturnType<typeof loadMessages> = [];
382467 const stats = computeStats(messages);
383-
384- // Init plugins
385- const context: AgentContext = {
468+ const promptContext = await loadPromptContext(filterModelMessages(messages), {
386469 cwd,
387- messages: filterModelMessages(messages),
388- dataDir: DATA_DIR,
389- };
390- const plugins = await initPlugins(pluginEntries, context, (entry, err) => {
391- console.error(`Plugin "${entry.name}" failed to init: ${err.message}`);
392470 });
393471
394- // Build theme from defaults + plugin overrides
395- const themeOverrides = plugins
396- .map((p) => p.result.theme)
397- .filter((t): t is Partial<Theme> => t != null);
398- const theme = mergeThemes(DEFAULT_THEME, ...themeOverrides);
399-
400472 return {
401473 db,
402474 session: null,
@@ -404,17 +476,17 @@ export async function init(): Promise<AppState> {
404476 effort,
405477 messages,
406478 stats,
407- agentsMd,
408- skills,
409- plugins,
410- theme,
411- git,
479+ agentsMd: promptContext.agentsMd,
480+ skills: promptContext.skills,
481+ plugins: promptContext.plugins,
482+ theme: promptContext.theme,
483+ git: promptContext.git,
412484 providers,
413485 oauthCredentials,
414486 settings,
415487 settingsPath: SETTINGS_PATH,
416- cwd,
417- canonicalCwd,
488+ cwd: promptContext.cwd,
489+ canonicalCwd: promptContext.canonicalCwd,
418490 running: false,
419491 abortController: null,
420492 activeTurnPromise: null,
src/prompt.test.ts+46−0
@@ -14,6 +14,7 @@ import {
1414 buildSystemPrompt,
1515 discoverAgentsMd,
1616 formatGitLine,
17+ resolveAgentsScanRoot,
1718 } from "./prompt.ts";
1819 import type { Skill } from "./skills.ts";
1920
@@ -142,6 +143,51 @@ describe("discoverAgentsMd", () => {
142143 "Project instructions",
143144 ]);
144145 });
146+
147+ test("does not walk outside cwd when the scan root is not an ancestor", () => {
148+ const home = join(tmp, "home");
149+ const project = join(tmp, "outside", "project");
150+
151+ mkdirSync(home, { recursive: true });
152+ mkdirSync(project, { recursive: true });
153+
154+ writeFileSync(join(tmp, "AGENTS.md"), "Tmp instructions");
155+ writeFileSync(join(project, "AGENTS.md"), "Project instructions");
156+
157+ const files = discoverAgentsMd(project, home);
158+ expect(files.map((file) => file.content)).toEqual(["Project instructions"]);
159+ });
160+});
161+
162+// ---------------------------------------------------------------------------
163+// resolveAgentsScanRoot
164+// ---------------------------------------------------------------------------
165+
166+describe("resolveAgentsScanRoot", () => {
167+ test("prefers the git root when one is available", () => {
168+ const project = join(tmp, "project");
169+ const home = join(tmp, "home");
170+ mkdirSync(project, { recursive: true });
171+ mkdirSync(home, { recursive: true });
172+
173+ expect(resolveAgentsScanRoot(project, project, home, "/")).toBe(
174+ canonicalizePath(project),
175+ );
176+ });
177+
178+ test("falls back to the home directory unless MC_AGENTS_ROOT=/ is set", () => {
179+ const project = join(tmp, "project");
180+ const home = join(tmp, "home");
181+ mkdirSync(project, { recursive: true });
182+ mkdirSync(home, { recursive: true });
183+
184+ expect(resolveAgentsScanRoot(project, null, home)).toBe(
185+ canonicalizePath(home),
186+ );
187+ expect(resolveAgentsScanRoot(project, null, home, "/")).toBe(
188+ canonicalizePath("/"),
189+ );
190+ });
145191 });
146192
147193 // ---------------------------------------------------------------------------
src/prompt.ts+40−11
@@ -9,7 +9,7 @@
99 */
1010
1111 import { existsSync, readFileSync } from "node:fs";
12-import { dirname, join } from "node:path";
12+import { dirname, join, relative } from "node:path";
1313 import type { GitState } from "./git.ts";
1414 import { canonicalizePath } from "./paths.ts";
1515 import { buildSkillCatalog, type Skill } from "./skills.ts";
@@ -49,6 +49,30 @@ export interface BuildSystemPromptOpts {
4949 /** File name to look for during the AGENTS.md walk. */
5050 const AGENT_FILENAME = "AGENTS.md";
5151
52+/** Resolve the AGENTS.md scan root from git/home/env inputs. */
53+export function resolveAgentsScanRoot(
54+ _cwd: string,
55+ gitRoot: string | null,
56+ homeDir: string,
57+ agentsRootEnv = process.env.MC_AGENTS_ROOT,
58+): string {
59+ if (gitRoot) {
60+ return canonicalizePath(gitRoot);
61+ }
62+ if (agentsRootEnv === "/") {
63+ return canonicalizePath("/");
64+ }
65+ return canonicalizePath(homeDir);
66+}
67+
68+function isWithinScanRoot(path: string, scanRoot: string): boolean {
69+ const relativePath = relative(scanRoot, path);
70+ return (
71+ relativePath === "" ||
72+ (!relativePath.startsWith("..") && relativePath !== "..")
73+ );
74+}
75+
5276 /**
5377 * Walk from `cwd` up to `scanRoot`, collecting AGENTS.md files.
5478 *
@@ -72,17 +96,22 @@ export function discoverAgentsMd(
7296 // Collect canonical directories from scanRoot to cwd
7397 const dirs: string[] = [];
7498 let current = start;
75- while (true) {
76- dirs.push(current);
77- if (current === root) break;
78- const parent = dirname(current);
79- // Safety: stop if we can't go higher (e.g., filesystem root)
80- if (parent === current) break;
81- current = parent;
82- }
8399
84- // Reverse so we go root-to-leaf
85- dirs.reverse();
100+ if (!isWithinScanRoot(start, root)) {
101+ dirs.push(start);
102+ } else {
103+ while (true) {
104+ dirs.push(current);
105+ if (current === root) break;
106+ const parent = dirname(current);
107+ // Safety: stop if we can't go higher (e.g., filesystem root)
108+ if (parent === current) break;
109+ current = parent;
110+ }
111+
112+ // Reverse so we go root-to-leaf
113+ dirs.reverse();
114+ }
86115
87116 // Collect files from the global agents dir first
88117 const files: AgentsMdFile[] = [];
src/tools.test.ts+2−1
@@ -226,6 +226,7 @@ describe("shell", () => {
226226 test("returns stdout from a command", async () => {
227227 const result = await executeShell({ command: "echo hello" }, tmp);
228228 expect(result.isError).toBe(false);
229+ expect(resultText(result)).toContain("Exit code: 0");
229230 expect(resultText(result)).toContain("hello");
230231 });
231232
@@ -238,7 +239,7 @@ describe("shell", () => {
238239 test("passes through exit code", async () => {
239240 const result = await executeShell({ command: "exit 42" }, tmp);
240241 expect(result.isError).toBe(true);
241- expect(resultText(result)).toContain("exit code 42");
242+ expect(resultText(result)).toContain("Exit code: 42");
242243 });
243244
244245 test("runs in the specified cwd", async () => {
src/tools.ts+2−4
@@ -258,10 +258,8 @@ export async function executeShell(
258258 );
259259
260260 const isError = exitCode !== 0;
261- const prefix = isError ? `Command failed with exit code ${exitCode}\n` : "";
262- const text = prefix + output;
263-
264- return textResult(text || "(no output)", isError);
261+ const body = output || "(no output)";
262+ return textResult(`Exit code: ${exitCode}\n${body}`, isError);
265263 } catch (err) {
266264 const message = err instanceof Error ? err.message : String(err);
267265 return textResult(`Shell error: ${message}`, true);
src/ui.commands.test.ts+57−0
@@ -90,6 +90,7 @@ describe("ui/commands", () => {
9090 appendInfoMessage: () => {},
9191 scrollConversationToBottom: () => {},
9292 render: () => {},
93+ reloadPromptContext: async () => {},
9394 openInBrowser: () => {},
9495 });
9596
@@ -133,6 +134,7 @@ describe("ui/commands", () => {
133134 appendInfoMessage: () => {},
134135 scrollConversationToBottom: () => {},
135136 render: () => {},
137+ reloadPromptContext: async () => {},
136138 openInBrowser: () => {},
137139 });
138140
@@ -179,6 +181,7 @@ describe("ui/commands", () => {
179181 appendInfoMessage: () => {},
180182 scrollConversationToBottom: () => {},
181183 render: () => {},
184+ reloadPromptContext: async () => {},
182185 openInBrowser: () => {},
183186 });
184187
@@ -189,6 +192,59 @@ describe("ui/commands", () => {
189192 }
190193 });
191194
195+ test("/new clears the active session state and reloads prompt context", async () => {
196+ const state = createTestState();
197+ let reloadCount = 0;
198+ const controller = createCommandController({
199+ openOverlay: () => {},
200+ dismissOverlay: () => {},
201+ setInputValue: () => {},
202+ appendInfoMessage: () => {},
203+ scrollConversationToBottom: () => {},
204+ render: () => {},
205+ reloadPromptContext: async (nextState) => {
206+ reloadCount++;
207+ nextState.agentsMd = [
208+ { path: "/tmp/reloaded/AGENTS.md", content: "Reloaded context" },
209+ ];
210+ },
211+ openInBrowser: () => {},
212+ });
213+
214+ state.session = {
215+ id: "session-1",
216+ cwd: state.canonicalCwd,
217+ model: null,
218+ effort: state.effort,
219+ forkedFrom: null,
220+ createdAt: 1,
221+ updatedAt: 1,
222+ };
223+ state.messages = [
224+ { role: "ui", kind: "info", content: "old", timestamp: 1 },
225+ ];
226+ state.stats = { totalInput: 10, totalOutput: 20, totalCost: 0.5 };
227+
228+ try {
229+ expect(controller.handleCommand("new", state)).toBe(true);
230+ await Bun.sleep(0);
231+
232+ expect(reloadCount).toBe(1);
233+ expect(state.session).toBeNull();
234+ expect(state.messages).toEqual([]);
235+ expect(state.stats).toEqual({
236+ totalInput: 0,
237+ totalOutput: 0,
238+ totalCost: 0,
239+ });
240+ expect(state.agentsMd).toEqual([
241+ { path: "/tmp/reloaded/AGENTS.md", content: "Reloaded context" },
242+ ]);
243+ } finally {
244+ state.db.close();
245+ }
246+ });
247+
192248 test("applyModelSelection updates the state and persists the default model", () => {
193249 const faux = registerFauxProvider();
194250 const state = createTestState();
@@ -200,6 +256,7 @@ describe("ui/commands", () => {
200256 appendInfoMessage: () => {},
201257 scrollConversationToBottom: () => {},
202258 render: () => {},
259+ reloadPromptContext: async () => {},
203260 openInBrowser: () => {},
204261 });
205262
src/ui.conversation.test.ts+29−0
@@ -128,6 +128,35 @@ describe("ui/conversation", () => {
128128 expect(text).not.toContain("line 21");
129129 });
130130
131+ test("renderToolResult shows shell exit codes", () => {
132+ const node = renderToolResult(
133+ "shell",
134+ { command: "exit 42" },
135+ "Exit code: 42\n[stderr]\nboom",
136+ true,
137+ RENDER_OPTS,
138+ );
139+ const text = collectText(node);
140+
141+ expect(text).toContain("$ exit 42");
142+ expect(text).toContain("Exit code: 42");
143+ });
144+
145+ test("renderToolResult shows a diff for newly created files", () => {
146+ const node = renderToolResult(
147+ "edit",
148+ { path: "src/new.ts", oldText: "", newText: "first\nsecond\n" },
149+ "Created src/new.ts",
150+ false,
151+ { ...RENDER_OPTS, verbose: true },
152+ );
153+ const text = collectText(node);
154+
155+ expect(text).toContain("+first");
156+ expect(text).toContain("+second");
157+ expect(text).not.toContain("(new file)");
158+ });
159+
131160 test("renderToolResult shows full edit diffs in verbose mode", () => {
132161 const oldText = Array.from({ length: 25 }, (_, i) => `old ${i + 1}`).join(
133162 "\n",
src/ui.test.ts+74−0
@@ -46,6 +46,7 @@ import {
4646 renderStatusBar,
4747 renderToolResult,
4848 resetUiState,
49+ suspendToBackground,
4950 type ToolRenderLine,
5051 } from "./ui.ts";
5152
@@ -1659,6 +1660,21 @@ describe("ui rendering", () => {
16591660 }
16601661 });
16611662
1663+ test("renderStatusBar left-truncates the cwd on narrow terminals", () => {
1664+ const state = createTestState();
1665+ state.cwd = "/tmp/very/long/path/to/mini-coder";
1666+
1667+ try {
1668+ const node = renderStatusBar(state, 30);
1669+ const text = collectText(node);
1670+
1671+ expect(text).toContain("…/mini-coder");
1672+ expect(text).not.toContain(state.cwd);
1673+ } finally {
1674+ state.db.close();
1675+ }
1676+ });
1677+
16621678 test("renderBaseLayout keeps a single divider between the log and input", () => {
16631679 const state = createTestState();
16641680 const controller: InputController = {
@@ -1685,6 +1701,64 @@ describe("ui rendering", () => {
16851701 }
16861702 });
16871703
1704+ test("renderBaseLayout delegates Ctrl+Z to the suspend handler", () => {
1705+ const state = createTestState();
1706+ const controller: InputController = {
1707+ onChange: () => {},
1708+ onFocus: () => {},
1709+ onBlur: () => {},
1710+ onKeyPress: () => undefined,
1711+ };
1712+ let suspended = false;
1713+
1714+ try {
1715+ const node = renderBaseLayout(state, 80, controller, () => {
1716+ suspended = true;
1717+ });
1718+
1719+ expect(node.type).toBe("vstack");
1720+ if (node.type !== "vstack") {
1721+ throw new Error("Expected app layout to be a VStack");
1722+ }
1723+
1724+ node.props.onKeyPress?.("ctrl+z");
1725+ expect(suspended).toBe(true);
1726+ } finally {
1727+ state.db.close();
1728+ }
1729+ });
1730+
1731+ test("suspendToBackground stops immediately and resumes on SIGCONT", () => {
1732+ const calls: string[] = [];
1733+ let resumeHandler = (): void => {
1734+ throw new Error(
1735+ "Expected suspendToBackground to register a resume handler",
1736+ );
1737+ };
1738+
1739+ suspendToBackground(
1740+ () => {
1741+ calls.push("resume");
1742+ },
1743+ {
1744+ stop: () => {
1745+ calls.push("stop");
1746+ },
1747+ onResume: (handler: () => void) => {
1748+ calls.push("onResume");
1749+ resumeHandler = handler;
1750+ },
1751+ suspend: () => {
1752+ calls.push("suspend");
1753+ },
1754+ },
1755+ );
1756+
1757+ expect(calls).toEqual(["stop", "onResume", "suspend"]);
1758+ resumeHandler();
1759+ expect(calls).toEqual(["stop", "onResume", "suspend", "resume"]);
1760+ });
1761+
16881762 test("renderStatusBar estimates context usage from the latest valid assistant usage plus trailing model-visible messages", () => {
16891763 const faux = registerFauxProvider();
16901764 const state = createTestState();
src/ui.ts+92−3
@@ -13,7 +13,11 @@ import { platform } from "node:os";
1313 import { cel, HStack, ProcessTerminal, Text, VStack } from "@cel-tui/core";
1414 import type { Node } from "@cel-tui/types";
1515 import type { AppState } from "./index.ts";
16-import { MAX_SESSIONS_PER_CWD, shutdown } from "./index.ts";
16+import {
17+ MAX_SESSIONS_PER_CWD,
18+ reloadPromptContext,
19+ shutdown,
20+} from "./index.ts";
1721 import {
1822 appendMessage,
1923 createSession,
@@ -87,6 +91,9 @@ let dividerTick = 0;
8791 /** Divider animation timer handle. */
8892 let dividerTimer: ReturnType<typeof setInterval> | null = null;
8993
94+/** Whether stdin was already in raw mode before the TUI initialized. */
95+let stdinWasRaw = false;
96+
9097 // ---------------------------------------------------------------------------
9198 // Overlay state
9299 // ---------------------------------------------------------------------------
@@ -108,6 +115,7 @@ export function resetUiState(): void {
108115 stopDividerAnimation();
109116 resetUiAgentState();
110117 activeOverlay = null;
118+ stdinWasRaw = false;
111119 }
112120
113121 // ---------------------------------------------------------------------------
@@ -355,6 +363,7 @@ const commandController = createCommandController({
355363 render: () => {
356364 cel.render();
357365 },
366+ reloadPromptContext,
358367 openInBrowser,
359368 });
360369
@@ -396,6 +405,67 @@ async function gracefulExit(state: AppState): Promise<void> {
396405 process.exit(0);
397406 }
398407
408+/** Restore the terminal to the shell before suspending. */
409+function suspendTerminalUi(): void {
410+ stopDividerAnimation();
411+ process.stdout.write("\x1b[?1006l\x1b[?1000l");
412+ process.stdout.write("\x1b[<u");
413+ process.stdout.write("\x1b[?25h");
414+ process.stdout.write("\x1b[?1049l");
415+ process.stdin.pause();
416+ if (process.stdin.setRawMode) {
417+ process.stdin.setRawMode(stdinWasRaw);
418+ }
419+}
420+
421+/** Re-enter the TUI terminal modes after a suspended process is resumed. */
422+function resumeTerminalUi(): void {
423+ if (process.stdin.setRawMode) {
424+ process.stdin.setRawMode(true);
425+ }
426+ process.stdin.resume();
427+ process.stdout.write("\x1b[?1049h");
428+ process.stdout.write("\x1b[>1u");
429+ process.stdout.write("\x1b[?1000h\x1b[?1006h");
430+ process.stdout.write("\x1b[?25l");
431+}
432+
433+/** Suspend the app to the background and restore the UI on SIGCONT. */
434+export function suspendToBackground(
435+ resumeUi: () => void,
436+ runtime?: {
437+ stop?: () => void;
438+ onResume?: (resume: () => void) => void;
439+ suspend?: () => void;
440+ },
441+): void {
442+ const stop = runtime?.stop ?? suspendTerminalUi;
443+ const onResume =
444+ runtime?.onResume ??
445+ ((resume: () => void) => {
446+ process.once("SIGCONT", resume);
447+ });
448+ const suspend =
449+ runtime?.suspend ??
450+ (() => {
451+ process.kill(process.pid, "SIGTSTP");
452+ });
453+ const keepAlive = setInterval(() => {}, 1 << 30);
454+
455+ stop();
456+ onResume(() => {
457+ clearInterval(keepAlive);
458+ resumeUi();
459+ });
460+
461+ try {
462+ suspend();
463+ } catch (error) {
464+ clearInterval(keepAlive);
465+ throw error;
466+ }
467+}
468+
399469 // ---------------------------------------------------------------------------
400470 // Main
401471 // ---------------------------------------------------------------------------
@@ -432,6 +502,7 @@ export function renderBaseLayout(
432502 state: AppState,
433503 cols: number,
434504 inputController: InputController,
505+ onSuspend?: () => void,
435506 ): Node {
436507 return VStack(
437508 {
@@ -449,6 +520,10 @@ export function renderBaseLayout(
449520 gracefulExit(state).catch(() => process.exit(1));
450521 return;
451522 }
523+ if (key === "ctrl+z") {
524+ onSuspend?.();
525+ return;
526+ }
452527 if (key === "escape" && state.running) {
453528 if (state.abortController) state.abortController.abort();
454529 return;
@@ -467,7 +542,7 @@ export function renderBaseLayout(
467542 renderInputArea(state.theme, inputController),
468543
469544 // ── Status bar (1 line) ──
470- renderStatusBar(state),
545+ renderStatusBar(state, cols),
471546 ],
472547 );
473548 }
@@ -482,13 +557,23 @@ export function renderBaseLayout(
482557 */
483558 export function startUI(state: AppState): void {
484559 resetUiState();
560+ stdinWasRaw = process.stdin.isRaw || false;
485561 const terminal = new ProcessTerminal();
486562 const inputController = createInputController(state);
487563 cel.init(terminal);
488564
489565 cel.viewport(() => {
490566 const cols = terminal.columns;
491- const base = renderBaseLayout(state, cols, inputController);
567+ const base = renderBaseLayout(state, cols, inputController, () => {
568+ suspendToBackground(() => {
569+ resumeTerminalUi();
570+ cel._getBuffer()?.clear();
571+ if (state.running) {
572+ startDividerAnimation();
573+ }
574+ cel.render();
575+ });
Cut short: this commit's diff is over 1000 lines.
src/ui/commands.ts+10−2
Cut short: this commit's diff is over 1000 lines.
src/ui/conversation.ts+36−24
Cut short: this commit's diff is over 1000 lines.
src/ui/status.ts+50−3
Cut short: this commit's diff is over 1000 lines.