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
|
# Desktop development
|
||||||
bun run dev:desktop
|
bun run dev:desktop
|
||||||
|
|
||||||
|
# Desktop development on an isolated port set
|
||||||
|
T3CODE_DEV_INSTANCE=feature-xyz bun run dev:desktop
|
||||||
|
|
||||||
# Production
|
# Production
|
||||||
bun run build
|
bun run build
|
||||||
bun run start
|
bun run start
|
||||||
@@ -67,6 +70,16 @@ npx t3
|
|||||||
- `bun run typecheck` — Strict TypeScript checks for all packages.
|
- `bun run typecheck` — Strict TypeScript checks for all packages.
|
||||||
- `bun run test` — Runs workspace tests.
|
- `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
|
## Runtime modes
|
||||||
|
|
||||||
T3 Code has a global runtime mode switch in the chat toolbar:
|
T3 Code has a global runtime mode switch in the chat toolbar:
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "./dist/index.mjs",
|
"main": "./dist/index.mjs",
|
||||||
"scripts": {
|
"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",
|
"build": "tsdown && node scripts/bundle-client.mjs",
|
||||||
"start": "node dist/index.mjs",
|
"start": "node dist/index.mjs",
|
||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit",
|
||||||
|
|||||||
+108
-5
@@ -2,7 +2,7 @@ import { existsSync } from "node:fs";
|
|||||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||||
import { tmpdir } from "node:os";
|
import { tmpdir } from "node:os";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
GitCoreService,
|
GitCoreService,
|
||||||
@@ -51,6 +51,25 @@ async function initRepoWithCommit(cwd: string): Promise<void> {
|
|||||||
await git(cwd, "commit -m 'initial commit'");
|
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 ──
|
// ── Tests ──
|
||||||
|
|
||||||
describe("git integration", () => {
|
describe("git integration", () => {
|
||||||
@@ -106,14 +125,82 @@ describe("git integration", () => {
|
|||||||
expect(current!.current).toBe(true);
|
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 using tmp = await makeTmpDir();
|
||||||
await initRepoWithCommit(tmp.path);
|
await initRepoWithCommit(tmp.path);
|
||||||
await createGitBranch({ cwd: tmp.path, branch: "aaa-first-alpha" });
|
const initialBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
|
||||||
await createGitBranch({ cwd: tmp.path, branch: "zzz-last" });
|
(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 });
|
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 () => {
|
it("lists multiple branches after creating them", async () => {
|
||||||
@@ -516,5 +603,21 @@ describe("git integration", () => {
|
|||||||
const skipped = await core.pushCurrentBranch(tmp.path, null);
|
const skipped = await core.pushCurrentBranch(tmp.path, null);
|
||||||
expect(skipped.status).toBe("skipped_up_to_date");
|
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;
|
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> {
|
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"], {
|
const result = await executeGit(input.cwd, ["branch", "--no-color"], {
|
||||||
timeoutMs: 10_000,
|
timeoutMs: 10_000,
|
||||||
allowNonZeroExit: true,
|
allowNonZeroExit: true,
|
||||||
@@ -326,7 +359,7 @@ export class GitCoreService {
|
|||||||
throw new Error(stderr || "git branch failed");
|
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"], {
|
executeGit(input.cwd, ["symbolic-ref", "refs/remotes/origin/HEAD"], {
|
||||||
timeoutMs: 5_000,
|
timeoutMs: 5_000,
|
||||||
allowNonZeroExit: true,
|
allowNonZeroExit: true,
|
||||||
@@ -335,6 +368,7 @@ export class GitCoreService {
|
|||||||
timeoutMs: 5_000,
|
timeoutMs: 5_000,
|
||||||
allowNonZeroExit: true,
|
allowNonZeroExit: true,
|
||||||
}),
|
}),
|
||||||
|
branchRecencyPromise,
|
||||||
]);
|
]);
|
||||||
const defaultBranch =
|
const defaultBranch =
|
||||||
defaultRef.code === 0
|
defaultRef.code === 0
|
||||||
@@ -370,8 +404,13 @@ export class GitCoreService {
|
|||||||
};
|
};
|
||||||
})
|
})
|
||||||
.toSorted((a, b) => {
|
.toSorted((a, b) => {
|
||||||
if (a.current !== b.current) return a.current ? -1 : 1;
|
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
|
||||||
if (a.isDefault !== b.isDefault) return a.isDefault ? -1 : 1;
|
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);
|
return a.name.localeCompare(b.name);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -137,7 +137,11 @@ describe("TerminalManager", () => {
|
|||||||
|
|
||||||
function makeManager(
|
function makeManager(
|
||||||
historyLineLimit = 5,
|
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-"));
|
const logsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-terminal-"));
|
||||||
tempDirs.push(logsDir);
|
tempDirs.push(logsDir);
|
||||||
@@ -147,6 +151,10 @@ describe("TerminalManager", () => {
|
|||||||
ptyAdapter,
|
ptyAdapter,
|
||||||
historyLineLimit,
|
historyLineLimit,
|
||||||
shellResolver: options.shellResolver ?? (() => "/bin/bash"),
|
shellResolver: options.shellResolver ?? (() => "/bin/bash"),
|
||||||
|
...(options.subprocessChecker ? { subprocessChecker: options.subprocessChecker } : {}),
|
||||||
|
...(options.subprocessPollIntervalMs
|
||||||
|
? { subprocessPollIntervalMs: options.subprocessPollIntervalMs }
|
||||||
|
: {}),
|
||||||
});
|
});
|
||||||
return { logsDir, ptyAdapter, manager };
|
return { logsDir, ptyAdapter, manager };
|
||||||
}
|
}
|
||||||
@@ -273,6 +281,42 @@ describe("TerminalManager", () => {
|
|||||||
manager.dispose();
|
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 () => {
|
it("caps persisted history to configured line limit", async () => {
|
||||||
const { manager, ptyAdapter } = makeManager(3);
|
const { manager, ptyAdapter } = makeManager(3);
|
||||||
await manager.open(openInput());
|
await manager.open(openInput());
|
||||||
@@ -334,15 +378,18 @@ describe("TerminalManager", () => {
|
|||||||
manager.dispose();
|
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 { manager, logsDir } = makeManager();
|
||||||
const legacyPath = path.join(logsDir, "thread-1.log");
|
const legacyPath = path.join(logsDir, "thread-1.log");
|
||||||
|
const nextPath = historyLogPath(logsDir);
|
||||||
fs.writeFileSync(legacyPath, "legacy-line\n", "utf8");
|
fs.writeFileSync(legacyPath, "legacy-line\n", "utf8");
|
||||||
|
|
||||||
const snapshot = await manager.open(openInput());
|
const snapshot = await manager.open(openInput());
|
||||||
|
|
||||||
expect(snapshot.history).toBe("legacy-line\n");
|
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();
|
manager.dispose();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -21,9 +21,13 @@ import {
|
|||||||
|
|
||||||
import { createLogger } from "./logger";
|
import { createLogger } from "./logger";
|
||||||
import { NodePtyAdapter, type PtyAdapter, type PtyExitEvent, type PtyProcess } from "./ptyAdapter";
|
import { NodePtyAdapter, type PtyAdapter, type PtyExitEvent, type PtyProcess } from "./ptyAdapter";
|
||||||
|
import { runProcess } from "./processRunner";
|
||||||
|
|
||||||
const DEFAULT_HISTORY_LINE_LIMIT = 5_000;
|
const DEFAULT_HISTORY_LINE_LIMIT = 5_000;
|
||||||
const DEFAULT_PERSIST_DEBOUNCE_MS = 40;
|
const DEFAULT_PERSIST_DEBOUNCE_MS = 40;
|
||||||
|
const DEFAULT_SUBPROCESS_POLL_INTERVAL_MS = 1_000;
|
||||||
|
|
||||||
|
type TerminalSubprocessChecker = (terminalPid: number) => Promise<boolean>;
|
||||||
|
|
||||||
export interface TerminalManagerEvents {
|
export interface TerminalManagerEvents {
|
||||||
event: [event: TerminalEvent];
|
event: [event: TerminalEvent];
|
||||||
@@ -34,6 +38,8 @@ export interface TerminalManagerOptions {
|
|||||||
historyLineLimit?: number;
|
historyLineLimit?: number;
|
||||||
ptyAdapter?: PtyAdapter;
|
ptyAdapter?: PtyAdapter;
|
||||||
shellResolver?: () => string;
|
shellResolver?: () => string;
|
||||||
|
subprocessChecker?: TerminalSubprocessChecker;
|
||||||
|
subprocessPollIntervalMs?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface TerminalSessionState {
|
interface TerminalSessionState {
|
||||||
@@ -51,6 +57,7 @@ interface TerminalSessionState {
|
|||||||
process: PtyProcess | null;
|
process: PtyProcess | null;
|
||||||
unsubscribeData: (() => void) | null;
|
unsubscribeData: (() => void) | null;
|
||||||
unsubscribeExit: (() => void) | null;
|
unsubscribeExit: (() => void) | null;
|
||||||
|
hasRunningSubprocess: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
function defaultShellResolver(): string {
|
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 {
|
function capHistory(history: string, maxLines: number): string {
|
||||||
if (history.length === 0) return history;
|
if (history.length === 0) return history;
|
||||||
const hasTrailingNewline = history.endsWith("\n");
|
const hasTrailingNewline = history.endsWith("\n");
|
||||||
@@ -161,6 +245,10 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
private readonly pendingPersistHistory = new Map<string, string>();
|
private readonly pendingPersistHistory = new Map<string, string>();
|
||||||
private readonly threadLocks = new Map<string, Promise<void>>();
|
private readonly threadLocks = new Map<string, Promise<void>>();
|
||||||
private readonly persistDebounceMs: number;
|
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");
|
private readonly logger = createLogger("terminal");
|
||||||
|
|
||||||
constructor(options: TerminalManagerOptions = {}) {
|
constructor(options: TerminalManagerOptions = {}) {
|
||||||
@@ -170,6 +258,9 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
this.ptyAdapter = options.ptyAdapter ?? new NodePtyAdapter();
|
this.ptyAdapter = options.ptyAdapter ?? new NodePtyAdapter();
|
||||||
this.shellResolver = options.shellResolver ?? defaultShellResolver;
|
this.shellResolver = options.shellResolver ?? defaultShellResolver;
|
||||||
this.persistDebounceMs = DEFAULT_PERSIST_DEBOUNCE_MS;
|
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 });
|
fs.mkdirSync(this.logsDir, { recursive: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -198,6 +289,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
process: null,
|
process: null,
|
||||||
unsubscribeData: null,
|
unsubscribeData: null,
|
||||||
unsubscribeExit: null,
|
unsubscribeExit: null,
|
||||||
|
hasRunningSubprocess: false,
|
||||||
};
|
};
|
||||||
this.sessions.set(sessionKey, session);
|
this.sessions.set(sessionKey, session);
|
||||||
this.startSession(session, input, "started");
|
this.startSession(session, input, "started");
|
||||||
@@ -294,6 +386,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
process: null,
|
process: null,
|
||||||
unsubscribeData: null,
|
unsubscribeData: null,
|
||||||
unsubscribeExit: null,
|
unsubscribeExit: null,
|
||||||
|
hasRunningSubprocess: false,
|
||||||
};
|
};
|
||||||
this.sessions.set(sessionKey, session);
|
this.sessions.set(sessionKey, session);
|
||||||
} else {
|
} else {
|
||||||
@@ -334,14 +427,17 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
if (input.deleteHistory) {
|
if (input.deleteHistory) {
|
||||||
await this.deleteAllHistoryForThread(input.threadId);
|
await this.deleteAllHistoryForThread(input.threadId);
|
||||||
}
|
}
|
||||||
|
this.updateSubprocessPollingState();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
dispose(): void {
|
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.stopProcess(session);
|
||||||
}
|
}
|
||||||
this.sessions.clear();
|
|
||||||
for (const timer of this.persistTimers.values()) {
|
for (const timer of this.persistTimers.values()) {
|
||||||
clearTimeout(timer);
|
clearTimeout(timer);
|
||||||
}
|
}
|
||||||
@@ -364,6 +460,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
session.rows = input.rows;
|
session.rows = input.rows;
|
||||||
session.exitCode = null;
|
session.exitCode = null;
|
||||||
session.exitSignal = null;
|
session.exitSignal = null;
|
||||||
|
session.hasRunningSubprocess = false;
|
||||||
session.updatedAt = new Date().toISOString();
|
session.updatedAt = new Date().toISOString();
|
||||||
|
|
||||||
let ptyProcess: PtyProcess | null = null;
|
let ptyProcess: PtyProcess | null = null;
|
||||||
@@ -413,6 +510,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
session.unsubscribeExit = ptyProcess.onExit((event) => {
|
session.unsubscribeExit = ptyProcess.onExit((event) => {
|
||||||
this.onProcessExit(session, event);
|
this.onProcessExit(session, event);
|
||||||
});
|
});
|
||||||
|
this.updateSubprocessPollingState();
|
||||||
this.emitEvent({
|
this.emitEvent({
|
||||||
type: eventType,
|
type: eventType,
|
||||||
threadId: session.threadId,
|
threadId: session.threadId,
|
||||||
@@ -431,7 +529,9 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
session.status = "error";
|
session.status = "error";
|
||||||
session.pid = null;
|
session.pid = null;
|
||||||
session.process = null;
|
session.process = null;
|
||||||
|
session.hasRunningSubprocess = false;
|
||||||
session.updatedAt = new Date().toISOString();
|
session.updatedAt = new Date().toISOString();
|
||||||
|
this.updateSubprocessPollingState();
|
||||||
const message = error instanceof Error ? error.message : "Terminal start failed";
|
const message = error instanceof Error ? error.message : "Terminal start failed";
|
||||||
this.emitEvent({
|
this.emitEvent({
|
||||||
type: "error",
|
type: "error",
|
||||||
@@ -466,6 +566,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
this.cleanupProcessHandles(session);
|
this.cleanupProcessHandles(session);
|
||||||
session.process = null;
|
session.process = null;
|
||||||
session.pid = null;
|
session.pid = null;
|
||||||
|
session.hasRunningSubprocess = false;
|
||||||
session.status = "exited";
|
session.status = "exited";
|
||||||
session.exitCode = Number.isInteger(event.exitCode) ? event.exitCode : null;
|
session.exitCode = Number.isInteger(event.exitCode) ? event.exitCode : null;
|
||||||
session.exitSignal = Number.isInteger(event.signal) ? event.signal : null;
|
session.exitSignal = Number.isInteger(event.signal) ? event.signal : null;
|
||||||
@@ -478,6 +579,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
exitCode: session.exitCode,
|
exitCode: session.exitCode,
|
||||||
exitSignal: session.exitSignal,
|
exitSignal: session.exitSignal,
|
||||||
});
|
});
|
||||||
|
this.updateSubprocessPollingState();
|
||||||
}
|
}
|
||||||
|
|
||||||
private stopProcess(session: TerminalSessionState): void {
|
private stopProcess(session: TerminalSessionState): void {
|
||||||
@@ -486,6 +588,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
this.cleanupProcessHandles(session);
|
this.cleanupProcessHandles(session);
|
||||||
session.process = null;
|
session.process = null;
|
||||||
session.pid = null;
|
session.pid = null;
|
||||||
|
session.hasRunningSubprocess = false;
|
||||||
session.status = "exited";
|
session.status = "exited";
|
||||||
session.updatedAt = new Date().toISOString();
|
session.updatedAt = new Date().toISOString();
|
||||||
try {
|
try {
|
||||||
@@ -498,6 +601,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
error: message,
|
error: message,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
this.updateSubprocessPollingState();
|
||||||
}
|
}
|
||||||
|
|
||||||
private cleanupProcessHandles(session: TerminalSessionState): void {
|
private cleanupProcessHandles(session: TerminalSessionState): void {
|
||||||
@@ -582,12 +686,12 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async readHistory(threadId: string, terminalId: string): Promise<string> {
|
private async readHistory(threadId: string, terminalId: string): Promise<string> {
|
||||||
const historyPath = this.historyPath(threadId, terminalId);
|
const nextPath = this.historyPath(threadId, terminalId);
|
||||||
try {
|
try {
|
||||||
const raw = await fs.promises.readFile(historyPath, "utf8");
|
const raw = await fs.promises.readFile(nextPath, "utf8");
|
||||||
const capped = capHistory(raw, this.historyLineLimit);
|
const capped = capHistory(raw, this.historyLineLimit);
|
||||||
if (capped !== raw) {
|
if (capped !== raw) {
|
||||||
await fs.promises.writeFile(historyPath, capped, "utf8");
|
await fs.promises.writeFile(nextPath, capped, "utf8");
|
||||||
}
|
}
|
||||||
return capped;
|
return capped;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -600,12 +704,22 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const legacyPath = this.legacyHistoryPath(threadId);
|
||||||
try {
|
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);
|
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;
|
return capped;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
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> {
|
private async assertValidCwd(cwd: string): Promise<void> {
|
||||||
let stats: fs.Stats;
|
let stats: fs.Stats;
|
||||||
try {
|
try {
|
||||||
@@ -676,6 +870,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
this.stopProcess(session);
|
this.stopProcess(session);
|
||||||
this.sessions.delete(key);
|
this.sessions.delete(key);
|
||||||
}
|
}
|
||||||
|
this.updateSubprocessPollingState();
|
||||||
await this.flushPersistQueue(threadId, terminalId);
|
await this.flushPersistQueue(threadId, terminalId);
|
||||||
if (deleteHistory) {
|
if (deleteHistory) {
|
||||||
await this.deleteHistory(threadId, terminalId);
|
await this.deleteHistory(threadId, terminalId);
|
||||||
|
|||||||
@@ -27,6 +27,16 @@ function EventRouter() {
|
|||||||
});
|
});
|
||||||
}, [api, dispatch]);
|
}, [api, dispatch]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!api) return;
|
||||||
|
return api.terminal.onEvent((event) => {
|
||||||
|
dispatch({
|
||||||
|
type: "APPLY_TERMINAL_EVENT",
|
||||||
|
event,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}, [api, dispatch]);
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -82,6 +92,7 @@ function AutoProjectBootstrap() {
|
|||||||
terminalOpen: false,
|
terminalOpen: false,
|
||||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||||
|
runningTerminalIds: [],
|
||||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||||
terminalGroups: [
|
terminalGroups: [
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -263,12 +263,23 @@ export default function ChatView() {
|
|||||||
const toggleTerminalVisibility = useCallback(() => {
|
const toggleTerminalVisibility = useCallback(() => {
|
||||||
if (!activeThreadId) return;
|
if (!activeThreadId) return;
|
||||||
const isOpen = Boolean(activeThread?.terminalOpen);
|
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({
|
dispatch({
|
||||||
type: "SET_THREAD_TERMINAL_OPEN",
|
type: "SET_THREAD_TERMINAL_OPEN",
|
||||||
threadId: activeThreadId,
|
threadId: activeThreadId,
|
||||||
open: !isOpen,
|
open: !isOpen,
|
||||||
});
|
});
|
||||||
}, [activeThread?.terminalOpen, activeThreadId, dispatch]);
|
}, [activeThread?.terminalOpen, activeThreadId, api, dispatch]);
|
||||||
const splitTerminal = useCallback(() => {
|
const splitTerminal = useCallback(() => {
|
||||||
if (!activeThreadId) return;
|
if (!activeThreadId) return;
|
||||||
dispatch({
|
dispatch({
|
||||||
@@ -303,21 +314,13 @@ export default function ChatView() {
|
|||||||
(terminalId: string) => {
|
(terminalId: string) => {
|
||||||
if (!activeThreadId || !api) return;
|
if (!activeThreadId || !api) return;
|
||||||
const fallbackExitWrite = () =>
|
const fallbackExitWrite = () =>
|
||||||
api.terminal
|
api.terminal.write({ threadId: activeThreadId, terminalId, data: "exit\n" }).catch(() => undefined);
|
||||||
.write({ threadId: activeThreadId, terminalId, data: "exit\n" })
|
|
||||||
.catch(() => undefined);
|
|
||||||
const fallbackClearAndExit = () =>
|
|
||||||
api.terminal
|
|
||||||
.clear({ threadId: activeThreadId, terminalId })
|
|
||||||
.catch(() => undefined)
|
|
||||||
.then(() => fallbackExitWrite())
|
|
||||||
.catch(() => undefined);
|
|
||||||
if ("close" in api.terminal && typeof api.terminal.close === "function") {
|
if ("close" in api.terminal && typeof api.terminal.close === "function") {
|
||||||
void api.terminal
|
void api.terminal
|
||||||
.close({ threadId: activeThreadId, terminalId, deleteHistory: true })
|
.close({ threadId: activeThreadId, terminalId })
|
||||||
.catch(() => fallbackClearAndExit());
|
.catch(() => fallbackExitWrite());
|
||||||
} else {
|
} else {
|
||||||
void fallbackClearAndExit();
|
void fallbackExitWrite();
|
||||||
}
|
}
|
||||||
dispatch({
|
dispatch({
|
||||||
type: "CLOSE_THREAD_TERMINAL",
|
type: "CLOSE_THREAD_TERMINAL",
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ export const GitHubIcon: Icon = (props) => (
|
|||||||
clipRule="evenodd"
|
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"
|
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)"
|
transform="scale(64)"
|
||||||
fill="#1B1F23"
|
fill="currentColor"
|
||||||
/>
|
/>
|
||||||
</svg>
|
</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 { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import { isElectron } from "../env";
|
import { isElectron } from "../env";
|
||||||
import { useTheme } from "../hooks/useTheme";
|
import { useTheme } from "../hooks/useTheme";
|
||||||
@@ -38,6 +38,12 @@ interface ThreadStatusPill {
|
|||||||
pulse: boolean;
|
pulse: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface TerminalStatusIndicator {
|
||||||
|
label: "Terminal process running";
|
||||||
|
colorClass: string;
|
||||||
|
pulse: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
function hasUnseenCompletion(thread: Thread): boolean {
|
function hasUnseenCompletion(thread: Thread): boolean {
|
||||||
if (!thread.latestTurnCompletedAt) return false;
|
if (!thread.latestTurnCompletedAt) return false;
|
||||||
const completedAt = Date.parse(thread.latestTurnCompletedAt);
|
const completedAt = Date.parse(thread.latestTurnCompletedAt);
|
||||||
@@ -89,6 +95,17 @@ function threadStatusPill(thread: Thread, hasPendingApprovals: boolean): ThreadS
|
|||||||
return null;
|
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() {
|
export default function Sidebar() {
|
||||||
const { state, dispatch } = useStore();
|
const { state, dispatch } = useStore();
|
||||||
const api = useNativeApi();
|
const api = useNativeApi();
|
||||||
@@ -118,6 +135,7 @@ export default function Sidebar() {
|
|||||||
terminalOpen: false,
|
terminalOpen: false,
|
||||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||||
|
runningTerminalIds: [],
|
||||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||||
terminalGroups: [
|
terminalGroups: [
|
||||||
{
|
{
|
||||||
@@ -388,6 +406,7 @@ export default function Sidebar() {
|
|||||||
thread,
|
thread,
|
||||||
pendingApprovalByThreadId.get(thread.id) === true,
|
pendingApprovalByThreadId.get(thread.id) === true,
|
||||||
);
|
);
|
||||||
|
const terminalStatus = terminalStatusIndicator(thread);
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
key={thread.id}
|
key={thread.id}
|
||||||
@@ -426,9 +445,23 @@ export default function Sidebar() {
|
|||||||
)}
|
)}
|
||||||
<span className="min-w-0 flex-1 truncate text-xs">{thread.title}</span>
|
<span className="min-w-0 flex-1 truncate text-xs">{thread.title}</span>
|
||||||
</div>
|
</div>
|
||||||
<span className="shrink-0 text-[10px] text-muted-foreground/40">
|
<div className="ml-2 flex shrink-0 items-center gap-1.5">
|
||||||
{formatRelativeTime(thread.createdAt)}
|
{terminalStatus && (
|
||||||
</span>
|
<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>
|
</button>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|||||||
@@ -278,6 +278,7 @@ describe("toPersistedState", () => {
|
|||||||
terminalOpen: true,
|
terminalOpen: true,
|
||||||
terminalHeight: 320,
|
terminalHeight: 320,
|
||||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||||
|
runningTerminalIds: [],
|
||||||
activeTerminalId: "term-2",
|
activeTerminalId: "term-2",
|
||||||
terminalGroups: [
|
terminalGroups: [
|
||||||
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
|
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
|
||||||
|
|||||||
@@ -243,6 +243,7 @@ function hydrateThread(
|
|||||||
terminalOpen: thread.terminalOpen ?? false,
|
terminalOpen: thread.terminalOpen ?? false,
|
||||||
terminalHeight: thread.terminalHeight ?? DEFAULT_THREAD_TERMINAL_HEIGHT,
|
terminalHeight: thread.terminalHeight ?? DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||||
terminalIds: safeTerminalIds,
|
terminalIds: safeTerminalIds,
|
||||||
|
runningTerminalIds: [],
|
||||||
activeTerminalId,
|
activeTerminalId,
|
||||||
terminalGroups: normalizedGroups,
|
terminalGroups: normalizedGroups,
|
||||||
activeTerminalGroupId,
|
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 { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
import { type AppState, reducer } from "./store";
|
import { type AppState, reducer } from "./store";
|
||||||
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
|
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
|
||||||
import type { Thread } 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 {
|
function makeSession(overrides: Partial<ProviderSession> = {}): ProviderSession {
|
||||||
return {
|
return {
|
||||||
sessionId: "sess-1",
|
sessionId: "sess-1",
|
||||||
@@ -38,6 +41,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
|||||||
terminalOpen: false,
|
terminalOpen: false,
|
||||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||||
|
runningTerminalIds: [],
|
||||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||||
terminalGroups: [
|
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", () => {
|
describe("store reducer thread continuity", () => {
|
||||||
it("stores codexThreadId from UPDATE_SESSION", () => {
|
it("stores codexThreadId from UPDATE_SESSION", () => {
|
||||||
const state = makeState(
|
const state = makeState(
|
||||||
@@ -255,6 +295,7 @@ describe("store reducer thread continuity", () => {
|
|||||||
const state = makeState(
|
const state = makeState(
|
||||||
makeThread({
|
makeThread({
|
||||||
terminalOpen: true,
|
terminalOpen: true,
|
||||||
|
runningTerminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
const next = reducer(state, {
|
const next = reducer(state, {
|
||||||
@@ -265,6 +306,7 @@ describe("store reducer thread continuity", () => {
|
|||||||
|
|
||||||
expect(next.threads[0]?.terminalOpen).toBe(false);
|
expect(next.threads[0]?.terminalOpen).toBe(false);
|
||||||
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
|
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]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
|
||||||
expect(next.threads[0]?.terminalGroups).toEqual([
|
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", () => {
|
it("backfills codexThreadId from routed provider events", () => {
|
||||||
const state = makeState(makeThread({ codexThreadId: null }));
|
const state = makeState(makeThread({ codexThreadId: null }));
|
||||||
const next = reducer(state, {
|
const next = reducer(state, {
|
||||||
|
|||||||
+47
-1
@@ -8,7 +8,7 @@ import {
|
|||||||
useReducer,
|
useReducer,
|
||||||
} from "react";
|
} from "react";
|
||||||
|
|
||||||
import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
|
import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/contracts";
|
||||||
import { resolveModelSlug } from "./model-logic";
|
import { resolveModelSlug } from "./model-logic";
|
||||||
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
|
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
|
||||||
import { applyEventToMessages, asObject, asString, evolveSession } from "./session-logic";
|
import { applyEventToMessages, asObject, asString, evolveSession } from "./session-logic";
|
||||||
@@ -43,6 +43,7 @@ type Action =
|
|||||||
event: ProviderEvent;
|
event: ProviderEvent;
|
||||||
activeAssistantItemRef: { current: string | null };
|
activeAssistantItemRef: { current: string | null };
|
||||||
}
|
}
|
||||||
|
| { type: "APPLY_TERMINAL_EVENT"; event: TerminalEvent }
|
||||||
| { type: "UPDATE_SESSION"; threadId: string; session: ProviderSession }
|
| { type: "UPDATE_SESSION"; threadId: string; session: ProviderSession }
|
||||||
| {
|
| {
|
||||||
type: "PUSH_USER_MESSAGE";
|
type: "PUSH_USER_MESSAGE";
|
||||||
@@ -149,6 +150,17 @@ function normalizeTerminalIds(terminalIds: string[]): string[] {
|
|||||||
return [DEFAULT_THREAD_TERMINAL_ID];
|
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[] {
|
function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
|
||||||
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
|
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
|
||||||
}
|
}
|
||||||
@@ -252,6 +264,7 @@ function normalizeThreadTerminals(thread: Thread): Thread {
|
|||||||
return {
|
return {
|
||||||
...thread,
|
...thread,
|
||||||
terminalIds,
|
terminalIds,
|
||||||
|
runningTerminalIds: normalizeRunningTerminalIds(thread.runningTerminalIds, terminalIds),
|
||||||
activeTerminalId,
|
activeTerminalId,
|
||||||
terminalGroups,
|
terminalGroups,
|
||||||
activeTerminalGroupId,
|
activeTerminalGroupId,
|
||||||
@@ -269,6 +282,7 @@ function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
|
|||||||
...thread,
|
...thread,
|
||||||
terminalOpen: false,
|
terminalOpen: false,
|
||||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||||
|
runningTerminalIds: [],
|
||||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||||
terminalGroups: [
|
terminalGroups: [
|
||||||
{
|
{
|
||||||
@@ -309,6 +323,7 @@ function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
|
|||||||
return normalizeThreadTerminals({
|
return normalizeThreadTerminals({
|
||||||
...thread,
|
...thread,
|
||||||
terminalIds: remainingTerminalIds,
|
terminalIds: remainingTerminalIds,
|
||||||
|
runningTerminalIds: thread.runningTerminalIds.filter((id) => id !== terminalId),
|
||||||
activeTerminalId: nextActiveTerminalId,
|
activeTerminalId: nextActiveTerminalId,
|
||||||
terminalGroups: nextTerminalGroups,
|
terminalGroups: nextTerminalGroups,
|
||||||
});
|
});
|
||||||
@@ -650,6 +665,37 @@ export function reducer(state: AppState, action: Action): AppState {
|
|||||||
case "TOGGLE_DIFF":
|
case "TOGGLE_DIFF":
|
||||||
return { ...state, diffOpen: !state.diffOpen };
|
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": {
|
case "APPLY_EVENT": {
|
||||||
const { event, activeAssistantItemRef } = action;
|
const { event, activeAssistantItemRef } = action;
|
||||||
const target = findThreadBySessionId(state.threads, event.sessionId);
|
const target = findThreadBySessionId(state.threads, event.sessionId);
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ export interface Thread {
|
|||||||
terminalOpen: boolean;
|
terminalOpen: boolean;
|
||||||
terminalHeight: number;
|
terminalHeight: number;
|
||||||
terminalIds: string[];
|
terminalIds: string[];
|
||||||
|
runningTerminalIds: string[];
|
||||||
activeTerminalId: string;
|
activeTerminalId: string;
|
||||||
terminalGroups: ThreadTerminalGroup[];
|
terminalGroups: ThreadTerminalGroup[];
|
||||||
activeTerminalGroupId: string;
|
activeTerminalGroupId: string;
|
||||||
|
|||||||
+4
-4
@@ -6,10 +6,10 @@
|
|||||||
"packages/*"
|
"packages/*"
|
||||||
],
|
],
|
||||||
"scripts": {
|
"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": "bun run scripts/dev-runner.mjs dev",
|
||||||
"dev:server": "turbo run dev --filter=t3",
|
"dev:server": "bun run scripts/dev-runner.mjs dev:server",
|
||||||
"dev:web": "VITE_WS_URL=ws://localhost:3773 turbo run dev --filter=@t3tools/web",
|
"dev:web": "bun run scripts/dev-runner.mjs dev:web",
|
||||||
"dev:desktop": "turbo run dev --filter=@t3tools/desktop --filter=@t3tools/web --parallel",
|
"dev:desktop": "bun run scripts/dev-runner.mjs dev:desktop",
|
||||||
"start": "turbo run start --filter=t3",
|
"start": "turbo run start --filter=t3",
|
||||||
"start:desktop": "turbo run start --filter=@t3tools/desktop",
|
"start:desktop": "turbo run start --filter=@t3tools/desktop",
|
||||||
"build": "turbo run build",
|
"build": "turbo run build",
|
||||||
|
|||||||
@@ -139,4 +139,15 @@ describe("terminalEventSchema", () => {
|
|||||||
});
|
});
|
||||||
expect(result.success).toBe(true);
|
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,
|
snapshot: terminalSessionSnapshotSchema,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export const terminalActivityEventSchema = terminalEventBaseSchema.extend({
|
||||||
|
type: z.literal("activity"),
|
||||||
|
hasRunningSubprocess: z.boolean(),
|
||||||
|
});
|
||||||
|
|
||||||
export const terminalEventSchema = z.discriminatedUnion("type", [
|
export const terminalEventSchema = z.discriminatedUnion("type", [
|
||||||
terminalStartedEventSchema,
|
terminalStartedEventSchema,
|
||||||
terminalOutputEventSchema,
|
terminalOutputEventSchema,
|
||||||
@@ -98,6 +103,7 @@ export const terminalEventSchema = z.discriminatedUnion("type", [
|
|||||||
terminalErrorEventSchema,
|
terminalErrorEventSchema,
|
||||||
terminalClearedEventSchema,
|
terminalClearedEventSchema,
|
||||||
terminalRestartedEventSchema,
|
terminalRestartedEventSchema,
|
||||||
|
terminalActivityEventSchema,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
export type TerminalThreadInput = z.input<typeof terminalThreadInputSchema>;
|
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",
|
"PORT",
|
||||||
"VITE_WS_URL",
|
"VITE_WS_URL",
|
||||||
"VITE_DEV_SERVER_URL",
|
"VITE_DEV_SERVER_URL",
|
||||||
|
"ELECTRON_RENDERER_PORT",
|
||||||
"T3CODE_LOG_WS_EVENTS",
|
"T3CODE_LOG_WS_EVENTS",
|
||||||
"T3CODE_MODE",
|
"T3CODE_MODE",
|
||||||
"T3CODE_PORT",
|
"T3CODE_PORT",
|
||||||
|
|||||||
Reference in new issue
Block a user