Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,9 @@ mock.module("main/lib/terminal", () => ({
sessions: [],
};
},
getDaemonTerminalManager: () => ({
reset: () => {},
}),
}));

// Mock terminal-host/client to avoid Electron app import
Expand Down
81 changes: 45 additions & 36 deletions apps/desktop/src/lib/trpc/routers/terminal/terminal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ import { TRPCError } from "@trpc/server";
import { observable } from "@trpc/server/observable";
import { eq } from "drizzle-orm";
import { localDb } from "main/lib/local-db";
import { tryListExistingDaemonSessions } from "main/lib/terminal";
import {
getDaemonTerminalManager,
tryListExistingDaemonSessions,
} from "main/lib/terminal";
import { getTerminalHostClient } from "main/lib/terminal-host/client";
import { getWorkspaceRuntimeRegistry } from "main/lib/workspace-runtime";
import { z } from "zod";
Expand Down Expand Up @@ -43,7 +46,6 @@ const SAFE_ID = z
* - SUPERSET_PORT: The hooks server port for agent completion notifications
*/
export const createTerminalRouter = () => {
// Get the workspace runtime registry (selects backend based on settings)
const registry = getWorkspaceRuntimeRegistry();
const terminal = registry.getDefault().terminal;
if (DEBUG_TERMINAL) {
Expand Down Expand Up @@ -98,7 +100,6 @@ export const createTerminalRouter = () => {
});
}

// Resolve cwd: absolute paths stay as-is, relative paths resolve against workspace path
const workspace = localDb
.select()
.from(workspaces)
Expand All @@ -124,7 +125,6 @@ export const createTerminalRouter = () => {
});
}

// Get project info for environment variables
const project = workspace
? localDb
.select()
Expand Down Expand Up @@ -198,10 +198,8 @@ export const createTerminalRouter = () => {
const message =
error instanceof Error ? error.message : "Write failed";

// If session is gone, emit exit instead of error.
// This prevents error toast floods when workspaces with terminals are deleted.
// Emit exit instead of error for deleted sessions to prevent toast floods
if (message.includes("not found or not alive")) {
// SIGTERM (15) - synthetic signal for consistent event typing.
terminal.emit(`exit:${input.paneId}`, 0, 15);
return;
}
Expand All @@ -213,10 +211,6 @@ export const createTerminalRouter = () => {
}
}),

/**
* Acknowledge cold restore - clears the sticky cold restore info.
* Call this after displaying the cold restore UI and starting a new shell.
*/
ackColdRestore: publicProcedure
.input(z.object({ paneId: z.string() }))
.mutation(({ input }) => {
Expand Down Expand Up @@ -258,9 +252,6 @@ export const createTerminalRouter = () => {
await terminal.kill(input);
}),

/**
* Detach from terminal (keep session alive)
*/
detach: publicProcedure
.input(
z.object({
Expand All @@ -272,10 +263,6 @@ export const createTerminalRouter = () => {
terminal.detach(input);
}),

/**
* Clear scrollback buffer for terminal (used by Cmd+K / clear command)
* This clears both in-memory scrollback and persistent history file
*/
clearScrollback: publicProcedure
.input(
z.object({
Expand All @@ -298,7 +285,6 @@ export const createTerminalRouter = () => {
return { daemonModeEnabled: false, killedCount: 0, remainingCount: 0 };
}

// Get sessions before kill for accurate count
const before = await client.listSessions();
const beforeIds = before.sessions.map((s) => s.sessionId);
for (const id of beforeIds) {
Expand All @@ -311,11 +297,9 @@ export const createTerminalRouter = () => {
beforeIds,
);

// Request kill of all sessions
await client.killAll({});

// Wait and verify loop - poll until sessions are actually dead
// This ensures we don't return success before daemon has finished cleanup
// Poll until sessions are actually dead
const MAX_RETRIES = 10;
const RETRY_DELAY_MS = 100;
let remainingCount = before.sessions.length;
Expand Down Expand Up @@ -379,16 +363,50 @@ export const createTerminalRouter = () => {
return { success: true };
}),

/** Restart daemon to recover from stuck state. Kills all sessions. */
restartDaemon: publicProcedure.mutation(async () => {
console.log("[restartDaemon] Starting daemon restart...");

try {
const client = getTerminalHostClient();
const connected = await client.tryConnectAndAuthenticate();

if (connected) {
const { sessions } = await client.listSessions();
const aliveCount = sessions.filter((s) => s.isAlive).length;
console.log(
`[restartDaemon] Shutting down daemon with ${aliveCount} alive sessions`,
);

for (const session of sessions) {
userKilledSessions.add(session.sessionId);
}

await client.shutdownIfRunning({ killSessions: true });
} else {
console.log("[restartDaemon] Daemon was not running");
}
} catch (error) {
console.warn(
"[restartDaemon] Error during shutdown (continuing):",
error,
);
}

const manager = getDaemonTerminalManager();
manager.reset();

console.log("[restartDaemon] Complete");

return { success: true };
}),

getSession: publicProcedure
.input(z.string())
.query(async ({ input: paneId }) => {
return terminal.getSession(paneId);
}),

/**
* Get the current working directory for a workspace
* This is used for resolving relative file paths in terminal output
*/
getWorkspaceCwd: publicProcedure
.input(z.string())
.query(({ input: workspaceId }) => {
Expand All @@ -413,10 +431,6 @@ export const createTerminalRouter = () => {
return worktree?.path ?? null;
}),

/**
* List directory contents for navigation
* Returns directories and files in the specified path
*/
listDirectory: publicProcedure
.input(
z.object({
Expand Down Expand Up @@ -488,11 +502,7 @@ export const createTerminalRouter = () => {
};

const onExit = (exitCode: number, signal?: number) => {
// IMPORTANT: Do not `emit.complete()` on exit.
// The renderer uses a stable `paneId` input and `@trpc/react-query`
// won't auto-resubscribe after completion unless the subscription key changes.
// We reuse the same paneId across restarts/cold restore, so completing here
// would strand the pane with no listeners (terminal output never renders again).
// Don't emit.complete() - paneId is reused across restarts, completion would strand listeners
emit.next({ type: "exit", exitCode, signal });
};

Expand All @@ -513,7 +523,6 @@ export const createTerminalRouter = () => {
terminal.on(`disconnect:${paneId}`, onDisconnect);
terminal.on(`error:${paneId}`, onError);

// Cleanup on unsubscribe
return () => {
if (DEBUG_TERMINAL) {
console.log(`[Terminal Stream] Unsubscribe: ${paneId}`);
Expand Down
66 changes: 60 additions & 6 deletions apps/desktop/src/main/lib/terminal-host/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ const SOCKET_PATH = join(SUPERSET_HOME_DIR, "terminal-host.sock");
const TOKEN_PATH = join(SUPERSET_HOME_DIR, "terminal-host.token");
const PID_PATH = join(SUPERSET_HOME_DIR, "terminal-host.pid");
const SPAWN_LOCK_PATH = join(SUPERSET_HOME_DIR, "terminal-host.spawn.lock");
const SCRIPT_MTIME_PATH = join(SUPERSET_HOME_DIR, "terminal-host.mtime");

// Connection timeouts
const CONNECT_TIMEOUT_MS = 5000;
Expand Down Expand Up @@ -295,7 +296,18 @@ export class TerminalHostClient extends EventEmitter {
*/
private async connectAndAuthenticate(): Promise<void> {
for (let attempt = 0; attempt < 2; attempt++) {
// Control socket (RPC)
if (attempt === 0 && process.env.NODE_ENV === "development") {
if (this.isDaemonScriptStale()) {
if (DEBUG_CLIENT) {
console.log(
"[TerminalHostClient] Daemon script rebuilt, restarting...",
);
}
this.killDaemonFromPidFile();
await this.waitForDaemonShutdown();
}
}

let controlConnected = await this.tryConnectControl();
if (!controlConnected) {
await this.spawnDaemon();
Expand All @@ -305,14 +317,10 @@ export class TerminalHostClient extends EventEmitter {
}
}

// Token is created by the daemon at startup, so we must read it after we’ve
// ensured a daemon exists (fresh installs / cleaned ~/.superset).
let token: string;
try {
token = this.readAuthToken();
} catch (error) {
// If a socket exists but the token is missing, we can’t authenticate; force
// a daemon restart to re-create a coherent socket+token pair.
if (attempt === 0) {
if (DEBUG_CLIENT) {
console.log(
Expand Down Expand Up @@ -346,7 +354,6 @@ export class TerminalHostClient extends EventEmitter {
throw error;
}

// Stream socket (events)
const streamConnected = await this.tryConnectStream();
if (!streamConnected) {
throw new Error("Failed to connect stream socket");
Expand All @@ -360,6 +367,47 @@ export class TerminalHostClient extends EventEmitter {
throw new Error("Failed to connect after protocol upgrade");
}

/**
* Check if the daemon script has been rebuilt since the daemon was spawned.
* Only used in development mode to detect stale daemons.
*/
private isDaemonScriptStale(): boolean {
try {
if (!existsSync(SCRIPT_MTIME_PATH)) {
return false; // No mtime file = first run or manual cleanup
}

const savedMtime = readFileSync(SCRIPT_MTIME_PATH, "utf-8").trim();
const scriptPath = this.getDaemonScriptPath();

if (!existsSync(scriptPath)) {
return false;
}

const currentMtime = statSync(scriptPath).mtimeMs.toString();
return savedMtime !== currentMtime;
} catch {
return false; // On error, don't restart
}
}

/**
* Save the daemon script's mtime to detect rebuilds.
*/
private saveDaemonScriptMtime(): void {
try {
const scriptPath = this.getDaemonScriptPath();
if (!existsSync(scriptPath)) {
return;
}

const mtime = statSync(scriptPath).mtimeMs.toString();
writeFileSync(SCRIPT_MTIME_PATH, mtime, { mode: 0o600 });
} catch {
// Best-effort
}
}

private killDaemonFromPidFile(): void {
if (!existsSync(PID_PATH)) return;

Expand Down Expand Up @@ -1080,6 +1128,12 @@ export class TerminalHostClient extends EventEmitter {
console.log("[TerminalHostClient] Waiting for daemon to start...");
}
await this.waitForDaemon();

// In development mode, save the script mtime to detect rebuilds
if (process.env.NODE_ENV === "development") {
this.saveDaemonScriptMtime();
}

if (DEBUG_CLIENT) {
console.log("[TerminalHostClient] Daemon started successfully");
}
Expand Down
Loading