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 @@ -12,7 +12,8 @@ namespace {

constexpr uint32_t kSnapshotMagic = 0x54563354; // "T3VT" in little endian.
constexpr uint16_t kSnapshotVersion = 1;
constexpr size_t kMaxScrollbackRows = 10000;
// TERMINAL_VIEW_SCROLLBACK_ROWS in packages/contracts.
constexpr size_t kMaxScrollbackRows = 60000;

enum CellFlag : uint16_t {
kBold = 1 << 0,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package expo.modules.t3terminal

import java.util.ArrayDeque

private const val REPLAY_LIMIT = 512 * 1024
private const val REPLAY_LIMIT = 4 * 1024 * 1024
private const val REPLAY_CHUNK_SIZE = 16 * 1024

// Keep only replay history for intentional terminal recreation.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import Foundation
final class TerminalOutputBuffer {
private var storage = Data()
private var retainedStart = 0
private let limit = 512 * 1024
private let limit = 4 * 1024 * 1024

var data: Data { storage.subdata(in: retainedStart..<storage.count) }

Expand All @@ -19,7 +19,7 @@ final class TerminalOutputBuffer {
while retainedStart < storage.count && storage[retainedStart] & 0xC0 == 0x80 {
retainedStart += 1
}
// Compact once per history window, rather than copying 512 KiB on every append.
// Compact once per history window, rather than copying the window on every append.
if retainedStart >= limit {
storage = storage.subdata(in: retainedStart..<storage.count)
retainedStart = 0
Expand Down
9 changes: 8 additions & 1 deletion apps/mobile/src/features/home/HomeScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ import {
ThreadListV2Row,
ThreadListV2SettledShelfHeader,
ThreadListV2ShowMoreRow,
ThreadSearchMoreRow,
ThreadListV2SnoozedShelfHeader,
ThreadListV2WorkingShelfHeader,
} from "../threads/thread-list-v2-items";
Expand Down Expand Up @@ -814,7 +815,13 @@ export function HomeScreen(props: HomeScreenProps) {
// Lifted above the rows so an iOS filter menu's dismissal morph is not covered.
ListHeaderComponentStyle={{ zIndex: 1 }}
ListFooterComponent={
settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0 ? (
hasSearchQuery && (threadSearch.hasMore || threadSearch.partial) ? (
<ThreadSearchMoreRow
loading={threadSearch.isPending}
partial={threadSearch.partial}
onPress={threadSearch.loadMore}
/>
) : settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0 ? (
<ThreadListV2ShowMoreRow
hiddenCount={threadListV2Layout.hiddenSettledCount}
{...(olderSettledShelf.loading
Expand Down
78 changes: 77 additions & 1 deletion apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@ import {
ThreadId,
sessionGrantsScope,
} from "@t3tools/contracts";
import { type KnownTerminalSession } from "@t3tools/client-runtime/state/terminal";
import {
canLoadNewerTerminalOutput,
canLoadOlderTerminalOutput,
type KnownTerminalSession,
} from "@t3tools/client-runtime/state/terminal";
import { SymbolView } from "../../components/ui/AppSymbol";
import { AppBar } from "../../components/ui/AppBar";
import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
Expand Down Expand Up @@ -105,6 +109,11 @@ function TerminalHeader(props: {
readonly onIncreaseFontSize: () => void;
readonly onOpenNewTerminal: () => void;
readonly onSelectTerminal: (terminalId: string) => void;
/** Null when the view already holds the oldest output the server keeps. */
readonly onLoadOlderOutput: (() => void) | null;
/** Set while the view shows earlier output instead of following the live output. */
readonly onLoadNewerOutput: (() => void) | null;
readonly onShowLatestOutput: (() => void) | null;
}) {
return (
<AppBar
Expand Down Expand Up @@ -159,6 +168,38 @@ function TerminalHeader(props: {
selected: session.terminalId === props.terminalId,
onPress: () => props.onSelectTerminal(session.terminalId),
})),
...(props.onLoadOlderOutput === null
? []
: [
{
id: "terminal-load-older",
title: "Load earlier output",
icon: "arrow.up",
subtitle: "Older output the environment still keeps",
onPress: props.onLoadOlderOutput,
},
]),
...(props.onLoadNewerOutput === null
? []
: [
{
id: "terminal-load-newer",
title: "Load later output",
icon: "arrow.down",
subtitle: "Showing earlier output; live output is paused here",
onPress: props.onLoadNewerOutput,
},
]),
...(props.onShowLatestOutput === null
? []
: [
{
id: "terminal-show-latest",
title: "Jump to latest output",
icon: "arrow.down.circle",
onPress: props.onShowLatestOutput,
},
]),
{
id: "terminal-new",
disabled: !props.canOperateTerminal,
Expand Down Expand Up @@ -511,6 +552,11 @@ function ThreadTerminal(props: {
? { threadId: selectedThread.id, terminalId }
: null,
});
const outputTarget = {
environmentId: selectedThread.environmentId,
threadId: selectedThread.id,
terminalId,
};
useAtomMount(
terminalSessionDriver.driver(
canOperateTerminal
Expand Down Expand Up @@ -829,6 +875,36 @@ function ThreadTerminal(props: {
onIncreaseFontSize={handleIncreaseFontSize}
onOpenNewTerminal={handleOpenNewTerminal}
onSelectTerminal={handleSelectTerminal}
onLoadOlderOutput={
canLoadOlderTerminalOutput(terminal.output)
? () =>
void terminalEnvironment.loadOlderOutput(
appAtomRegistry,
outputTarget,
terminal.output,
)
: null
}
onLoadNewerOutput={
canLoadNewerTerminalOutput(terminal.output)
? () =>
void terminalEnvironment.loadNewerOutput(
appAtomRegistry,
outputTarget,
terminal.output,
)
: null
}
onShowLatestOutput={
canLoadNewerTerminalOutput(terminal.output)
? () =>
void terminalEnvironment.showLatestOutput(
appAtomRegistry,
outputTarget,
terminal.output,
)
: null
}
/>

<ScreenContent>
Expand Down
10 changes: 7 additions & 3 deletions apps/mobile/src/features/terminal/terminalOutputWriter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,18 +26,22 @@ it("appends across rollover without replay and seeds fresh writers with only bou
let state = EMPTY_TERMINAL_BUFFER_STATE;
const chunks: string[] = [];
await writer.write(state.output);
for (let index = 0; index < 128; index += 1) {
const retainedChunks = DEFAULT_MAX_TERMINAL_BUFFER_BYTES / (16 * 1024);
const total = retainedChunks * 4;
for (let index = 0; index < total; index += 1) {
const chunk = `${index}\r\n`.padEnd(16 * 1024, "x");
chunks.push(chunk);
state = append(state, chunk);
await writer.write(state.output);
expect(write).toHaveBeenLastCalledWith(chunk, false);
}
expect(state.output.retainedBytes).toBe(DEFAULT_MAX_TERMINAL_BUFFER_BYTES);
const retained = chunks.slice(-32).join("");
const retained = chunks.slice(-retainedChunks).join("");
expect(terminalOutputText(state.output)).toBe(retained);
expect(write.mock.calls.filter(([, reset]) => reset)).toEqual([["", true]]);
expect(write.mock.calls.reduce((total, [data]) => total + data.length, 0)).toBe(2 * 1024 * 1024);
expect(write.mock.calls.reduce((total, [data]) => total + data.length, 0)).toBe(
total * 16 * 1024,
);

const remountedWrite = vi.fn(async () => {});
await createTerminalOutputWriter(remountedWrite).write(state.output);
Expand Down
2 changes: 2 additions & 0 deletions apps/mobile/src/features/terminal/terminalTheme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,8 @@ export function buildGhosttyThemeConfig(theme: TerminalTheme): string {
`foreground = ${theme.foreground}`,
`cursor-color = ${theme.cursorForeground}`,
`cursor-text = ${theme.cursorBackground}`,
// Bytes of scrollback, about TERMINAL_VIEW_SCROLLBACK_ROWS rows; the default holds 10 MB.
"scrollback-limit = 60000000",
];

for (const [index, color] of theme.palette.entries()) {
Expand Down
12 changes: 12 additions & 0 deletions apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ import {
ThreadListV2Row,
ThreadListV2SettledShelfHeader,
ThreadListV2ShowMoreRow,
ThreadSearchMoreRow,
ThreadListV2SnoozedShelfHeader,
ThreadListV2WorkingShelfHeader,
} from "./thread-list-v2-items";
Expand Down Expand Up @@ -556,6 +557,15 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) {
}}
/>
);
const searchMoreRow =
props.searchQuery.trim().length > 0 && (threadSearch.hasMore || threadSearch.partial) ? (
<ThreadSearchMoreRow
pane="sidebar"
loading={threadSearch.isPending}
partial={threadSearch.partial}
onPress={threadSearch.loadMore}
/>
) : null;
const listEmpty = (
<Text
className={
Expand Down Expand Up @@ -614,6 +624,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) {
showsVerticalScrollIndicator={false}
style={styles.threadList}
ListEmptyComponent={listEmpty}
ListFooterComponent={searchMoreRow}
/>
</GestureDetector>
</SwipeableScrollGateProvider>
Expand Down Expand Up @@ -667,6 +678,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) {
showsVerticalScrollIndicator={false}
style={styles.threadList}
ListEmptyComponent={listEmpty}
ListFooterComponent={searchMoreRow}
/>
</GestureDetector>
</SwipeableScrollGateProvider>
Expand Down
40 changes: 39 additions & 1 deletion apps/mobile/src/features/threads/thread-list-v2-items.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,11 @@ import {
formatWorkingDurationLabel,
resolveThreadWorkingStartedAt,
} from "@t3tools/client-runtime/state/models";
import { AuthOrchestrationOperateScope, type EnvironmentMachineKind } from "@t3tools/contracts";
import {
AuthOrchestrationOperateScope,
THREAD_SEARCH_MAX_EXCLUDED_THREADS,
type EnvironmentMachineKind,
} from "@t3tools/contracts";
import type { SnoozePresetSetting } from "@t3tools/contracts/settings";
import { canSnooze } from "@t3tools/client-runtime/state/thread-settled";
import { threadChipCopyTarget } from "@t3tools/client-runtime/thread-reference";
Expand Down Expand Up @@ -360,6 +364,40 @@ export const ThreadListV2ShowMoreRow = memo(function ThreadListV2ShowMoreRow(pro
);
});

/** Reads the next page of message matches, or says the search stopped at its most threads. */
export const ThreadSearchMoreRow = memo(function ThreadSearchMoreRow(props: {
readonly pane?: "screen" | "sidebar";
readonly loading: boolean;
readonly partial?: boolean;
readonly onPress: () => void;
}) {
const label = props.partial
? `Showing the first ${THREAD_SEARCH_MAX_EXCLUDED_THREADS.toLocaleString()} threads with matching messages`
: props.loading
? "Searching older messages…"
: "Search older messages";
return (
<Pressable
accessibilityRole="button"
accessibilityLabel={label}
disabled={props.loading || props.partial === true}
onPress={props.onPress}
className="mx-4 mt-2 items-center rounded-lg border border-dashed border-border py-2.5"
style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
>
<Text
className={
props.pane === "sidebar"
? "text-xs font-t3-medium text-drawer-foreground-muted"
: "text-xs font-t3-medium text-foreground-muted"
}
>
{label}
</Text>
</Pressable>
);
});

const PENDING_TASK_MENU_ACTIONS: MenuAction[] = [
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
];
Expand Down
12 changes: 12 additions & 0 deletions apps/mobile/src/state/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ const EMPTY_THREAD_SEARCH_MATCHES: ReadonlyArray<EnvironmentThreadSearchMatch> =
const EMPTY_THREAD_SEARCH_ATOM = Atom.make<ThreadSearchResultsState>({
matches: EMPTY_THREAD_SEARCH_MATCHES,
isLoading: false,
hasMore: false,
partial: false,
rows: [],
}).pipe(Atom.withLabel("mobile:thread-search:empty"));

Expand Down Expand Up @@ -206,6 +208,11 @@ export function useThreadSearch(
scope: ThreadSearchScope = {},
): {
readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
/** Older messages may hold more matches for the shown query. */
readonly hasMore: boolean;
/** The search stopped at the most threads it can list; older matches are not shown. */
readonly partial: boolean;
readonly loadMore: () => void;
/** The query `matches` are for, which lags the typed one while a search runs. */
readonly query: string;
readonly isPending: boolean;
Expand Down Expand Up @@ -262,6 +269,11 @@ export function useThreadSearch(
matches: visible.matches,
query: visible.query,
isPending,
hasMore: searchKey !== null && visible.query === settledQuery && result.hasMore,
partial: searchKey !== null && visible.query === settledQuery && result.partial,
loadMore: () => {
if (searchKey !== null) threadSearch.loadMore(appAtomRegistry, searchKey);
},
};
}

Expand Down
1 change: 1 addition & 0 deletions apps/server/src/auth/RpcAuthorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.terminalOpen]: AuthTerminalOperateScope,
[WS_METHODS.terminalAttach]: AuthTerminalOperateScope,
[WS_METHODS.terminalObserve]: AuthTerminalReadScope,
[WS_METHODS.terminalHistory]: AuthTerminalReadScope,
[WS_METHODS.terminalWrite]: AuthTerminalOperateScope,
[WS_METHODS.terminalResize]: AuthTerminalOperateScope,
[WS_METHODS.terminalClear]: AuthTerminalOperateScope,
Expand Down
3 changes: 2 additions & 1 deletion apps/server/src/mcp/toolkits/thread/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,8 @@ const ThreadSearchTool = Tool.make("t3_thread_search", {
"Search active threads by title, branch, PR, project, then message text. Skips subagent threads. `projectId`: one project, else yours, else all outside a thread. Not exhaustive.",
parameters: Schema.Struct({
environmentId: OrchestratorMcpEnvironmentTarget,
...OrchestrationSearchThreadsInput.fields,
query: OrchestrationSearchThreadsInput.fields.query,
limit: OrchestrationSearchThreadsInput.fields.limit,
projectId: Schema.optional(ProjectId),
}),
success: Schema.Struct({
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/observability/RpcInstrumentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,7 @@ const RPC_AGGREGATES = {
[WS_METHODS.terminalOpen]: "terminal",
[WS_METHODS.terminalAttach]: "terminal",
[WS_METHODS.terminalObserve]: "terminal",
[WS_METHODS.terminalHistory]: "terminal",
[WS_METHODS.terminalWrite]: "terminal",
[WS_METHODS.terminalResize]: "terminal",
[WS_METHODS.terminalClear]: "terminal",
Expand Down
Loading
Loading