Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
7 changes: 5 additions & 2 deletions apps/mobile/src/features/terminal/terminalMenu.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { describe, expect, it } from "vite-plus/test";

import { type KnownTerminalSession } from "@t3tools/client-runtime/state/terminal";
import {
EMPTY_TERMINAL_BUFFER_STATE,
type KnownTerminalSession,
} from "@t3tools/client-runtime/state/terminal";
import { DEFAULT_TERMINAL_ID, EnvironmentId, ThreadId } from "@t3tools/contracts";

import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
Expand Down Expand Up @@ -55,7 +58,7 @@ function makeKnownSession(input: {
updatedAt: input.updatedAt ?? "2026-04-15T20:00:00.000Z",
}
: null,
buffer: "",
output: EMPTY_TERMINAL_BUFFER_STATE.output,
status: input.status,
error: null,
hasRunningSubprocess: false,
Expand Down
22 changes: 18 additions & 4 deletions apps/mobile/src/state/use-terminal-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
combineTerminalSessionState,
EMPTY_TERMINAL_BUFFER_STATE,
EMPTY_TERMINAL_SESSION_STATE,
terminalOutputText,
type KnownTerminalSession,
type TerminalSessionState,
} from "@t3tools/client-runtime/state/terminal";
Expand All @@ -11,10 +12,16 @@ import { useMemo } from "react";
import { useEnvironmentQuery } from "./query";
import { terminalEnvironment } from "./terminal";

type LegacyTerminalSessionState = TerminalSessionState & { readonly buffer: string };
const EMPTY_LEGACY_TERMINAL_SESSION_STATE: LegacyTerminalSessionState = {
...EMPTY_TERMINAL_SESSION_STATE,
buffer: "",
};

export function useAttachedTerminalSession(input: {
readonly environmentId: EnvironmentId | null;
readonly terminal: TerminalAttachInput | null;
}): TerminalSessionState {
}): LegacyTerminalSessionState {
const attach = useEnvironmentQuery(
input.environmentId !== null && input.terminal !== null
? terminalEnvironment.attach({
Expand All @@ -31,20 +38,27 @@ export function useAttachedTerminalSession(input: {
input: null,
}),
);
const output = attach.data?.output ?? EMPTY_TERMINAL_BUFFER_STATE.output;
// Installed native binaries still accept initialBuffer. Keep materialization
// at this mobile boundary until the native streaming API is released.
const buffer = useMemo(() => terminalOutputText(output), [output]);

return useMemo(() => {
if (input.environmentId === null || input.terminal === null) {
return EMPTY_TERMINAL_SESSION_STATE;
return EMPTY_LEGACY_TERMINAL_SESSION_STATE;
}
const summary =
metadata.data?.find(
(terminal) =>
terminal.threadId === input.terminal?.threadId &&
terminal.terminalId === input.terminal?.terminalId,
) ?? null;
const state = combineTerminalSessionState(summary, attach.data ?? EMPTY_TERMINAL_BUFFER_STATE);
const state = {
...combineTerminalSessionState(summary, attach.data ?? EMPTY_TERMINAL_BUFFER_STATE),
buffer,
};
return attach.error === null ? state : { ...state, error: attach.error, status: "error" };
}, [attach.data, attach.error, input.environmentId, input.terminal, metadata.data]);
}, [attach.data, attach.error, buffer, input.environmentId, input.terminal, metadata.data]);
}

export function useKnownTerminalSessions(input: {
Expand Down
52 changes: 34 additions & 18 deletions apps/web/src/components/ThreadTerminalDrawer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,13 @@ import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { type TerminalSessionState } from "@t3tools/client-runtime/state/terminal";
import {
INITIAL_TERMINAL_OUTPUT_CURSOR,
readTerminalOutputUpdate,
type TerminalOutputCursor,
type TerminalOutputUpdate,
type TerminalSessionState,
} from "@t3tools/client-runtime/state/terminal";
import {
Plus,
Square,
Expand Down Expand Up @@ -95,8 +101,15 @@ function writeSystemMessage(terminal: GhosttyTerminalSurface, message: string):
terminal.write(`\r\n[terminal] ${message}\r\n`);
}

function writeTerminalBuffer(terminal: GhosttyTerminalSurface, buffer: string): void {
terminal.resetAndWrite(buffer);
export function writeTerminalOutputUpdate(
terminal: Pick<GhosttyTerminalSurface, "resetAndWrite" | "write">,
update: TerminalOutputUpdate,
): void {
if (update.type === "reset") {
terminal.resetAndWrite(update.data);
} else if (update.type === "append") {
terminal.write(update.data);
}
}

function parseTerminalColor(value: string, fallback: GhosttyColor): GhosttyColor {
Expand Down Expand Up @@ -425,9 +438,10 @@ export function TerminalViewport({
input: { threadId, terminalId, cols, rows },
}),
);
const terminalBuffer = terminalSession.buffer;
const terminalOutput = terminalSession.output;
const terminalError = terminalSession.error;
const terminalStatus = terminalSession.status;
const outputCursorRef = useRef<TerminalOutputCursor>(INITIAL_TERMINAL_OUTPUT_CURSOR);
const synchronizedStatusRef = useRef<TerminalSessionState["status"]>("closed");
const synchronizeTerminalStatus = useEffectEvent(
(terminal: GhosttyTerminalSurface, status: TerminalSessionState["status"]) => {
Expand All @@ -448,14 +462,14 @@ export function TerminalViewport({
);
const terminalVersion = terminalSession.version;
const previousSessionRef = useRef({
buffer: terminalBuffer,
output: terminalOutput,
error: terminalError,
status: terminalStatus,
version: terminalVersion,
});
const latestSessionRef = useRef(previousSessionRef.current);
latestSessionRef.current = {
buffer: terminalBuffer,
output: terminalOutput,
error: terminalError,
status: terminalStatus,
version: terminalVersion,
Expand Down Expand Up @@ -518,7 +532,14 @@ export function TerminalViewport({
}
const latestSession = latestSessionRef.current;
previousSessionRef.current = latestSession;
if (latestSession.buffer.length > 0) terminal.resetAndWrite(latestSession.buffer);
const initialOutput = readTerminalOutputUpdate(
latestSession.output,
INITIAL_TERMINAL_OUTPUT_CURSOR,
);
if (initialOutput.type === "reset" && initialOutput.data.length > 0) {
writeTerminalOutputUpdate(terminal, initialOutput);
}
outputCursorRef.current = initialOutput.cursor;
if (latestSession.error !== null) writeSystemMessage(terminal, latestSession.error);
// Attaching to a session that already exited must still run exit handling
// once, so mount synchronization starts from the empty "closed" state.
Expand Down Expand Up @@ -910,7 +931,7 @@ export function TerminalViewport({
useEffect(() => {
const terminal = terminalRef.current;
const current = {
buffer: terminalBuffer,
output: terminalOutput,
error: terminalError,
status: terminalStatus,
version: terminalVersion,
Expand All @@ -922,18 +943,13 @@ export function TerminalViewport({

const previous = previousSessionRef.current;
synchronizeTerminalStatus(terminal, current.status);
if (current.version === previous.version) {
if (current.version === previous.version && current.output === previous.output) {
return;
}

if (
current.buffer.length >= previous.buffer.length &&
current.buffer.startsWith(previous.buffer)
) {
terminal.write(current.buffer.slice(previous.buffer.length));
} else {
writeTerminalBuffer(terminal, current.buffer);
}
const outputUpdate = readTerminalOutputUpdate(current.output, outputCursorRef.current);
writeTerminalOutputUpdate(terminal, outputUpdate);
outputCursorRef.current = outputUpdate.cursor;
terminal.clearSelection();

if (current.error !== null && current.error !== previous.error) {
Expand All @@ -946,7 +962,7 @@ export function TerminalViewport({
});
}
previousSessionRef.current = current;
}, [autoFocus, terminalBuffer, terminalError, terminalStatus, terminalVersion]);
}, [autoFocus, terminalOutput, terminalError, terminalStatus, terminalVersion]);

useEffect(() => {
if (!autoFocus) return;
Expand Down
22 changes: 20 additions & 2 deletions packages/client-runtime/src/state/terminal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,23 @@ import { subscribe, type EnvironmentRpcInput } from "../rpc/client.ts";
import {
applyTerminalAttachStreamEvent,
applyTerminalMetadataStreamEvent,
nextTerminalAttachSeedState,
} from "./terminalSession.ts";

export {
applyTerminalAttachStreamEvent,
combineTerminalSessionState,
DEFAULT_MAX_TERMINAL_BUFFER_BYTES,
EMPTY_TERMINAL_BUFFER_STATE,
EMPTY_TERMINAL_SESSION_STATE,
INITIAL_TERMINAL_OUTPUT_CURSOR,
nextTerminalAttachSeedState,
readTerminalOutputUpdate,
selectRunningSubprocessTerminalIds,
terminalOutputText,
type KnownTerminalSession,
type TerminalBufferState,
type TerminalSessionState,
} from "./terminalSession.ts";

export function createTerminalEnvironmentAtoms<R, E>(
Expand All @@ -40,8 +56,10 @@ export function createTerminalEnvironmentAtoms<R, E>(
attach: createEnvironmentSubscriptionAtomFamily(runtime, {
label: "environment-data:terminal:attach",
subscribe: (input: EnvironmentRpcInput<typeof WS_METHODS.terminalAttach>) =>
subscribe(WS_METHODS.terminalAttach, input).pipe(
Stream.scan(EMPTY_TERMINAL_BUFFER_STATE, applyTerminalAttachStreamEvent),
Stream.suspend(() =>
subscribe(WS_METHODS.terminalAttach, input).pipe(
Stream.scan(nextTerminalAttachSeedState(), applyTerminalAttachStreamEvent),
),
),
}),
events: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
Expand Down
Loading
Loading