Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
51c0cb5c78 | ||
|
|
7408f04bbc | ||
|
|
6dfb9f1598 | ||
|
|
5da67c40eb | ||
|
|
804572c8ff | ||
|
|
ddc4a93c36 | ||
|
|
901579233c | ||
|
|
d27b08bae6 | ||
|
|
485747b892 | ||
|
|
15380f2b5f | ||
|
|
48b1f7c388 | ||
|
|
b26e2d192e | ||
|
|
e6d6450728 | ||
|
|
739205872f | ||
|
|
07210d0c91 | ||
|
|
ee463f6b76 | ||
|
|
800eb3b547 |
No files matched your search
@@ -49,6 +49,9 @@ bun run dev
|
||||
# Desktop development
|
||||
bun run dev:desktop
|
||||
|
||||
# Desktop development on an isolated port set
|
||||
T3CODE_DEV_INSTANCE=feature-xyz bun run dev:desktop
|
||||
|
||||
# Production
|
||||
bun run build
|
||||
bun run start
|
||||
@@ -67,6 +70,16 @@ npx t3
|
||||
- `bun run typecheck` — Strict TypeScript checks for all packages.
|
||||
- `bun run test` — Runs workspace tests.
|
||||
|
||||
### Running multiple dev instances
|
||||
|
||||
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
|
||||
|
||||
- Default ports: server `3773`, web `5173`
|
||||
- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`)
|
||||
- Example: `T3CODE_DEV_INSTANCE=branch-a bun run dev:desktop`
|
||||
|
||||
If you want full control instead of hashing, set `T3CODE_PORT_OFFSET` to a numeric offset.
|
||||
|
||||
## Runtime modes
|
||||
|
||||
T3 Code has a global runtime mode switch in the chat toolbar:
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"type": "module",
|
||||
"main": "./dist/index.mjs",
|
||||
"scripts": {
|
||||
"dev": "VITE_DEV_SERVER_URL=http://localhost:5173 bun run src/index.ts",
|
||||
"dev": "VITE_DEV_SERVER_URL=${VITE_DEV_SERVER_URL:-http://localhost:5173} bun run src/index.ts",
|
||||
"build": "tsdown && node scripts/bundle-client.mjs",
|
||||
"start": "node dist/index.mjs",
|
||||
"typecheck": "tsc --noEmit",
|
||||
|
||||
+108
-5
@@ -2,7 +2,7 @@ import { existsSync } from "node:fs";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
GitCoreService,
|
||||
@@ -51,6 +51,25 @@ async function initRepoWithCommit(cwd: string): Promise<void> {
|
||||
await git(cwd, "commit -m 'initial commit'");
|
||||
}
|
||||
|
||||
async function commitWithDate(
|
||||
cwd: string,
|
||||
fileName: string,
|
||||
fileContents: string,
|
||||
dateIsoString: string,
|
||||
message: string,
|
||||
): Promise<void> {
|
||||
await writeFile(path.join(cwd, fileName), fileContents);
|
||||
await git(cwd, `add ${fileName}`);
|
||||
const commitResult = await runTerminalCommand({
|
||||
command: `GIT_AUTHOR_DATE="${dateIsoString}" GIT_COMMITTER_DATE="${dateIsoString}" git commit -m "${message}"`,
|
||||
cwd,
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
if (commitResult.code !== 0) {
|
||||
throw new Error(`git dated commit failed: ${commitResult.stderr}`);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Tests ──
|
||||
|
||||
describe("git integration", () => {
|
||||
@@ -106,14 +125,82 @@ describe("git integration", () => {
|
||||
expect(current!.current).toBe(true);
|
||||
});
|
||||
|
||||
it("sorts current branch first", async () => {
|
||||
it("keeps current branch first and sorts the remaining branches by recency", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
await createGitBranch({ cwd: tmp.path, branch: "aaa-first-alpha" });
|
||||
await createGitBranch({ cwd: tmp.path, branch: "zzz-last" });
|
||||
const initialBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
|
||||
await createGitBranch({ cwd: tmp.path, branch: "older-branch" });
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: "older-branch" });
|
||||
await commitWithDate(
|
||||
tmp.path,
|
||||
"older.txt",
|
||||
"older branch change\n",
|
||||
"Thu, 1 Jan 2037 00:00:00 +0000",
|
||||
"older branch change",
|
||||
);
|
||||
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: initialBranch });
|
||||
await createGitBranch({ cwd: tmp.path, branch: "newer-branch" });
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: "newer-branch" });
|
||||
await commitWithDate(
|
||||
tmp.path,
|
||||
"newer.txt",
|
||||
"newer branch change\n",
|
||||
"Fri, 1 Jan 2038 00:00:00 +0000",
|
||||
"newer branch change",
|
||||
);
|
||||
|
||||
// Switch away to show current branch is pinned, then remaining branches are recency-sorted.
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: "older-branch" });
|
||||
|
||||
const result = await listGitBranches({ cwd: tmp.path });
|
||||
expect(result.branches[0]!.current).toBe(true);
|
||||
expect(result.branches[0]!.name).toBe("older-branch");
|
||||
expect(result.branches[1]!.name).toBe("newer-branch");
|
||||
});
|
||||
|
||||
it("keeps default branch right after current branch", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await using remote = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
const defaultBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
|
||||
await git(remote.path, "init --bare");
|
||||
await git(tmp.path, `remote add origin ${JSON.stringify(remote.path)}`);
|
||||
await git(tmp.path, `push -u origin ${defaultBranch}`);
|
||||
await git(tmp.path, `remote set-head origin ${defaultBranch}`);
|
||||
|
||||
await createGitBranch({ cwd: tmp.path, branch: "current-branch" });
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: "current-branch" });
|
||||
await commitWithDate(
|
||||
tmp.path,
|
||||
"current.txt",
|
||||
"current change\n",
|
||||
"Thu, 1 Jan 2037 00:00:00 +0000",
|
||||
"current change",
|
||||
);
|
||||
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: defaultBranch });
|
||||
await createGitBranch({ cwd: tmp.path, branch: "newer-branch" });
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: "newer-branch" });
|
||||
await commitWithDate(
|
||||
tmp.path,
|
||||
"newer.txt",
|
||||
"newer change\n",
|
||||
"Fri, 1 Jan 2038 00:00:00 +0000",
|
||||
"newer change",
|
||||
);
|
||||
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: "current-branch" });
|
||||
|
||||
const result = await listGitBranches({ cwd: tmp.path });
|
||||
expect(result.branches[0]!.name).toBe("current-branch");
|
||||
expect(result.branches[1]!.name).toBe(defaultBranch);
|
||||
expect(result.branches[2]!.name).toBe("newer-branch");
|
||||
});
|
||||
|
||||
it("lists multiple branches after creating them", async () => {
|
||||
@@ -516,5 +603,21 @@ describe("git integration", () => {
|
||||
const skipped = await core.pushCurrentBranch(tmp.path, null);
|
||||
expect(skipped.status).toBe("skipped_up_to_date");
|
||||
});
|
||||
|
||||
it("lists branches when recency lookup fails", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
const core = new GitCoreService();
|
||||
const recencySpy = vi
|
||||
.spyOn(core as any, "readBranchRecency")
|
||||
.mockRejectedValueOnce(new Error("timeout"));
|
||||
|
||||
const result = await core.listBranches({ cwd: tmp.path });
|
||||
|
||||
expect(result.isRepo).toBe(true);
|
||||
expect(result.branches.length).toBeGreaterThan(0);
|
||||
expect(result.branches[0]?.current).toBe(true);
|
||||
recencySpy.mockRestore();
|
||||
});
|
||||
});
|
||||
});
|
||||
+42
-3
@@ -312,7 +312,40 @@ export class GitCoreService {
|
||||
return value.length > 0 ? value : null;
|
||||
}
|
||||
|
||||
private async readBranchRecency(cwd: string): Promise<Map<string, number>> {
|
||||
const branchRecency = await executeGit(
|
||||
cwd,
|
||||
["for-each-ref", "--format=%(refname:short)%09%(committerdate:unix)", "refs/heads"],
|
||||
{
|
||||
timeoutMs: 15_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
);
|
||||
|
||||
const branchLastCommit = new Map<string, number>();
|
||||
if (branchRecency.code !== 0) {
|
||||
return branchLastCommit;
|
||||
}
|
||||
|
||||
for (const line of branchRecency.stdout.split("\n")) {
|
||||
if (line.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const [name, lastCommitRaw] = line.split("\t");
|
||||
if (!name) {
|
||||
continue;
|
||||
}
|
||||
const lastCommit = Number.parseInt(lastCommitRaw ?? "0", 10);
|
||||
branchLastCommit.set(name, Number.isFinite(lastCommit) ? lastCommit : 0);
|
||||
}
|
||||
|
||||
return branchLastCommit;
|
||||
}
|
||||
|
||||
async listBranches(input: GitListBranchesInput): Promise<GitListBranchesResult> {
|
||||
const branchRecencyPromise = this.readBranchRecency(input.cwd).catch(
|
||||
() => new Map<string, number>(),
|
||||
);
|
||||
const result = await executeGit(input.cwd, ["branch", "--no-color"], {
|
||||
timeoutMs: 10_000,
|
||||
allowNonZeroExit: true,
|
||||
@@ -326,7 +359,7 @@ export class GitCoreService {
|
||||
throw new Error(stderr || "git branch failed");
|
||||
}
|
||||
|
||||
const [defaultRef, worktreeList] = await Promise.all([
|
||||
const [defaultRef, worktreeList, branchLastCommit] = await Promise.all([
|
||||
executeGit(input.cwd, ["symbolic-ref", "refs/remotes/origin/HEAD"], {
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
@@ -335,6 +368,7 @@ export class GitCoreService {
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
}),
|
||||
branchRecencyPromise,
|
||||
]);
|
||||
const defaultBranch =
|
||||
defaultRef.code === 0
|
||||
@@ -370,8 +404,13 @@ export class GitCoreService {
|
||||
};
|
||||
})
|
||||
.toSorted((a, b) => {
|
||||
if (a.current !== b.current) return a.current ? -1 : 1;
|
||||
if (a.isDefault !== b.isDefault) return a.isDefault ? -1 : 1;
|
||||
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
|
||||
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
|
||||
if (aPriority !== bPriority) return aPriority - bPriority;
|
||||
|
||||
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
|
||||
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
|
||||
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
|
||||
@@ -137,7 +137,11 @@ describe("TerminalManager", () => {
|
||||
|
||||
function makeManager(
|
||||
historyLineLimit = 5,
|
||||
options: { shellResolver?: () => string } = {},
|
||||
options: {
|
||||
shellResolver?: () => string;
|
||||
subprocessChecker?: (terminalPid: number) => Promise<boolean>;
|
||||
subprocessPollIntervalMs?: number;
|
||||
} = {},
|
||||
) {
|
||||
const logsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-terminal-"));
|
||||
tempDirs.push(logsDir);
|
||||
@@ -147,6 +151,10 @@ describe("TerminalManager", () => {
|
||||
ptyAdapter,
|
||||
historyLineLimit,
|
||||
shellResolver: options.shellResolver ?? (() => "/bin/bash"),
|
||||
...(options.subprocessChecker ? { subprocessChecker: options.subprocessChecker } : {}),
|
||||
...(options.subprocessPollIntervalMs
|
||||
? { subprocessPollIntervalMs: options.subprocessPollIntervalMs }
|
||||
: {}),
|
||||
});
|
||||
return { logsDir, ptyAdapter, manager };
|
||||
}
|
||||
@@ -273,6 +281,42 @@ describe("TerminalManager", () => {
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("emits subprocess activity events when child-process state changes", async () => {
|
||||
let hasRunningSubprocess = false;
|
||||
const { manager } = makeManager(5, {
|
||||
subprocessChecker: async () => hasRunningSubprocess,
|
||||
subprocessPollIntervalMs: 20,
|
||||
});
|
||||
const events: TerminalEvent[] = [];
|
||||
manager.on("event", (event) => {
|
||||
events.push(event);
|
||||
});
|
||||
|
||||
await manager.open(openInput());
|
||||
await waitFor(() => events.some((event) => event.type === "started"));
|
||||
expect(events.some((event) => event.type === "activity")).toBe(false);
|
||||
|
||||
hasRunningSubprocess = true;
|
||||
await waitFor(
|
||||
() =>
|
||||
events.some(
|
||||
(event) => event.type === "activity" && event.hasRunningSubprocess === true,
|
||||
),
|
||||
1_200,
|
||||
);
|
||||
|
||||
hasRunningSubprocess = false;
|
||||
await waitFor(
|
||||
() =>
|
||||
events.some(
|
||||
(event) => event.type === "activity" && event.hasRunningSubprocess === false,
|
||||
),
|
||||
1_200,
|
||||
);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("caps persisted history to configured line limit", async () => {
|
||||
const { manager, ptyAdapter } = makeManager(3);
|
||||
await manager.open(openInput());
|
||||
@@ -334,15 +378,18 @@ describe("TerminalManager", () => {
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("loads existing legacy transcript filenames and keeps new naming for writes", async () => {
|
||||
it("migrates legacy transcript filenames to terminal-scoped history path on open", async () => {
|
||||
const { manager, logsDir } = makeManager();
|
||||
const legacyPath = path.join(logsDir, "thread-1.log");
|
||||
const nextPath = historyLogPath(logsDir);
|
||||
fs.writeFileSync(legacyPath, "legacy-line\n", "utf8");
|
||||
|
||||
const snapshot = await manager.open(openInput());
|
||||
|
||||
expect(snapshot.history).toBe("legacy-line\n");
|
||||
expect(fs.existsSync(legacyPath)).toBe(true);
|
||||
expect(fs.existsSync(nextPath)).toBe(true);
|
||||
expect(fs.readFileSync(nextPath, "utf8")).toBe("legacy-line\n");
|
||||
expect(fs.existsSync(legacyPath)).toBe(false);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
@@ -21,9 +21,13 @@ import {
|
||||
|
||||
import { createLogger } from "./logger";
|
||||
import { NodePtyAdapter, type PtyAdapter, type PtyExitEvent, type PtyProcess } from "./ptyAdapter";
|
||||
import { runProcess } from "./processRunner";
|
||||
|
||||
const DEFAULT_HISTORY_LINE_LIMIT = 5_000;
|
||||
const DEFAULT_PERSIST_DEBOUNCE_MS = 40;
|
||||
const DEFAULT_SUBPROCESS_POLL_INTERVAL_MS = 1_000;
|
||||
|
||||
type TerminalSubprocessChecker = (terminalPid: number) => Promise<boolean>;
|
||||
|
||||
export interface TerminalManagerEvents {
|
||||
event: [event: TerminalEvent];
|
||||
@@ -34,6 +38,8 @@ export interface TerminalManagerOptions {
|
||||
historyLineLimit?: number;
|
||||
ptyAdapter?: PtyAdapter;
|
||||
shellResolver?: () => string;
|
||||
subprocessChecker?: TerminalSubprocessChecker;
|
||||
subprocessPollIntervalMs?: number;
|
||||
}
|
||||
|
||||
interface TerminalSessionState {
|
||||
@@ -51,6 +57,7 @@ interface TerminalSessionState {
|
||||
process: PtyProcess | null;
|
||||
unsubscribeData: (() => void) | null;
|
||||
unsubscribeExit: (() => void) | null;
|
||||
hasRunningSubprocess: boolean;
|
||||
}
|
||||
|
||||
function defaultShellResolver(): string {
|
||||
@@ -122,6 +129,83 @@ function isRetryableShellSpawnError(error: unknown): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
async function checkWindowsSubprocessActivity(terminalPid: number): Promise<boolean> {
|
||||
const command = [
|
||||
`$children = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${terminalPid}" -ErrorAction SilentlyContinue`,
|
||||
"if ($children) { exit 0 }",
|
||||
"exit 1",
|
||||
].join("; ");
|
||||
try {
|
||||
const result = await runProcess(
|
||||
"powershell.exe",
|
||||
["-NoProfile", "-NonInteractive", "-Command", command],
|
||||
{
|
||||
timeoutMs: 1_500,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: 32_768,
|
||||
outputMode: "truncate",
|
||||
},
|
||||
);
|
||||
return result.code === 0;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function checkPosixSubprocessActivity(terminalPid: number): Promise<boolean> {
|
||||
try {
|
||||
const pgrepResult = await runProcess("pgrep", ["-P", String(terminalPid)], {
|
||||
timeoutMs: 1_000,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: 32_768,
|
||||
outputMode: "truncate",
|
||||
});
|
||||
if (pgrepResult.code === 0) {
|
||||
return pgrepResult.stdout.trim().length > 0;
|
||||
}
|
||||
if (pgrepResult.code === 1) {
|
||||
return false;
|
||||
}
|
||||
} catch {
|
||||
// Fall back to ps when pgrep is unavailable.
|
||||
}
|
||||
|
||||
try {
|
||||
const psResult = await runProcess("ps", ["-eo", "pid=,ppid="], {
|
||||
timeoutMs: 1_000,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: 262_144,
|
||||
outputMode: "truncate",
|
||||
});
|
||||
if (psResult.code !== 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (const line of psResult.stdout.split(/\r?\n/g)) {
|
||||
const [pidRaw, ppidRaw] = line.trim().split(/\s+/g);
|
||||
const pid = Number(pidRaw);
|
||||
const ppid = Number(ppidRaw);
|
||||
if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;
|
||||
if (ppid === terminalPid) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function defaultSubprocessChecker(terminalPid: number): Promise<boolean> {
|
||||
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
|
||||
return false;
|
||||
}
|
||||
if (process.platform === "win32") {
|
||||
return checkWindowsSubprocessActivity(terminalPid);
|
||||
}
|
||||
return checkPosixSubprocessActivity(terminalPid);
|
||||
}
|
||||
|
||||
function capHistory(history: string, maxLines: number): string {
|
||||
if (history.length === 0) return history;
|
||||
const hasTrailingNewline = history.endsWith("\n");
|
||||
@@ -161,6 +245,10 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
private readonly pendingPersistHistory = new Map<string, string>();
|
||||
private readonly threadLocks = new Map<string, Promise<void>>();
|
||||
private readonly persistDebounceMs: number;
|
||||
private readonly subprocessChecker: TerminalSubprocessChecker;
|
||||
private readonly subprocessPollIntervalMs: number;
|
||||
private subprocessPollTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private subprocessPollInFlight = false;
|
||||
private readonly logger = createLogger("terminal");
|
||||
|
||||
constructor(options: TerminalManagerOptions = {}) {
|
||||
@@ -170,6 +258,9 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
this.ptyAdapter = options.ptyAdapter ?? new NodePtyAdapter();
|
||||
this.shellResolver = options.shellResolver ?? defaultShellResolver;
|
||||
this.persistDebounceMs = DEFAULT_PERSIST_DEBOUNCE_MS;
|
||||
this.subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker;
|
||||
this.subprocessPollIntervalMs =
|
||||
options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;
|
||||
fs.mkdirSync(this.logsDir, { recursive: true });
|
||||
}
|
||||
|
||||
@@ -198,6 +289,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
process: null,
|
||||
unsubscribeData: null,
|
||||
unsubscribeExit: null,
|
||||
hasRunningSubprocess: false,
|
||||
};
|
||||
this.sessions.set(sessionKey, session);
|
||||
this.startSession(session, input, "started");
|
||||
@@ -294,6 +386,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
process: null,
|
||||
unsubscribeData: null,
|
||||
unsubscribeExit: null,
|
||||
hasRunningSubprocess: false,
|
||||
};
|
||||
this.sessions.set(sessionKey, session);
|
||||
} else {
|
||||
@@ -334,14 +427,17 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
if (input.deleteHistory) {
|
||||
await this.deleteAllHistoryForThread(input.threadId);
|
||||
}
|
||||
this.updateSubprocessPollingState();
|
||||
});
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
for (const session of this.sessions.values()) {
|
||||
this.stopSubprocessPolling();
|
||||
const sessions = [...this.sessions.values()];
|
||||
this.sessions.clear();
|
||||
for (const session of sessions) {
|
||||
this.stopProcess(session);
|
||||
}
|
||||
this.sessions.clear();
|
||||
for (const timer of this.persistTimers.values()) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
@@ -364,6 +460,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
session.rows = input.rows;
|
||||
session.exitCode = null;
|
||||
session.exitSignal = null;
|
||||
session.hasRunningSubprocess = false;
|
||||
session.updatedAt = new Date().toISOString();
|
||||
|
||||
let ptyProcess: PtyProcess | null = null;
|
||||
@@ -413,6 +510,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
session.unsubscribeExit = ptyProcess.onExit((event) => {
|
||||
this.onProcessExit(session, event);
|
||||
});
|
||||
this.updateSubprocessPollingState();
|
||||
this.emitEvent({
|
||||
type: eventType,
|
||||
threadId: session.threadId,
|
||||
@@ -431,7 +529,9 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
session.status = "error";
|
||||
session.pid = null;
|
||||
session.process = null;
|
||||
session.hasRunningSubprocess = false;
|
||||
session.updatedAt = new Date().toISOString();
|
||||
this.updateSubprocessPollingState();
|
||||
const message = error instanceof Error ? error.message : "Terminal start failed";
|
||||
this.emitEvent({
|
||||
type: "error",
|
||||
@@ -466,6 +566,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
this.cleanupProcessHandles(session);
|
||||
session.process = null;
|
||||
session.pid = null;
|
||||
session.hasRunningSubprocess = false;
|
||||
session.status = "exited";
|
||||
session.exitCode = Number.isInteger(event.exitCode) ? event.exitCode : null;
|
||||
session.exitSignal = Number.isInteger(event.signal) ? event.signal : null;
|
||||
@@ -478,6 +579,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
exitCode: session.exitCode,
|
||||
exitSignal: session.exitSignal,
|
||||
});
|
||||
this.updateSubprocessPollingState();
|
||||
}
|
||||
|
||||
private stopProcess(session: TerminalSessionState): void {
|
||||
@@ -486,6 +588,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
this.cleanupProcessHandles(session);
|
||||
session.process = null;
|
||||
session.pid = null;
|
||||
session.hasRunningSubprocess = false;
|
||||
session.status = "exited";
|
||||
session.updatedAt = new Date().toISOString();
|
||||
try {
|
||||
@@ -498,6 +601,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
error: message,
|
||||
});
|
||||
}
|
||||
this.updateSubprocessPollingState();
|
||||
}
|
||||
|
||||
private cleanupProcessHandles(session: TerminalSessionState): void {
|
||||
@@ -582,12 +686,12 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
}
|
||||
|
||||
private async readHistory(threadId: string, terminalId: string): Promise<string> {
|
||||
const historyPath = this.historyPath(threadId, terminalId);
|
||||
const nextPath = this.historyPath(threadId, terminalId);
|
||||
try {
|
||||
const raw = await fs.promises.readFile(historyPath, "utf8");
|
||||
const raw = await fs.promises.readFile(nextPath, "utf8");
|
||||
const capped = capHistory(raw, this.historyLineLimit);
|
||||
if (capped !== raw) {
|
||||
await fs.promises.writeFile(historyPath, capped, "utf8");
|
||||
await fs.promises.writeFile(nextPath, capped, "utf8");
|
||||
}
|
||||
return capped;
|
||||
} catch (error) {
|
||||
@@ -600,12 +704,22 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
return "";
|
||||
}
|
||||
|
||||
const legacyPath = this.legacyHistoryPath(threadId);
|
||||
try {
|
||||
const raw = await fs.promises.readFile(this.legacyHistoryPath(threadId), "utf8");
|
||||
const raw = await fs.promises.readFile(legacyPath, "utf8");
|
||||
const capped = capHistory(raw, this.historyLineLimit);
|
||||
if (capped !== raw) {
|
||||
await fs.promises.writeFile(this.legacyHistoryPath(threadId), capped, "utf8");
|
||||
|
||||
// Migrate legacy transcript filename to the terminal-scoped path.
|
||||
await fs.promises.writeFile(nextPath, capped, "utf8");
|
||||
try {
|
||||
await fs.promises.rm(legacyPath, { force: true });
|
||||
} catch (cleanupError) {
|
||||
this.logger.warn("failed to remove legacy terminal history", {
|
||||
threadId,
|
||||
error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError),
|
||||
});
|
||||
}
|
||||
|
||||
return capped;
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
||||
@@ -650,6 +764,86 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
}
|
||||
}
|
||||
|
||||
private updateSubprocessPollingState(): void {
|
||||
const hasRunningSessions = [...this.sessions.values()].some(
|
||||
(session) => session.status === "running" && session.pid !== null,
|
||||
);
|
||||
if (hasRunningSessions) {
|
||||
this.ensureSubprocessPolling();
|
||||
return;
|
||||
}
|
||||
this.stopSubprocessPolling();
|
||||
}
|
||||
|
||||
private ensureSubprocessPolling(): void {
|
||||
if (this.subprocessPollTimer) return;
|
||||
this.subprocessPollTimer = setInterval(() => {
|
||||
void this.pollSubprocessActivity();
|
||||
}, this.subprocessPollIntervalMs);
|
||||
this.subprocessPollTimer.unref?.();
|
||||
void this.pollSubprocessActivity();
|
||||
}
|
||||
|
||||
private stopSubprocessPolling(): void {
|
||||
if (!this.subprocessPollTimer) return;
|
||||
clearInterval(this.subprocessPollTimer);
|
||||
this.subprocessPollTimer = null;
|
||||
}
|
||||
|
||||
private async pollSubprocessActivity(): Promise<void> {
|
||||
if (this.subprocessPollInFlight) return;
|
||||
|
||||
const runningSessions = [...this.sessions.values()].filter(
|
||||
(session): session is TerminalSessionState & { pid: number } =>
|
||||
session.status === "running" && Number.isInteger(session.pid),
|
||||
);
|
||||
if (runningSessions.length === 0) {
|
||||
this.stopSubprocessPolling();
|
||||
return;
|
||||
}
|
||||
|
||||
this.subprocessPollInFlight = true;
|
||||
try {
|
||||
await Promise.all(
|
||||
runningSessions.map(async (session) => {
|
||||
const terminalPid = session.pid;
|
||||
let hasRunningSubprocess = false;
|
||||
try {
|
||||
hasRunningSubprocess = await this.subprocessChecker(terminalPid);
|
||||
} catch (error) {
|
||||
this.logger.warn("failed to check terminal subprocess activity", {
|
||||
threadId: session.threadId,
|
||||
terminalId: session.terminalId,
|
||||
terminalPid,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const liveSession = this.sessions.get(toSessionKey(session.threadId, session.terminalId));
|
||||
if (!liveSession || liveSession.status !== "running" || liveSession.pid !== terminalPid) {
|
||||
return;
|
||||
}
|
||||
if (liveSession.hasRunningSubprocess === hasRunningSubprocess) {
|
||||
return;
|
||||
}
|
||||
|
||||
liveSession.hasRunningSubprocess = hasRunningSubprocess;
|
||||
liveSession.updatedAt = new Date().toISOString();
|
||||
this.emitEvent({
|
||||
type: "activity",
|
||||
threadId: liveSession.threadId,
|
||||
terminalId: liveSession.terminalId,
|
||||
createdAt: new Date().toISOString(),
|
||||
hasRunningSubprocess,
|
||||
});
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
this.subprocessPollInFlight = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async assertValidCwd(cwd: string): Promise<void> {
|
||||
let stats: fs.Stats;
|
||||
try {
|
||||
@@ -676,6 +870,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
this.stopProcess(session);
|
||||
this.sessions.delete(key);
|
||||
}
|
||||
this.updateSubprocessPollingState();
|
||||
await this.flushPersistQueue(threadId, terminalId);
|
||||
if (deleteHistory) {
|
||||
await this.deleteHistory(threadId, terminalId);
|
||||
|
||||
@@ -27,6 +27,16 @@ function EventRouter() {
|
||||
});
|
||||
}, [api, dispatch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!api) return;
|
||||
return api.terminal.onEvent((event) => {
|
||||
dispatch({
|
||||
type: "APPLY_TERMINAL_EVENT",
|
||||
event,
|
||||
});
|
||||
});
|
||||
}, [api, dispatch]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -82,6 +92,7 @@ function AutoProjectBootstrap() {
|
||||
terminalOpen: false,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
|
||||
@@ -263,12 +263,23 @@ export default function ChatView() {
|
||||
const toggleTerminalVisibility = useCallback(() => {
|
||||
if (!activeThreadId) return;
|
||||
const isOpen = Boolean(activeThread?.terminalOpen);
|
||||
|
||||
if (isOpen && api) {
|
||||
if (typeof api.terminal.close === "function") {
|
||||
void api.terminal.close({ threadId: activeThreadId }).catch(() => {
|
||||
void api.terminal.write({ threadId: activeThreadId, data: "exit\n" }).catch(() => undefined);
|
||||
});
|
||||
} else {
|
||||
void api.terminal.write({ threadId: activeThreadId, data: "exit\n" }).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
dispatch({
|
||||
type: "SET_THREAD_TERMINAL_OPEN",
|
||||
threadId: activeThreadId,
|
||||
open: !isOpen,
|
||||
});
|
||||
}, [activeThread?.terminalOpen, activeThreadId, dispatch]);
|
||||
}, [activeThread?.terminalOpen, activeThreadId, api, dispatch]);
|
||||
const splitTerminal = useCallback(() => {
|
||||
if (!activeThreadId) return;
|
||||
dispatch({
|
||||
@@ -303,21 +314,13 @@ export default function ChatView() {
|
||||
(terminalId: string) => {
|
||||
if (!activeThreadId || !api) return;
|
||||
const fallbackExitWrite = () =>
|
||||
api.terminal
|
||||
.write({ threadId: activeThreadId, terminalId, data: "exit\n" })
|
||||
.catch(() => undefined);
|
||||
const fallbackClearAndExit = () =>
|
||||
api.terminal
|
||||
.clear({ threadId: activeThreadId, terminalId })
|
||||
.catch(() => undefined)
|
||||
.then(() => fallbackExitWrite())
|
||||
.catch(() => undefined);
|
||||
api.terminal.write({ threadId: activeThreadId, terminalId, data: "exit\n" }).catch(() => undefined);
|
||||
if ("close" in api.terminal && typeof api.terminal.close === "function") {
|
||||
void api.terminal
|
||||
.close({ threadId: activeThreadId, terminalId, deleteHistory: true })
|
||||
.catch(() => fallbackClearAndExit());
|
||||
.close({ threadId: activeThreadId, terminalId })
|
||||
.catch(() => fallbackExitWrite());
|
||||
} else {
|
||||
void fallbackClearAndExit();
|
||||
void fallbackExitWrite();
|
||||
}
|
||||
dispatch({
|
||||
type: "CLOSE_THREAD_TERMINAL",
|
||||
|
||||
@@ -9,7 +9,7 @@ export const GitHubIcon: Icon = (props) => (
|
||||
clipRule="evenodd"
|
||||
d="M8 0C3.58 0 0 3.58 0 8C0 11.54 2.29 14.53 5.47 15.59C5.87 15.66 6.02 15.42 6.02 15.21C6.02 15.02 6.01 14.39 6.01 13.72C4 14.09 3.48 13.23 3.32 12.78C3.23 12.55 2.84 11.84 2.5 11.65C2.22 11.5 1.82 11.13 2.49 11.12C3.12 11.11 3.57 11.7 3.72 11.94C4.44 13.15 5.59 12.81 6.05 12.6C6.12 12.08 6.33 11.73 6.56 11.53C4.78 11.33 2.92 10.64 2.92 7.58C2.92 6.71 3.23 5.99 3.74 5.43C3.66 5.23 3.38 4.41 3.82 3.31C3.82 3.31 4.49 3.1 6.02 4.13C6.66 3.95 7.34 3.86 8.02 3.86C8.7 3.86 9.38 3.95 10.02 4.13C11.55 3.09 12.22 3.31 12.22 3.31C12.66 4.41 12.38 5.23 12.3 5.43C12.81 5.99 13.12 6.7 13.12 7.58C13.12 10.65 11.25 11.33 9.47 11.53C9.76 11.78 10.01 12.26 10.01 13.01C10.01 14.08 10 14.94 10 15.21C10 15.42 10.15 15.67 10.55 15.59C13.71 14.53 16 11.53 16 8C16 3.58 12.42 0 8 0Z"
|
||||
transform="scale(64)"
|
||||
fill="#1B1F23"
|
||||
fill="currentColor"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
@@ -1,4 +1,4 @@
|
||||
import { MonitorIcon, MoonIcon, SunIcon } from "lucide-react";
|
||||
import { MonitorIcon, MoonIcon, SunIcon, TerminalIcon } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { isElectron } from "../env";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
@@ -38,6 +38,12 @@ interface ThreadStatusPill {
|
||||
pulse: boolean;
|
||||
}
|
||||
|
||||
interface TerminalStatusIndicator {
|
||||
label: "Terminal process running";
|
||||
colorClass: string;
|
||||
pulse: boolean;
|
||||
}
|
||||
|
||||
function hasUnseenCompletion(thread: Thread): boolean {
|
||||
if (!thread.latestTurnCompletedAt) return false;
|
||||
const completedAt = Date.parse(thread.latestTurnCompletedAt);
|
||||
@@ -89,6 +95,17 @@ function threadStatusPill(thread: Thread, hasPendingApprovals: boolean): ThreadS
|
||||
return null;
|
||||
}
|
||||
|
||||
function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null {
|
||||
if (thread.runningTerminalIds.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
label: "Terminal process running",
|
||||
colorClass: "text-teal-600 dark:text-teal-300/90",
|
||||
pulse: true,
|
||||
};
|
||||
}
|
||||
|
||||
export default function Sidebar() {
|
||||
const { state, dispatch } = useStore();
|
||||
const api = useNativeApi();
|
||||
@@ -118,6 +135,7 @@ export default function Sidebar() {
|
||||
terminalOpen: false,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
@@ -388,6 +406,7 @@ export default function Sidebar() {
|
||||
thread,
|
||||
pendingApprovalByThreadId.get(thread.id) === true,
|
||||
);
|
||||
const terminalStatus = terminalStatusIndicator(thread);
|
||||
return (
|
||||
<button
|
||||
key={thread.id}
|
||||
@@ -426,9 +445,23 @@ export default function Sidebar() {
|
||||
)}
|
||||
<span className="min-w-0 flex-1 truncate text-xs">{thread.title}</span>
|
||||
</div>
|
||||
<span className="shrink-0 text-[10px] text-muted-foreground/40">
|
||||
{formatRelativeTime(thread.createdAt)}
|
||||
</span>
|
||||
<div className="ml-2 flex shrink-0 items-center gap-1.5">
|
||||
{terminalStatus && (
|
||||
<span
|
||||
role="img"
|
||||
aria-label={terminalStatus.label}
|
||||
title={terminalStatus.label}
|
||||
className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
|
||||
>
|
||||
<TerminalIcon
|
||||
className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`}
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
<span className="text-[10px] text-muted-foreground/40">
|
||||
{formatRelativeTime(thread.createdAt)}
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -278,6 +278,7 @@ describe("toPersistedState", () => {
|
||||
terminalOpen: true,
|
||||
terminalHeight: 320,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: "term-2",
|
||||
terminalGroups: [
|
||||
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
|
||||
|
||||
@@ -243,6 +243,7 @@ function hydrateThread(
|
||||
terminalOpen: thread.terminalOpen ?? false,
|
||||
terminalHeight: thread.terminalHeight ?? DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: safeTerminalIds,
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId,
|
||||
terminalGroups: normalizedGroups,
|
||||
activeTerminalGroupId,
|
||||
|
||||
+108
-1
@@ -1,10 +1,13 @@
|
||||
import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
|
||||
import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { type AppState, reducer } from "./store";
|
||||
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
|
||||
import type { Thread } from "./types";
|
||||
|
||||
type TerminalStartedEvent = Extract<TerminalEvent, { type: "started" }>;
|
||||
type TerminalActivityEvent = Extract<TerminalEvent, { type: "activity" }>;
|
||||
|
||||
function makeSession(overrides: Partial<ProviderSession> = {}): ProviderSession {
|
||||
return {
|
||||
sessionId: "sess-1",
|
||||
@@ -38,6 +41,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
terminalOpen: false,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
@@ -75,6 +79,42 @@ function makeState(thread: Thread): AppState {
|
||||
};
|
||||
}
|
||||
|
||||
function makeTerminalStartedEvent(
|
||||
overrides: Partial<TerminalStartedEvent> = {},
|
||||
): TerminalStartedEvent {
|
||||
return {
|
||||
type: "started",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
createdAt: "2026-02-09T00:00:01.000Z",
|
||||
snapshot: {
|
||||
threadId: "thread-local-1",
|
||||
terminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
cwd: "/tmp/project",
|
||||
status: "running",
|
||||
pid: 1234,
|
||||
history: "",
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: "2026-02-09T00:00:01.000Z",
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeTerminalActivityEvent(
|
||||
overrides: Partial<TerminalActivityEvent> = {},
|
||||
): TerminalActivityEvent {
|
||||
return {
|
||||
type: "activity",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
createdAt: "2026-02-09T00:00:02.000Z",
|
||||
hasRunningSubprocess: true,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("store reducer thread continuity", () => {
|
||||
it("stores codexThreadId from UPDATE_SESSION", () => {
|
||||
const state = makeState(
|
||||
@@ -255,6 +295,7 @@ describe("store reducer thread continuity", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalOpen: true,
|
||||
runningTerminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
}),
|
||||
);
|
||||
const next = reducer(state, {
|
||||
@@ -265,6 +306,7 @@ describe("store reducer thread continuity", () => {
|
||||
|
||||
expect(next.threads[0]?.terminalOpen).toBe(false);
|
||||
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
|
||||
expect(next.threads[0]?.runningTerminalIds).toEqual([]);
|
||||
expect(next.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
|
||||
expect(next.threads[0]?.terminalGroups).toEqual([
|
||||
{
|
||||
@@ -274,6 +316,71 @@ describe("store reducer thread continuity", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("tracks running terminals from subprocess activity events", () => {
|
||||
const state = makeState(makeThread());
|
||||
const started = reducer(state, {
|
||||
type: "APPLY_TERMINAL_EVENT",
|
||||
event: makeTerminalStartedEvent(),
|
||||
});
|
||||
expect(started.threads[0]?.runningTerminalIds).toEqual([]);
|
||||
|
||||
const active = reducer(started, {
|
||||
type: "APPLY_TERMINAL_EVENT",
|
||||
event: makeTerminalActivityEvent(),
|
||||
});
|
||||
expect(active.threads[0]?.runningTerminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
|
||||
|
||||
const idle = reducer(active, {
|
||||
type: "APPLY_TERMINAL_EVENT",
|
||||
event: makeTerminalActivityEvent({ hasRunningSubprocess: false }),
|
||||
});
|
||||
expect(idle.threads[0]?.runningTerminalIds).toEqual([]);
|
||||
|
||||
const exited = reducer(active, {
|
||||
type: "APPLY_TERMINAL_EVENT",
|
||||
event: {
|
||||
type: "exited",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
createdAt: "2026-02-09T00:00:05.000Z",
|
||||
exitCode: 0,
|
||||
exitSignal: null,
|
||||
},
|
||||
});
|
||||
expect(exited.threads[0]?.runningTerminalIds).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps running status when another terminal in the thread is still running", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
runningTerminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
activeTerminalId: "term-2",
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
}),
|
||||
);
|
||||
|
||||
const next = reducer(state, {
|
||||
type: "APPLY_TERMINAL_EVENT",
|
||||
event: {
|
||||
type: "exited",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
createdAt: "2026-02-09T00:00:07.000Z",
|
||||
exitCode: 0,
|
||||
exitSignal: null,
|
||||
},
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.runningTerminalIds).toEqual(["term-2"]);
|
||||
});
|
||||
|
||||
it("backfills codexThreadId from routed provider events", () => {
|
||||
const state = makeState(makeThread({ codexThreadId: null }));
|
||||
const next = reducer(state, {
|
||||
|
||||
+47
-1
@@ -8,7 +8,7 @@ import {
|
||||
useReducer,
|
||||
} from "react";
|
||||
|
||||
import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
|
||||
import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/contracts";
|
||||
import { resolveModelSlug } from "./model-logic";
|
||||
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
|
||||
import { applyEventToMessages, asObject, asString, evolveSession } from "./session-logic";
|
||||
@@ -43,6 +43,7 @@ type Action =
|
||||
event: ProviderEvent;
|
||||
activeAssistantItemRef: { current: string | null };
|
||||
}
|
||||
| { type: "APPLY_TERMINAL_EVENT"; event: TerminalEvent }
|
||||
| { type: "UPDATE_SESSION"; threadId: string; session: ProviderSession }
|
||||
| {
|
||||
type: "PUSH_USER_MESSAGE";
|
||||
@@ -149,6 +150,17 @@ function normalizeTerminalIds(terminalIds: string[]): string[] {
|
||||
return [DEFAULT_THREAD_TERMINAL_ID];
|
||||
}
|
||||
|
||||
function normalizeRunningTerminalIds(
|
||||
runningTerminalIds: string[],
|
||||
terminalIds: string[],
|
||||
): string[] {
|
||||
if (runningTerminalIds.length === 0) return [];
|
||||
const validTerminalIdSet = new Set(terminalIds);
|
||||
return [...new Set(runningTerminalIds)]
|
||||
.map((id) => id.trim())
|
||||
.filter((id) => id.length > 0 && validTerminalIdSet.has(id));
|
||||
}
|
||||
|
||||
function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
|
||||
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
|
||||
}
|
||||
@@ -252,6 +264,7 @@ function normalizeThreadTerminals(thread: Thread): Thread {
|
||||
return {
|
||||
...thread,
|
||||
terminalIds,
|
||||
runningTerminalIds: normalizeRunningTerminalIds(thread.runningTerminalIds, terminalIds),
|
||||
activeTerminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId,
|
||||
@@ -269,6 +282,7 @@ function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
|
||||
...thread,
|
||||
terminalOpen: false,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
@@ -309,6 +323,7 @@ function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
|
||||
return normalizeThreadTerminals({
|
||||
...thread,
|
||||
terminalIds: remainingTerminalIds,
|
||||
runningTerminalIds: thread.runningTerminalIds.filter((id) => id !== terminalId),
|
||||
activeTerminalId: nextActiveTerminalId,
|
||||
terminalGroups: nextTerminalGroups,
|
||||
});
|
||||
@@ -650,6 +665,37 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
case "TOGGLE_DIFF":
|
||||
return { ...state, diffOpen: !state.diffOpen };
|
||||
|
||||
case "APPLY_TERMINAL_EVENT":
|
||||
if (!state.threads.some((thread) => thread.id === action.event.threadId)) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.event.threadId, (thread) => {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
const runningTerminalIdSet = new Set(normalizedThread.runningTerminalIds);
|
||||
if (
|
||||
action.event.type === "started" ||
|
||||
action.event.type === "restarted"
|
||||
) {
|
||||
runningTerminalIdSet.delete(action.event.terminalId);
|
||||
} else if (action.event.type === "activity") {
|
||||
if (action.event.hasRunningSubprocess) {
|
||||
runningTerminalIdSet.add(action.event.terminalId);
|
||||
} else {
|
||||
runningTerminalIdSet.delete(action.event.terminalId);
|
||||
}
|
||||
} else if (action.event.type === "exited" || action.event.type === "error") {
|
||||
runningTerminalIdSet.delete(action.event.terminalId);
|
||||
}
|
||||
|
||||
return normalizeThreadTerminals({
|
||||
...normalizedThread,
|
||||
runningTerminalIds: [...runningTerminalIdSet],
|
||||
});
|
||||
}),
|
||||
};
|
||||
|
||||
case "APPLY_EVENT": {
|
||||
const { event, activeAssistantItemRef } = action;
|
||||
const target = findThreadBySessionId(state.threads, event.sessionId);
|
||||
|
||||
@@ -48,6 +48,7 @@ export interface Thread {
|
||||
terminalOpen: boolean;
|
||||
terminalHeight: number;
|
||||
terminalIds: string[];
|
||||
runningTerminalIds: string[];
|
||||
activeTerminalId: string;
|
||||
terminalGroups: ThreadTerminalGroup[];
|
||||
activeTerminalGroupId: string;
|
||||
|
||||
+4
-4
@@ -6,10 +6,10 @@
|
||||
"packages/*"
|
||||
],
|
||||
"scripts": {
|
||||
"dev": "T3CODE_LOG_WS_EVENTS=1 VITE_WS_URL=ws://localhost:3773 turbo run dev --ui=tui --filter=@t3tools/contracts --filter=@t3tools/web --filter=t3 --parallel",
|
||||
"dev:server": "turbo run dev --filter=t3",
|
||||
"dev:web": "VITE_WS_URL=ws://localhost:3773 turbo run dev --filter=@t3tools/web",
|
||||
"dev:desktop": "turbo run dev --filter=@t3tools/desktop --filter=@t3tools/web --parallel",
|
||||
"dev": "bun run scripts/dev-runner.mjs dev",
|
||||
"dev:server": "bun run scripts/dev-runner.mjs dev:server",
|
||||
"dev:web": "bun run scripts/dev-runner.mjs dev:web",
|
||||
"dev:desktop": "bun run scripts/dev-runner.mjs dev:desktop",
|
||||
"start": "turbo run start --filter=t3",
|
||||
"start:desktop": "turbo run start --filter=@t3tools/desktop",
|
||||
"build": "turbo run build",
|
||||
|
||||
@@ -139,4 +139,15 @@ describe("terminalEventSchema", () => {
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts activity events", () => {
|
||||
const result = terminalEventSchema.safeParse({
|
||||
type: "activity",
|
||||
threadId: "thread-1",
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
createdAt: new Date().toISOString(),
|
||||
hasRunningSubprocess: true,
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -91,6 +91,11 @@ export const terminalRestartedEventSchema = terminalEventBaseSchema.extend({
|
||||
snapshot: terminalSessionSnapshotSchema,
|
||||
});
|
||||
|
||||
export const terminalActivityEventSchema = terminalEventBaseSchema.extend({
|
||||
type: z.literal("activity"),
|
||||
hasRunningSubprocess: z.boolean(),
|
||||
});
|
||||
|
||||
export const terminalEventSchema = z.discriminatedUnion("type", [
|
||||
terminalStartedEventSchema,
|
||||
terminalOutputEventSchema,
|
||||
@@ -98,6 +103,7 @@ export const terminalEventSchema = z.discriminatedUnion("type", [
|
||||
terminalErrorEventSchema,
|
||||
terminalClearedEventSchema,
|
||||
terminalRestartedEventSchema,
|
||||
terminalActivityEventSchema,
|
||||
]);
|
||||
|
||||
export type TerminalThreadInput = z.input<typeof terminalThreadInputSchema>;
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
const BASE_SERVER_PORT = 3773;
|
||||
const BASE_WEB_PORT = 5173;
|
||||
const MAX_HASH_OFFSET = 3000;
|
||||
const MODE_ARGS = {
|
||||
dev: [
|
||||
"run",
|
||||
"dev",
|
||||
"--ui=tui",
|
||||
"--filter=@t3tools/contracts",
|
||||
"--filter=@t3tools/web",
|
||||
"--filter=t3",
|
||||
"--parallel",
|
||||
],
|
||||
"dev:server": ["run", "dev", "--filter=t3"],
|
||||
"dev:web": ["run", "dev", "--filter=@t3tools/web"],
|
||||
"dev:desktop": ["run", "dev", "--filter=@t3tools/desktop", "--filter=@t3tools/web", "--parallel"],
|
||||
};
|
||||
|
||||
function parseInteger(value, envName) {
|
||||
const parsed = Number(value);
|
||||
if (!Number.isInteger(parsed)) {
|
||||
throw new Error(`Invalid ${envName}: ${value}`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function hashSeed(seed) {
|
||||
let hash = 0x811c9dc5;
|
||||
for (let i = 0; i < seed.length; i += 1) {
|
||||
hash ^= seed.charCodeAt(i);
|
||||
hash = Math.imul(hash, 0x01000193);
|
||||
}
|
||||
return hash >>> 0;
|
||||
}
|
||||
|
||||
function resolveOffset() {
|
||||
const explicitOffset = process.env.T3CODE_PORT_OFFSET?.trim();
|
||||
if (explicitOffset) {
|
||||
const parsed = parseInteger(explicitOffset, "T3CODE_PORT_OFFSET");
|
||||
if (parsed < 0) {
|
||||
throw new Error(`Invalid T3CODE_PORT_OFFSET: ${explicitOffset}`);
|
||||
}
|
||||
return { offset: parsed, source: `T3CODE_PORT_OFFSET=${explicitOffset}` };
|
||||
}
|
||||
|
||||
const seed = process.env.T3CODE_DEV_INSTANCE?.trim();
|
||||
if (!seed) {
|
||||
return { offset: 0, source: "default ports" };
|
||||
}
|
||||
|
||||
if (/^\d+$/.test(seed)) {
|
||||
return { offset: Number(seed), source: `numeric T3CODE_DEV_INSTANCE=${seed}` };
|
||||
}
|
||||
|
||||
const offset = (hashSeed(seed) % MAX_HASH_OFFSET) + 1;
|
||||
return { offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` };
|
||||
}
|
||||
|
||||
function main() {
|
||||
const mode = process.argv[2];
|
||||
const isDryRun = process.argv.includes("--dry-run");
|
||||
if (!mode || !(mode in MODE_ARGS)) {
|
||||
const supportedModes = Object.keys(MODE_ARGS).join(", ");
|
||||
throw new Error(`Usage: bun scripts/dev-runner.mjs <mode>. Supported modes: ${supportedModes}`);
|
||||
}
|
||||
|
||||
const { offset, source } = resolveOffset();
|
||||
const serverPort = BASE_SERVER_PORT + offset;
|
||||
const webPort = BASE_WEB_PORT + offset;
|
||||
|
||||
if (serverPort > 65535 || webPort > 65535) {
|
||||
throw new Error(
|
||||
`Port offset too large (${offset}). Computed ports: server=${serverPort}, web=${webPort}`,
|
||||
);
|
||||
}
|
||||
|
||||
const env = {
|
||||
...process.env,
|
||||
T3CODE_PORT: String(serverPort),
|
||||
PORT: String(webPort),
|
||||
ELECTRON_RENDERER_PORT: String(webPort),
|
||||
VITE_WS_URL: `ws://localhost:${serverPort}`,
|
||||
VITE_DEV_SERVER_URL: `http://localhost:${webPort}`,
|
||||
};
|
||||
if (mode === "dev" && !env.T3CODE_LOG_WS_EVENTS) {
|
||||
env.T3CODE_LOG_WS_EVENTS = "1";
|
||||
}
|
||||
|
||||
console.info(
|
||||
`[dev-runner] mode=${mode} source=${source} serverPort=${serverPort} webPort=${webPort}`,
|
||||
);
|
||||
|
||||
if (isDryRun) {
|
||||
return;
|
||||
}
|
||||
|
||||
const command = process.platform === "win32" ? "turbo.cmd" : "turbo";
|
||||
const child = spawn(command, MODE_ARGS[mode], {
|
||||
stdio: "inherit",
|
||||
env,
|
||||
});
|
||||
|
||||
child.on("exit", (code, signal) => {
|
||||
if (signal) {
|
||||
process.kill(process.pid, signal);
|
||||
return;
|
||||
}
|
||||
process.exit(code ?? 0);
|
||||
});
|
||||
|
||||
child.on("error", (error) => {
|
||||
console.error("[dev-runner] failed to start turbo", error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
main();
|
||||
} catch (error) {
|
||||
console.error("[dev-runner]", error);
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
"PORT",
|
||||
"VITE_WS_URL",
|
||||
"VITE_DEV_SERVER_URL",
|
||||
"ELECTRON_RENDERER_PORT",
|
||||
"T3CODE_LOG_WS_EVENTS",
|
||||
"T3CODE_MODE",
|
||||
"T3CODE_PORT",
|
||||
|
||||
Reference in new issue
Block a user