Skip to content
Open
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
1 change: 1 addition & 0 deletions apps/server/src/terminal/Manager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -560,6 +560,7 @@ it.layer(
assert.equal(second.threadId, "thread-1");
assert.equal(third.threadId, "thread-1");
expect(ptyAdapter.spawnInputs).toHaveLength(1);
expect(first.shell).toBe(ptyAdapter.spawnInputs[0]?.shell);
}),
);

Expand Down
1 change: 1 addition & 0 deletions apps/server/src/terminal/Manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,7 @@ function snapshot(session: TerminalSessionState): TerminalSessionSnapshot {
exitCode: session.exitCode,
exitSignal: session.exitSignal,
label: terminalWireLabel(session),
shell: session.shell,
updatedAt: session.updatedAt,
sequence: session.eventSequence,
cols: session.cols,
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/appInit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { startHostFreezeToasts } from "./components/HostFreezeToastCoordinator";
import { startKeybindingsUpdateToasts } from "./components/KeybindingsUpdateToast";
import { startLegacyThreadMigrationToast } from "./components/LegacyThreadMigrationToast";
import { startPermissionUpdateNotices } from "./components/PermissionUpdateNotice";
import { startProjectScriptRunCoordinator } from "./components/projectScriptRuns/ProjectScriptRunCoordinator";
import { startAgentOpenedPreviews } from "./components/preview/agentOpenedPreviews";
import { startMainAppLocationTracking } from "./components/sidebar/mainAppLocation";
import { startDesktopUpdateLaunchNotice } from "./components/sidebar/updateEverythingRun";
Expand Down Expand Up @@ -301,6 +302,7 @@ export function startAppServices(): AppRouter {
startPermissionUpdateNotices(router);
startThreadNotifications(appAtomRegistry, router);
startGuideRunNotifications(appAtomRegistry, router);
startProjectScriptRunCoordinator(appAtomRegistry);
if (isElectron) startDesktopUpdateLaunchNotice();

return router;
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/components/AppSidebarLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import {
usePanelNavigationSuppression,
} from "../panelAnimations";
import { BackgroundThreadAnnouncer } from "./BackgroundThreadAnnouncer";
import { ProjectScriptRunsHost } from "./projectScriptRuns/ProjectScriptRunsHost";
import { HistorySwipeNavigation } from "./HistorySwipeNavigation";
import ThreadSidebar from "./Sidebar";
import { SidebarBrandWidthProbe } from "./sidebar/SidebarChrome";
Expand Down Expand Up @@ -490,6 +491,7 @@ export function AppSidebarLayout({
) : null}
{children}
<BackgroundThreadAnnouncer />
<ProjectScriptRunsHost />
<SidebarControl showSidebar={showSidebar} />
{isElectron ? <HistorySwipeNavigation /> : null}
</SidebarProvider>
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/components/Sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,7 @@ import {
import { SidebarContent, SidebarGroup, useSidebar } from "./ui/sidebar";
import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome";
import { SidebarHeaderIconButton, SidebarThreadHeader } from "./sidebar/SidebarThreadHeader";
import { ProjectScriptRunsControl } from "./projectScriptRuns/ProjectScriptRunsControl";
import { TooltipProvider } from "./ui/tooltip";
import {
composerDraftHasUserContent,
Expand Down Expand Up @@ -2983,6 +2984,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
<SidebarGroup className="z-[1]">
<SidebarThreadHeader
hasProjects={projectGroups.length > 0}
runsControl={<ProjectScriptRunsControl />}
projectScope={
<Combobox
items={projectScopeItems}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
import type { TerminalBufferState } from "@t3tools/client-runtime/state/terminal";
import {
INITIAL_TERMINAL_OUTPUT_CURSOR,
readTerminalOutputUpdate,
} from "@t3tools/client-runtime/state/terminal";
import { AsyncResult, type AtomRegistry } from "effect/reactivity";

import {
isProjectScriptRunActive,
isProjectScriptWrapperLine,
PROJECT_SCRIPT_OUTPUT_TAIL_LINES,
projectScriptBeginMarker,
projectScriptSentinelPattern,
projectScriptStoppedPatch,
stripProjectScriptOutput,
type ProjectScriptRun,
type ProjectScriptRunPatch,
} from "../../projectScriptRuns";
import { useProjectScriptRunsStore } from "../../projectScriptRunsStore";
import { terminalEnvironment } from "../../state/terminal";

const LOST_TERMINAL_GRACE_MS = 5_000;

export function startProjectScriptRunCoordinator(registry: AtomRegistry.AtomRegistry): () => void {
const watchers = new Map<string, () => void>();
const sync = (runs: Record<string, ProjectScriptRun>) => {
for (const [runId, stop] of watchers) {
const run = runs[runId];
if (run !== undefined && isProjectScriptRunActive(run)) continue;
watchers.delete(runId);
stop();
}
for (const run of Object.values(runs)) {
if (!isProjectScriptRunActive(run) || watchers.has(run.id)) continue;
watchers.set(run.id, watchProjectScriptRun(registry, run));
}
};

sync(useProjectScriptRunsStore.getState().runs);
const unsubscribe = useProjectScriptRunsStore.subscribe((state, previous) => {
if (state.runs !== previous.runs) sync(state.runs);
});

return () => {
unsubscribe();
for (const stop of watchers.values()) stop();
watchers.clear();
};
}

function watchProjectScriptRun(
registry: AtomRegistry.AtomRegistry,
run: ProjectScriptRun,
): () => void {
const atom = terminalEnvironment.observe({
environmentId: run.environmentId,
input: { threadId: run.threadId, terminalId: run.terminalId },
});
const sentinelPattern = projectScriptSentinelPattern(run.sentinel);
const beginMarker = projectScriptBeginMarker(run.sentinel);
let cursor = INITIAL_TERMINAL_OUTPUT_CURSOR;
let lineBuffer = "";
let tail: string[] = [];
let sawBegin = false;
let sawLive = false;
let stopped = false;
let unsubscribe: (() => void) | null = null;
let lostTimer: ReturnType<typeof setTimeout> | null = null;

const stop = () => {
if (stopped) return;
stopped = true;
if (lostTimer !== null) {
clearTimeout(lostTimer);
lostTimer = null;
}
unsubscribe?.();
};

const settle = (patch: ProjectScriptRunPatch, closeTerminal = true) => {
if (stopped) return;
useProjectScriptRunsStore.getState().updateRun(run.id, {
...patch,
outputTail: tail.slice(-PROJECT_SCRIPT_OUTPUT_TAIL_LINES).join("\n"),
endedAt: Date.now(),
});
stop();
if (!closeTerminal) return;
void runAtomCommand(registry, terminalEnvironment.close, {
environmentId: run.environmentId,
input: { threadId: run.threadId, terminalId: run.terminalId, deleteHistory: false },
});
};

const stopPending = () => useProjectScriptRunsStore.getState().pendingStopRunIds.has(run.id);

const settleRequestedStop = () => {
const currentRun = useProjectScriptRunsStore.getState().runs[run.id];
const stoppedPatch =
currentRun === undefined ? null : projectScriptStoppedPatch(currentRun, Date.now());
if (stoppedPatch !== null) settle(stoppedPatch, false);
};

lostTimer = setTimeout(() => {
if (!stopped && !sawLive) {
if (stopPending()) settleRequestedStop();
else settle({ status: "lost", errorMessage: "The terminal is no longer available." });
}
}, LOST_TERMINAL_GRACE_MS);

const handleLine = (rawLine: string): boolean => {
const sentinel = sentinelPattern.exec(rawLine);
if (sentinel !== null) {
const parsed = Number(sentinel[1]);
const exitCode = Number.isFinite(parsed) ? parsed : null;
settle({
status: exitCode === 0 ? "succeeded" : "failed",
exitCode,
errorMessage:
exitCode === 0 ? null : (tail.at(-1) ?? `Exited with code ${exitCode ?? "unknown"}.`),
});
return true;
}
if (!sawBegin) {
if (rawLine.includes(beginMarker)) sawBegin = true;
return false;
}
const cleaned = stripProjectScriptOutput(rawLine).trimEnd();
if (cleaned.length === 0 || isProjectScriptWrapperLine(cleaned)) return false;
tail.push(cleaned.slice(0, 400));
if (tail.length > PROJECT_SCRIPT_OUTPUT_TAIL_LINES) tail.shift();
return false;
};

const onResult = (result: AsyncResult.AsyncResult<TerminalBufferState, unknown>) => {
if (stopped) return;
if (result._tag === "Failure") {
if (sawLive) {
settle({ status: "lost", errorMessage: "The terminal is no longer available." });
}
return;
}
if (result._tag !== "Success") return;
const state = result.value;

const update = readTerminalOutputUpdate(state.output, cursor);
cursor = update.cursor;
if (update.type === "reset") {
lineBuffer = "";
tail = [];
}
if (update.type !== "none") {
lineBuffer += update.data;
const lines = lineBuffer.split(/\r\n|\r|\n/);
lineBuffer = (lines.pop() ?? "").slice(-4096);
for (const line of lines) {
if (handleLine(line)) return;
}
}
if (state.status === "error") {
settle({
status: "failed",
errorMessage: state.error ?? "The terminal failed to start.",
});
return;
}
if (state.status === "exited") {
settle({
status: "failed",
errorMessage: "The terminal exited before the command reported a result.",
});
return;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
if (state.status === "closed") {
if (stopPending()) {
settleRequestedStop();
} else if (sawLive) {
settle({
status: "lost",
errorMessage: "The terminal closed before the command reported a result.",
});
}
return;
}
sawLive = true;
if (lostTimer !== null) {
clearTimeout(lostTimer);
lostTimer = null;
}
if (
state.status === "running" &&
useProjectScriptRunsStore.getState().runs[run.id]?.status === "starting"
) {
useProjectScriptRunsStore.getState().updateRun(run.id, { status: "running" });
}
};

unsubscribe = registry.subscribe(atom, onResult, { immediate: true });
if (stopped) unsubscribe();
return stop;
}
Loading
Loading