Compare commits

..
Author SHA1 Message Date
theomini 02ed33118c fix(mobile): harden redesigned interactions 2026-08-04 21:15:07 -07:00
theomini e9921b0231 fix(mobile): address redesign edge cases 2026-08-04 21:11:06 -07:00
theomini 73cc66ff74 feat(mobile): modernize composer and model picker 2026-08-04 21:06:07 -07:00
theomini 021853bc73 feat(mobile): redesign core app surfaces 2026-08-04 20:47:18 -07:00
Hwanseo Choi 3d429662c9 fix(mcp): unblock Kimi models in OpenCode with preview tools (#5128) 2026-08-04 23:03:15 -04:00
Theo Browne 7b38fb5c6b fix(server): allow remote updates with database migrations (#5374) 2026-08-04 18:41:56 -07:00
Fllip 7537adc30f fix(web): prevent legacy model picker layout shift (#5349) 2026-08-04 20:05:44 -04:00
Theo Browne 94696b0f54 fix(desktop,web): improve in-app browser shortcuts and URL behavior (#4703) 2026-08-04 17:01:34 -07:00
Theo BrowneandClaude Fable 5 fff6a5b028 feat(web): make pairing QR codes actually scannable, with endpoint choice (#5360)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-04 16:53:54 -07:00
Theo BrowneandClaude Fable 5 da6e1a9678 feat(sidebar-v2): thread pinning for sidebar v2 (#5312)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-04 16:35:51 -07:00
8eca20005b feat(web): configurable fonts and sizes under Settings → Appearance (#5103)
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-08-05 00:55:06 +02:00
Theo Browne 2fa1fec8d8 refactor(server): make title prompts plaintext (#5368) 2026-08-04 15:51:56 -07:00
Theo Browne 9bd2a4c688 fix(server): keep regenerated titles on topic (#5365) 2026-08-04 15:32:05 -07:00
maria 4fb03aff0b fix(web): better right panel (new diffs styling) (#5260) 2026-08-05 00:00:24 +02:00
Theo Browne d7950ac153 fix(server): generate durable thread titles (#5357) 2026-08-04 14:02:33 -07:00
Theo BrowneandClaude Fable 5 36caf34c68 fix(desktop,web): contain renderer memory growth and recover from renderer OOM crashes (#5148)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-04 13:37:03 -07:00
Bilal Bakr 90e3778660 fix(web): stop the chat timeline reading through the provider status banner (#5353) 2026-08-04 15:41:07 -04:00
Rushikesh Gaikwad 94331c58ec fix(mobile): show correct provider icons for Grok, Cursor, and OpenCode (#4586) 2026-08-04 11:04:37 -07:00
Arham AminandClaude Opus 4.8 c30a6d9b99 fix(server): scrub AppImage XDG_DATA_DIRS and GSETTINGS_SCHEMA_DIR from terminals (#5075)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-08-04 09:35:10 -04:00
Yukun Shan 37ae1abbe9 fix(ssh): isolate managed tunnel processes (#4347) 2026-08-04 09:34:23 -04:00
Arham AminandClaude Opus 4.8 82b76e2138 fix(server): use a Cursor todo's title when its content is blank (#5073)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-08-04 09:19:12 -04:00
naMqe 8a16cadbaf fix(web): increase tooltip z-index to overlay popovers and menus (#5326) 2026-08-04 09:18:34 -04:00
Julius Marminge 2b1d4fecb8 Upgrade Effect to beta.103 (#5331) 2026-08-04 13:56:50 +02:00
t3-code[bot] cec1bb9de3 fix(web): align multiline error alert controls (#5304) 2026-08-04 13:34:22 +02:00
t3-code[bot] 25ec0b9d13 fix(web): simplify chat code blocks (#5301) 2026-08-04 13:34:10 +02:00
Rodrigo BrechardandRodrigo Brechard 966cc05a90 fix(contracts): decode ServerProviders forward-compatibly (#5327)
Co-authored-by: Rodrigo Brechard <[email protected]>
2026-08-04 13:07:22 +02:00
Wout Stiens 1cbd88aba0 fix(server): strip replayable terminal queries from history (#5319) 2026-08-04 12:52:05 +02:00
Wout Stiens 553867262c fix(terminal): protect held Ctrl/Cmd+W close shortcut (#5322) 2026-08-04 12:51:36 +02:00
Wout StiensandClaude Opus 5 11639bf439 fix(web): blink the terminal cursor again (#5314)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-04 12:50:19 +02:00
t3-code[bot] a261a6440a fix(web): match loading screen to dark theme (#5303) 2026-08-04 00:50:56 +02:00
212 changed files with 9222 additions and 4356 deletions

No files matched your search

+2 -2
View File
@@ -16,7 +16,7 @@ import {
DesktopPreviewSetColorSchemeInputSchema,
DesktopPreviewTabInputSchema,
DesktopPreviewWebviewConfigSchema,
PreviewAnnotationPayloadSchema,
PreviewAnnotationSubmissionResultSchema,
PreviewAutomationSnapshot,
PreviewAutomationStatus,
} from "@t3tools/contracts";
@@ -227,7 +227,7 @@ export const setAnnotationTheme = DesktopIpc.makeIpcMethod({
export const pickElement = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL,
payload: DesktopPreviewTabInputSchema,
result: Schema.NullOr(PreviewAnnotationPayloadSchema),
result: Schema.NullOr(PreviewAnnotationSubmissionResultSchema),
handler: Effect.fn("desktop.ipc.preview.pickElement")(function* ({ tabId }) {
const manager = yield* PreviewManager.PreviewManager;
return yield* manager.pickElement(tabId);
@@ -0,0 +1,28 @@
import { describe, expect, it } from "vite-plus/test";
import { resolveAnnotationSubmission } from "./AnnotationKeyboard.ts";
const keyboardEvent = (
overrides: Partial<Parameters<typeof resolveAnnotationSubmission>[0]> = {},
) => ({
key: "Enter",
metaKey: false,
ctrlKey: false,
shiftKey: false,
isComposing: false,
...overrides,
});
describe("resolveAnnotationSubmission", () => {
it("attaches on Enter and sends on Cmd/Ctrl+Enter", () => {
expect(resolveAnnotationSubmission(keyboardEvent())).toBe("attach");
expect(resolveAnnotationSubmission(keyboardEvent({ metaKey: true }))).toBe("send");
expect(resolveAnnotationSubmission(keyboardEvent({ ctrlKey: true }))).toBe("send");
});
it("leaves Shift+Enter and composition events available for editing", () => {
expect(resolveAnnotationSubmission(keyboardEvent({ shiftKey: true }))).toBeNull();
expect(resolveAnnotationSubmission(keyboardEvent({ isComposing: true }))).toBeNull();
expect(resolveAnnotationSubmission(keyboardEvent({ key: " " }))).toBeNull();
});
});
@@ -0,0 +1,16 @@
import type { PreviewAnnotationSubmission } from "@t3tools/contracts";
interface AnnotationKeyboardEvent {
readonly key: string;
readonly metaKey: boolean;
readonly ctrlKey: boolean;
readonly shiftKey: boolean;
readonly isComposing: boolean;
}
export function resolveAnnotationSubmission(
event: AnnotationKeyboardEvent,
): PreviewAnnotationSubmission | null {
if (event.key !== "Enter" || event.shiftKey || event.isComposing) return null;
return event.metaKey || event.ctrlKey ? "send" : "attach";
}
@@ -23,6 +23,10 @@ const ALLOWED_PREVIEW_PERMISSIONS: ReadonlySet<string> = new Set([
"clipboard-sanitized-write",
"notifications",
"geolocation",
// Deliberately NOT local-fonts: preview sessions run untrusted web content,
// and silently granting it would hand every page the user's installed-font
// fingerprint (and font file bytes via FontData.blob()). The app's own font
// picker runs in the main window session, which is unaffected by this list.
]);
export class BrowserSessionPartitionDerivationError extends Schema.TaggedErrorClass<BrowserSessionPartitionDerivationError>()(
+22
View File
@@ -36,6 +36,28 @@ describe("fitPictureInPictureContentSize", () => {
});
});
describe("isPreviewRefreshShortcut", () => {
const input = (overrides: Partial<Electron.Input> = {}) =>
({
type: "keyDown",
key: "r",
meta: true,
control: false,
shift: false,
alt: false,
...overrides,
}) as Electron.Input;
it("recognizes the platform refresh chord without matching modified variants", () => {
expect(PreviewManager.isPreviewRefreshShortcut(input())).toBe(true);
expect(PreviewManager.isPreviewRefreshShortcut(input({ meta: false, control: true }))).toBe(
true,
);
expect(PreviewManager.isPreviewRefreshShortcut(input({ shift: true }))).toBe(false);
expect(PreviewManager.isPreviewRefreshShortcut(input({ type: "keyUp" }))).toBe(false);
});
});
const {
browserWindowConstructor,
createFromPath,
+26 -7
View File
@@ -11,6 +11,7 @@ import type {
DesktopPreviewPointerEvent,
PreviewAnnotationPayload,
PreviewAnnotationRect,
PreviewAnnotationSubmissionResult,
DesktopPreviewRecordingArtifact,
DesktopPreviewRecordingFrame,
DesktopPreviewScreenshotArtifact,
@@ -109,7 +110,7 @@ const DIAGNOSTIC_BUFFER_LIMIT = 200;
const MAX_ARTIFACT_SITE_SLUG_LENGTH = 80;
const AGENT_CURSOR_MOVE_MS = 160;
const AGENT_CURSOR_CLICK_LEAD_MS = 40;
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
const DEFAULT_ANNOTATION_THEME: DesktopPreviewAnnotationTheme = {
colorScheme: "light",
radius: "0.625rem",
@@ -406,6 +407,13 @@ const APP_FORWARDED_SHORTCUTS: ReadonlyArray<{
{ key: "w", meta: true, shift: false, control: false },
]);
export const isPreviewRefreshShortcut = (input: Electron.Input): boolean =>
input.type === "keyDown" &&
input.key.toLowerCase() === "r" &&
(input.meta || input.control) &&
!input.shift &&
!input.alt;
const isPreviewInputSignal = (value: unknown): value is PreviewInputSignal => {
if (typeof value !== "object" || value === null || !("kind" in value)) return false;
if (value.kind === "pointer") {
@@ -1365,6 +1373,15 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
});
});
const beforeInput = (event: Electron.Event, input: Electron.Input): void => {
if (isPreviewRefreshShortcut(input)) {
event.preventDefault();
runFork(
attempt({ operation: "shortcut.refresh", tabId, webContentsId: wc.id }, () =>
wc.reload(),
).pipe(Effect.ignore),
);
return;
}
runFork(forwardShortcut(event, input));
};
yield* Scope.addFinalizer(
@@ -1792,7 +1809,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const wc = yield* requireWebContents(tabId);
yield* cancelPickElement(tabId);
const annotationTheme = yield* Ref.get(annotationThemeRef);
return yield* Effect.callback<PreviewAnnotationPayload | null, PreviewManagerError>(
return yield* Effect.callback<PreviewAnnotationSubmissionResult | null, PreviewManagerError>(
(resume) => {
const cleanup = Effect.fn("PreviewManager.cleanupPickElement")(function* () {
yield* attempt({ operation: "pickElement.cleanup", tabId, webContentsId: wc.id }, () => {
@@ -1807,14 +1824,14 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
);
});
const settlePick = Effect.fn("PreviewManager.settlePickElement")(function* (
payload: PreviewAnnotationPayload | null,
payload: PreviewAnnotationSubmissionResult | null,
) {
const active = (yield* Ref.get(pickSessionsRef)).get(tabId);
if (!active || active.cancel !== cancel) return;
yield* cleanup();
resume(Effect.succeed(payload));
});
const settle = (payload: PreviewAnnotationPayload | null) => {
const settle = (payload: PreviewAnnotationSubmissionResult | null) => {
runFork(settlePick(payload));
};
const cancelPickSession = Effect.fn("PreviewManager.cancelPickSession")(function* () {
@@ -1844,11 +1861,13 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
return;
}
const cropRect = normalizeCaptureRect(args[1]);
const submission = args[2] === "send" ? "send" : "attach";
runFork(
captureAnnotationScreenshot(tabId, wc, cropRect).pipe(
Effect.matchEffect({
onFailure: () => Effect.sync(() => settle(payload)),
onSuccess: (screenshot) => Effect.sync(() => settle({ ...payload, screenshot })),
onFailure: () => Effect.sync(() => settle({ annotation: payload, submission })),
onSuccess: (screenshot) =>
Effect.sync(() => settle({ annotation: { ...payload, screenshot }, submission })),
}),
Effect.ensuring(
attempt(
@@ -3586,7 +3605,7 @@ export class PreviewManager extends Context.Service<
) => Effect.Effect<void, PreviewManagerError>;
readonly pickElement: (
tabId: string,
) => Effect.Effect<PreviewAnnotationPayload | null, PreviewManagerError>;
) => Effect.Effect<PreviewAnnotationSubmissionResult | null, PreviewManagerError>;
readonly cancelPickElement: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly captureScreenshot: (
tabId: string,
+14 -7
View File
@@ -11,8 +11,10 @@ import type {
PreviewAnnotationRegionTarget,
PreviewAnnotationStrokeTarget,
PreviewAnnotationStyleChange,
PreviewAnnotationSubmission,
} from "@t3tools/contracts";
import { resolveAnnotationSubmission } from "./AnnotationKeyboard.ts";
import { previewAnnotationStyles } from "./AnnotationStyles.generated.ts";
import {
ANNOTATION_CAPTURED_CHANNEL,
@@ -426,7 +428,7 @@ function startAnnotation(): void {
"hidden h-8 w-6 shrink-0 cursor-grab select-none border-0 bg-transparent p-0 font-sans text-lg font-bold leading-5 text-muted-foreground";
composerRow.appendChild(dragHandle);
const submit = createButton("Attach", "Attach annotation and screenshot");
const submit = createButton("Attach", "Attach annotation and screenshot (Enter)");
submit.className +=
" h-8 shrink-0 border-primary bg-primary px-3 text-primary-foreground shadow-sm hover:bg-primary/90";
composerRow.appendChild(submit);
@@ -1182,7 +1184,7 @@ function startAnnotation(): void {
refreshToolButtons();
};
submit.addEventListener("click", () => {
const submitAnnotation = (submission: PreviewAnnotationSubmission): void => {
if (pendingCapture || (selected.size === 0 && regions.length === 0 && strokes.length === 0))
return;
pendingCapture = true;
@@ -1223,13 +1225,18 @@ function startAnnotation(): void {
...regions.map((region) => region.rect),
...strokes.map((stroke) => stroke.bounds),
]);
ipcRenderer.send(ELEMENT_PICKED_CHANNEL, annotation, screenshotRect);
ipcRenderer.send(ELEMENT_PICKED_CHANNEL, annotation, screenshotRect, submission);
});
});
comment.addEventListener("keydown", (event) => {
if (event.key !== "Enter" || !(event.metaKey || event.ctrlKey)) return;
};
submit.addEventListener("click", () => submitAnnotation("attach"));
root.addEventListener("keydown", (event) => {
const submission = event.target === comment ? resolveAnnotationSubmission(event) : null;
// Keep this in the bubble phase so editor inputs receive the event before
// it is isolated from listeners installed by the inspected page.
event.stopImmediatePropagation();
if (!submission) return;
event.preventDefault();
submit.click();
submitAnnotation(submission);
});
window.addEventListener("pointermove", onPointerMove, { capture: true, passive: false });
@@ -8,7 +8,7 @@ import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
const require = NodeModule.createRequire(import.meta.url);
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
const PLAYWRIGHT_PACKAGE_SPECIFIER = "playwright-core/package.json";
const PLAYWRIGHT_SOURCE_MARKER = "source3 = ";
const PLAYWRIGHT_SOURCE_TERMINATOR = ";\n }\n});";
@@ -20,6 +20,15 @@ const clientSettings: ClientSettings = {
diffIgnoreWhitespace: true,
environmentIdentificationMode: "artwork",
favorites: [],
fontFamilyCode: "",
fontFamilyComposer: "",
fontFamilySans: "",
fontFamilyTerminal: "",
fontSizeCode: 13,
fontSizeInterface: 16,
fontSizePrompt: 14,
fontSizeTerminal: 12,
fontSmoothing: true,
glassOpacity: 80,
providerModelPreferences: {},
sidebarAutoSettleAfterDays: 3,
@@ -438,6 +438,51 @@ describe("DesktopWindow", () => {
}),
);
it.effect("blocks only repeated Cmd+W input before it reaches the native window menu", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
const beforeInput = fakeWindow.webContentsListeners.get("before-input-event");
if (!beforeInput) {
return yield* Effect.die("before-input-event listener was not registered");
}
let prevented = false;
const event = { preventDefault: () => (prevented = true) };
const input = {
type: "keyDown",
isAutoRepeat: true,
key: "W",
meta: true,
control: false,
alt: false,
shift: false,
};
beforeInput(event, input);
assert.isTrue(prevented);
prevented = false;
beforeInput(event, { ...input, isAutoRepeat: false });
assert.isFalse(prevented);
prevented = false;
beforeInput(event, { ...input, meta: false });
assert.isFalse(prevented);
}).pipe(Effect.provide(layer));
}),
);
it.effect("uses the persisted main window bounds when opening the window", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
+53 -4
View File
@@ -1,3 +1,4 @@
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
@@ -25,6 +26,12 @@ const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
const MAIN_WINDOW_BOUNDS_PERSIST_DEBOUNCE_MS = 500;
const DEVELOPMENT_LOAD_RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000] as const;
// Renderer crash (usually V8 OOM on long sessions) recovery: reload after a
// short delay, at most MAX_ATTEMPTS times per rolling WINDOW so a renderer
// that dies on boot cannot reload-loop forever.
const RENDERER_RECOVERY_RELOAD_DELAY_MS = 500;
const RENDERER_RECOVERY_MAX_ATTEMPTS = 3;
const RENDERER_RECOVERY_WINDOW_MS = 60_000;
const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([
-2, // ERR_FAILED
-7, // ERR_TIMED_OUT
@@ -514,6 +521,18 @@ export const make = Effect.gen(function* () {
}
});
// Electron's windowMenu close role owns CmdOrCtrl+W. Holding the
// close-terminal shortcut can outlive the terminal that handled its first
// press, so reject repeats before they reach the native window accelerator.
// Deliberate presses still flow through the renderer or native menu.
window.webContents.on("before-input-event", (event, input) => {
if (input.type !== "keyDown" || !input.isAutoRepeat) return;
const modifier = environment.platform === "darwin" ? input.meta : input.control;
if (modifier && !input.alt && !input.shift && input.key.toLowerCase() === "w") {
event.preventDefault();
}
});
window.on("page-title-updated", (event) => {
event.preventDefault();
window.setTitle(environment.displayName);
@@ -537,6 +556,7 @@ export const make = Effect.gen(function* () {
let developmentLoadRetryIndex = 0;
let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
let rendererRecoveryTimestamps: number[] = [];
const clearDevelopmentLoadRetry = () => {
if (developmentLoadRetryFiber === undefined) {
return;
@@ -618,10 +638,39 @@ export const make = Effect.gen(function* () {
},
);
window.webContents.on("render-process-gone", (_event, details) => {
void runPromise(
logWindowWarning("main window render process gone", {
reason: details.reason,
exitCode: details.exitCode,
const recoverable =
details.reason === "crashed" ||
details.reason === "oom" ||
details.reason === "abnormal-exit";
// Long sessions can OOM the renderer (V8 heap exhaustion from
// accumulated thread state). Without a reload the user is left staring
// at a dead white window while agents keep running invisibly, so
// recover by reloading — the renderer rehydrates from the backend,
// which is unaffected. Recovery attempts are bounded so a renderer
// that dies immediately on boot cannot reload-loop forever.
runFork(
Effect.gen(function* () {
const now = yield* Clock.currentTimeMillis;
rendererRecoveryTimestamps = rendererRecoveryTimestamps.filter(
(timestamp) => now - timestamp < RENDERER_RECOVERY_WINDOW_MS,
);
const shouldRecover =
recoverable &&
!window.isDestroyed() &&
rendererRecoveryTimestamps.length < RENDERER_RECOVERY_MAX_ATTEMPTS;
yield* logWindowWarning("main window render process gone", {
reason: details.reason,
exitCode: details.exitCode,
recovering: shouldRecover,
});
if (!shouldRecover) {
return;
}
rendererRecoveryTimestamps.push(now);
yield* Effect.sleep(RENDERER_RECOVERY_RELOAD_DELAY_MS);
if (!window.isDestroyed()) {
loadApplication();
}
}),
);
});
+11 -11
View File
@@ -100,13 +100,13 @@
@variant dark {
/* Page backgrounds */
--color-screen: #0a0a0a;
--color-sheet: rgba(14, 14, 14, 0.98);
--color-screen: #000000;
--color-sheet: rgba(6, 6, 7, 0.98);
/* Card / surface */
--color-card: #171717;
--color-card-alt: #1c1c1c;
--color-card-translucent: rgba(17, 17, 17, 0.8);
--color-card: #111113;
--color-card-alt: #171719;
--color-card-translucent: rgba(13, 13, 15, 0.92);
/* Text */
--color-foreground: #f5f5f5;
@@ -143,7 +143,7 @@
--color-danger-foreground: #fca5a5;
/* Inputs */
--color-input: #141414;
--color-input: #0d0d0f;
--color-input-border: rgba(255, 255, 255, 0.08);
--color-sidebar-search: rgba(118, 118, 128, 0.24);
--color-placeholder: #8e8e93;
@@ -154,13 +154,13 @@
--color-icon-subtle: #8e8e93;
/* Header / glass chrome */
--color-header: rgba(10, 10, 10, 0.97);
--color-header: rgba(0, 0, 0, 0.97);
--color-header-border: rgba(255, 255, 255, 0.06);
--color-glass-surface: rgba(23, 23, 23, 0.78);
--color-glass-tint: rgba(23, 23, 23, 0.24);
--color-glass-surface: rgba(13, 13, 15, 0.92);
--color-glass-tint: rgba(13, 13, 15, 0.24);
/* StatusBar */
--color-status-bar: #0a0a0a;
--color-status-bar: #000000;
/* Markdown */
--color-md-body: #e5e5e5;
@@ -183,7 +183,7 @@
/* Drawer / modal backdrop */
--color-backdrop: rgba(0, 0, 0, 0.48);
--color-drawer: rgba(14, 14, 14, 0.99);
--color-drawer: rgba(6, 6, 7, 0.99);
--color-drawer-shadow: rgba(0, 0, 0, 0.32);
/* Misc */
+10
View File
@@ -50,6 +50,9 @@ import {
IconMinus,
IconNetwork,
IconPalette,
IconPaperclip,
IconPin,
IconPinnedOff,
IconPlayerPlay,
IconPlayerStopFilled,
IconPlus,
@@ -59,6 +62,8 @@ import {
IconServer,
IconSettings,
IconSparkles,
IconStar,
IconStarFilled,
IconLayoutSidebarRight,
IconTerminal2,
IconTextDecrease,
@@ -120,7 +125,10 @@ const ANDROID_ICON_BY_SF_SYMBOL: Partial<Record<SFSymbol, Icon>> = {
"line.3.horizontal.decrease.circle.fill": IconFilter,
magnifyingglass: IconSearch,
paintbrush: IconPalette,
paperclip: IconPaperclip,
"person.crop.circle": IconUserCircle,
pin: IconPin,
"pin.slash": IconPinnedOff,
play: IconPlayerPlay,
plus: IconPlus,
"qrcode.viewfinder": IconQrcode,
@@ -133,6 +141,8 @@ const ANDROID_ICON_BY_SF_SYMBOL: Partial<Record<SFSymbol, Icon>> = {
"slider.horizontal.3": IconAdjustmentsHorizontal,
"square.and.pencil": IconEdit,
"square.split.2x1": IconLayoutColumns,
star: IconStar,
"star.fill": IconStarFilled,
"stop.fill": IconPlayerStopFilled,
terminal: IconTerminal2,
"text.bubble": IconMessage,
@@ -1,4 +1,3 @@
import Constants from "expo-constants";
import type {
NativeStackHeaderItem,
NativeStackNavigationOptions,
@@ -8,7 +7,6 @@ import { Platform, View } from "react-native";
import { AppText as Text } from "./AppText";
import { T3Wordmark } from "./T3Wordmark";
import { IPAD_HOME_TITLE_OFFSET } from "../lib/layoutMetrics";
import { resolveMobileStageLabel } from "../lib/mobileBranding";
import { useThemeColor } from "../lib/useThemeColor";
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../native/native-glass";
@@ -26,8 +24,6 @@ export function CompactBrandTitle(
) {
const iconColor = useThemeColor("--color-icon");
const mutedColor = useThemeColor("--color-foreground-muted");
const subtleColor = useThemeColor("--color-subtle");
const stageLabel = resolveMobileStageLabel(Constants.expoConfig?.extra?.appVariant);
const titleOffset =
Platform.OS !== "ios"
? 0
@@ -48,7 +44,7 @@ export function CompactBrandTitle(
style={{
alignItems: "center",
flexDirection: "row",
gap: 6,
gap: 4,
marginLeft: titleOffset,
}}
>
@@ -63,26 +59,6 @@ export function CompactBrandTitle(
>
Code
</Text>
<View
style={{
backgroundColor: subtleColor,
borderRadius: 999,
paddingHorizontal: 6,
paddingVertical: 2,
}}
>
<Text
style={{
color: mutedColor,
fontFamily: "DMSans-Bold",
fontSize: 9,
letterSpacing: 0.9,
textTransform: "uppercase",
}}
>
{stageLabel}
</Text>
</View>
</View>
);
}
@@ -11,6 +11,7 @@ import {
type StyleProp,
type ViewStyle,
} from "react-native";
import Svg, { Circle } from "react-native-svg";
import { useThemeColor } from "../lib/useThemeColor";
import { cn } from "../lib/cn";
@@ -146,8 +147,9 @@ export function ComposerToolbarButton(props: {
readonly minWidth?: number;
readonly onPress?: () => void;
readonly showChevron?: boolean;
readonly size?: "default" | "compact";
readonly textTransform?: "none" | "uppercase";
readonly variant?: "default" | "primary" | "danger";
readonly variant?: "default" | "ghost" | "primary" | "danger";
readonly className?: string;
readonly style?: StyleProp<ViewStyle>;
}) {
@@ -157,6 +159,7 @@ export function ComposerToolbarButton(props: {
const primaryFg = useThemeColor("--color-primary-foreground");
const dangerFg = useThemeColor("--color-danger-foreground");
const variant = props.variant ?? "default";
const isCompact = props.size === "compact";
const isCircle = !props.label && props.showChevron === false;
const defaultBorderColor = isDarkMode ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.06)";
const activeBorderColor = isDarkMode ? "rgba(255,255,255,0.13)" : "rgba(0,0,0,0.1)";
@@ -173,66 +176,86 @@ export function ComposerToolbarButton(props: {
: primaryFg
: variant === "danger"
? dangerFg
: iconColor;
: variant === "ghost"
? iconSubtle
: iconColor;
return (
<Pressable
accessibilityLabel={props.accessibilityLabel ?? props.label}
accessibilityRole="button"
disabled={props.disabled}
hitSlop={isCompact ? 4 : undefined}
onPress={props.onPress}
className={cn(
// Default width cap lives in the class chain (not the inline style)
// so callers can lift it with max-w-full — flex-filling pills in the
// thread composer stretch to the row's edge. The numeric maxWidth
// prop still wins via the inline style below.
"h-11 max-w-[172px] flex-row items-center justify-center rounded-full active:opacity-70",
isCircle ? "w-11" : "gap-2 px-3.5",
"max-w-[172px] flex-row items-center justify-center rounded-full active:opacity-70",
isCompact ? "h-9" : "h-11",
isCircle ? (isCompact ? "w-9" : "w-11") : isCompact ? "gap-1.5 px-1.5" : "gap-2 px-3.5",
variant === "primary"
? props.disabled
? "bg-subtle-strong"
: "bg-primary"
: variant === "danger"
? "bg-danger"
: props.active
? "bg-subtle-strong"
: "bg-subtle",
: variant === "ghost"
? "bg-transparent"
: props.active
? "bg-subtle-strong"
: "bg-subtle",
props.className,
)}
style={({ pressed }) => [
{
borderColor:
variant === "default"
? props.active
? activeBorderColor
: defaultBorderColor
: filledBorderColor,
borderWidth: 1,
variant === "ghost"
? "transparent"
: variant === "default"
? props.active
? activeBorderColor
: defaultBorderColor
: filledBorderColor,
borderWidth: variant === "ghost" ? 0 : 1,
maxWidth: props.maxWidth,
minWidth: props.minWidth,
opacity: props.disabled ? 0.55 : pressed ? 0.72 : 1,
shadowColor: "#000",
shadowOffset: { width: 0, height: isDarkMode ? 3 : 2 },
shadowOpacity: props.disabled ? 0 : isDarkMode ? 0.24 : 0.08,
shadowOpacity: props.disabled || variant === "ghost" ? 0 : isDarkMode ? 0.24 : 0.08,
shadowRadius: isDarkMode ? 10 : 8,
},
props.style,
]}
>
{props.iconNode ? (
<View className="h-4 w-4 items-center justify-center">{props.iconNode}</View>
<View
className={cn("items-center justify-center", isCompact ? "h-4 w-4" : "h-[18px] w-[18px]")}
>
{props.iconNode}
</View>
) : props.icon ? (
<SymbolView name={props.icon} size={16} tintColor={iconTintColor} type="monochrome" />
<SymbolView
name={props.icon}
size={isCompact ? 16 : 18}
tintColor={iconTintColor}
type="monochrome"
/>
) : null}
{props.label ? (
<Text
className={cn(
"shrink text-center text-sm font-t3-bold",
"shrink text-center font-t3-bold",
isCompact ? "text-sm" : "text-base",
variant === "primary"
? props.disabled
? "text-foreground-muted"
: "text-primary-foreground"
: "text-foreground",
: variant === "ghost"
? "text-foreground-muted"
: "text-foreground",
)}
ellipsizeMode="tail"
numberOfLines={1}
@@ -248,4 +271,49 @@ export function ComposerToolbarButton(props: {
);
}
/**
* The mobile composer keeps the web context-window affordance in the footer.
* Usage is optional because the mobile thread shell does not always include a
* context snapshot; in that case the quiet track still reserves the control.
*/
export function ComposerContextRing(props: { readonly usedPercentage?: number | null }) {
const trackColor = useThemeColor("--color-border");
const progressColor = useThemeColor("--color-icon-subtle");
const normalizedPercentage = Math.max(0, Math.min(100, props.usedPercentage ?? 0));
const radius = 7;
const circumference = 2 * Math.PI * radius;
const dashOffset = circumference - (normalizedPercentage / 100) * circumference;
return (
<View
accessible
accessibilityLabel={
props.usedPercentage == null
? "Context window"
: `Context window ${Math.round(normalizedPercentage)} percent used`
}
className="h-11 w-9 items-center justify-center"
>
<Svg width={20} height={20} viewBox="0 0 18 18">
<Circle cx={9} cy={9} r={radius} fill="none" stroke={trackColor} strokeWidth={2.5} />
{normalizedPercentage > 0 ? (
<Circle
cx={9}
cy={9}
r={radius}
fill="none"
rotation={-90}
origin="9, 9"
stroke={progressColor}
strokeDasharray={`${circumference} ${circumference}`}
strokeDashoffset={dashOffset}
strokeLinecap="round"
strokeWidth={2.5}
/>
) : null}
</Svg>
</View>
);
}
export const ComposerToolbarTrigger = ComposerToolbarButton;
@@ -0,0 +1,277 @@
import type { ModelSelection, ProviderInstanceId } from "@t3tools/contracts";
import { useEffect, useMemo, useState } from "react";
import { FlatList, Keyboard, Modal, Platform, Pressable, TextInput, View } from "react-native";
import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context";
import {
buildModelPickerProviderGroups,
type ModelOption,
type ProviderGroup,
} from "../lib/modelOptions";
import { AppText as Text } from "./AppText";
import { SymbolView } from "./AppSymbol";
import { ProviderIcon } from "./ProviderIcon";
type ModelPickerListItem =
| {
readonly key: string;
readonly type: "provider";
readonly providerLabel: string;
}
| {
readonly key: string;
readonly type: "legacy";
readonly providerKey: ProviderInstanceId;
readonly count: number;
readonly expanded: boolean;
readonly searching: boolean;
}
| {
readonly key: string;
readonly type: "model";
readonly option: ModelOption;
};
function selectedModelKey(selection: ModelSelection | null): string | null {
return selection ? `${selection.instanceId}:${selection.model}` : null;
}
function favoriteModelsFirst(
models: ReadonlyArray<ModelOption>,
favoriteModelKeys: ReadonlySet<string>,
): ReadonlyArray<ModelOption> {
return models
.map((model, index) => ({ model, index }))
.sort((a, b) => {
const favoriteDelta =
Number(favoriteModelKeys.has(b.model.key)) - Number(favoriteModelKeys.has(a.model.key));
return favoriteDelta === 0 ? a.index - b.index : favoriteDelta;
})
.map(({ model }) => model);
}
export function ModelPickerSheet(props: {
readonly visible: boolean;
readonly groups: ReadonlyArray<ProviderGroup>;
readonly selectedModel: ModelSelection | null;
readonly favoriteModelKeys: ReadonlySet<string>;
readonly favoritesEnabled: boolean;
readonly onClose: () => void;
readonly onSelectModel: (option: ModelOption) => void;
readonly onToggleFavorite: (option: ModelOption) => void;
}) {
const insets = useSafeAreaInsets();
const [query, setQuery] = useState("");
const [expandedLegacyProviders, setExpandedLegacyProviders] = useState(
() => new Set<ProviderInstanceId>(),
);
const selectedKey = selectedModelKey(props.selectedModel);
useEffect(() => {
if (!props.visible) return;
setQuery("");
const selectedLegacy = props.groups
.flatMap((group) => group.models)
.find((model) => model.key === selectedKey && model.isLegacy);
setExpandedLegacyProviders(selectedLegacy ? new Set([selectedLegacy.providerKey]) : new Set());
}, [props.groups, props.visible, selectedKey]);
const filteredGroups = useMemo(
() => buildModelPickerProviderGroups(props.groups, query),
[props.groups, query],
);
const searching = query.trim().length > 0;
const listItems = useMemo(() => {
const items: ModelPickerListItem[] = [];
for (const group of filteredGroups) {
items.push({
key: `provider:${group.providerKey}`,
type: "provider",
providerLabel: group.providerLabel,
});
for (const option of favoriteModelsFirst(group.currentModels, props.favoriteModelKeys)) {
items.push({ key: `model:${option.key}`, type: "model", option });
}
if (group.legacyModels.length > 0) {
const expanded = searching || expandedLegacyProviders.has(group.providerKey);
items.push({
key: `legacy:${group.providerKey}`,
type: "legacy",
providerKey: group.providerKey,
count: group.legacyModels.length,
expanded,
searching,
});
if (expanded) {
for (const option of favoriteModelsFirst(group.legacyModels, props.favoriteModelKeys)) {
items.push({ key: `model:${option.key}`, type: "model", option });
}
}
}
}
return items;
}, [expandedLegacyProviders, filteredGroups, props.favoriteModelKeys, searching]);
const toggleLegacyProvider = (providerKey: ProviderInstanceId) => {
setExpandedLegacyProviders((current) => {
const next = new Set(current);
if (next.has(providerKey)) next.delete(providerKey);
else next.add(providerKey);
return next;
});
};
return (
<Modal
allowSwipeDismissal
animationType="slide"
onRequestClose={props.onClose}
presentationStyle={Platform.OS === "ios" ? "pageSheet" : "fullScreen"}
statusBarTranslucent={Platform.OS === "android"}
visible={props.visible}
>
<SafeAreaView
className="flex-1 bg-black"
edges={["bottom"]}
style={{ paddingTop: Platform.OS === "android" ? insets.top : 0 }}
>
<View className="items-center pb-1 pt-2">
<View className="h-1.5 w-16 rounded-full bg-[#515157]" />
</View>
<View className="h-[68px] flex-row items-center px-5">
<Pressable
accessibilityLabel="Close model picker"
accessibilityRole="button"
className="h-12 w-[92px] items-center justify-center rounded-full border border-white/10 bg-[#242426] active:opacity-70"
onPress={props.onClose}
>
<Text className="text-lg font-t3-medium text-[#f4f4f5]">Cancel</Text>
</Pressable>
<Text className="flex-1 text-center text-xl font-t3-bold text-white">Choose model</Text>
<View className="w-[92px]" />
</View>
<View className="px-5 pb-3">
<View className="h-[52px] flex-row items-center gap-3 rounded-full border border-white/10 bg-[#202022] px-4">
<SymbolView name="magnifyingglass" size={22} tintColor="#f4f4f5" type="monochrome" />
<TextInput
accessibilityLabel="Search models"
autoCapitalize="none"
autoCorrect={false}
className="min-w-0 flex-1 text-lg text-white"
clearButtonMode="while-editing"
onChangeText={setQuery}
placeholder="Search models"
placeholderTextColor="#85858b"
selectionColor="#60a5fa"
value={query}
/>
</View>
</View>
<FlatList
data={listItems}
keyExtractor={(item) => item.key}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 24) }}
ListEmptyComponent={
<View className="items-center px-8 py-16">
<Text className="text-center text-base text-[#85858b]">
{query.trim().length > 0
? `No models match “${query.trim()}”.`
: "No models found."}
</Text>
</View>
}
renderItem={({ item }) => {
if (item.type === "provider") {
return (
<Text className="px-5 pb-3 pt-8 text-lg font-t3-bold text-[#85858b]">
{item.providerLabel}
</Text>
);
}
if (item.type === "legacy") {
return (
<Pressable
accessibilityLabel={`${item.expanded ? "Hide" : "Show"} ${item.count} legacy models`}
accessibilityRole="button"
className="mx-5 min-h-[58px] flex-row items-center border-b border-white/10 active:opacity-70"
disabled={item.searching}
onPress={() => toggleLegacyProvider(item.providerKey)}
>
<SymbolView name="archivebox" size={20} tintColor="#77777d" type="monochrome" />
<Text className="ml-3 flex-1 text-base font-t3-medium text-[#a2a2a8]">
Legacy models
</Text>
<Text className="mr-2 text-sm text-[#6f6f75]">{item.count}</Text>
{!item.searching ? (
<SymbolView
name={item.expanded ? "chevron.up" : "chevron.down"}
size={14}
tintColor="#77777d"
type="monochrome"
/>
) : null}
</Pressable>
);
}
const selected = item.option.key === selectedKey;
const favorite = props.favoriteModelKeys.has(item.option.key);
return (
<View className="mx-5 min-h-[82px] flex-row items-center border-b border-white/10">
<Pressable
accessibilityLabel={`${item.option.label}, ${item.option.selection.model}`}
accessibilityRole="button"
accessibilityState={{ selected }}
className="min-w-0 flex-1 flex-row items-center self-stretch active:opacity-70"
onPress={() => {
Keyboard.dismiss();
props.onSelectModel(item.option);
props.onClose();
}}
>
<View className="w-12 items-start">
<ProviderIcon provider={item.option.providerDriver} size={28} />
</View>
<View className="min-w-0 flex-1 py-3">
<Text className="text-lg font-t3-bold text-[#f5f5f6]" numberOfLines={1}>
{item.option.label}
</Text>
<Text className="mt-0.5 text-sm text-[#909096]" numberOfLines={1}>
{item.option.selection.model}
</Text>
</View>
{selected ? (
<SymbolView name="checkmark" size={22} tintColor="#f5f5f6" type="monochrome" />
) : null}
</Pressable>
<Pressable
accessibilityLabel={favorite ? "Remove from favorites" : "Add to favorites"}
accessibilityRole="button"
accessibilityState={{ disabled: !props.favoritesEnabled }}
className="ml-3 h-11 w-11 items-center justify-center active:opacity-60"
disabled={!props.favoritesEnabled}
hitSlop={4}
onPress={() => props.onToggleFavorite(item.option)}
style={{ opacity: props.favoritesEnabled ? 1 : 0.45 }}
>
<SymbolView
name={favorite ? "star.fill" : "star"}
size={23}
tintColor={favorite ? "#facc15" : "#77777d"}
type="monochrome"
/>
</Pressable>
</View>
);
}}
/>
</SafeAreaView>
</Modal>
);
}
+39 -1
View File
@@ -9,6 +9,7 @@ type ProviderIconProps = {
export function ProviderIcon(props: ProviderIconProps) {
const isDarkMode = useColorScheme() === "dark";
const size = props.size ?? 16;
const mono = isDarkMode ? "#e5e5e5" : "#171717";
if (props.provider === "claudeAgent") {
return (
@@ -21,10 +22,47 @@ export function ProviderIcon(props: ProviderIconProps) {
);
}
if (props.provider === "grok") {
const fill = isDarkMode ? "#F5F5F5" : "#0F0F0F";
return (
<Svg width={size} height={size} viewBox="0 0 24 24" fill="none">
<Path
fill={fill}
d="M9.26905 15.284L17.2479 9.36086C17.6391 9.07047 18.1981 9.18374 18.3845 9.63478C19.3655 12.0135 18.9272 14.8721 16.9755 16.8349C15.0238 18.7976 12.3082 19.228 9.8261 18.2477L7.1146 19.5102C11.0037 22.1834 15.7263 21.5223 18.6774 18.5525C21.0182 16.1985 21.7432 12.9897 21.0653 10.0961L21.0714 10.1023C20.0884 5.85143 21.3131 4.15233 23.8218 0.677913C23.8812 0.595532 23.9406 0.513151 24 0.428711L20.6987 3.74866V3.73836L9.267 15.2861"
/>
<Path
fill={fill}
d="M7.62249 16.7237C4.83113 14.0422 5.3124 9.89222 7.69417 7.49905C9.45541 5.72786 12.341 5.00497 14.86 6.06768L17.5653 4.81138C17.0779 4.45714 16.4533 4.07613 15.7365 3.80839C12.4966 2.46764 8.6178 3.13492 5.98413 5.78141C3.45081 8.32904 2.65415 12.2463 4.02219 15.5889C5.04412 18.0871 3.36889 19.8541 1.68137 21.6377C1.08337 22.2699 0.483318 22.9022 0 23.5716L7.62045 16.7257"
/>
</Svg>
);
}
if (props.provider === "cursor") {
return (
<Svg width={size} height={size} viewBox="0 0 466.73 532.09" fill="none">
<Path
fill={isDarkMode ? "#EDECEC" : "#26251E"}
d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"
/>
</Svg>
);
}
if (props.provider === "opencode") {
return (
<Svg width={size} height={size} viewBox="0 0 32 40" fill="none">
<Path d="M24 32H8V16H24V32Z" fill={isDarkMode ? "#4B4646" : "#CFCECD"} />
<Path d="M24 8H8V32H24V8ZM32 40H0V0H32V40Z" fill={isDarkMode ? "#F1ECEC" : "#211E1E"} />
</Svg>
);
}
// codex (and unknown drivers)
return (
<Svg width={size} height={size} viewBox="0 0 256 260" fill="none">
<Path
fill={isDarkMode ? "#e5e5e5" : "#171717"}
fill={mono}
d="M239.184 106.203a64.716 64.716 0 0 0-5.576-53.103C219.452 28.459 191 15.784 163.213 21.74A65.586 65.586 0 0 0 52.096 45.22a64.716 64.716 0 0 0-43.23 31.36c-14.31 24.602-11.061 55.634 8.033 76.74a64.665 64.665 0 0 0 5.525 53.102c14.174 24.65 42.644 37.324 70.446 31.36a64.72 64.72 0 0 0 48.754 21.744c28.481.025 53.714-18.361 62.414-45.481a64.767 64.767 0 0 0 43.229-31.36c14.137-24.558 10.875-55.423-8.083-76.483Zm-97.56 136.338a48.397 48.397 0 0 1-31.105-11.255l1.535-.87 51.67-29.825a8.595 8.595 0 0 0 4.247-7.367v-72.85l21.845 12.636c.218.111.37.32.409.563v60.367c-.056 26.818-21.783 48.545-48.601 48.601Zm-104.466-44.61a48.345 48.345 0 0 1-5.781-32.589l1.534.921 51.722 29.826a8.339 8.339 0 0 0 8.441 0l63.181-36.425v25.221a.87.87 0 0 1-.358.665l-52.335 30.184c-23.257 13.398-52.97 5.431-66.404-17.803ZM23.549 85.38a48.499 48.499 0 0 1 25.58-21.333v61.39a8.288 8.288 0 0 0 4.195 7.316l62.874 36.272-21.845 12.636a.819.819 0 0 1-.767 0L41.353 151.53c-23.211-13.454-31.171-43.144-17.804-66.405v.256Zm179.466 41.695-63.08-36.63L161.73 77.86a.819.819 0 0 1 .768 0l52.233 30.184a48.6 48.6 0 0 1-7.316 87.635v-61.391a8.544 8.544 0 0 0-4.4-7.213Zm21.742-32.69-1.535-.922-51.619-30.081a8.39 8.39 0 0 0-8.492 0L99.98 99.808V74.587a.716.716 0 0 1 .307-.665l52.233-30.133a48.652 48.652 0 0 1 72.236 50.391v.205ZM88.061 139.097l-21.845-12.585a.87.87 0 0 1-.41-.614V65.685a48.652 48.652 0 0 1 79.757-37.346l-1.535.87-51.67 29.825a8.595 8.595 0 0 0-4.246 7.367l-.051 72.697Zm11.868-25.58 28.138-16.217 28.188 16.218v32.434l-28.086 16.218-28.188-16.218-.052-32.434Z"
/>
</Svg>
+186 -314
View File
@@ -1,40 +1,36 @@
import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
import type { EnvironmentId, SidebarThreadSortOrder } from "@t3tools/contracts";
import type { MenuAction } from "@react-native-menu/menu";
import Constants from "expo-constants";
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { useCallback, useMemo, useRef } from "react";
import { Platform, Pressable, Text as RNText, TextInput, View } from "react-native";
import type { SearchBarCommands } from "react-native-screens";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Pressable, TextInput, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { ControlPillMenu } from "../../components/ControlPill";
import { SymbolView } from "../../components/AppSymbol";
import { AppText as Text } from "../../components/AppText";
import { ControlPillMenu } from "../../components/ControlPill";
import { T3Wordmark } from "../../components/T3Wordmark";
import { HOME_HORIZONTAL_INSET } from "../../lib/layoutMetrics";
import { resolveMobileStageLabel } from "../../lib/mobileBranding";
import { useThemeColor } from "../../lib/useThemeColor";
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import type { WorkspaceState } from "../../state/workspaceModel";
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
import {
createNativeMailSearchToolbarItem,
NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED,
} from "../layout/native-mail-search-toolbar";
import type { HomeProjectSortOrder } from "./homeThreadList";
import {
buildHomeListFilterMenu,
type HomeListFilterMenuEnvironment,
type HomeListFilterMenuProject,
import type {
HomeListFilterMenuEnvironment,
HomeListFilterMenuProject,
} from "./home-list-filter-menu";
import {
hasCustomHomeListOptions,
PROJECT_SORT_OPTIONS,
THREAD_SORT_OPTIONS,
} from "./home-list-options";
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
import { WorkspaceConnectionStatus } from "./WorkspaceConnectionStatus";
export type HomeHeaderEnvironment = HomeListFilterMenuEnvironment;
export type HomeHeaderEnvironment = HomeListFilterMenuEnvironment & {
readonly connectionState: EnvironmentConnectionPhase;
};
export function HomeHeader(props: {
readonly catalogState: WorkspaceState;
readonly environments: ReadonlyArray<HomeHeaderEnvironment>;
readonly projects: ReadonlyArray<HomeListFilterMenuProject>;
readonly searchQuery: string;
@@ -48,33 +44,26 @@ export function HomeHeader(props: {
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
readonly onOpenSettings: () => void;
readonly onStartNewTask: () => void;
readonly onReconnectEnvironment: (environmentId: EnvironmentId) => void;
}) {
if (Platform.OS === "android") {
return <AndroidHomeHeader {...props} />;
}
return <IosHomeHeader {...props} />;
}
type HomeHeaderProps = Parameters<typeof HomeHeader>[0];
function checkedMenuState(checked: boolean) {
return checked ? ("on" as const) : undefined;
}
function AndroidHomeHeader(props: HomeHeaderProps) {
const insets = useSafeAreaInsets();
const iconColor = useThemeColor("--color-icon");
const mutedColor = useThemeColor("--color-foreground-muted");
const stageLabel = resolveMobileStageLabel(Constants.expoConfig?.extra?.appVariant);
// Thread List v2 lays the list out in fixed creation order, so the
// sort/group filter controls would be silently ignored — hide them and
// key the "customized" icon state off the environment filter alone.
const searchInputRef = useRef<TextInput>(null);
const [searchVisible, setSearchVisible] = useState(props.searchQuery.length > 0);
const threadListV2Enabled = useThreadListV2Enabled();
const hasCustomListOptions = threadListV2Enabled
? props.selectedEnvironmentId !== null || props.selectedProjectKey !== null
: hasCustomHomeListOptions(props);
const focusSearch = useCallback(() => {
setSearchVisible(true);
searchInputRef.current?.focus();
return true;
}, []);
useHardwareKeyboardCommand("focusSearch", focusSearch);
useEffect(() => {
if (searchVisible) searchInputRef.current?.focus();
}, [searchVisible]);
const menuActions = useMemo<MenuAction[]>(
() => [
{
@@ -84,12 +73,15 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
{
id: "environment:all",
title: "All environments",
state: checkedMenuState(props.selectedEnvironmentId === null),
state: props.selectedEnvironmentId === null ? "on" : undefined,
},
...props.environments.map((environment) => ({
id: `environment:${environment.environmentId}`,
title: environment.label,
state: checkedMenuState(props.selectedEnvironmentId === environment.environmentId),
state:
props.selectedEnvironmentId === environment.environmentId
? ("on" as const)
: undefined,
})),
],
},
@@ -103,12 +95,12 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
{
id: "project:all",
title: "All projects",
state: checkedMenuState(props.selectedProjectKey === null),
state: props.selectedProjectKey === null ? ("on" as const) : undefined,
},
...props.projects.map((project) => ({
id: `project:${project.key}`,
title: project.label,
state: checkedMenuState(props.selectedProjectKey === project.key),
state: props.selectedProjectKey === project.key ? ("on" as const) : undefined,
})),
],
},
@@ -122,7 +114,7 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
subactions: PROJECT_SORT_OPTIONS.map((option) => ({
id: `project-sort:${option.value}`,
title: option.label,
state: checkedMenuState(props.projectSortOrder === option.value),
state: props.projectSortOrder === option.value ? ("on" as const) : undefined,
})),
},
{
@@ -131,10 +123,11 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
subactions: THREAD_SORT_OPTIONS.map((option) => ({
id: `thread-sort:${option.value}`,
title: option.label,
state: checkedMenuState(props.threadSortOrder === option.value),
state: props.threadSortOrder === option.value ? ("on" as const) : undefined,
})),
},
] satisfies MenuAction[])),
{ id: "settings", title: "Settings", image: "gearshape" },
],
[
props.environments,
@@ -146,30 +139,30 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
threadListV2Enabled,
],
);
const handleMenuAction = useCallback(
(event: { nativeEvent: { event: string } }) => {
const id = event.nativeEvent.event;
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
const id = nativeEvent.event;
if (id === "settings") {
props.onOpenSettings();
return;
}
if (id === "environment:all") {
props.onEnvironmentChange(null);
return;
}
if (id.startsWith("environment:")) {
const environmentId = id.slice("environment:".length);
const environment = props.environments.find(
(candidate) => candidate.environmentId === environmentId,
);
if (environment) {
props.onEnvironmentChange(environment.environmentId);
}
if (environment) props.onEnvironmentChange(environment.environmentId);
return;
}
if (id === "project:all") {
props.onProjectChange(null);
return;
}
if (id.startsWith("project:")) {
const projectKey = id.slice("project:".length);
if (props.projects.some((project) => project.key === projectKey)) {
@@ -177,7 +170,6 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
}
return;
}
const projectSort = PROJECT_SORT_OPTIONS.find(
(option) => id === `project-sort:${option.value}`,
);
@@ -185,281 +177,161 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
props.onProjectSortOrderChange(projectSort.value);
return;
}
const threadSort = THREAD_SORT_OPTIONS.find((option) => id === `thread-sort:${option.value}`);
if (threadSort) {
props.onThreadSortOrderChange(threadSort.value);
return;
}
if (threadSort) props.onThreadSortOrderChange(threadSort.value);
},
[props],
);
const troubledEnvironment =
(props.selectedEnvironmentId === null
? undefined
: props.environments.find(
(environment) =>
environment.environmentId === props.selectedEnvironmentId &&
environment.connectionState !== "connected",
)) ??
props.environments.find(
(environment) =>
environment.connectionState === "connecting" ||
environment.connectionState === "reconnecting",
) ??
props.environments.find((environment) => environment.connectionState !== "connected") ??
props.environments[0];
const selectedEnvironment =
props.selectedEnvironmentId === null
? null
: (props.environments.find(
(environment) => environment.environmentId === props.selectedEnvironmentId,
) ?? null);
const selectedProjectLabel =
props.projects.find((project) => project.key === props.selectedProjectKey)?.label ??
"All projects";
return (
<>
<NativeStackScreenOptions options={{ headerShown: false }} />
<View
className="border-b border-header-border bg-header pb-3"
style={{
paddingHorizontal: HOME_HORIZONTAL_INSET,
paddingTop: Math.max(insets.top, 12),
backgroundColor: "#000",
borderBottomColor: "rgba(255,255,255,0.06)",
borderBottomWidth: 1,
paddingTop: insets.top,
}}
>
<View className="w-full max-w-[720px] self-center gap-3">
<View className="flex-row items-center gap-2.5">
<View className="flex-1 flex-row items-center gap-2">
{/* Mirrors the desktop SidebarBrand: T3 mark + muted "Code". */}
<T3Wordmark color={iconColor} height={15} />
<RNText className="-ml-0.5 text-[21px] font-t3-medium tracking-[-0.5px] text-foreground-muted">
Code
</RNText>
<View className="rounded-full bg-subtle px-2 py-0.75">
<RNText className="text-[11px] font-t3-bold tracking-[1.1px] text-foreground-muted uppercase">
{stageLabel}
</RNText>
</View>
</View>
<ControlPillMenu
actions={menuActions}
isAnchoredToRight
onPressAction={handleMenuAction}
>
<Pressable
accessibilityLabel="Filter and sort threads"
accessibilityRole="button"
className="size-11 items-center justify-center rounded-full bg-subtle"
>
<SymbolView
name={
hasCustomListOptions
? "line.3.horizontal.decrease.circle.fill"
: "line.3.horizontal.decrease.circle"
}
size={16}
tintColor={iconColor}
type="monochrome"
/>
</Pressable>
</ControlPillMenu>
{/* Built identically to the filter button so the two circles
match exactly (ControlPill sizes via Tailwind classes and
resolves to a different box). */}
<Pressable
accessibilityLabel="Open settings"
accessibilityRole="button"
<View className="h-14 flex-row items-center px-4">
<View className="min-w-0 flex-1">
<WorkspaceConnectionStatus
state={props.catalogState}
environmentLabel={troubledEnvironment?.label}
environmentConnectionState={troubledEnvironment?.connectionState}
onPress={props.onOpenSettings}
className="size-11 items-center justify-center rounded-full bg-subtle"
>
<SymbolView name="gearshape" size={18} tintColor={iconColor} type="monochrome" />
</Pressable>
</View>
<View className="min-h-12 flex-row items-center gap-2.5 rounded-2xl border border-input-border bg-input px-3.5">
<SymbolView name="magnifyingglass" size={17} tintColor={mutedColor} type="monochrome" />
<TextInput
accessibilityLabel="Search threads"
autoCapitalize="none"
onChangeText={props.onSearchQueryChange}
placeholder="Search threads"
placeholderTextColorClassName="accent-placeholder"
className="flex-1 py-2.5 text-base font-sans text-foreground"
value={props.searchQuery}
onReconnect={
troubledEnvironment
? () => props.onReconnectEnvironment(troubledEnvironment.environmentId)
: undefined
}
variant="header"
fallback={
<View
accessibilityLabel="T3 Code, Threads"
accessibilityRole="header"
className="flex-row items-center gap-2"
>
<T3Wordmark color="#f5f5f5" height={16} />
<Text className="text-[21px] font-t3-medium tracking-[-0.5px] text-[#8e8e93]">
Code
</Text>
</View>
}
/>
{props.searchQuery.length > 0 ? (
<Pressable
accessibilityLabel="Clear search"
hitSlop={10}
onPress={() => props.onSearchQueryChange("")}
>
<SymbolView
name="xmark.circle.fill"
size={17}
tintColor={mutedColor}
type="monochrome"
/>
</Pressable>
) : null}
</View>
<Pressable
accessibilityLabel={searchVisible ? "Close thread search" : "Search threads"}
accessibilityRole="button"
className="size-12 items-center justify-center"
hitSlop={4}
onPress={() => {
if (searchVisible) {
props.onSearchQueryChange("");
setSearchVisible(false);
} else {
setSearchVisible(true);
}
}}
>
<SymbolView
name={searchVisible ? "xmark" : "magnifyingglass"}
size={20}
tintColor="#b9bbc2"
type="monochrome"
/>
</Pressable>
<ControlPillMenu actions={menuActions} isAnchoredToRight onPressAction={handleMenuAction}>
<Pressable
accessibilityLabel="Filter threads and open settings"
accessibilityRole="button"
className="size-12 items-center justify-center"
hitSlop={4}
>
<SymbolView
name={
hasCustomListOptions
? "line.3.horizontal.decrease.circle.fill"
: "line.3.horizontal.decrease.circle"
}
size={20}
tintColor="#b9bbc2"
type="monochrome"
/>
</Pressable>
</ControlPillMenu>
</View>
<View className="h-11 flex-row items-center px-4">
{searchVisible ? (
<>
<SymbolView name="magnifyingglass" size={16} tintColor="#71717a" type="monochrome" />
<TextInput
ref={searchInputRef}
accessibilityLabel="Search threads"
autoCapitalize="none"
autoCorrect={false}
className="ml-2 flex-1 py-0 text-base font-sans text-white"
onChangeText={props.onSearchQueryChange}
placeholder="Search threads"
placeholderTextColor="#52525b"
returnKeyType="search"
value={props.searchQuery}
/>
</>
) : (
<View className="flex-1">
<ControlPillMenu actions={menuActions} onPressAction={handleMenuAction}>
<Pressable
accessibilityLabel={`Project filter, ${selectedProjectLabel}`}
accessibilityRole="button"
className="h-11 w-full flex-row items-center"
>
<SymbolView name="folder" size={16} tintColor="#71717a" type="monochrome" />
<Text
className="ml-2 max-w-[70%] text-sm font-t3-medium text-[#8e8e93]"
numberOfLines={1}
>
{selectedProjectLabel}
</Text>
<SymbolView name="chevron.down" size={10} tintColor="#636366" type="monochrome" />
{selectedEnvironment ? (
<Text className="ml-2 text-xs text-[#71717a]" numberOfLines={1}>
{selectedEnvironment.label}
</Text>
) : null}
</Pressable>
</ControlPillMenu>
</View>
)}
</View>
</View>
</>
);
}
function IosHomeHeader(props: HomeHeaderProps) {
const searchBarRef = useRef<SearchBarCommands>(null);
const iconColor = useThemeColor("--color-icon");
// Thread List v2 lays the list out in fixed creation order, so the
// sort/group filter controls would be silently ignored — hide them and
// key the "customized" icon state off the environment filter alone.
const threadListV2Enabled = useThreadListV2Enabled();
const hasCustomListOptions = threadListV2Enabled
? props.selectedEnvironmentId !== null || props.selectedProjectKey !== null
: hasCustomHomeListOptions(props);
const focusSearch = useCallback(() => {
searchBarRef.current?.focus();
return searchBarRef.current !== null;
}, []);
useHardwareKeyboardCommand("focusSearch", focusSearch);
const filterMenu = buildHomeListFilterMenu({
...props,
listOrganization: !threadListV2Enabled,
});
return (
<>
<NativeStackScreenOptions
optionsVersion={filterMenu.items}
options={{
// Static header config (glass, title, fonts) lives in Stack.tsx
// (GLASS_HEADER_OPTIONS). Only dynamic values are set here.
headerTintColor: iconColor,
unstable_headerRightItems:
Platform.OS === "ios"
? () => [
withNativeGlassHeaderItem({
accessibilityLabel: "Open settings",
icon: { name: "ellipsis", type: "sfSymbol" } as const,
identifier: "home-settings",
label: "",
onPress: props.onOpenSettings,
type: "button",
}),
]
: undefined,
// The keys below are set per-branch (not `undefined`) so a later
// reapply cannot clobber options owned by NativeHeaderToolbar.
...(NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED
? {
unstable_headerToolbarItems: () => [
createNativeMailSearchToolbarItem({
composeButtonId: "home-new-task",
composeSystemImageName: "square.and.pencil",
filterMenu,
filterButtonId: "home-filter",
filterSystemImageName: hasCustomListOptions
? "line.3.horizontal.decrease.circle.fill"
: "line.3.horizontal.decrease",
onComposePress: props.onStartNewTask,
onSearchTextChange: props.onSearchQueryChange,
placeholder: "Search",
searchTextChangeId: "home-search-text",
}),
],
}
: {
// Pre-Liquid-Glass iOS: standard pull-down search in the nav
// bar; create + sort live in the plain bottom toolbar below.
headerSearchBarOptions: {
ref: searchBarRef,
autoCapitalize: "none" as const,
hideNavigationBar: false,
placeholder: "Search",
onCancelButtonPress: () => {
props.onSearchQueryChange("");
},
onChangeText: (event) => {
props.onSearchQueryChange(event.nativeEvent.text);
},
},
}),
}}
/>
{NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED ? null : (
<NativeHeaderToolbar placement="bottom">
<NativeHeaderToolbar.Menu
accessibilityLabel="Filter and sort threads"
icon={
hasCustomListOptions
? "line.3.horizontal.decrease.circle.fill"
: "line.3.horizontal.decrease.circle"
}
title="Thread list options"
separateBackground
>
<NativeHeaderToolbar.Menu title="Environment">
<NativeHeaderToolbar.Label>Environment</NativeHeaderToolbar.Label>
<NativeHeaderToolbar.MenuAction
isOn={props.selectedEnvironmentId === null}
onPress={() => props.onEnvironmentChange(null)}
subtitle="Show threads from every environment"
>
<NativeHeaderToolbar.Label>All environments</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
{props.environments.map((environment) => (
<NativeHeaderToolbar.MenuAction
key={environment.environmentId}
isOn={props.selectedEnvironmentId === environment.environmentId}
onPress={() => props.onEnvironmentChange(environment.environmentId)}
>
<NativeHeaderToolbar.Label>{environment.label}</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
))}
</NativeHeaderToolbar.Menu>
{props.projects.length > 0 ? (
<NativeHeaderToolbar.Menu title="Project">
<NativeHeaderToolbar.Label>Project</NativeHeaderToolbar.Label>
<NativeHeaderToolbar.MenuAction
isOn={props.selectedProjectKey === null}
onPress={() => props.onProjectChange(null)}
subtitle="Show threads from every project"
>
<NativeHeaderToolbar.Label>All projects</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
{props.projects.map((project) => (
<NativeHeaderToolbar.MenuAction
key={project.key}
isOn={props.selectedProjectKey === project.key}
onPress={() => props.onProjectChange(project.key)}
>
<NativeHeaderToolbar.Label>{project.label}</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
))}
</NativeHeaderToolbar.Menu>
) : null}
{threadListV2Enabled ? null : (
<NativeHeaderToolbar.Menu title="Sort projects">
<NativeHeaderToolbar.Label>Sort projects</NativeHeaderToolbar.Label>
{PROJECT_SORT_OPTIONS.map((option) => (
<NativeHeaderToolbar.MenuAction
key={option.value}
isOn={props.projectSortOrder === option.value}
onPress={() => props.onProjectSortOrderChange(option.value)}
>
<NativeHeaderToolbar.Label>{option.label}</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
))}
</NativeHeaderToolbar.Menu>
)}
{threadListV2Enabled ? null : (
<NativeHeaderToolbar.Menu title="Sort threads">
<NativeHeaderToolbar.Label>Sort threads</NativeHeaderToolbar.Label>
{THREAD_SORT_OPTIONS.map((option) => (
<NativeHeaderToolbar.MenuAction
key={option.value}
isOn={props.threadSortOrder === option.value}
onPress={() => props.onThreadSortOrderChange(option.value)}
>
<NativeHeaderToolbar.Label>{option.label}</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
))}
</NativeHeaderToolbar.Menu>
)}
</NativeHeaderToolbar.Menu>
<NativeHeaderToolbar.Spacer flexible />
<NativeHeaderToolbar.Button
accessibilityLabel="New task"
icon="square.and.pencil"
onPress={props.onStartNewTask}
separateBackground
/>
</NativeHeaderToolbar>
)}
</>
);
}
@@ -2,22 +2,25 @@ import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { useNavigation } from "@react-navigation/native";
import { useEffect, useMemo, useState } from "react";
import { View } from "react-native";
import { getCompactBrandHeaderOptions } from "../../components/CompactBrandTitle";
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { useProjects, useThreadShells } from "../../state/entities";
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
import { useWorkspaceState } from "../../state/workspace";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
import {
useRemoteConnections,
useSavedRemoteConnections,
} from "../../state/use-remote-environment-registry";
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
import { WorkspaceEmptyDetail } from "../layout/WorkspaceEmptyDetail";
import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
import { checkForAppUpdateOnLaunch } from "../updates/app-updates";
import { AndroidHomeFabLayout } from "./AndroidHomeFab";
import { HomeScreen } from "./HomeScreen";
import { HomeHeader } from "./HomeHeader";
import { useHomeListOptions } from "./home-list-options";
import { buildHomeProjectScopes } from "./homeThreadList";
import { resolveHomeEnvironmentConnectionPhase } from "./workspace-connection-status";
import { usePendingTaskListActions } from "./usePendingTaskListActions";
import { useThreadListActions } from "./useThreadListActions";
@@ -29,6 +32,7 @@ export function HomeRouteScreen() {
const threads = useThreadShells();
const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState();
const { savedConnectionsById } = useSavedRemoteConnections();
const { onReconnectEnvironment } = useRemoteConnections();
const navigation = useNavigation();
const [searchQuery, setSearchQuery] = useState("");
@@ -42,6 +46,8 @@ export function HomeRouteScreen() {
settleThread,
snoozeThread,
unsnoozeThread,
pinThread,
unpinThread,
unsettleThread,
} = useThreadListActions();
const pendingTasks = usePendingNewTasks();
@@ -56,12 +62,14 @@ export function HomeRouteScreen() {
Object.values(savedConnectionsById).map((connection) => ({
environmentId: connection.environmentId,
label: connection.environmentLabel,
connectionState:
connectionStateByEnvironmentId.get(connection.environmentId) ?? "available",
connectionState: resolveHomeEnvironmentConnectionPhase(
connectionStateByEnvironmentId.get(connection.environmentId),
catalogState.isLoadingConnections,
),
})),
Order.mapInput(Order.String, (environment: { readonly label: string }) => environment.label),
);
}, [savedConnectionsById, workspaceEnvironments]);
}, [catalogState.isLoadingConnections, savedConnectionsById, workspaceEnvironments]);
const availableEnvironmentIds = useMemo(
() => new Set(environments.map((environment) => environment.environmentId)),
[environments],
@@ -101,7 +109,12 @@ export function HomeRouteScreen() {
return (
<>
<NativeStackScreenOptions
options={{ title: "", headerTitle: "", unstable_headerLeftItems: () => [] }}
options={{
headerShown: true,
title: "",
headerTitle: "",
unstable_headerLeftItems: () => [],
}}
/>
<WorkspaceSidebarToolbar
afterSidebarButton={
@@ -120,83 +133,80 @@ export function HomeRouteScreen() {
}
return (
<AndroidHomeFabLayout
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
>
<>
{/* Restore the compact title after the split branch blanks the detail header. */}
<NativeStackScreenOptions options={getCompactBrandHeaderOptions()} />
<HomeHeader
environments={environments}
projects={projectFilterOptions}
searchQuery={searchQuery}
selectedEnvironmentId={selectedEnvironmentId}
selectedProjectKey={selectedProjectKey}
projectSortOrder={listOptions.projectSortOrder}
threadSortOrder={listOptions.threadSortOrder}
onEnvironmentChange={setSelectedEnvironmentId}
onProjectChange={setSelectedProjectKey}
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
onProjectSortOrderChange={setProjectSortOrder}
onSearchQueryChange={setSearchQuery}
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
onThreadSortOrderChange={setThreadSortOrder}
/>
<View className="flex-1 bg-black">
<HomeHeader
catalogState={catalogState}
environments={environments}
projects={projectFilterOptions}
searchQuery={searchQuery}
selectedEnvironmentId={selectedEnvironmentId}
selectedProjectKey={selectedProjectKey}
projectSortOrder={listOptions.projectSortOrder}
threadSortOrder={listOptions.threadSortOrder}
onEnvironmentChange={setSelectedEnvironmentId}
onProjectChange={setSelectedProjectKey}
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
onProjectSortOrderChange={setProjectSortOrder}
onReconnectEnvironment={onReconnectEnvironment}
onSearchQueryChange={setSearchQuery}
onThreadSortOrderChange={setThreadSortOrder}
/>
<HomeScreen
catalogState={catalogState}
environments={environments}
onAddConnection={() =>
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" })
}
onArchiveThread={archiveThread}
onDeleteThread={confirmDeleteThread}
onSettleThread={settleThread}
onSnoozeThread={snoozeThread}
onUnsnoozeThread={unsnoozeThread}
onUnsettleThread={unsettleThread}
onEnvironmentChange={setSelectedEnvironmentId}
onProjectChange={setSelectedProjectKey}
onOpenEnvironments={() =>
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
}
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
onProjectSortOrderChange={setProjectSortOrder}
onSearchQueryChange={setSearchQuery}
onSelectThread={(thread) => {
// Settled threads are live shells: opening one is plain
// navigation, and sending a message un-settles server-side.
navigation.navigate("Thread", {
environmentId: thread.environmentId,
threadId: thread.id,
});
}}
onSelectPendingTask={openPendingTask}
onDeletePendingTask={confirmDeletePendingTask}
onNewThreadInProject={(project) => {
navigation.navigate("NewTaskSheet", {
screen: "NewTaskDraft",
params: {
environmentId: String(project.environmentId),
projectId: String(project.id),
title: project.title,
},
});
}}
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
onThreadSortOrderChange={setThreadSortOrder}
pendingTasks={pendingTasks}
projectGroupingMode={listOptions.projectGroupingMode}
projects={projects}
projectSortOrder={listOptions.projectSortOrder}
savedConnectionsById={savedConnectionsById}
searchQuery={searchQuery}
selectedEnvironmentId={selectedEnvironmentId}
selectedProjectKey={selectedProjectKey}
threads={threads}
threadSortOrder={listOptions.threadSortOrder}
/>
</>
</AndroidHomeFabLayout>
<HomeScreen
catalogState={catalogState}
environments={environments}
onAddConnection={() =>
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" })
}
onArchiveThread={archiveThread}
onDeleteThread={confirmDeleteThread}
onSettleThread={settleThread}
onSnoozeThread={snoozeThread}
onUnsnoozeThread={unsnoozeThread}
onUnsettleThread={unsettleThread}
onPinThread={pinThread}
onUnpinThread={unpinThread}
onEnvironmentChange={setSelectedEnvironmentId}
onProjectChange={setSelectedProjectKey}
onOpenEnvironments={() =>
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
}
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
onProjectSortOrderChange={setProjectSortOrder}
onSearchQueryChange={setSearchQuery}
onSelectThread={(thread) => {
// Settled threads are live shells: opening one is plain
// navigation, and sending a message un-settles server-side.
navigation.navigate("Thread", {
environmentId: thread.environmentId,
threadId: thread.id,
});
}}
onSelectPendingTask={openPendingTask}
onDeletePendingTask={confirmDeletePendingTask}
onNewThreadInProject={(project) => {
navigation.navigate("NewTaskSheet", {
screen: "NewTaskDraft",
params: {
environmentId: String(project.environmentId),
projectId: String(project.id),
title: project.title,
},
});
}}
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
onThreadSortOrderChange={setThreadSortOrder}
pendingTasks={pendingTasks}
projectGroupingMode={listOptions.projectGroupingMode}
projects={projects}
projectSortOrder={listOptions.projectSortOrder}
savedConnectionsById={savedConnectionsById}
searchQuery={searchQuery}
selectedEnvironmentId={selectedEnvironmentId}
selectedProjectKey={selectedProjectKey}
threads={threads}
threadSortOrder={listOptions.threadSortOrder}
/>
</View>
);
}
+87 -99
View File
@@ -19,17 +19,16 @@ import type {
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { ActivityIndicator, FlatList, Platform, Pressable, View } from "react-native";
import { FlatList, Platform, Pressable, View } from "react-native";
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { SymbolView } from "../../components/AppSymbol";
import { EmptyState } from "../../components/EmptyState";
import type { WorkspaceEnvironment, WorkspaceState } from "../../state/workspaceModel";
import type { SavedRemoteConnection } from "../../lib/connection";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
import { useThreadSearch } from "../../state/queries";
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
@@ -71,8 +70,6 @@ import {
type HomeProjectSortOrder,
} from "./homeThreadList";
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "./thread-swipe-actions";
import { WorkspaceConnectionStatus } from "./WorkspaceConnectionStatus";
import { shouldShowWorkspaceConnectionStatus } from "./workspace-connection-status";
/* ─── Types ──────────────────────────────────────────────────────────── */
@@ -111,6 +108,8 @@ interface HomeScreenProps {
) => Promise<boolean>;
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
readonly onPinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly onUnpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
@@ -118,14 +117,7 @@ interface HomeScreenProps {
/* ─── Layout constants ───────────────────────────────────────────────── */
const ESTIMATED_THREAD_ROW_HEIGHT = 72;
const PRE_LIQUID_GLASS_BOTTOM_TOOLBAR_HEIGHT = 44;
/**
* Top spacing between the list and the Android custom header. The Android
* header (AndroidHomeHeader) is rendered in-flow above this screen and
* already consumes the top safe-area inset, so the list only needs breathing
* room here.
*/
const ESTIMATED_THREAD_ROW_HEIGHT = 92;
function deriveEmptyState(props: {
readonly catalogState: WorkspaceState;
@@ -190,10 +182,6 @@ function deriveEmptyState(props: {
};
}
function HomeTopContentSpacer() {
return <View className="h-4" />;
}
/* ─── Main screen ────────────────────────────────────────────────────── */
export function HomeScreen(props: HomeScreenProps) {
@@ -206,11 +194,6 @@ export function HomeScreen(props: HomeScreenProps) {
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
const listRef = useRef<LegendListRef | null>(null);
const insets = useSafeAreaInsets();
const accentColor = useThemeColor("--color-icon-muted");
const iosBottomToolbarClearance =
Platform.OS === "ios" && !NATIVE_LIQUID_GLASS_SUPPORTED
? PRE_LIQUID_GLASS_BOTTOM_TOOLBAR_HEIGHT
: 0;
const searchEnvironmentIds = useMemo(
() =>
props.selectedEnvironmentId === null
@@ -414,6 +397,16 @@ export function HomeScreen(props: HomeScreenProps) {
return map;
}, [props.projects]);
const connectionStateByEnvironmentId = useMemo(
() =>
new Map(
props.environments.map(
(environment) => [environment.environmentId, environment.connectionState] as const,
),
),
[props.environments],
);
const v2ProjectScopeKey = props.selectedProjectKey;
const v2ScopeProjects = useMemo(
() =>
@@ -516,6 +509,18 @@ export function HomeScreen(props: HomeScreenProps) {
},
[props.onUnsnoozeThread],
);
const handlePinThread = useCallback(
(thread: EnvironmentThreadShell) => {
void props.onPinThread(thread);
},
[props.onPinThread],
);
const handleUnpinThread = useCallback(
(thread: EnvironmentThreadShell) => {
void props.onUnpinThread(thread);
},
[props.onUnpinThread],
);
const handleDeleteThread = props.onDeleteThread;
const handleUnsettleThread = props.onUnsettleThread;
// The settled tail renders in pages; expansion resets when the filter
@@ -575,6 +580,15 @@ export function HomeScreen(props: HomeScreenProps) {
}
return supported;
}, [serverConfigs]);
const pinningEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>();
for (const [environmentId, config] of serverConfigs) {
if (config.environment.capabilities.threadPinning === true) {
supported.add(environmentId);
}
}
return supported;
}, [serverConfigs]);
const threadListV2Layout = useMemo(() => {
if (!threadListV2Enabled)
return {
@@ -683,11 +697,12 @@ export function HomeScreen(props: HomeScreenProps) {
project={projectByKey.get(pendingScopeKey) ?? null}
projectTitle={v2ProjectTitleByProjectKey.get(pendingScopeKey)}
environmentLabel={
Object.keys(props.savedConnectionsById).length > 1
? (props.savedConnectionsById[item.pendingTask.message.environmentId]
?.environmentLabel ?? null)
: null
props.savedConnectionsById[item.pendingTask.message.environmentId]
?.environmentLabel ?? null
}
environmentConnectionState={connectionStateByEnvironmentId.get(
item.pendingTask.message.environmentId,
)}
showPendingDivider={item.showPendingDivider}
onSelectPendingTask={props.onSelectPendingTask}
onDeletePendingTask={props.onDeletePendingTask}
@@ -718,6 +733,7 @@ export function HomeScreen(props: HomeScreenProps) {
thread={thread}
variant={item.item.variant}
snoozed={item.item.snoozed}
pinned={item.item.pinned}
snoozePresetMinute={nowMinute}
snoozeWakeLabelText={item.snoozeWakeLabelText}
project={
@@ -736,10 +752,9 @@ export function HomeScreen(props: HomeScreenProps) {
)?.driver ?? null
}
environmentLabel={
Object.keys(props.savedConnectionsById).length > 1
? (props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
: null
props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null
}
environmentConnectionState={connectionStateByEnvironmentId.get(thread.environmentId)}
searchMatch={threadSearchMatchByKey.get(
threadSearchMatchKey({
environmentId: thread.environmentId,
@@ -753,9 +768,12 @@ export function HomeScreen(props: HomeScreenProps) {
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
onSettleThread={handleSettleThread}
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
onSnoozeThread={handleSnoozeThread}
onUnsnoozeThread={handleUnsnoozeThread}
onUnsettleThread={handleUnsettleThread}
onPinThread={handlePinThread}
onUnpinThread={handleUnpinThread}
onChangeRequestState={handleChangeRequestState}
projectCwd={
projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
@@ -768,12 +786,16 @@ export function HomeScreen(props: HomeScreenProps) {
[
handleChangeRequestState,
handleDeleteThread,
handlePinThread,
handleSettleThread,
handleSnoozeThread,
handleUnpinThread,
handleUnsnoozeThread,
handleSwipeableClose,
handleSwipeableWillOpen,
handleUnsettleThread,
pinningEnvironmentIds,
connectionStateByEnvironmentId,
projectByKey,
projectCwdByKey,
props.onArchiveThread,
@@ -799,6 +821,7 @@ export function HomeScreen(props: HomeScreenProps) {
// HomeScreen render.
const v2ExtraData = useMemo(
() => ({
connectionStateByEnvironmentId,
projectByKey,
projectCwdByKey,
projectTitleByProjectKey: v2ProjectTitleByProjectKey,
@@ -809,6 +832,7 @@ export function HomeScreen(props: HomeScreenProps) {
threadSearchMatchByKey,
}),
[
connectionStateByEnvironmentId,
projectByKey,
projectCwdByKey,
props.searchQuery,
@@ -939,29 +963,34 @@ export function HomeScreen(props: HomeScreenProps) {
? null
: (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ??
"this environment");
const shouldShowConnectionStatus = shouldShowWorkspaceConnectionStatus(props.catalogState);
const emptyState = deriveEmptyState({
catalogState: props.catalogState,
projectCount: props.projects.length,
});
const connectionStatus =
shouldShowConnectionStatus && Platform.OS !== "ios" ? (
<View
className="absolute left-0 right-0 items-center"
style={{ bottom: Math.max(insets.bottom, 18) + 76 }}
>
<WorkspaceConnectionStatus state={props.catalogState} onPress={props.onOpenEnvironments} />
</View>
) : null;
const composeAction = (
<Pressable
accessibilityLabel="New task"
accessibilityRole="button"
className="absolute right-4 size-14 items-center justify-center rounded-full bg-white"
onPress={props.onStartNewTask}
style={({ pressed }) => ({
bottom: Math.max(insets.bottom, 16) + 9,
opacity: pressed ? 0.72 : 1,
shadowColor: "#000",
shadowOffset: { width: 0, height: 10 },
shadowOpacity: 0.7,
shadowRadius: 26,
})}
>
<SymbolView name="square.and.pencil" size={22} tintColor="#000" type="monochrome" />
</Pressable>
);
if (!hasAnyThreads) {
return (
<View
className="flex-1 items-center justify-center bg-screen px-8"
style={{
paddingBottom: Math.max(insets.bottom, 24) + iosBottomToolbarClearance,
paddingTop: NATIVE_LIQUID_GLASS_SUPPORTED ? insets.top + 72 : 0,
}}
className="flex-1 items-center justify-center px-8"
style={{ backgroundColor: "#000", paddingBottom: Math.max(insets.bottom, 24) }}
>
<View className="w-full max-w-[430px]">
<EmptyState
@@ -971,45 +1000,15 @@ export function HomeScreen(props: HomeScreenProps) {
onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
variant="plain"
/>
{emptyState.loading && !shouldShowConnectionStatus ? (
<View className="mt-4 items-center">
<ActivityIndicator color={accentColor} />
</View>
) : null}
{shouldShowConnectionStatus && Platform.OS === "ios" ? (
<View className="mt-4">
<WorkspaceConnectionStatus
state={props.catalogState}
onPress={props.onOpenEnvironments}
variant="sidebar"
/>
</View>
) : null}
</View>
{connectionStatus}
{composeAction}
</View>
);
}
const listHeader = (
<>
{Platform.OS === "ios" ? null : <HomeTopContentSpacer />}
{shouldShowConnectionStatus && Platform.OS === "ios" ? (
<View className="pb-4">
<WorkspaceConnectionStatus
state={props.catalogState}
onPress={props.onOpenEnvironments}
variant="sidebar"
/>
</View>
) : null}
</>
);
// Project scoping lives in the header filter menu (no inline chip row on
// mobile — the menu is the one filter surface).
const v2ListHeader = listHeader;
const listHeader = null;
const listEmpty = !hasResults ? (
hasSearchQuery && threadSearch.isPending ? null : hasSearchQuery ? (
@@ -1046,14 +1045,14 @@ export function HomeScreen(props: HomeScreenProps) {
if (threadListV2Enabled) {
return (
<View className="flex-1 bg-screen">
<View className="flex-1" style={{ backgroundColor: "#000" }}>
<SwipeableScrollGateProvider enabled={swipeEnabled}>
<FlatList
data={threadListV2Items}
renderItem={renderV2Item}
keyExtractor={v2KeyExtractor}
extraData={v2ExtraData}
ListHeaderComponent={v2ListHeader}
ListHeaderComponent={listHeader}
ListFooterComponent={
settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0 ? (
<Pressable
@@ -1071,28 +1070,25 @@ export function HomeScreen(props: HomeScreenProps) {
}
ListEmptyComponent={v2ListEmpty}
style={{ flex: 1 }}
automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
automaticallyAdjustsScrollIndicatorInsets={false}
contentInsetAdjustmentBehavior="never"
showsVerticalScrollIndicator={false}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
{...scrollGateHandlers}
scrollEventThrottle={16}
contentContainerStyle={{
paddingBottom:
Platform.OS === "ios"
? Math.max(insets.bottom, 24) + 96 + iosBottomToolbarClearance
: Math.max(insets.bottom, 16) + 88,
paddingBottom: Math.max(insets.bottom, 16) + 80,
}}
/>
</SwipeableScrollGateProvider>
{connectionStatus}
{composeAction}
</View>
);
}
return (
<View className="flex-1 bg-screen">
<View className="flex-1" style={{ backgroundColor: "#000" }}>
{/* Sticky headers are deliberately not wired up: LegendList's JS sticky
implementation mispositions pinned headers at mount under iOS
automatic content insets (headers render one nav-inset too low until
@@ -1112,8 +1108,8 @@ export function HomeScreen(props: HomeScreenProps) {
ListHeaderComponent={listHeader}
ListEmptyComponent={listEmpty}
style={{ flex: 1 }}
automaticallyAdjustsScrollIndicatorInsets={NATIVE_LIQUID_GLASS_SUPPORTED}
contentInsetAdjustmentBehavior={NATIVE_LIQUID_GLASS_SUPPORTED ? "automatic" : "never"}
automaticallyAdjustsScrollIndicatorInsets={false}
contentInsetAdjustmentBehavior="never"
showsVerticalScrollIndicator={false}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
@@ -1121,27 +1117,19 @@ export function HomeScreen(props: HomeScreenProps) {
recycleItems
scrollEventThrottle={16}
contentContainerStyle={{
// Android reserves room for the floating new-task FAB
// (56 button + 16 gap + bottom inset). Pre-glass iOS shows a
// standard 44pt bottom toolbar that overlays the list and is not
// reflected in insets while contentInsetAdjustmentBehavior is
// "never".
paddingBottom:
Platform.OS === "ios"
? Math.max(insets.bottom, 24) + 24 + iosBottomToolbarClearance
: Math.max(insets.bottom, 16) + 88,
paddingBottom: Math.max(insets.bottom, 16) + 80,
}}
scrollIndicatorInsets={
Platform.OS === "ios"
? {
bottom: Math.max(insets.bottom, 16) + 24 + iosBottomToolbarClearance,
bottom: Math.max(insets.bottom, 16) + 80,
top: 0,
}
: undefined
}
/>
</SwipeableScrollGateProvider>
{connectionStatus}
{composeAction}
</View>
);
}
@@ -2,7 +2,9 @@ import { describe, expect, it } from "vite-plus/test";
import type { WorkspaceState } from "../../state/workspaceModel";
import {
resolveHomeEnvironmentConnectionPhase,
shouldShowWorkspaceConnectionStatus,
workspaceConnectionHeaderPresentation,
workspaceConnectionStatusLabel,
} from "./workspace-connection-status";
@@ -25,6 +27,12 @@ function workspaceState(overrides: Partial<WorkspaceState> = {}): WorkspaceState
}
describe("workspace connection status", () => {
it("treats uncatalogued saved environments as connecting during startup", () => {
expect(resolveHomeEnvironmentConnectionPhase(undefined, true)).toBe("connecting");
expect(resolveHomeEnvironmentConnectionPhase(undefined, false)).toBe("available");
expect(resolveHomeEnvironmentConnectionPhase("connected", true)).toBe("connected");
});
it("stays hidden while a ready environment is connected", () => {
expect(shouldShowWorkspaceConnectionStatus(workspaceState())).toBe(false);
});
@@ -84,4 +92,56 @@ describe("workspace connection status", () => {
expect(shouldShowWorkspaceConnectionStatus(state)).toBe(true);
expect(workspaceConnectionStatusLabel(state)).toBe("Loading threads...");
});
it("keeps healthy shell synchronization out of the Home wordmark", () => {
const state = workspaceState({ hasPendingShellSnapshot: true });
expect(workspaceConnectionHeaderPresentation(state, "Leftbook")).toBeNull();
});
it("presents reconnecting environments in amber", () => {
const state = workspaceState({
hasConnectingEnvironment: true,
connectingEnvironments: [
{
environmentId: "environment-1" as never,
environmentLabel: "Leftbook",
displayUrl: "",
isRelayManaged: false,
connectionState: "reconnecting",
connectionError: null,
connectionErrorTraceId: null,
},
],
});
expect(workspaceConnectionHeaderPresentation(state, "Other device")).toEqual({
detail: "reconnecting",
label: "Leftbook",
tone: "amber",
});
});
it("presents unreachable environments in red", () => {
const state = workspaceState({
connectionError: "Connection refused",
hasReadyEnvironment: false,
});
expect(workspaceConnectionHeaderPresentation(state, "Steambox")).toEqual({
detail: "unreachable",
label: "Steambox",
tone: "red",
});
});
it("surfaces one unavailable device while other environments stay connected", () => {
const state = workspaceState();
expect(workspaceConnectionHeaderPresentation(state, "Steambox", "available")).toEqual({
detail: "unreachable",
label: "Steambox",
tone: "red",
});
});
});
@@ -1,17 +1,81 @@
import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
import { SymbolView } from "../../components/AppSymbol";
import { ActivityIndicator, Pressable } from "react-native";
import type { ReactNode } from "react";
import { Pressable, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { useThemeColor } from "../../lib/useThemeColor";
import type { WorkspaceState } from "../../state/workspaceModel";
import { workspaceConnectionStatusLabel } from "./workspace-connection-status";
import {
workspaceConnectionHeaderPresentation,
workspaceConnectionStatusLabel,
} from "./workspace-connection-status";
export function WorkspaceConnectionStatus(props: {
readonly state: WorkspaceState;
readonly onPress: () => void;
readonly variant?: "floating" | "sidebar";
readonly onReconnect?: () => void;
readonly environmentLabel?: string;
readonly environmentConnectionState?: EnvironmentConnectionPhase;
readonly fallback?: ReactNode;
readonly variant?: "floating" | "header" | "sidebar";
}) {
const iconColor = useThemeColor("--color-icon-muted");
if (props.variant === "header") {
const presentation = workspaceConnectionHeaderPresentation(
props.state,
props.environmentLabel,
props.environmentConnectionState,
);
if (presentation === null) return <>{props.fallback}</>;
const tintColor = presentation.tone === "amber" ? "#fbbf24" : "#f87171";
const label = `${presentation.label} ${presentation.detail}`;
return (
<View className="h-12 min-w-0 flex-row items-center gap-2.5">
<Pressable
accessibilityHint="Opens environment settings"
accessibilityLabel={label}
accessibilityRole="button"
className="min-w-0 flex-1 flex-row items-center gap-2.5 self-stretch"
onPress={props.onPress}
>
<SymbolView
name={
presentation.tone === "amber" ? "point.3.connected.trianglepath.dotted" : "wifi.slash"
}
size={17}
tintColor={tintColor}
type="monochrome"
/>
<Text
className="min-w-0 shrink text-base font-t3-bold"
numberOfLines={1}
style={{ color: tintColor }}
>
{presentation.label}{" "}
<Text className="text-sm font-t3-medium" style={{ color: tintColor, opacity: 0.72 }}>
{presentation.detail}
</Text>
</Text>
</Pressable>
{presentation.tone === "red" && props.onReconnect ? (
<Pressable
accessibilityLabel={`Reconnect ${presentation.label}`}
accessibilityRole="button"
hitSlop={8}
onPress={props.onReconnect}
>
<Text className="text-xs font-t3-bold" style={{ color: tintColor }}>
Reconnect
</Text>
</Pressable>
) : null}
</View>
);
}
const isSynchronizing =
props.state.networkStatus !== "offline" &&
props.state.connectionError === null &&
@@ -41,7 +105,12 @@ export function WorkspaceConnectionStatus(props: {
}
>
{isSynchronizing ? (
<ActivityIndicator color={iconColor} size="small" />
<SymbolView
name="point.3.connected.trianglepath.dotted"
size={15}
tintColor={iconColor}
type="monochrome"
/>
) : (
<SymbolView name="wifi.slash" size={15} tintColor={iconColor} type="monochrome" />
)}
@@ -29,6 +29,13 @@ function environmentSupportsSnooze(environmentId: EnvironmentThreadShell["enviro
);
}
function environmentSupportsPinning(environmentId: EnvironmentThreadShell["environmentId"]) {
return (
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
.threadPinning === true
);
}
type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";
const ACTION_VERBS: Record<ThreadListAction, string> = {
@@ -202,10 +209,14 @@ export function useThreadListActions(): {
readonly snoozeThread: (thread: EnvironmentThreadShell, snoozedUntil: string) => Promise<boolean>;
readonly unsnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly unsettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly pinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly unpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
} {
const executeAction = useThreadActionExecutor();
const snoozeMutation = useAtomCommand(threadEnvironment.snooze, { reportFailure: false });
const unsnoozeMutation = useAtomCommand(threadEnvironment.unsnooze, { reportFailure: false });
const pinMutation = useAtomCommand(threadEnvironment.pin, { reportFailure: false });
const unpinMutation = useAtomCommand(threadEnvironment.unpin, { reportFailure: false });
const snoozeInFlightThreadKeys = useRef(new Set<string>());
const archiveThread = useCallback(
@@ -310,6 +321,62 @@ export function useThreadListActions(): {
async (thread: EnvironmentThreadShell) => (await executeAction("unsettle", thread)) === true,
[executeAction],
);
const pinThread = useCallback(
async (thread: EnvironmentThreadShell) => {
if (!environmentSupportsPinning(thread.environmentId)) {
Alert.alert(
"Could not pin thread",
"This environment's server does not support pinning yet. Update the server to use Pin.",
);
return false;
}
selectionHaptic();
const result = await pinMutation({
environmentId: thread.environmentId,
input: { threadId: thread.id },
});
if (result._tag === "Failure") {
const error = Cause.squash(result.cause);
Alert.alert(
"Could not pin thread",
error instanceof Error && error.message.trim().length > 0
? error.message
: "The thread could not be pinned.",
);
return false;
}
return true;
},
[pinMutation],
);
const unpinThread = useCallback(
async (thread: EnvironmentThreadShell) => {
if (!environmentSupportsPinning(thread.environmentId)) {
Alert.alert(
"Could not unpin thread",
"This environment's server does not support pinning yet. Update the server to use Pin.",
);
return false;
}
selectionHaptic();
const result = await unpinMutation({
environmentId: thread.environmentId,
input: { threadId: thread.id },
});
if (result._tag === "Failure") {
const error = Cause.squash(result.cause);
Alert.alert(
"Could not unpin thread",
error instanceof Error && error.message.trim().length > 0
? error.message
: "The thread could not be unpinned.",
);
return false;
}
return true;
},
[unpinMutation],
);
const confirmDeleteThread = useConfirmDeleteThread(executeAction);
@@ -320,6 +387,8 @@ export function useThreadListActions(): {
snoozeThread,
unsnoozeThread,
unsettleThread,
pinThread,
unpinThread,
};
}
@@ -1,5 +1,14 @@
import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
import type { WorkspaceState } from "../../state/workspaceModel";
export function resolveHomeEnvironmentConnectionPhase(
connectionState: EnvironmentConnectionPhase | undefined,
isLoadingConnections: boolean,
): EnvironmentConnectionPhase {
return connectionState ?? (isLoadingConnections ? "connecting" : "available");
}
export function shouldShowWorkspaceConnectionStatus(state: WorkspaceState): boolean {
return (
state.networkStatus === "offline" ||
@@ -24,3 +33,71 @@ export function workspaceConnectionStatusLabel(state: WorkspaceState): string {
}
return "Not connected";
}
export interface WorkspaceConnectionHeaderPresentation {
readonly detail: "reconnecting" | "unreachable";
readonly label: string;
readonly tone: "amber" | "red";
}
/**
* Only actual connection trouble displaces the Home wordmark. Shell catch-up
* is healthy background work and deliberately leaves the header unchanged.
*/
export function workspaceConnectionHeaderPresentation(
state: WorkspaceState,
environmentLabel?: string,
environmentConnectionState?: EnvironmentConnectionPhase,
): WorkspaceConnectionHeaderPresentation | null {
if (state.networkStatus === "offline") {
return {
detail: "unreachable",
label: environmentLabel ?? "Network",
tone: "red",
};
}
if (
environmentConnectionState === "connecting" ||
environmentConnectionState === "reconnecting"
) {
return {
detail: "reconnecting",
label: environmentLabel ?? "Environment",
tone: "amber",
};
}
if (environmentConnectionState && environmentConnectionState !== "connected") {
return {
detail: "unreachable",
label: environmentLabel ?? "Environment",
tone: "red",
};
}
if (state.connectingEnvironments.length > 0) {
const connecting = state.connectingEnvironments[0];
return {
detail: "reconnecting",
label:
state.connectingEnvironments.length === 1
? (connecting?.environmentLabel ?? environmentLabel ?? "Environment")
: `${state.connectingEnvironments.length} environments`,
tone: "amber",
};
}
if (
state.connectionError !== null ||
(state.hasConnections && state.hasLoadedShellSnapshot && !state.hasReadyEnvironment)
) {
return {
detail: "unreachable",
label: environmentLabel ?? "Environment",
tone: "red",
};
}
return null;
}
@@ -1,11 +1,10 @@
import { NativeStackScreenOptions } from "../../native/StackHeader";
import { StackActions, useNavigation, usePreventRemove } from "@react-navigation/native";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Alert, InteractionManager, Platform, View, useColorScheme } from "react-native";
import { Alert, Keyboard, Pressable, View, useColorScheme } from "react-native";
import { KeyboardAvoidingView, useKeyboardState } from "react-native-keyboard-controller";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { useFontFamily } from "../../lib/useFontFamily";
import { EnvironmentId } from "@t3tools/contracts";
import {
@@ -20,9 +19,11 @@ import {
ComposerToolbarScroller,
ComposerToolbarTrigger,
} from "../../components/ComposerToolbarTrigger";
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
import { AppText as Text } from "../../components/AppText";
import { SymbolView } from "../../components/AppSymbol";
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
import { ControlPillMenu } from "../../components/ControlPill";
import { ModelPickerSheet } from "../../components/ModelPickerSheet";
import { ProviderIcon } from "../../components/ProviderIcon";
import { ComposerSurface } from "./ThreadComposer";
@@ -31,7 +32,6 @@ import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/
import {
applyProviderOptionMenuEvent,
buildProviderOptionMenuActions,
providerOptionsConfigurationLabel,
resolveProviderOptionDescriptors,
} from "../../lib/providerOptions";
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
@@ -43,7 +43,7 @@ import {
type ComposerDraft,
} from "../../state/use-composer-drafts";
import { useEnvironmentServerConfig, useProjects } from "../../state/entities";
import { buildModelMenuActions, resolveSelectableModelSelection } from "../../lib/modelOptions";
import { resolveSelectableModelSelection } from "../../lib/modelOptions";
import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";
@@ -51,18 +51,7 @@ import { useRemoteConnectionStatus } from "../../state/use-remote-environment-re
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
import { useCreateProjectThread } from "./use-project-actions";
import { useIncomingShare } from "../sharing/IncomingShareProvider";
function formatWorkspaceLabel(input: {
readonly workspaceMode: string;
readonly currentBranchName: string | null;
readonly selectedBranchName: string | null;
}): string {
const branchName = input.selectedBranchName ?? input.currentBranchName;
if (input.workspaceMode === "worktree") {
return branchName ? `New worktree · ${branchName}` : "New worktree";
}
return branchName ? `Current · ${branchName}` : "Current checkout";
}
import { useModelFavorites } from "./useModelFavorites";
export function NewTaskDraftScreen(props: {
readonly initialProjectRef?: {
@@ -94,6 +83,9 @@ export function NewTaskDraftScreen(props: {
const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
selectedProject?.environmentId ?? null,
);
const { favoriteModelKeys, favoritesReady, toggleFavorite } = useModelFavorites(
selectedProject?.environmentId ?? null,
);
const environmentConnected =
selectedProject !== null &&
connectedEnvironments.find(
@@ -101,12 +93,12 @@ export function NewTaskDraftScreen(props: {
)?.connectionState === "connected";
const promptInputRef = useRef<ComposerEditorHandle>(null);
const loadedBranchesProjectKeyRef = useRef<string | null>(null);
const [isComposerFocused, setIsComposerFocused] = useState(false);
const [importingShareKey, setImportingShareKey] = useState<string | null>(null);
const [isCancellingShareImport, setIsCancellingShareImport] = useState(false);
const [cancelledIncomingShareId, setCancelledIncomingShareId] = useState<string | null>(null);
const [isReturningToProjectPicker, setIsReturningToProjectPicker] = useState(false);
const [shareImportAttempt, setShareImportAttempt] = useState(0);
const [modelPickerVisible, setModelPickerVisible] = useState(false);
const startedShareImportKeyRef = useRef<string | null>(null);
const cancellingShareImportKeyRef = useRef<string | null>(null);
const shareImportDraftBackupRef = useRef(new Map<string, ComposerDraft>());
@@ -221,11 +213,8 @@ export function NewTaskDraftScreen(props: {
}, [props.pendingTaskId, cancelEditingPendingTask]);
const foregroundColor = useThemeColor("--color-foreground");
const regularFontFamily = useFontFamily("regular");
const bodyText = useScaledTextRole("body");
const headlineText = useScaledTextRole("headline");
const sheetFadeOpaque = colorScheme === "dark" ? "rgba(14,14,14,0.98)" : "rgba(242,242,247,0.98)";
const sheetFadeTransparent = colorScheme === "dark" ? "rgba(14,14,14,0)" : "rgba(242,242,247,0)";
// A new navigation to this mounted screen delivers a fresh initialProjectRef
// reference — treat it as a new request and let it apply again.
@@ -510,26 +499,6 @@ export function NewTaskDraftScreen(props: {
shareImportAttempt,
]);
useEffect(() => {
// Android starts with the collapsed composer pill (like an open thread)
// and only expands/focuses when tapped.
if (!selectedProject || Platform.OS === "android") {
return;
}
let focusFrame: ReturnType<typeof requestAnimationFrame> | null = null;
const interaction = InteractionManager.runAfterInteractions(() => {
focusFrame = requestAnimationFrame(() => promptInputRef.current?.focus());
});
return () => {
interaction.cancel();
if (focusFrame !== null) {
cancelAnimationFrame(focusFrame);
}
};
}, [selectedProject]);
const environmentMenuActions = useMemo(
() =>
flow.environments.map((environment) => ({
@@ -542,10 +511,6 @@ export function NewTaskDraftScreen(props: {
[flow.environments, flow.selectedEnvironmentId, isIncomingShareTransferPending],
);
const modelMenuActions = useMemo(
() => buildModelMenuActions(flow.providerGroups, flow.selectedModel),
[flow.providerGroups, flow.selectedModel],
);
const providerOptionDescriptors = useMemo(
() =>
resolveProviderOptionDescriptors({
@@ -669,30 +634,19 @@ export function NewTaskDraftScreen(props: {
flow.environments.find(
(environment) => environment.environmentId === flow.selectedEnvironmentId,
)?.environmentLabel ?? "Environment";
const currentBranchName =
flow.availableBranches.find((branch) => branch.current)?.name ??
flow.availableBranches.find((branch) => branch.isDefault)?.name ??
null;
const configurationLabel = useMemo(
() => providerOptionsConfigurationLabel(providerOptionDescriptors),
[providerOptionDescriptors],
const configurationMenuActions = useMemo(
() => [
...optionsMenuActions,
{
id: "options-environment",
title: "Environment",
subtitle: selectedEnvironmentLabel,
subactions: environmentMenuActions,
},
...workspaceMenuActions,
],
[environmentMenuActions, optionsMenuActions, selectedEnvironmentLabel, workspaceMenuActions],
);
const workspaceLabel = useMemo(
() =>
formatWorkspaceLabel({
currentBranchName,
selectedBranchName: flow.selectedBranchName,
workspaceMode: flow.workspaceMode,
}),
[currentBranchName, flow.selectedBranchName, flow.workspaceMode],
);
function handleModelMenuAction(event: string) {
if (isIncomingShareTransferPending || !event.startsWith("model:")) {
return;
}
flow.setSelectedModelKey(event.slice("model:".length));
}
function handleEnvironmentMenuAction(event: string) {
if (isIncomingShareTransferPending || !event.startsWith("environment:")) {
return;
@@ -745,6 +699,12 @@ export function NewTaskDraftScreen(props: {
}
}
function handleConfigurationMenuAction(event: string) {
handleOptionsMenuAction(event);
handleEnvironmentMenuAction(event);
handleWorkspaceMenuAction(event);
}
async function handlePickImages(): Promise<void> {
if (isIncomingShareTransferPending) {
return;
@@ -911,24 +871,13 @@ export function NewTaskDraftScreen(props: {
if (!selectedProject) {
return (
<View className="flex-1 bg-sheet">
{Platform.OS === "android" ? (
<>
<NativeStackScreenOptions options={{ headerShown: false }} />
<AndroidScreenHeader title="New Thread" onBack={() => navigation.goBack()} />
</>
) : (
<NativeStackScreenOptions options={{ title: "Loading task" }} />
)}
<View className="flex-1 bg-screen">
<NativeStackScreenOptions options={{ headerShown: false }} />
</View>
);
}
const isAndroid = Platform.OS === "android";
const isDarkMode = colorScheme === "dark";
// Android expansion follows native editor focus so relayout cannot race
// the touch gesture that opens the keyboard.
const isExpanded = !isAndroid || isComposerFocused;
const canStart =
Boolean(flow.selectedProject) &&
Boolean(flow.selectedModel) &&
@@ -940,90 +889,57 @@ export function NewTaskDraftScreen(props: {
const promptEditor = (
<ComposerEditor
ref={promptInputRef}
// Native autoFocus fires becomeFirstResponder in didMoveToWindow, which
// forces the iOS keyboard bring-up during the formSheet present
// animation and stalls it. The runAfterInteractions effect above focuses
// the editor once the transition settles instead.
autoFocus={false}
editable={!isIncomingShareTransferPending}
multiline
scrollEnabled={isExpanded}
scrollEnabled
value={flow.prompt}
skills={flow.selectedProviderSkills}
onChangeText={flow.setPrompt}
onFocus={() => setIsComposerFocused(true)}
onBlur={() => setIsComposerFocused(false)}
onPasteImages={(uris) => void handleNativePasteImages(uris)}
placeholder={`Describe a coding task in ${selectedProject.title}`}
// Same collapsed centering as ThreadComposer: native vertical gravity
// in a pill-height box.
singleLineCentered={!isExpanded}
contentInsetVertical={isAndroid ? 0 : undefined}
style={
isAndroid
? isExpanded
? { minHeight: 80, maxHeight: 160, paddingHorizontal: 4, paddingVertical: 4 }
: { height: 36 }
: { flex: 1, minHeight: 0 }
}
textStyle={
isAndroid
? { ...bodyText, color: foregroundColor, fontFamily: regularFontFamily }
: headlineText
}
placeholder="Ask anything..."
contentInsetVertical={0}
style={{
minHeight: 76,
maxHeight: 160,
paddingHorizontal: 4,
paddingVertical: 4,
}}
textStyle={{ ...bodyText, color: foregroundColor }}
/>
);
const toolbarPills = (
<>
<ComposerToolbarButton
icon="plus"
accessibilityLabel="Add attachment"
disabled={isIncomingShareTransferPending}
icon="paperclip"
onPress={() => void handlePickImages()}
showChevron={false}
variant="ghost"
/>
<ComposerToolbarTrigger
accessibilityLabel="Choose model"
disabled={isIncomingShareTransferPending}
iconNode={<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={18} />}
label={flow.selectedModelOption?.label ?? "Model"}
onPress={() => {
Keyboard.dismiss();
setModelPickerVisible(true);
}}
variant="ghost"
/>
<ControlPillMenu
actions={modelMenuActions}
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Model"
disabled={isIncomingShareTransferPending}
iconNode={<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />}
label={flow.selectedModelOption?.label ?? "Model"}
/>
</ControlPillMenu>
<ControlPillMenu
actions={optionsMenuActions}
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
actions={configurationMenuActions}
onPressAction={({ nativeEvent }) => handleConfigurationMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Configuration"
disabled={isIncomingShareTransferPending}
icon="slider.horizontal.3"
label={configurationLabel}
/>
</ControlPillMenu>
<ControlPillMenu
actions={environmentMenuActions}
onPressAction={({ nativeEvent }) => handleEnvironmentMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Environment"
disabled={isIncomingShareTransferPending}
icon="desktopcomputer"
label={selectedEnvironmentLabel}
/>
</ControlPillMenu>
<ControlPillMenu
actions={workspaceMenuActions}
onPressAction={({ nativeEvent }) => handleWorkspaceMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Workspace"
disabled={isIncomingShareTransferPending}
icon="point.topleft.down.curvedto.point.bottomright.up"
label={workspaceLabel}
showChevron={false}
variant="ghost"
/>
</ControlPillMenu>
</>
@@ -1034,7 +950,7 @@ export function NewTaskDraftScreen(props: {
accessibilityLabel={
flow.submitting ? "Starting task" : environmentConnected ? "Start task" : "Queue task"
}
icon={environmentConnected ? "arrow.up" : "tray.and.arrow.up"}
icon="arrow.up"
onPress={() => void handleStart()}
variant="primary"
showChevron={false}
@@ -1042,115 +958,126 @@ export function NewTaskDraftScreen(props: {
/>
);
if (isAndroid) {
// The draft is a thread that doesn't exist yet, so it mirrors the thread
// page: in-screen header, empty feed canvas above, and the same floating
// composer chrome as ThreadComposer (collapsed pill → expanded card).
return (
<View className="flex-1 bg-screen">
<NativeStackScreenOptions options={{ headerShown: false }} />
<AndroidScreenHeader title="New Thread" onBack={() => navigation.goBack()} />
<KeyboardAvoidingView automaticOffset behavior="padding" className="flex-1">
<View className="flex-1" />
<View
className="px-4 pt-2"
return (
<View
className="flex-1 overflow-hidden"
style={{
backgroundColor: isDarkMode ? "#000000" : "#f2f2f7",
borderColor: isDarkMode ? "rgba(255,255,255,0.14)" : "rgba(0,0,0,0.1)",
borderTopLeftRadius: 20,
borderTopRightRadius: 20,
borderTopWidth: 1,
}}
>
<NativeStackScreenOptions options={{ headerShown: false }} />
<KeyboardAvoidingView automaticOffset behavior="padding" className="flex-1">
<View style={{ paddingTop: Math.max(insets.top, 8) }}>
<Pressable
accessibilityRole="button"
disabled={isIncomingShareTransferPending || isCancellingShareImport}
hitSlop={8}
onPress={() => navigation.goBack()}
className="self-start px-4 py-3 active:opacity-60"
style={{
paddingBottom: controlsBottomPadding,
experimental_backgroundImage: isDarkMode
? "linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,0.85) 40%, rgba(0,0,0,0.95) 100%)"
: "linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.85) 40%, rgba(255,255,255,0.95) 100%)",
opacity: isIncomingShareTransferPending || isCancellingShareImport ? 0.45 : 1,
}}
>
<ComposerSurface
isDarkMode={isDarkMode}
style={
isExpanded
? {
borderRadius: 20,
overflow: "hidden",
paddingHorizontal: 14,
paddingVertical: 12,
}
: {
borderRadius: 999,
overflow: "hidden",
flexDirection: "row",
alignItems: "center",
paddingLeft: 18,
paddingRight: 5,
paddingVertical: 5,
}
}
<Text className="text-sm text-foreground-muted">Cancel</Text>
</Pressable>
</View>
<View className="min-h-0 flex-1 items-center justify-center px-6 pb-12">
<Text
className="text-center font-t3-medium text-foreground"
style={[headlineText, { fontSize: 28, lineHeight: 34, letterSpacing: -0.6 }]}
>
What should we build
</Text>
<View className="max-w-full flex-row items-center justify-center">
<Text
className="font-t3-medium text-foreground"
style={[headlineText, { fontSize: 28, lineHeight: 34, letterSpacing: -0.6 }]}
>
{isExpanded && flow.attachments.length > 0 ? (
<View className="pb-2.5">
<ComposerAttachmentStrip
attachments={flow.attachments}
onRemove={
isIncomingShareTransferPending ? () => undefined : flow.removeAttachment
}
/>
</View>
) : null}
<View className={isExpanded ? undefined : "min-w-0 flex-1"}>{promptEditor}</View>
{!isExpanded ? (
<ControlPill
icon="arrow.up"
variant="primary"
disabled={!canStart}
onPress={() => void handleStart()}
/>
) : null}
</ComposerSurface>
{isExpanded ? (
<ComposerToolbarRow paddingBottom={8} paddingHorizontal={0} paddingTop={8}>
<ComposerToolbarScroller
fadeOpaque={isDarkMode ? "rgba(0,0,0,0.95)" : "rgba(255,255,255,0.95)"}
fadeTransparent={isDarkMode ? "rgba(0,0,0,0)" : "rgba(255,255,255,0)"}
>
{toolbarPills}
</ComposerToolbarScroller>
{startButton}
</ComposerToolbarRow>
) : null}
</View>
</KeyboardAvoidingView>
</View>
);
}
return (
<View className="flex-1 bg-sheet">
<NativeStackScreenOptions options={{ title: selectedProject.title }} />
<KeyboardAvoidingView automaticOffset behavior="padding" className="flex-1">
<View className="min-h-0 flex-1 px-5 pt-2">{promptEditor}</View>
<View className="border-t border-border" style={{ paddingBottom: controlsBottomPadding }}>
{flow.attachments.length > 0 ? (
<View className="px-4 pt-3">
<ComposerAttachmentStrip
attachments={flow.attachments}
onRemove={isIncomingShareTransferPending ? () => undefined : flow.removeAttachment}
imageSize={88}
imageBorderRadius={20}
/>
in{" "}
</Text>
<View
className="max-w-[240px] border-b border-foreground-muted"
style={{ borderStyle: "dotted" }}
>
<Text
className="font-t3-medium text-foreground"
ellipsizeMode="tail"
numberOfLines={1}
style={[headlineText, { fontSize: 28, lineHeight: 34, letterSpacing: -0.6 }]}
>
{selectedProject.title}
</Text>
</View>
) : null}
<ComposerToolbarRow paddingBottom={controlsBottomPadding} paddingHorizontal={6}>
<ComposerToolbarScroller
fadeOpaque={sheetFadeOpaque}
fadeTransparent={sheetFadeTransparent}
<Text
className="font-t3-medium text-foreground"
style={[headlineText, { fontSize: 28, lineHeight: 34, letterSpacing: -0.6 }]}
>
{toolbarPills}
</ComposerToolbarScroller>
{startButton}
</ComposerToolbarRow>
?
</Text>
</View>
<View className="mt-2 flex-row items-center gap-1.5">
<SymbolView
name="desktopcomputer"
size={12}
tintColor={isDarkMode ? "#66676d" : "#8e8e93"}
type="monochrome"
/>
<Text className="text-xs text-foreground-tertiary">on {selectedEnvironmentLabel}</Text>
</View>
</View>
<View
style={{ paddingBottom: controlsBottomPadding, paddingHorizontal: 10, paddingTop: 8 }}
>
<ComposerSurface
isDarkMode={isDarkMode}
style={{
backgroundColor: isDarkMode ? "rgba(17,17,19,0.95)" : "rgba(255,255,255,0.95)",
borderRadius: 22,
overflow: "hidden",
paddingBottom: 6,
paddingHorizontal: 12,
paddingTop: 10,
}}
>
{flow.attachments.length > 0 ? (
<View className="pb-2.5">
<ComposerAttachmentStrip
attachments={flow.attachments}
onRemove={
isIncomingShareTransferPending ? () => undefined : flow.removeAttachment
}
/>
</View>
) : null}
{promptEditor}
<ComposerToolbarRow paddingBottom={0} paddingHorizontal={0} paddingTop={4}>
<ComposerToolbarScroller
fadeOpaque={isDarkMode ? "rgba(17,17,19,0.95)" : "rgba(255,255,255,0.95)"}
fadeTransparent={isDarkMode ? "rgba(17,17,19,0)" : "rgba(255,255,255,0)"}
>
{toolbarPills}
</ComposerToolbarScroller>
{startButton}
</ComposerToolbarRow>
</ComposerSurface>
</View>
</KeyboardAvoidingView>
<ModelPickerSheet
favoriteModelKeys={favoriteModelKeys}
favoritesEnabled={favoritesReady}
groups={flow.providerGroups}
onClose={() => setModelPickerVisible(false)}
onSelectModel={(option) => flow.setSelectedModelKey(option.key)}
onToggleFavorite={toggleFavorite}
selectedModel={flow.selectedModel}
visible={modelPickerVisible}
/>
</View>
);
}
@@ -2,10 +2,12 @@ import type { ApprovalRequestId, ProviderApprovalDecision } from "@t3tools/contr
import { Pressable, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { cn } from "../../lib/cn";
import type { PendingApproval } from "../../lib/threadActivity";
export interface PendingApprovalCardProps {
readonly approval: PendingApproval;
readonly approvalCount: number;
readonly respondingApprovalId: ApprovalRequestId | null;
readonly onRespond: (
requestId: ApprovalRequestId,
@@ -13,44 +15,106 @@ export interface PendingApprovalCardProps {
) => Promise<unknown>;
}
const APPROVAL_COPY = {
command: {
eyebrow: "Command",
title: "Command approval requested",
},
"file-read": {
eyebrow: "File read",
title: "File read approval requested",
},
"file-change": {
eyebrow: "File change",
title: "File change approval requested",
},
} as const satisfies Record<PendingApproval["requestKind"], { eyebrow: string; title: string }>;
export function PendingApprovalCard(props: PendingApprovalCardProps) {
const copy = APPROVAL_COPY[props.approval.requestKind];
const isResponding = props.respondingApprovalId === props.approval.requestId;
const respond = (decision: ProviderApprovalDecision) => {
void props.onRespond(props.approval.requestId, decision);
};
return (
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100/80 p-4 dark:border-white/6 dark:bg-neutral-900/80">
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
Approval needed
</Text>
<Text className="font-t3-bold text-lg text-neutral-950 dark:text-neutral-50">
{props.approval.requestKind}
</Text>
{props.approval.detail ? (
<Text className="font-sans text-sm leading-normal text-neutral-600 dark:text-neutral-400">
{props.approval.detail}
</Text>
) : null}
<View className="flex-row flex-wrap gap-2.5">
<Pressable
className="items-center justify-center rounded-[14px] bg-blue-500 px-3.5 py-3"
disabled={props.respondingApprovalId === props.approval.requestId}
onPress={() => void props.onRespond(props.approval.requestId, "accept")}
>
<Text className="font-t3-extrabold text-sm text-white">Allow once</Text>
</Pressable>
<Pressable
className="items-center justify-center rounded-[14px] bg-neutral-200 px-3.5 py-3 dark:bg-neutral-800"
disabled={props.respondingApprovalId === props.approval.requestId}
onPress={() => void props.onRespond(props.approval.requestId, "acceptForSession")}
>
<Text className="font-t3-bold text-sm text-neutral-950 dark:text-neutral-50">
Allow session
<View
accessibilityLabel={copy.title}
className="overflow-hidden rounded-[22px] border border-border bg-card"
>
<View className="gap-2.5 px-4 pb-3.5 pt-3.5">
<View className="flex-row items-center justify-between gap-3">
<Text className="font-t3-bold text-2xs uppercase tracking-[1.2px] text-amber-600 dark:text-amber-300">
Pending approval
</Text>
</Pressable>
<Pressable
className="items-center justify-center rounded-[14px] bg-rose-100 px-3.5 py-3 dark:bg-rose-500/18"
disabled={props.respondingApprovalId === props.approval.requestId}
onPress={() => void props.onRespond(props.approval.requestId, "decline")}
>
<Text className="font-t3-bold text-sm text-rose-700 dark:text-rose-300">Decline</Text>
</Pressable>
<Text className="font-t3-medium text-sm tabular-nums text-foreground-tertiary">
1/{Math.max(1, props.approvalCount)}
</Text>
</View>
<Text className="font-t3-bold text-lg text-foreground">{copy.title}</Text>
<View className="gap-1.5 rounded-xl border border-border-subtle bg-screen px-3 py-2.5">
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-foreground-tertiary">
{copy.eyebrow}
</Text>
<Text selectable className="font-mono text-sm leading-[21px] text-foreground-secondary">
{props.approval.detail ?? "Review the requested operation before continuing."}
</Text>
</View>
</View>
<View className="gap-2.5 border-t border-border px-3 pb-3 pt-2.5">
<View className="flex-row gap-2">
<Pressable
accessibilityLabel="Approve once"
accessibilityRole="button"
accessibilityState={{ disabled: isResponding }}
className={cn(
"min-h-12 flex-1 items-center justify-center rounded-xl bg-blue-600 px-3",
isResponding && "opacity-50",
)}
disabled={isResponding}
onPress={() => respond("accept")}
>
<Text className="font-t3-bold text-base text-white">Approve once</Text>
</Pressable>
<Pressable
accessibilityLabel="Always allow for this session"
accessibilityRole="button"
accessibilityState={{ disabled: isResponding }}
className={cn(
"min-h-12 flex-1 items-center justify-center rounded-xl border border-secondary-border bg-secondary px-3",
isResponding && "opacity-50",
)}
disabled={isResponding}
onPress={() => respond("acceptForSession")}
>
<Text className="font-t3-bold text-base text-secondary-foreground">Always allow</Text>
</Pressable>
</View>
<View className="flex-row items-center justify-center gap-8">
<Pressable
accessibilityLabel="Decline approval"
accessibilityRole="button"
accessibilityState={{ disabled: isResponding }}
className={cn("min-h-7 justify-center px-2", isResponding && "opacity-50")}
disabled={isResponding}
hitSlop={8}
onPress={() => respond("decline")}
>
<Text className="font-t3-bold text-base text-red-600 dark:text-red-400">Decline</Text>
</Pressable>
<Pressable
accessibilityLabel="Cancel turn"
accessibilityRole="button"
accessibilityState={{ disabled: isResponding }}
className={cn("min-h-7 justify-center px-2", isResponding && "opacity-50")}
disabled={isResponding}
hitSlop={8}
onPress={() => respond("cancel")}
>
<Text className="font-t3-medium text-base text-foreground-muted">Cancel turn</Text>
</Pressable>
</View>
</View>
</View>
);
@@ -1,9 +1,12 @@
import type { ApprovalRequestId } from "@t3tools/contracts";
import { useState } from "react";
import { Pressable, View } from "react-native";
import { SymbolView } from "../../components/AppSymbol";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { cn } from "../../lib/cn";
import type { PendingUserInput, PendingUserInputDraftAnswer } from "../../lib/threadActivity";
import { useThemeColor } from "../../lib/useThemeColor";
export interface PendingUserInputCardProps {
readonly pendingUserInput: PendingUserInput;
@@ -23,83 +26,176 @@ export interface PendingUserInputCardProps {
readonly onSubmit: () => Promise<unknown>;
}
function hasDraftAnswer(draft: PendingUserInputDraftAnswer | undefined): boolean {
return Boolean(draft?.customAnswer?.trim() || draft?.selectedOptionLabel?.trim());
}
function firstUnansweredQuestionIndex(
questions: PendingUserInput["questions"],
drafts: Record<string, PendingUserInputDraftAnswer>,
): number {
const index = questions.findIndex((question) => !hasDraftAnswer(drafts[question.id]));
return index === -1 ? Math.max(questions.length - 1, 0) : index;
}
export function PendingUserInputCard(props: PendingUserInputCardProps) {
const [questionIndex, setQuestionIndex] = useState(() =>
firstUnansweredQuestionIndex(props.pendingUserInput.questions, props.drafts),
);
const selectedColor = useThemeColor("--color-md-link");
const activeQuestion = props.pendingUserInput.questions[questionIndex] ?? null;
const draft = activeQuestion ? props.drafts[activeQuestion.id] : undefined;
const isResponding = props.respondingUserInputId === props.pendingUserInput.requestId;
const isLastQuestion = questionIndex >= props.pendingUserInput.questions.length - 1;
const canGoBack = questionIndex > 0 && !isResponding;
const canAdvance = hasDraftAnswer(draft);
const canContinue = isLastQuestion ? props.answers !== null : canAdvance;
if (!activeQuestion) {
return null;
}
const handleAdvance = () => {
if (!canContinue || isResponding) {
return;
}
if (!isLastQuestion) {
setQuestionIndex((current) =>
Math.min(current + 1, props.pendingUserInput.questions.length - 1),
);
return;
}
if (props.answers) {
void props.onSubmit();
}
};
const handleBack = () => {
if (!canGoBack) return;
setQuestionIndex((current) => Math.max(0, current - 1));
};
return (
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100/80 p-4 dark:border-white/6 dark:bg-neutral-900/80">
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
User input needed
</Text>
<Text className="font-t3-bold text-lg text-neutral-950 dark:text-neutral-50">
Fill in the pending answers
</Text>
{props.pendingUserInput.questions.map((question) => {
const draft = props.drafts[question.id];
return (
<View key={question.id} className="gap-2 pt-1">
<Text className="font-t3-bold text-xs uppercase tracking-[1px] text-neutral-500 dark:text-neutral-500">
{question.header}
</Text>
<Text className="font-sans text-base leading-snug text-neutral-950 dark:text-neutral-50">
{question.question}
</Text>
<View className="flex-row flex-wrap gap-2.5">
{question.options.map((option) => {
const selected =
draft?.selectedOptionLabel === option.label && !draft.customAnswer?.trim().length;
return (
<Pressable
key={option.label}
className={cn(
"rounded-full border px-3 py-2.5 ",
selected
? "border-blue-300/50 bg-blue-50 dark:border-blue-400/28 dark:bg-blue-400/14"
: "border-neutral-200 bg-white dark:border-white/6 dark:bg-neutral-950/70",
)}
onPress={() =>
props.onSelectOption(
props.pendingUserInput.requestId,
question.id,
option.label,
)
}
>
<Text
className={cn(
"font-t3-bold text-sm",
selected
? "text-sky-700 dark:text-sky-300"
: "text-neutral-600 dark:text-neutral-300",
)}
>
{option.label}
</Text>
</Pressable>
);
})}
</View>
<TextInput
value={draft?.customAnswer ?? ""}
onChangeText={(value) =>
props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
<View
accessibilityLabel={`Input needed: ${activeQuestion.question}`}
className="overflow-hidden rounded-[22px] border border-border bg-card"
>
<View className="gap-2 px-4 pb-3 pt-3.5">
<View className="flex-row items-center justify-between gap-3">
<Text
numberOfLines={1}
className="min-w-0 flex-1 font-t3-bold text-2xs uppercase tracking-[1.2px] text-indigo-600 dark:text-indigo-300"
>
{activeQuestion.header}
</Text>
<Text className="font-t3-medium text-sm tabular-nums text-foreground-tertiary">
{questionIndex + 1}/{props.pendingUserInput.questions.length}
</Text>
</View>
<Text className="font-t3-bold text-lg leading-[24px] text-foreground">
{activeQuestion.question}
</Text>
</View>
<View className="gap-1.5 border-t border-border px-3 py-2.5">
{activeQuestion.options.map((option, index) => {
const selected =
draft?.selectedOptionLabel === option.label && !draft.customAnswer?.trim().length;
return (
<Pressable
key={option.label}
accessibilityLabel={`${option.label}. ${option.description}`}
accessibilityRole="radio"
accessibilityState={{ checked: selected, disabled: isResponding }}
className={cn(
"min-h-[68px] flex-row items-center gap-3 rounded-xl border px-3 py-3",
selected ? "border-blue-500/45 bg-blue-500/10" : "border-transparent bg-subtle",
isResponding && "opacity-50",
)}
disabled={isResponding}
onPress={() =>
props.onSelectOption(
props.pendingUserInput.requestId,
activeQuestion.id,
option.label,
)
}
placeholder="Or type a custom answer"
className="min-h-[54px] rounded-2xl border border-neutral-200 bg-white px-3.5 py-3 font-sans text-base text-neutral-950 dark:border-white/8 dark:bg-neutral-950/70 dark:text-neutral-50"
/>
</View>
);
})}
<Pressable
className={cn(
"items-center justify-center rounded-2xl px-4 py-3.5",
props.answers ? "bg-blue-500" : "bg-neutral-200 dark:bg-neutral-700/60",
>
<View className="min-w-0 flex-1 gap-0.5">
<Text className="font-t3-bold text-base text-foreground">{option.label}</Text>
{option.description !== option.label ? (
<Text className="font-sans text-sm leading-[19px] text-foreground-muted">
{option.description}
</Text>
) : null}
</View>
{selected ? (
<SymbolView
name="checkmark"
size={16}
tintColor={selectedColor}
type="monochrome"
/>
) : index < 9 ? (
<View className="size-6 items-center justify-center rounded-md border border-border bg-screen/40">
<Text className="font-t3-medium text-xs tabular-nums text-foreground-muted">
{index + 1}
</Text>
</View>
) : null}
</Pressable>
);
})}
<TextInput
accessibilityLabel="Write a custom answer"
editable={!isResponding}
value={draft?.customAnswer ?? ""}
onChangeText={(value) =>
props.onChangeCustomAnswer(props.pendingUserInput.requestId, activeQuestion.id, value)
}
placeholder="Write a different answer"
selectionColor={selectedColor}
className="mt-1 min-h-12 rounded-xl bg-screen px-3 py-3 text-base"
/>
</View>
<View className="flex-row items-center justify-between border-t border-border px-3 py-2.5">
{questionIndex > 0 ? (
<Pressable
accessibilityLabel="Previous question"
accessibilityRole="button"
accessibilityState={{ disabled: !canGoBack }}
className={cn("min-h-11 items-center justify-center px-3", !canGoBack && "opacity-50")}
disabled={!canGoBack}
onPress={handleBack}
>
<Text className="font-t3-bold text-base text-foreground-muted">Back</Text>
</Pressable>
) : (
<View />
)}
disabled={
props.answers === null || props.respondingUserInputId === props.pendingUserInput.requestId
}
onPress={() => void props.onSubmit()}
>
<Text className="font-t3-extrabold text-sm text-white">Submit answers</Text>
</Pressable>
<Pressable
accessibilityLabel={isLastQuestion ? "Submit answers" : "Next question"}
accessibilityRole="button"
accessibilityState={{ disabled: !canContinue || isResponding }}
className={cn(
"min-h-11 items-center justify-center rounded-full px-5",
canContinue && !isResponding ? "bg-blue-600" : "bg-subtle-strong",
)}
disabled={!canContinue || isResponding}
onPress={handleAdvance}
>
<Text
className={cn(
"font-t3-bold text-base",
canContinue && !isResponding ? "text-white" : "text-foreground-tertiary",
)}
>
{isLastQuestion ? "Submit answers" : "Next question"}
</Text>
</Pressable>
</View>
</View>
);
}
@@ -17,8 +17,8 @@ import {
import type { ReactNode } from "react";
import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
import {
ActivityIndicator,
Image,
Keyboard,
Platform,
Pressable,
useColorScheme,
@@ -50,10 +50,11 @@ import {
ComposerToolbarScroller,
ComposerToolbarTrigger,
} from "../../components/ComposerToolbarTrigger";
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
import { ControlPillMenu } from "../../components/ControlPill";
import { ModelPickerSheet } from "../../components/ModelPickerSheet";
import { ProviderIcon } from "../../components/ProviderIcon";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import { buildModelMenuActions, buildModelOptions, groupByProvider } from "../../lib/modelOptions";
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
import type { RemoteClientConnectionState } from "../../lib/connection";
import {
@@ -64,23 +65,23 @@ import {
import {
applyProviderOptionMenuEvent,
buildProviderOptionMenuActions,
providerOptionsConfigurationLabel,
resolveProviderOptionDescriptors,
} from "../../lib/providerOptions";
import { useComposerPathSearch } from "../../state/use-composer-path-search";
import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";
import { useModelFavorites } from "./useModelFavorites";
/**
* Height of the collapsed composer (pill + vertical padding, excluding safe-area inset).
* Exported so the parent can compute feed overlap / content insets.
*/
export const COMPOSER_COLLAPSED_CHROME = 60;
export const COMPOSER_COLLAPSED_CHROME = 68;
/**
* Height of the expanded composer (card + toolbar + vertical padding, excluding safe-area inset).
* Used by the parent to compute the larger feed bottom inset when the composer is focused.
*/
export const COMPOSER_EXPANDED_CHROME = 174;
export const COMPOSER_EXPANDED_CHROME = 184;
export interface ThreadComposerProps {
readonly draftMessage: string;
@@ -168,7 +169,7 @@ export function ComposerSurface(props: {
style={[
props.style,
{
backgroundColor: props.isDarkMode ? "rgba(44,44,46,0.96)" : "rgba(255,255,255,0.96)",
backgroundColor: props.isDarkMode ? "rgba(17,17,19,0.96)" : "rgba(255,255,255,0.96)",
borderWidth: 1,
borderColor: props.isDarkMode ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.06)",
},
@@ -249,11 +250,11 @@ const ComposerConnectionStatusPill = memo(function ComposerConnectionStatusPill(
onPress={props.onPress}
className="max-w-full flex-row items-center gap-2 rounded-full bg-white/90 px-3 py-2 shadow-sm active:opacity-70 dark:bg-neutral-900/90"
>
{isReconnecting ? (
<ActivityIndicator size="small" color="#8e8e93" />
) : (
<View className="h-2 w-2 rounded-full bg-red-500" />
)}
<View
className={
isReconnecting ? "h-2 w-2 rounded-full bg-sky-400" : "h-2 w-2 rounded-full bg-red-500"
}
/>
<Text
className="max-w-[260px] text-sm font-t3-bold leading-snug text-foreground"
numberOfLines={1}
@@ -277,6 +278,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
const { onExpandedChange } = props;
const [previewImageUri, setPreviewImageUri] = useState<string | null>(null);
const [modelPickerVisible, setModelPickerVisible] = useState(false);
const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0;
const isExpanded = isFocused;
const canSend = hasContent;
@@ -322,7 +324,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
environmentLabel: props.environmentLabel,
threadSyncPhase: props.threadSyncPhase,
});
const toolbarFadeOpaque = isDarkMode ? "rgba(0,0,0,0.95)" : "rgba(255,255,255,0.95)";
const toolbarFadeOpaque = isDarkMode ? "rgba(17,17,19,0.95)" : "rgba(255,255,255,0.95)";
const toolbarFadeTransparent = isDarkMode ? "rgba(0,0,0,0)" : "rgba(255,255,255,0)";
const selectedProviderStatus = useMemo(() => {
if (!props.serverConfig) return null;
@@ -601,13 +603,8 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
}),
[currentModelOption?.capabilities, currentModelSelection.options],
);
const configurationLabel = useMemo(
() => providerOptionsConfigurationLabel(providerOptionDescriptors),
[providerOptionDescriptors],
);
const modelMenuActions = useMemo(
() => buildModelMenuActions(providerGroups, currentModelSelection),
[providerGroups, currentModelSelection],
const { favoriteModelKeys, favoritesReady, toggleFavorite } = useModelFavorites(
props.environmentId,
);
// ── Options menu ─────────────────────────────────────────
@@ -660,17 +657,6 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
);
// ── Menu handlers ────────────────────────────────────────
function handleModelMenuAction(event: string) {
if (!event.startsWith("model:")) {
return;
}
const modelKey = event.slice("model:".length);
const option = modelOptions.find((o) => o.key === modelKey);
if (option) {
props.onUpdateModelSelection(option.selection);
}
}
function handleOptionsMenuAction(event: string) {
const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event);
if (providerOptions) {
@@ -693,9 +679,9 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
return (
<Animated.View
className="px-4"
layout={COMPOSER_LAYOUT_TRANSITION}
style={{
paddingHorizontal: 14,
paddingTop: isExpanded ? 8 : 6,
paddingBottom: (props.bottomInset ?? 0) + (isExpanded ? 8 : 6),
experimental_backgroundImage: isDarkMode
@@ -731,19 +717,23 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
style={
isExpanded
? {
borderRadius: 20,
borderRadius: 22,
overflow: "hidden" as const,
paddingHorizontal: 14,
paddingVertical: 12,
paddingHorizontal: 12,
paddingBottom: 6,
paddingTop: 10,
backgroundColor: isDarkMode ? "rgba(17,17,19,0.95)" : "rgba(255,255,255,0.95)",
}
: {
borderRadius: 999,
borderRadius: 28,
overflow: "hidden" as const,
flexDirection: "row" as const,
alignItems: "center" as const,
minHeight: 54,
paddingLeft: 18,
paddingRight: 5,
paddingVertical: 5,
paddingVertical: 6,
backgroundColor: isDarkMode ? "rgba(17,17,19,0.95)" : "rgba(255,255,255,0.95)",
}
}
>
@@ -772,7 +762,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
onChangeText={props.onChangeDraftMessage}
onSelectionChange={handleSelectionChange}
onPasteImages={(uris) => void props.onNativePasteImages(uris)}
placeholder={props.placeholder}
placeholder={showStopAction ? "Message to queue..." : props.placeholder}
onFocus={handleFocus}
onBlur={handleBlur}
onSubmit={handleSend}
@@ -784,7 +774,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
style={
isExpanded
? {
minHeight: 80,
minHeight: 76,
maxHeight: 160,
paddingHorizontal: 4,
paddingVertical: 4,
@@ -822,81 +812,88 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
{!isExpanded ? (
<Animated.View entering={FadeIn.duration(180)} exiting={FadeOut.duration(100)}>
{showStopAction ? (
<ControlPill icon="stop.fill" variant="danger" onPress={props.onStopThread} />
<ComposerToolbarButton
accessibilityLabel="Stop"
icon="stop.fill"
variant="danger"
onPress={props.onStopThread}
showChevron={false}
/>
) : (
<ControlPill
<ComposerToolbarButton
accessibilityLabel={sendLabel}
icon="arrow.up"
variant="primary"
disabled={!canSend}
onPress={handleSend}
showChevron={false}
/>
)}
</Animated.View>
) : null}
</ComposerSurface>
{isExpanded ? (
// Toolbar row — matches draft page layout (expanded only)
<Animated.View entering={FadeIn.duration(160)} exiting={FadeOut.duration(120)}>
<ComposerToolbarRow paddingBottom={8} paddingHorizontal={0} paddingTop={8}>
<ComposerToolbarScroller
fadeOpaque={toolbarFadeOpaque}
fadeTransparent={toolbarFadeTransparent}
>
<ComposerToolbarButton
accessibilityLabel="Add attachment"
icon="plus"
onPress={() => void props.onPickDraftImages()}
showChevron={false}
/>
<ControlPillMenu
actions={modelMenuActions}
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
{isExpanded ? (
<Animated.View entering={FadeIn.duration(160)} exiting={FadeOut.duration(120)}>
<ComposerToolbarRow paddingBottom={0} paddingHorizontal={0} paddingTop={4}>
<ComposerToolbarScroller
fadeOpaque={toolbarFadeOpaque}
fadeTransparent={toolbarFadeTransparent}
>
<ComposerToolbarButton
accessibilityLabel="Add attachment"
icon="paperclip"
onPress={() => void props.onPickDraftImages()}
showChevron={false}
variant="ghost"
/>
<ComposerToolbarTrigger
accessibilityLabel="Model"
accessibilityLabel="Choose model"
iconNode={
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
<ProviderIcon provider={currentModelOption?.providerDriver} size={18} />
}
label={currentModelOption?.label ?? currentModelSelection.model}
onPress={() => {
Keyboard.dismiss();
setModelPickerVisible(true);
}}
variant="ghost"
/>
</ControlPillMenu>
<ControlPillMenu
actions={optionsMenuActions}
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Configuration"
icon="slider.horizontal.3"
label={configurationLabel}
/>
</ControlPillMenu>
{showStopAction ? (
<ComposerToolbarButton
accessibilityLabel="Stop"
icon="stop.fill"
variant="danger"
onPress={props.onStopThread}
showChevron={false}
/>
) : null}
</ComposerToolbarScroller>
<ComposerToolbarButton
accessibilityLabel={sendLabel}
icon="arrow.up"
variant="primary"
disabled={!canSend}
onPress={handleSend}
showChevron={false}
/>
</ComposerToolbarRow>
</Animated.View>
) : null}
<ControlPillMenu
actions={optionsMenuActions}
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Configuration"
icon="slider.horizontal.3"
showChevron={false}
variant="ghost"
/>
</ControlPillMenu>
{showStopAction ? (
<ComposerToolbarButton
accessibilityLabel="Stop"
icon="stop.fill"
variant="danger"
onPress={props.onStopThread}
showChevron={false}
/>
) : null}
</ComposerToolbarScroller>
<ComposerToolbarButton
accessibilityLabel={sendLabel}
icon="arrow.up"
variant="primary"
disabled={!canSend}
onPress={handleSend}
showChevron={false}
/>
</ComposerToolbarRow>
</Animated.View>
) : null}
</ComposerSurface>
{/* Queue count */}
{props.queueCount > 0 ? (
<Animated.View entering={FadeIn.duration(180)} exiting={FadeOut.duration(120)}>
<Text className="pt-2 text-xs text-foreground-muted">
<Text className="pt-1 text-sm text-foreground-muted">
{props.queueCount} queued message{props.queueCount === 1 ? "" : "s"} will send
automatically.
</Text>
@@ -912,6 +909,16 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
swipeToCloseEnabled
doubleTapToZoomEnabled
/>
<ModelPickerSheet
favoriteModelKeys={favoriteModelKeys}
favoritesEnabled={favoritesReady}
groups={providerGroups}
onClose={() => setModelPickerVisible(false)}
onSelectModel={(option) => props.onUpdateModelSelection(option.selection)}
onToggleFavorite={toggleFavorite}
selectedModel={currentModelSelection}
visible={modelPickerVisible}
/>
</Animated.View>
);
});
@@ -51,6 +51,7 @@ export interface ThreadDetailScreenProps {
readonly selectedThreadFeed: ReadonlyArray<ThreadFeedEntry>;
readonly activeWorkStartedAt: string | null;
readonly activePendingApproval: PendingApproval | null;
readonly activePendingApprovalCount: number;
readonly respondingApprovalId: ApprovalRequestId | null;
readonly activePendingUserInput: PendingUserInput | null;
readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
@@ -181,6 +182,8 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
const lastScrolledAnchorMessageIdRef = useRef<MessageId | null>(null);
const [composerExpanded, setComposerExpanded] = useState(false);
const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
const activePendingRequest = props.activePendingApproval ?? props.activePendingUserInput;
const activePendingRequestId = activePendingRequest?.requestId ?? null;
const composerBottomInset = composerExpanded ? 0 : Math.max(insets.bottom, 12);
const contentPresentationKind = props.contentPresentation.kind;
// The raw sync status enters "synchronizing" on every full fetch, cached or
@@ -201,7 +204,11 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
})();
const selectedThreadFeed = props.selectedThreadFeed;
const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
const composerOverlapHeight = composerChrome + composerBottomInset;
const requestChrome =
(props.activePendingApproval ? 270 : 0) + (props.activePendingUserInput ? 430 : 0);
const composerOverlapHeight = activePendingRequest
? requestChrome + Math.max(insets.bottom, 12)
: composerChrome + composerBottomInset;
const estimatedOverlayHeight = composerOverlapHeight;
// The overlay's measured height includes the home-indicator inset (the
// composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
@@ -242,6 +249,14 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
freeze.set(false);
}, [freeze, selectedThreadKey]);
useEffect(() => {
if (!activePendingRequestId) {
return;
}
setComposerExpanded(false);
composerEditorRef.current?.blur();
}, [activePendingRequestId]);
useEffect(() => {
if (
anchorMessageId === null ||
@@ -388,21 +403,24 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
pushes the resting content floor up by the same amount. */}
<View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
<View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
{props.activePendingApproval || props.activePendingUserInput ? (
{activePendingRequest ? (
<Animated.View
className="shrink-0 gap-3 px-4 pb-3"
className="shrink-0 gap-2 px-2.5 pt-1.5"
entering={FadeInDown.duration(220)}
exiting={FadeOut.duration(140)}
style={{ paddingBottom: Math.max(insets.bottom, 10) }}
>
{props.activePendingApproval ? (
<PendingApprovalCard
approval={props.activePendingApproval}
approvalCount={props.activePendingApprovalCount}
respondingApprovalId={props.respondingApprovalId}
onRespond={props.onRespondToApproval}
/>
) : null}
{props.activePendingUserInput ? (
<PendingUserInputCard
key={props.activePendingUserInput.requestId}
pendingUserInput={props.activePendingUserInput}
drafts={props.activePendingUserInputDrafts}
answers={props.activePendingUserInputAnswers}
@@ -416,35 +434,37 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
) : null}
</View>
<ThreadComposer
editorRef={composerEditorRef}
draftMessage={props.draftMessage}
draftAttachments={props.draftAttachments}
placeholder="Ask the repo agent, or run a command…"
contentMaxWidth={contentMaxWidth}
connectionState={props.connectionStateLabel}
connectionError={props.connectionError}
environmentLabel={props.environmentLabel}
threadSyncPhase={threadSyncPhase}
selectedThread={props.selectedThread}
serverConfig={props.serverConfig}
queueCount={props.selectedThreadQueueCount}
activeThreadBusy={props.activeThreadBusy}
environmentId={props.environmentId}
projectCwd={props.projectWorkspaceRoot}
bottomInset={composerBottomInset}
onChangeDraftMessage={props.onChangeDraftMessage}
onPickDraftImages={props.onPickDraftImages}
onNativePasteImages={props.onNativePasteImages}
onRemoveDraftImage={props.onRemoveDraftImage}
onStopThread={props.onStopThread}
onSendMessage={handleSendMessage}
onReconnectEnvironment={props.onReconnectEnvironment}
onUpdateModelSelection={props.onUpdateThreadModelSelection}
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
onExpandedChange={setComposerExpanded}
/>
{activePendingRequest ? null : (
<ThreadComposer
editorRef={composerEditorRef}
draftMessage={props.draftMessage}
draftAttachments={props.draftAttachments}
placeholder="Ask anything..."
contentMaxWidth={contentMaxWidth}
connectionState={props.connectionStateLabel}
connectionError={props.connectionError}
environmentLabel={props.environmentLabel}
threadSyncPhase={threadSyncPhase}
selectedThread={props.selectedThread}
serverConfig={props.serverConfig}
queueCount={props.selectedThreadQueueCount}
activeThreadBusy={props.activeThreadBusy}
environmentId={props.environmentId}
projectCwd={props.projectWorkspaceRoot}
bottomInset={composerBottomInset}
onChangeDraftMessage={props.onChangeDraftMessage}
onPickDraftImages={props.onPickDraftImages}
onNativePasteImages={props.onNativePasteImages}
onRemoveDraftImage={props.onRemoveDraftImage}
onStopThread={props.onStopThread}
onSendMessage={handleSendMessage}
onReconnectEnvironment={props.onReconnectEnvironment}
onUpdateModelSelection={props.onUpdateThreadModelSelection}
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
onExpandedChange={setComposerExpanded}
/>
)}
</View>
</KeyboardStickyView>
) : null}
@@ -205,6 +205,8 @@ function ThreadNavigationSidebarPane(
snoozeThread,
unsnoozeThread,
unsettleThread,
pinThread,
unpinThread,
} = useThreadListActions();
const threadListV2Enabled = useThreadListV2Enabled();
const pendingTasks = usePendingNewTasks();
@@ -481,6 +483,15 @@ function ThreadNavigationSidebarPane(
}
return supported;
}, [serverConfigs]);
const pinningEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>();
for (const [environmentId, config] of serverConfigs) {
if (config.environment.capabilities.threadPinning === true) {
supported.add(environmentId);
}
}
return supported;
}, [serverConfigs]);
const threadListV2Layout = useMemo(() => {
if (!threadListV2Enabled)
return {
@@ -792,6 +803,7 @@ function ThreadNavigationSidebarPane(
previous.item.thread === item.item.thread &&
previous.item.variant === item.item.variant &&
previous.item.snoozed === item.item.snoozed &&
previous.item.pinned === item.item.pinned &&
previous.snoozeWakeLabelText === item.snoozeWakeLabelText
);
}
@@ -879,6 +891,7 @@ function ThreadNavigationSidebarPane(
thread={thread}
variant={item.item.variant}
snoozed={item.item.snoozed}
pinned={item.item.pinned}
snoozePresetMinute={nowMinute}
snoozeWakeLabelText={item.snoozeWakeLabelText}
project={projectByKey.get(scopeKey) ?? null}
@@ -915,9 +928,12 @@ function ThreadNavigationSidebarPane(
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
onSettleThread={settleThread}
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
onSnoozeThread={snoozeThread}
onUnsnoozeThread={unsnoozeThread}
onUnsettleThread={unsettleThread}
onPinThread={pinThread}
onUnpinThread={unpinThread}
onChangeRequestState={handleChangeRequestState}
projectCwd={projectCwdByKey.get(scopeKey) ?? null}
onSwipeableClose={handleSwipeableClose}
@@ -1045,6 +1061,8 @@ function ThreadNavigationSidebarPane(
handleSwipeableClose,
handleSwipeableWillOpen,
openPendingTask,
pinThread,
pinningEnvironmentIds,
projectByKey,
projectCwdByKey,
projectTitleByProjectKey,
@@ -1064,6 +1082,7 @@ function ThreadNavigationSidebarPane(
nowMinute,
toggleSettledShelf,
toggleSnoozedShelf,
unpinThread,
unsettleThread,
unsnoozeThread,
updateGroupDisplay,
@@ -9,7 +9,7 @@ import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } fro
import * as Option from "effect/Option";
import { EnvironmentId, ThreadId, type ProjectScript } from "@t3tools/contracts";
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
import { Platform, ScrollView, View } from "react-native";
import { Platform, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useWorkspaceState } from "../../state/workspace";
import { useEnvironmentQuery } from "../../state/query";
@@ -17,6 +17,7 @@ import { dismissGitActionResult, useGitActionProgress } from "../../state/use-vc
import { vcsEnvironment } from "../../state/vcs";
import { EmptyState } from "../../components/EmptyState";
import { AppText as Text } from "../../components/AppText";
import {
AndroidScreenHeader,
type AndroidHeaderAction,
@@ -60,6 +61,10 @@ import { useSelectedThreadWorktree } from "../../state/use-selected-thread-workt
import { useThreadComposerState } from "../../state/use-thread-composer-state";
import { threadEnvironment } from "../../state/threads";
import { projectThreadContentPresentation } from "./threadContentPresentation";
import {
resolveThreadHeaderStatus,
type ThreadHeaderStatusPresentation,
} from "./threadHeaderPresentation";
import {
useAdaptiveWorkspaceLayout,
useAdaptiveWorkspacePaneRole,
@@ -79,6 +84,42 @@ interface ThreadInspectorSelection {
type NativeHeaderItems = ReadonlyArray<Record<string, unknown>>;
function isUnknownRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function ThreadHeaderStatus(props: {
readonly status: ThreadHeaderStatusPresentation;
readonly onPress: () => void;
}) {
return (
<Pressable
accessibilityHint="Opens git controls"
accessibilityLabel={`Thread status: ${props.status.label}`}
accessibilityRole="button"
hitSlop={8}
onPress={props.onPress}
className="min-h-11 flex-row items-center justify-center px-1"
>
<Text
className={
props.status.kind === "approval"
? "font-t3-bold text-base text-amber-600 dark:text-amber-300"
: props.status.kind === "input"
? "font-t3-bold text-base text-indigo-600 dark:text-indigo-300"
: props.status.kind === "working"
? "font-t3-bold text-base tabular-nums text-sky-600 dark:text-sky-400"
: props.status.kind === "failed"
? "font-t3-bold text-base text-red-600 dark:text-red-400"
: "font-t3-bold text-base text-green-600 dark:text-green-400"
}
>
{props.status.nativeLabel}
</Text>
</Pressable>
);
}
function InspectorPaneRoleActivation() {
useAdaptiveWorkspacePaneRole("inspector");
return null;
@@ -281,11 +322,37 @@ function ThreadRouteContent(
/* ─── Native header theming ──────────────────────────────────────── */
const usesNativeHeaderGlass = NATIVE_LIQUID_GLASS_SUPPORTED;
const headerSubtitle = [
selectedThreadProject?.title ?? null,
selectedThread?.branch ? `⑂ ${selectedThread.branch}` : null,
selectedEnvironmentConnection?.environmentLabel ?? null,
]
.filter(Boolean)
.join(" · ");
const headerHasPendingApproval = Boolean(
requests.activePendingApproval ?? selectedThread?.hasPendingApprovals,
);
const headerHasPendingUserInput = Boolean(
requests.activePendingUserInput ?? selectedThread?.hasPendingUserInput,
);
const headerTimerEnabled =
composer.activeThreadBusy && !headerHasPendingApproval && !headerHasPendingUserInput;
const [headerNowMs, setHeaderNowMs] = useState(() => Date.now());
useEffect(() => {
if (!headerTimerEnabled) {
return;
}
setHeaderNowMs(Date.now());
const intervalId = setInterval(() => setHeaderNowMs(Date.now()), 1_000);
return () => clearInterval(intervalId);
}, [composer.activeWorkStartedAt, headerTimerEnabled]);
const threadHeaderStatus = resolveThreadHeaderStatus({
hasPendingApproval: headerHasPendingApproval,
hasPendingUserInput: headerHasPendingUserInput,
active: composer.activeThreadBusy,
failed:
selectedThread?.session?.status === "error" || selectedThread?.latestTurn?.state === "error",
activeWorkStartedAt: composer.activeWorkStartedAt,
nowMs: headerNowMs,
});
/* ─── Git status for native header trigger ───────────────────────── */
const gitStatus = useEnvironmentQuery(
selectedThread !== null && selectedThreadCwd !== null
@@ -685,11 +752,6 @@ function ThreadRouteContent(
onPress: () => handleOpenTerminal(null),
});
}
actions.push({
accessibilityLabel: "Open git controls",
icon: "point.topleft.down.curvedto.point.bottomright.up",
onPress: handleOpenGitInspector,
});
if (fileInspector.supported && selectedThreadCwd !== null) {
actions.push({
accessibilityLabel: "Toggle inspector",
@@ -725,6 +787,92 @@ function ThreadRouteContent(
],
[navigation],
);
const compactThreadActionItem = useMemo(() => {
const gitItem = compactRightHeaderItems.find((item) => item.identifier === "thread-right-git");
if (!gitItem) {
return null;
}
const existingMenu = isUnknownRecord(gitItem.menu) ? gitItem.menu : null;
const existingMenuItems =
existingMenu && Array.isArray(existingMenu.items) ? existingMenu.items : [];
return {
...gitItem,
accessibilityLabel: "Thread actions",
icon: { name: "ellipsis", type: "sfSymbol" as const },
identifier: "thread-right-actions",
label: undefined,
menu: {
...existingMenu,
items: [
...existingMenuItems,
{
description: "Browse this thread's worktree",
disabled: selectedThreadCwd === null,
icon: { name: "folder", type: "sfSymbol" as const },
label: "Files",
onPress: handleOpenFilesInspector,
type: "action" as const,
},
{
description: "Open this thread's shell",
disabled: !selectedThreadProject?.workspaceRoot,
icon: { name: "terminal", type: "sfSymbol" as const },
label: "Terminal",
onPress: () => handleOpenTerminal(null),
type: "action" as const,
},
],
title: "Thread actions",
},
sharesBackground: false,
tintColor: undefined,
width: 44,
};
}, [
compactRightHeaderItems,
handleOpenFilesInspector,
handleOpenTerminal,
selectedThreadCwd,
selectedThreadProject?.workspaceRoot,
]);
const compactThreadStatusItem = useMemo(
() => ({
accessibilityLabel: `Thread status: ${threadHeaderStatus.label}`,
icon: {
name:
threadHeaderStatus.kind === "done"
? "checkmark.circle"
: threadHeaderStatus.kind === "working"
? "timer"
: threadHeaderStatus.kind === "approval"
? "exclamationmark.circle"
: threadHeaderStatus.kind === "input"
? "questionmark.circle"
: "xmark.circle",
type: "sfSymbol" as const,
},
identifier: "thread-right-status",
label: threadHeaderStatus.nativeLabel,
onPress: handleOpenGitInspector,
sharesBackground: false,
tintColor: threadHeaderStatus.tintColor,
type: "button" as const,
}),
[handleOpenGitInspector, threadHeaderStatus],
);
const nativeThreadRightHeaderItems = useMemo<NativeHeaderItems>(() => {
if (layout.usesSplitView) {
return threadCenterHeaderItems;
}
return compactThreadActionItem
? [compactThreadStatusItem, compactThreadActionItem]
: [compactThreadStatusItem];
}, [
compactThreadActionItem,
compactThreadStatusItem,
layout.usesSplitView,
threadCenterHeaderItems,
]);
if (!environmentId || !threadId) {
return <OpeningThreadLoadingScreen />;
@@ -757,6 +905,7 @@ function ThreadRouteContent(
selectedThreadFeed={composer.selectedThreadFeed}
activeWorkStartedAt={composer.activeWorkStartedAt}
activePendingApproval={requests.activePendingApproval}
activePendingApprovalCount={requests.activePendingApprovalCount}
respondingApprovalId={requests.respondingApprovalId}
activePendingUserInput={requests.activePendingUserInput}
activePendingUserInputDrafts={requests.activePendingUserInputDrafts}
@@ -798,17 +947,16 @@ function ThreadRouteContent(
<>
{activeInspectorRenderer ? <InspectorPaneRoleActivation /> : null}
<NativeStackScreenOptions
optionsVersion={nativeThreadRightHeaderItems}
options={{
// Android draws its own in-flow header (AndroidScreenHeader below);
// the native stack header stays iOS-only.
headerShown: Platform.OS !== "android",
headerTitle: selectedThread.title,
headerTitleStyle: usesNativeHeaderGlass
? {
fontSize: 17,
fontWeight: "800",
}
: undefined,
headerTitleStyle: {
fontSize: 19,
fontWeight: "800",
},
title: selectedThread.title,
headerBackVisible: !layout.usesSplitView,
// Compact uses the NATIVE back button when a previous route exists;
@@ -826,10 +974,8 @@ function ThreadRouteContent(
// the git controls on the RIGHT (no center items — center space is
// reserved for future breadcrumbs/status).
unstable_headerRightItems:
Platform.OS === "ios"
? () => (layout.usesSplitView ? threadCenterHeaderItems : compactRightHeaderItems)
: undefined,
unstable_headerSubtitle: usesNativeHeaderGlass ? headerSubtitle : undefined,
Platform.OS === "ios" ? () => nativeThreadRightHeaderItems : undefined,
unstable_headerSubtitle: headerSubtitle.length > 0 ? headerSubtitle : undefined,
}}
/>
@@ -839,6 +985,9 @@ function ThreadRouteContent(
subtitle={headerSubtitle}
onBack={layout.usesSplitView ? undefined : () => navigation.goBack()}
actions={androidHeaderActions}
trailing={
<ThreadHeaderStatus status={threadHeaderStatus} onPress={handleOpenGitInspector} />
}
/>
) : null}
@@ -2,6 +2,7 @@ import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
import type { EnvironmentThreadSearchMatch } from "@t3tools/client-runtime/state/thread-search";
import { canSnooze, resolveSnoozePresets } from "@t3tools/client-runtime/state/thread-settled";
import type { MenuAction } from "@react-native-menu/menu";
@@ -53,12 +54,28 @@ const MONO_FONT = Platform.select({
// Live Activity/widgets (amber approval, indigo input, sky working) so a
// thread reads the same color everywhere it surfaces.
const STATUS_LABEL_BY_STATUS: Partial<
Record<ThreadListV2Status, { label: string; className: string }>
Record<ThreadListV2Status, { label: string; className: string; screenColor: string }>
> = {
approval: { label: "Approval", className: "text-amber-700 dark:text-amber-300" },
input: { label: "Input", className: "text-indigo-600 dark:text-indigo-300" },
working: { label: "Working", className: "text-sky-600 dark:text-sky-400" },
failed: { label: "Failed", className: "text-red-700 dark:text-red-300" },
approval: {
label: "Approval",
className: "text-amber-700 dark:text-amber-300",
screenColor: "#fbbf24",
},
input: {
label: "Input",
className: "text-indigo-600 dark:text-indigo-300",
screenColor: "#a5b4fc",
},
working: {
label: "Working",
className: "text-sky-600 dark:text-sky-400",
screenColor: "#38bdf8",
},
failed: {
label: "Failed",
className: "text-red-700 dark:text-red-300",
screenColor: "#f87171",
},
};
function threadTimeLabel(thread: EnvironmentThreadShell): string {
@@ -104,7 +121,14 @@ export const ThreadListV2SectionDivider = memo(function ThreadListV2SectionDivid
props.pane === "sidebar" ? "px-3" : "px-5",
)}
>
<Text className="text-xs font-t3-medium text-foreground-tertiary">{props.label}</Text>
<Text
className={cn(
"font-t3-medium text-foreground-tertiary",
props.pane === "sidebar" ? "text-xs" : "text-sm",
)}
>
{props.label}
</Text>
<View className="h-px flex-1" style={{ backgroundColor: borderColor }} />
</View>
);
@@ -129,14 +153,21 @@ export const ThreadListV2SnoozedShelfHeader = memo(function ThreadListV2SnoozedS
accessibilityRole="button"
accessibilityState={{ expanded: props.expanded }}
className={cn(
"mb-1.5 mt-4 flex-row items-center gap-2.5",
props.pane === "sidebar" ? "px-3" : "px-5",
"flex-row items-center gap-2.5",
props.pane === "sidebar" ? "mb-1.5 mt-4 px-3" : "h-[42px] px-4",
)}
onPress={props.onToggle}
style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
>
<Text className="text-xs font-t3-medium text-blue-600 dark:text-blue-400">
{props.expanded ? "Snoozed" : `Snoozed (${props.count})`}
<Text
className={cn(
"text-xs font-t3-medium",
props.pane === "sidebar"
? "text-xs text-blue-600 dark:text-blue-400"
: "text-sm text-[#60a5fa]",
)}
>
{props.pane === "sidebar" && props.expanded ? "Snoozed" : `Snoozed (${props.count})`}
</Text>
<View className="h-px flex-1 bg-blue-500/20 dark:bg-blue-400/15" />
<SymbolView
@@ -165,13 +196,18 @@ export const ThreadListV2SettledShelfHeader = memo(function ThreadListV2SettledS
accessibilityRole="button"
accessibilityState={{ expanded: props.expanded }}
className={cn(
"mb-1.5 mt-4 flex-row items-center gap-2.5",
props.pane === "sidebar" ? "px-3" : "px-5",
"flex-row items-center gap-2.5",
props.pane === "sidebar" ? "mb-1.5 mt-4 px-3" : "h-[42px] px-4",
)}
onPress={props.onToggle}
style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
>
<Text className="text-xs font-t3-medium text-foreground-tertiary">
<Text
className={cn(
"font-t3-medium",
props.pane === "sidebar" ? "text-xs text-foreground-tertiary" : "text-sm text-[#74757b]",
)}
>
{props.expanded ? "Settled" : `Settled (${props.count})`}
</Text>
<View className="h-px flex-1 bg-border" />
@@ -201,6 +237,7 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
readonly project: EnvironmentProject | null;
readonly projectTitle?: string;
readonly environmentLabel: string | null;
readonly environmentConnectionState?: EnvironmentConnectionPhase;
readonly pane?: "screen" | "sidebar";
/** Draws the "Pending" divider above the first queued row. */
readonly showPendingDivider: boolean;
@@ -214,6 +251,9 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
const projectTitle =
props.projectTitle ?? props.project?.title ?? pendingTask.creation.projectTitle ?? "";
const branch = pendingTask.creation.branch;
const staleEnvironment =
props.environmentConnectionState !== undefined &&
props.environmentConnectionState !== "connected";
const handleMenuAction = useCallback(
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
@@ -228,34 +268,90 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
{props.project ? (
<ProjectFavicon
environmentId={pendingTask.message.environmentId}
size={15}
size={sidebarPane ? 15 : 18}
projectTitle={projectTitle}
workspaceRoot={props.project.workspaceRoot}
/>
) : null}
<Text className="flex-1 text-sm font-t3-medium text-foreground-muted" numberOfLines={1}>
<Text
className={cn(
"flex-1 font-t3-medium",
sidebarPane ? "text-sm text-foreground-muted" : "text-sm text-[#9a9ba1]",
)}
numberOfLines={1}
>
{projectTitle}
</Text>
<Text className="text-xs text-foreground-tertiary">Queued</Text>
<Text
className={cn(
sidebarPane ? "text-xs text-foreground-tertiary" : "text-xs text-[#818289]",
)}
>
Queued
</Text>
</View>
{/* One line, unlike the two an active row allows: a queued title is
derived from the whole prompt rather than written as a title, so the
second line is usually a stray word or emoji rather than meaning. */}
<Text className="mt-1 text-base font-t3-medium text-foreground" numberOfLines={1}>
<Text
className={cn(
"mt-1 font-t3-medium",
sidebarPane ? "text-base text-foreground" : "text-[17px] leading-[22px] text-[#f5f5f5]",
)}
numberOfLines={1}
>
{pendingTask.title}
</Text>
{branch || props.environmentLabel ? (
<Text className="mt-1 text-xs text-foreground-muted" numberOfLines={1}>
<View className="mt-1 flex-row items-center gap-1.5">
{branch ? (
<Text className="text-xs text-foreground-muted" style={{ fontFamily: MONO_FONT }}>
{branch}
</Text>
<>
{!sidebarPane ? (
<SymbolView
name="arrow.triangle.branch"
size={13}
tintColor="#696a70"
type="monochrome"
/>
) : null}
<Text
className={cn(
"min-w-0 shrink",
sidebarPane ? "text-xs text-foreground-muted" : "text-sm text-[#77787f]",
)}
numberOfLines={1}
style={{ fontFamily: MONO_FONT }}
>
{branch}
</Text>
</>
) : null}
{branch && props.environmentLabel ? " · " : null}
{props.environmentLabel ? (
<Text className="text-xs text-foreground-tertiary">{props.environmentLabel}</Text>
<View className="ml-auto flex-row items-center gap-1">
{!sidebarPane ? (
<SymbolView
name={staleEnvironment ? "wifi.slash" : "desktopcomputer"}
size={13}
tintColor={staleEnvironment ? "#f87171" : "#696a70"}
type="monochrome"
/>
) : null}
<Text
className={cn(
sidebarPane ? "text-xs" : "text-[13px]",
sidebarPane
? "text-foreground-tertiary"
: staleEnvironment
? "text-[#f87171]"
: "text-[#696a70]",
)}
numberOfLines={1}
>
{props.environmentLabel}
</Text>
</View>
) : null}
</Text>
</View>
) : null}
</>
);
@@ -289,9 +385,8 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
{sidebarPane ? (
rowContent
) : (
<View className="bg-screen">
<View className="px-5 py-2.5">{rowContent}</View>
<View className="ml-5 h-px bg-border-subtle" />
<View style={{ backgroundColor: "#000" }}>
<View className="min-h-[92px] px-4 py-2.5">{rowContent}</View>
</View>
)}
</Pressable>
@@ -305,6 +400,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly variant: "card" | "slim";
/** Snoozed-shelf row: shows its wake time and offers Wake. */
readonly snoozed?: boolean;
/** Pinned-block row: shows the pin glyph and offers Unpin. */
readonly pinned?: boolean;
/** Preformatted against the parent minute tick so this memoized row's
countdown keeps moving. */
readonly snoozeWakeLabelText?: string;
@@ -314,13 +411,12 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly project: EnvironmentProject | null;
readonly projectTitle?: string;
readonly providerDriver: string | null;
/** Which machine hosts the thread. Null when only one environment is
connected — repeating the same label on every row is noise. Mirrors
the web sidebar's remote-environment cloud icon, but as text since
phones have no hover tooltips. */
/** Which machine hosts the thread. Compact Home always passes this so the
merged multi-environment list keeps attribution visible. */
readonly environmentLabel: string | null;
readonly environmentConnectionState?: EnvironmentConnectionPhase;
/** Hosting surface. "screen" (default) renders the compact Home idiom:
flat edge-to-edge rows on the screen background with inset hairlines.
flat edge-to-edge rows on a true-black background.
"sidebar" renders the iPad split-view idiom: rounded rows blending
into the drawer surface, selection filled with the accent color —
matching the v1 sidebar rows. */
@@ -337,11 +433,15 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => void;
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
readonly onPinThread: (thread: EnvironmentThreadShell) => void;
readonly onUnpinThread: (thread: EnvironmentThreadShell) => void;
/** False on environments whose server predates thread.settle/unsettle:
swipe + menu fall back to Archive instead of failing on use. */
readonly settlementSupported: boolean;
/** False on servers that predate thread.snooze/unsnooze. */
readonly snoozeSupported: boolean;
/** False on servers that predate thread.pin/unpin. */
readonly pinningSupported: boolean;
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
/** Reports this row's live PR state up so the partition can auto-settle
@@ -368,9 +468,12 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
onUnsnoozeThread,
onUnsettleThread,
onArchiveThread,
onPinThread,
onUnpinThread,
onChangeRequestState,
} = props;
const snoozedRow = props.snoozed === true;
const pinnedRow = props.pinned === true;
const pr = useThreadPr(thread, props.projectCwd ?? props.project?.workspaceRoot ?? null);
const prState = pr?.state ?? null;
@@ -379,16 +482,22 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
onChangeRequestState?.(threadKey, prState);
}, [onChangeRequestState, prState, threadKey]);
const screenColor = useThemeColor("--color-screen");
const drawerColor = useThemeColor("--color-drawer");
const pressedBackgroundColor = useThemeColor("--color-subtle");
const selectedBackgroundColor = useThemeColor("--color-user-bubble");
const pinTintColor = useThemeColor("--color-foreground-muted");
const sidebarPane = props.pane === "sidebar";
const selected = props.selected === true;
const status = resolveThreadListV2Status(thread);
// Quiescent is the absence of an actionable state, not a persistent
// "Done" badge. A stopped session often just means the user opened this
// thread before, so using session presence made read rows look completed.
const statusLabel = STATUS_LABEL_BY_STATUS[status];
const timeLabel = threadTimeLabel(thread);
const staleEnvironment =
props.environmentConnectionState !== undefined &&
props.environmentConnectionState !== "connected";
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
const handleSettle = useCallback(() => onSettleThread(thread), [onSettleThread, thread]);
@@ -398,6 +507,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
);
const handleUnsnooze = useCallback(() => onUnsnoozeThread(thread), [onUnsnoozeThread, thread]);
const handleUnsettle = useCallback(() => onUnsettleThread(thread), [onUnsettleThread, thread]);
const handlePin = useCallback(() => onPinThread(thread), [onPinThread, thread]);
const handleUnpin = useCallback(() => onUnpinThread(thread), [onUnpinThread, thread]);
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
// Swipe: the v2 primary action is the lifecycle transition. Every settled
@@ -434,6 +545,20 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
})),
[snoozePresets],
);
// Pinned cards keep the full lifecycle menu; only the pin item flips to
// Unpin. (Settling a pinned thread clears the pin server-side; snoozing
// hides the card until wake with the pin intact.)
const pinMenuItem = useMemo<MenuAction[]>(
() =>
props.pinningSupported
? [
pinnedRow
? { id: "unpin", title: "Unpin", image: "pin.slash" }
: { id: "pin", title: "Pin", image: "pin" },
]
: [],
[pinnedRow, props.pinningSupported],
);
const snoozableCardMenuActions = useMemo<MenuAction[]>(
() => [
{ id: "settle", title: "Settle", image: "checkmark" },
@@ -443,15 +568,22 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
image: "clock",
subactions: snoozePresetActions,
},
...pinMenuItem,
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
],
[snoozePresetActions],
[pinMenuItem, snoozePresetActions],
);
const cardMenuActions = useMemo<MenuAction[]>(
() => [CARD_MENU_ACTIONS[0]!, ...pinMenuItem, ...CARD_MENU_ACTIONS.slice(1)],
[pinMenuItem],
);
const handleMenuAction = useCallback(
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
if (nativeEvent.event === "settle") handleSettle();
if (nativeEvent.event === "unsettle") handleUnsettle();
if (nativeEvent.event === "unsnooze") handleUnsnooze();
if (nativeEvent.event === "pin") handlePin();
if (nativeEvent.event === "unpin") handleUnpin();
if (nativeEvent.event === "archive") handleArchive();
if (nativeEvent.event === "delete") handleDelete();
const snoozeSelection = resolveThreadListV2SnoozeMenuSelection({
@@ -468,8 +600,10 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
[
handleArchive,
handleDelete,
handlePin,
handleSettle,
handleSnooze,
handleUnpin,
handleUnsettle,
handleUnsnooze,
snoozePresets,
@@ -546,35 +680,53 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
{props.project ? (
<ProjectFavicon
environmentId={thread.environmentId}
size={15}
size={sidebarPane ? 15 : 18}
projectTitle={props.projectTitle ?? props.project.title}
workspaceRoot={props.project.workspaceRoot}
/>
) : null}
<Text
className={cn(
"flex-1 text-sm font-t3-medium",
selected ? "text-user-bubble-foreground-muted" : "text-foreground-muted",
"flex-1 font-t3-medium",
selected
? "text-sm text-user-bubble-foreground-muted"
: sidebarPane
? "text-sm text-foreground-muted"
: "text-sm text-[#9a9ba1]",
)}
numberOfLines={1}
>
{props.projectTitle ?? props.project?.title ?? ""}
</Text>
{pinnedRow ? (
<SymbolView name="pin" size={11} tintColor={pinTintColor} type="monochrome" />
) : null}
<Text
className={cn(
"text-xs tabular-nums",
selected ? "text-white" : (statusLabel?.className ?? "text-foreground-tertiary"),
"tabular-nums",
selected
? "text-xs text-white"
: sidebarPane
? cn("text-xs", statusLabel?.className ?? "text-foreground-tertiary")
: "text-xs",
)}
style={
selected || sidebarPane ? undefined : { color: statusLabel?.screenColor ?? "#71717a" }
}
>
{statusLabel?.label ?? timeLabel}
</Text>
</View>
<Text
className={cn(
"mt-1 text-base font-t3-medium",
selected ? "text-user-bubble-foreground" : "text-foreground",
"mt-1 font-t3-medium",
selected
? "text-base text-user-bubble-foreground"
: sidebarPane
? "text-base text-foreground"
: "text-[17px] leading-[22px] text-[#f5f5f5]",
)}
numberOfLines={2}
numberOfLines={sidebarPane ? 2 : 1}
>
{thread.title}
</Text>
@@ -588,67 +740,112 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
</View>
) : null}
<View className="mt-1 flex-row items-center gap-2">
{status === "failed" && thread.session?.lastError ? (
<Text
className={cn(
"flex-1 text-xs",
selected
? "text-user-bubble-foreground-muted"
: "text-red-600/80 dark:text-red-400/80",
)}
numberOfLines={1}
>
{sidebarPane ? (
status === "failed" && thread.session?.lastError ? (
<Text
className={cn(
"flex-1 text-xs",
selected
? "text-user-bubble-foreground-muted"
: "text-red-600/80 dark:text-red-400/80",
)}
numberOfLines={1}
>
{thread.session.lastError}
</Text>
) : thread.branch || props.environmentLabel ? (
<Text
className={cn(
"flex-1 text-xs",
selected ? "text-user-bubble-foreground-muted" : "text-foreground-muted",
)}
numberOfLines={1}
>
{thread.branch ? (
<Text
className={cn(
"text-xs",
selected ? "text-user-bubble-foreground-muted" : "text-foreground-muted",
)}
style={{ fontFamily: MONO_FONT }}
>
{thread.branch}
</Text>
) : null}
{thread.branch && props.environmentLabel ? " · " : null}
{props.environmentLabel ? (
<Text
className={cn(
"text-xs",
selected ? "text-user-bubble-foreground-muted" : "text-foreground-tertiary",
)}
>
{props.environmentLabel}
</Text>
) : null}
</Text>
) : (
<View className="flex-1" />
)
) : status === "failed" && thread.session?.lastError ? (
<Text className="flex-1 text-sm text-[#f87171]" numberOfLines={1}>
{thread.session.lastError}
</Text>
) : thread.branch || props.environmentLabel ? (
/* "branch · machine" share one truncating line. The machine sits
last so a tight fit cuts the repetitive label, not the branch —
and machine-only fills the row for non-git projects. */
<Text
className={cn(
"flex-1 text-xs",
selected ? "text-user-bubble-foreground-muted" : "text-foreground-muted",
)}
numberOfLines={1}
>
{thread.branch ? (
<Text
className={cn(
"text-xs",
selected ? "text-user-bubble-foreground-muted" : "text-foreground-muted",
)}
style={{ fontFamily: MONO_FONT }}
>
{thread.branch}
</Text>
) : null}
{thread.branch && props.environmentLabel ? " · " : null}
{props.environmentLabel ? (
<Text
className={cn(
"text-xs",
selected ? "text-user-bubble-foreground-muted" : "text-foreground-tertiary",
)}
>
{props.environmentLabel}
</Text>
) : null}
</Text>
) : (
<View className="flex-1" />
<View className="min-w-0 flex-1 flex-row items-center gap-1.5">
{thread.branch ? (
<>
<SymbolView
name="arrow.triangle.branch"
size={13}
tintColor="#696a70"
type="monochrome"
/>
<Text
className="min-w-0 shrink text-sm text-[#77787f]"
numberOfLines={1}
style={{ fontFamily: MONO_FONT }}
>
{thread.branch}
</Text>
</>
) : null}
</View>
)}
{pr ? (
<Text
accessibilityLabel={pr.accessibilityLabel}
className={cn("text-xs", selected ? "text-white" : pr.textClassName)}
className={cn(
"text-xs",
selected ? "text-white" : sidebarPane ? pr.textClassName : "text-[#71717a]",
)}
style={{ fontFamily: MONO_FONT }}
>
#{pr.label}
</Text>
) : null}
{!sidebarPane && props.environmentLabel ? (
<View className="flex-row items-center gap-1">
<SymbolView
name={staleEnvironment ? "wifi.slash" : "desktopcomputer"}
size={13}
tintColor={staleEnvironment ? "#f87171" : "#696a70"}
type="monochrome"
/>
<Text
className={cn(
"max-w-28 text-[13px]",
staleEnvironment ? "text-[#f87171]" : "text-[#696a70]",
)}
numberOfLines={1}
>
{props.environmentLabel}
</Text>
</View>
) : null}
{props.providerDriver ? (
<View className="opacity-60">
<ProviderIcon provider={props.providerDriver} size={14} />
<ProviderIcon provider={props.providerDriver} size={16} />
</View>
) : null}
</View>
@@ -684,13 +881,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
{sidebarPane ? (
cardContent
) : (
/* Flat native list rows: no tonal containers — colored status
labels and text hierarchy carry state, an inset hairline
separates rows. The opaque screen background stays so swipe
actions reveal behind the row. */
<View className="bg-screen">
<View className="px-5 py-2.5">{cardContent}</View>
<View className="ml-5 h-px bg-border-subtle" />
<View style={{ backgroundColor: "#000" }}>
<View className="min-h-[92px] px-4 py-2.5">{cardContent}</View>
</View>
)}
</Pressable>
@@ -700,7 +892,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
accessibilityLabel={thread.title}
accessibilityRole="button"
accessibilityState={{ selected }}
className={sidebarPane ? undefined : "bg-screen"}
onPress={() => {
close();
onSelectThread(thread);
@@ -715,21 +906,21 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
: drawerColor,
borderRadius: SIDEBAR_V2_ROW_RADIUS,
})
: ({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })
: ({ pressed }) => ({ backgroundColor: "#000", opacity: pressed ? 0.7 : 1 })
}
>
{/* Settled history recedes: dimmed favicon + muted title. */}
<View
className={cn(
"min-h-[44px] flex-row items-center gap-2.5 py-2",
sidebarPane ? "px-3" : "px-5",
"min-h-[54px] flex-row items-center gap-2.5 py-2.5",
sidebarPane ? "px-3" : "px-4",
)}
>
{props.project ? (
<View className="opacity-40">
<ProjectFavicon
environmentId={thread.environmentId}
size={15}
size={sidebarPane ? 15 : 17}
projectTitle={props.projectTitle ?? props.project.title}
workspaceRoot={props.project.workspaceRoot}
/>
@@ -738,8 +929,12 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
<View className="min-w-0 flex-1">
<Text
className={cn(
"text-base",
selected ? "text-user-bubble-foreground" : "text-foreground-muted",
sidebarPane ? "text-base" : "text-sm",
selected
? "text-user-bubble-foreground"
: sidebarPane
? "text-foreground-muted"
: "text-[#7d7e84]",
)}
numberOfLines={1}
>
@@ -755,12 +950,14 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
</View>
<Text
className={cn(
"text-sm tabular-nums",
sidebarPane ? "text-sm tabular-nums" : "text-xs tabular-nums",
selected
? "text-user-bubble-foreground-muted"
: snoozedRow
? "text-blue-600 dark:text-blue-400"
: "text-foreground-tertiary",
: sidebarPane
? "text-foreground-tertiary"
: "text-[#55565b]",
)}
style={{ fontFamily: MONO_FONT }}
>
@@ -775,7 +972,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
return (
<>
<ThreadSwipeable
backgroundColor={sidebarPane ? drawerColor : screenColor}
backgroundColor={sidebarPane ? drawerColor : "#000"}
compactActions={variant === "slim"}
containerStyle={
sidebarPane ? { borderRadius: SIDEBAR_V2_ROW_RADIUS, overflow: "hidden" } : undefined
@@ -805,7 +1002,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
? SLIM_MENU_ACTIONS
: swipeActions.secondary === "snooze"
? snoozableCardMenuActions
: CARD_MENU_ACTIONS
: cardMenuActions
}
onPressAction={handleMenuAction}
shouldOpenOnLongPress
@@ -0,0 +1,71 @@
import { describe, expect, it } from "vite-plus/test";
import { formatThreadHeaderElapsed, resolveThreadHeaderStatus } from "./threadHeaderPresentation";
describe("thread header presentation", () => {
it("formats the working timer as compact minutes and seconds", () => {
expect(
formatThreadHeaderElapsed("2026-07-31T12:00:00.000Z", Date.parse("2026-07-31T12:02:14.000Z")),
).toBe("2:14");
expect(formatThreadHeaderElapsed("invalid", Date.now())).toBeNull();
});
it("prioritizes actionable states over active work", () => {
expect(
resolveThreadHeaderStatus({
hasPendingApproval: true,
hasPendingUserInput: true,
active: true,
failed: false,
activeWorkStartedAt: "2026-07-31T12:00:00.000Z",
nowMs: Date.parse("2026-07-31T12:02:14.000Z"),
}).kind,
).toBe("approval");
expect(
resolveThreadHeaderStatus({
hasPendingApproval: false,
hasPendingUserInput: true,
active: true,
failed: false,
activeWorkStartedAt: null,
nowMs: 0,
}).kind,
).toBe("input");
});
it("shows a timed working state and a green done state", () => {
expect(
resolveThreadHeaderStatus({
hasPendingApproval: false,
hasPendingUserInput: false,
active: true,
failed: false,
activeWorkStartedAt: "2026-07-31T12:00:00.000Z",
nowMs: Date.parse("2026-07-31T12:02:14.000Z"),
}),
).toMatchObject({ kind: "working", label: "2:14", nativeLabel: "2:14" });
expect(
resolveThreadHeaderStatus({
hasPendingApproval: false,
hasPendingUserInput: false,
active: false,
failed: false,
activeWorkStartedAt: null,
nowMs: 0,
}),
).toMatchObject({ kind: "done", label: "Done", nativeLabel: "Done" });
});
it("does not label failed work as done", () => {
expect(
resolveThreadHeaderStatus({
hasPendingApproval: false,
hasPendingUserInput: false,
active: false,
failed: true,
activeWorkStartedAt: null,
nowMs: 0,
}),
).toMatchObject({ kind: "failed", label: "Failed" });
});
});
@@ -0,0 +1,72 @@
export type ThreadHeaderStatusKind = "approval" | "input" | "working" | "failed" | "done";
export interface ThreadHeaderStatusPresentation {
readonly kind: ThreadHeaderStatusKind;
readonly label: string;
readonly nativeLabel: string;
readonly tintColor: string;
}
export function formatThreadHeaderElapsed(startedAt: string | null, nowMs: number): string | null {
if (!startedAt) {
return null;
}
const startedAtMs = Date.parse(startedAt);
if (Number.isNaN(startedAtMs)) {
return null;
}
const totalSeconds = Math.max(0, Math.floor((nowMs - startedAtMs) / 1_000));
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
return `${minutes}:${String(seconds).padStart(2, "0")}`;
}
export function resolveThreadHeaderStatus(input: {
readonly hasPendingApproval: boolean;
readonly hasPendingUserInput: boolean;
readonly active: boolean;
readonly failed: boolean;
readonly activeWorkStartedAt: string | null;
readonly nowMs: number;
}): ThreadHeaderStatusPresentation {
if (input.hasPendingApproval) {
return {
kind: "approval",
label: "Approval",
nativeLabel: "Approval",
tintColor: "#ffd60a",
};
}
if (input.hasPendingUserInput) {
return {
kind: "input",
label: "Input",
nativeLabel: "Input",
tintColor: "#7d7aff",
};
}
if (input.active) {
const elapsed = formatThreadHeaderElapsed(input.activeWorkStartedAt, input.nowMs);
return {
kind: "working",
label: elapsed ?? "Working",
nativeLabel: elapsed ?? "Working",
tintColor: "#0a84ff",
};
}
if (input.failed) {
return {
kind: "failed",
label: "Failed",
nativeLabel: "Failed",
tintColor: "#f87171",
};
}
return {
kind: "done",
label: "Done",
nativeLabel: "Done",
tintColor: "#30d158",
};
}
@@ -288,6 +288,57 @@ describe("buildThreadListV2Items", () => {
expect(layout.snoozedCount).toBe(1);
});
it("renders pinned threads first and exempts them from auto-settle — parity with web", () => {
const layout = buildThreadListV2Items({
threads: [
makeThread({ id: ThreadId.make("active"), title: "Active" }),
makeThread({
id: ThreadId.make("pinned-settled"),
title: "Pinned while settled",
pinnedAt: "2026-06-01T12:00:00.000Z",
// Stale settled state (the decider clears it on pin): the pin wins.
settledOverride: "settled",
settledAt: "2026-06-01T12:00:00.000Z",
}),
],
environmentId: null,
searchQuery: "",
now: NOW,
});
expect(layout.items.map((item) => item.thread.id)).toEqual(["pinned-settled", "active"]);
expect(layout.items.map((item) => item.pinned)).toEqual([true, false]);
expect(layout.settledCount).toBe(0);
});
it("snooze hides a pinned thread and wake restores it to the pinned block", () => {
const snoozedInput = {
threads: [
makeThread({ id: ThreadId.make("active"), title: "Active" }),
makeThread({
id: ThreadId.make("pinned-snoozed"),
title: "Pinned and snoozed",
pinnedAt: "2026-06-01T12:00:00.000Z",
snoozedUntil: "2026-06-03T09:00:00.000Z",
snoozedAt: "2026-06-01T11:00:00.000Z",
}),
],
environmentId: null,
searchQuery: "",
};
// Before the wake time: the snooze wins; the pin holds underneath.
const whileSnoozed = buildThreadListV2Items({ ...snoozedInput, now: NOW });
expect(whileSnoozed.items.map((item) => item.thread.id)).toEqual(["active"]);
expect(whileSnoozed.snoozedCount).toBe(1);
// After the wake time: the thread returns pinned, back on top.
const afterWake = buildThreadListV2Items({ ...snoozedInput, now: "2026-06-03T10:00:00.000Z" });
expect(afterWake.items.map((item) => item.thread.id)).toEqual(["pinned-snoozed", "active"]);
expect(afterWake.items[0]?.pinned).toBe(true);
expect(afterWake.snoozedCount).toBe(0);
});
it("classifies snooze with the second-precise clock and reports the next wake", () => {
const layout = buildThreadListV2Items({
threads: [
@@ -180,6 +180,8 @@ export interface ThreadListV2Item {
readonly variant: "card" | "slim";
/** Snoozed-shelf row: shows the wake countdown and offers Wake. */
readonly snoozed: boolean;
/** Pinned-block row: renders the pin glyph and offers Unpin. */
readonly pinned: boolean;
readonly isLast: boolean;
}
@@ -351,6 +353,7 @@ export function buildThreadListV2Items(input: {
? new Set(input.projectRefs.map((ref) => `${ref.environmentId}:${ref.projectId}`))
: null;
const pinned: EnvironmentThreadShell[] = [];
const active: EnvironmentThreadShell[] = [];
const settled: EnvironmentThreadShell[] = [];
const snoozed: EnvironmentThreadShell[] = [];
@@ -378,9 +381,10 @@ export function buildThreadListV2Items(input: {
const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true;
const changeRequestState =
input.changeRequestStateByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null;
// Visibility parity with web: a snoozed thread leaves the list until it
// wakes (or raises its hand — effectiveSnoozed refuses blocked/failed
// work). Snooze outranks settled classification, same as web.
// Visibility parity with web: snooze outranks everything, including a
// pin — a snoozed thread leaves the list until it wakes (or raises its
// hand). The pin survives underneath, so a woken thread reappears at
// its original spot in the creation-ordered pinned block.
if (supportsSnooze && effectiveSnoozed(thread, { now: snoozeNow })) {
snoozed.push(thread);
if (
@@ -392,6 +396,12 @@ export function buildThreadListV2Items(input: {
}
continue;
}
// A pin otherwise overrides the lifecycle: pinned threads render above
// the inbox and never auto-settle out of sight.
if (thread.pinnedAt != null) {
pinned.push(thread);
continue;
}
if (
supportsSettlement &&
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
@@ -434,11 +444,21 @@ export function buildThreadListV2Items(input: {
);
const items: ThreadListV2Item[] = [];
for (const thread of sortThreadsForListV2(pinned)) {
items.push({
thread,
variant: "card",
snoozed: false,
pinned: true,
isLast: false,
});
}
for (const thread of orderedActive) {
items.push({
thread,
variant: "card",
snoozed: false,
pinned: false,
isLast: false,
});
}
@@ -448,6 +468,7 @@ export function buildThreadListV2Items(input: {
thread,
variant: "slim",
snoozed: true,
pinned: false,
isLast: false,
});
}
@@ -457,6 +478,7 @@ export function buildThreadListV2Items(input: {
thread,
variant: "slim",
snoozed: false,
pinned: false,
isLast: false,
});
}
@@ -0,0 +1,44 @@
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import type { EnvironmentId } from "@t3tools/contracts";
import { useCallback, useMemo } from "react";
import { AsyncResult } from "effect/unstable/reactivity";
import type { ModelOption } from "../../lib/modelOptions";
import type { Preferences } from "../../persistence/mobile-preferences";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
/** Persists model favorites on this device without inventing a server setting. */
export function useModelFavorites(environmentId: EnvironmentId | null) {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const favoritesReady = AsyncResult.isSuccess(preferencesResult);
const storedKeys = favoritesReady ? (preferencesResult.value.favoriteModelKeys ?? []) : [];
const environmentPrefix = environmentId === null ? null : `${environmentId}:`;
const favoriteModelKeys = useMemo(() => {
if (environmentPrefix === null) return new Set<string>();
return new Set(
storedKeys.flatMap((key) =>
key.startsWith(environmentPrefix) ? [key.slice(environmentPrefix.length)] : [],
),
);
}, [environmentPrefix, storedKeys]);
const toggleFavorite = useCallback(
(option: ModelOption) => {
if (environmentPrefix === null || !favoritesReady) return;
const scopedKey = `${environmentPrefix}${option.key}`;
savePreferences((current: Preferences) => {
const currentKeys = current.favoriteModelKeys ?? [];
return {
favoriteModelKeys: currentKeys.includes(scopedKey)
? currentKeys.filter((key) => key !== scopedKey)
: [...currentKeys, scopedKey],
};
});
},
[environmentPrefix, favoritesReady, savePreferences],
);
return { favoriteModelKeys, favoritesReady, toggleFavorite };
}
+41
View File
@@ -5,6 +5,7 @@ import { ProviderInstanceId, type ServerConfig } from "@t3tools/contracts";
import {
buildModelMenuActions,
buildModelOptions,
buildModelPickerProviderGroups,
groupByProvider,
resolveSelectableModelSelection,
} from "./modelOptions";
@@ -88,6 +89,46 @@ describe("mobile model options", () => {
]);
});
it("keeps legacy models folded into their provider while search can reveal them", () => {
const config = {
providers: [
{
instanceId: "codex",
driver: "codex",
displayName: "Codex",
enabled: true,
installed: true,
auth: { status: "authenticated" },
models: [
{
slug: "gpt-current",
name: "GPT Current",
isCustom: false,
capabilities: null,
},
{
slug: "gpt-legacy",
name: "GPT Legacy",
isCustom: false,
isLegacy: true,
capabilities: null,
},
],
},
],
} as unknown as ServerConfig;
const groups = groupByProvider(buildModelOptions(config, null));
expect(buildModelPickerProviderGroups(groups, "")[0]).toMatchObject({
currentModels: [{ label: "GPT Current" }],
legacyModels: [{ label: "GPT Legacy" }],
});
expect(buildModelPickerProviderGroups(groups, "legacy")[0]).toMatchObject({
currentModels: [],
legacyModels: [{ label: "GPT Legacy" }],
});
});
it("normalizes a legacy fallback selection against current capabilities", () => {
const config = {
providers: [
+40 -3
View File
@@ -1,6 +1,7 @@
import type {
ModelCapabilities,
ModelSelection,
ProviderInstanceId,
ServerConfig as T3ServerConfig,
} from "@t3tools/contracts";
import type { MenuAction } from "@react-native-menu/menu";
@@ -13,7 +14,7 @@ export type ModelOption = {
readonly key: string;
readonly label: string;
readonly subtitle: string;
readonly providerKey: string;
readonly providerKey: ProviderInstanceId;
readonly providerLabel: string;
readonly providerDriver: string;
readonly isDefault: boolean;
@@ -23,11 +24,16 @@ export type ModelOption = {
};
export type ProviderGroup = {
readonly providerKey: string;
readonly providerKey: ProviderInstanceId;
readonly providerLabel: string;
readonly models: ReadonlyArray<ModelOption>;
};
export type ModelPickerProviderGroup = ProviderGroup & {
readonly currentModels: ReadonlyArray<ModelOption>;
readonly legacyModels: ReadonlyArray<ModelOption>;
};
function providerDisplayLabel(provider: {
readonly displayName?: string | undefined;
readonly driver: string;
@@ -149,7 +155,7 @@ export function buildModelOptions(
}
export function groupByProvider(options: ReadonlyArray<ModelOption>): ReadonlyArray<ProviderGroup> {
const groups = new Map<string, { providerLabel: string; models: ModelOption[] }>();
const groups = new Map<ProviderInstanceId, { providerLabel: string; models: ModelOption[] }>();
for (const option of options) {
const existing = groups.get(option.providerKey);
if (existing) {
@@ -169,6 +175,37 @@ export function groupByProvider(options: ReadonlyArray<ModelOption>): ReadonlyAr
}));
}
/**
* Builds the provider sections used by the full-screen mobile picker. Legacy
* models stay separate so the UI can keep them folded until requested while
* search can still reveal a matching legacy model immediately.
*/
export function buildModelPickerProviderGroups(
groups: ReadonlyArray<ProviderGroup>,
query: string,
): ReadonlyArray<ModelPickerProviderGroup> {
const tokens = query.trim().toLocaleLowerCase().split(/\s+/u).filter(Boolean);
const matches = (option: ModelOption) => {
if (tokens.length === 0) return true;
const searchable = [
option.label,
option.selection.model,
option.providerLabel,
option.providerDriver,
]
.join(" ")
.toLocaleLowerCase();
return tokens.every((token) => searchable.includes(token));
};
return groups.flatMap((group) => {
const currentModels = group.models.filter((model) => !model.isLegacy && matches(model));
const legacyModels = group.models.filter((model) => model.isLegacy && matches(model));
if (currentModels.length === 0 && legacyModels.length === 0) return [];
return [{ ...group, currentModels, legacyModels }];
});
}
function modelMenuAction(option: ModelOption, selectedModel: ModelSelection | null): MenuAction {
return {
id: `model:${option.key}`,
@@ -22,6 +22,8 @@ export interface Preferences {
readonly codeWordBreak?: boolean;
readonly connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
readonly collapsedProjectGroups?: readonly string[];
/** Device-local model favorites, scoped as environment:model-option keys. */
readonly favoriteModelKeys?: readonly string[];
readonly projectGroupingEnabled?: boolean;
/**
* Device-local mirror of the web beta's `sidebarV2Enabled`. Mobile has no
@@ -79,6 +81,7 @@ function sanitizePreferences(parsed: Preferences): Preferences {
codeWordBreak?: boolean;
connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
collapsedProjectGroups?: readonly string[];
favoriteModelKeys?: readonly string[];
projectGroupingEnabled?: boolean;
threadListV2Enabled?: boolean;
} = {};
@@ -107,6 +110,11 @@ function sanitizePreferences(parsed: Preferences): Preferences {
(key): key is string => typeof key === "string",
);
}
if (Array.isArray(parsed.favoriteModelKeys)) {
preferences.favoriteModelKeys = parsed.favoriteModelKeys.filter(
(key): key is string => typeof key === "string",
);
}
if (typeof parsed.projectGroupingEnabled === "boolean") {
preferences.projectGroupingEnabled = parsed.projectGroupingEnabled;
}
+30
View File
@@ -124,6 +124,36 @@ describe("mobile preferences state", () => {
}),
);
it.effect("applies functional preference updates against the latest optimistic value", () =>
Effect.gen(function* () {
const state = makePreferencesState({
load: Effect.succeed({ favoriteModelKeys: ["env:codex:gpt-5"] }),
savePatch: (patch) => Effect.succeed(patch),
});
const registry = AtomRegistry.make();
const unmountPreferences = registry.mount(state.preferencesAtom);
const unmountUpdate = registry.mount(state.updatePreferencesAtom);
yield* AtomRegistry.getResult(registry, state.preferencesAtom, {
suspendOnWaiting: true,
});
registry.set(state.updatePreferencesAtom, (current) => ({
favoriteModelKeys: [...(current.favoriteModelKeys ?? []), "env:claude:opus"],
}));
registry.set(state.updatePreferencesAtom, (current) => ({
favoriteModelKeys: [...(current.favoriteModelKeys ?? []), "other:codex:gpt-6"],
}));
expect(Option.getOrThrow(AsyncResult.value(registry.get(state.preferencesAtom)))).toEqual({
favoriteModelKeys: ["env:codex:gpt-5", "env:claude:opus", "other:codex:gpt-6"],
});
unmountUpdate();
unmountPreferences();
registry.dispose();
}),
);
it.effect("falls back to empty preferences when secure storage cannot be read", () =>
Effect.gen(function* () {
const state = makePreferencesState({
+13 -1
View File
@@ -15,6 +15,10 @@ interface OptimisticPreferences {
readonly versions: Partial<Record<keyof Preferences, number>>;
}
export type PreferencesUpdate =
| Partial<Preferences>
| ((current: Preferences) => Partial<Preferences>);
/**
* Owns the device preference blob for the lifetime of the app registry.
* Optimistic patches are kept separately so writes made while persistence is
@@ -57,7 +61,15 @@ export function createMobilePreferencesState(runtime: Atom.AtomRuntime<MobilePre
const updatePreferencesAtom = runtime
.fn(
(patch: Partial<Preferences>, get) => {
(update: PreferencesUpdate, get) => {
const preferences = get(preferencesAtom);
let patch: Partial<Preferences>;
if (typeof update === "function") {
if (!AsyncResult.isSuccess(preferences)) return Effect.void;
patch = update(preferences.value);
} else {
patch = update;
}
const version = ++nextPatchVersion;
const current = get(optimisticPatchAtom);
const versions = { ...current.versions };
@@ -168,6 +168,7 @@ export function useSelectedThreadRequests() {
return {
activePendingApproval,
activePendingApprovalCount: activePendingApprovals.length,
activePendingUserInput,
activePendingUserInputDrafts,
activePendingUserInputAnswers,
+1
View File
@@ -75,6 +75,7 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.vcsSwitchRef]: AuthOrchestrationOperateScope,
[WS_METHODS.vcsInit]: AuthOrchestrationOperateScope,
[WS_METHODS.reviewGetDiffPreview]: AuthReviewWriteScope,
[WS_METHODS.reviewGetDiffFileContents]: AuthReviewWriteScope,
[WS_METHODS.terminalOpen]: AuthTerminalOperateScope,
[WS_METHODS.terminalAttach]: AuthTerminalOperateScope,
[WS_METHODS.terminalWrite]: AuthTerminalOperateScope,
+6 -2
View File
@@ -1,3 +1,5 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import { assert, expect, it } from "@effect/vitest";
@@ -56,8 +58,10 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
const encoded = yield* encodeDesktopBootstrap(payload);
yield* fs.writeFileString(filePath, `${encoded}\n`);
const { fd } = yield* fs.open(filePath, { flag: "r" });
return fd;
return yield* Effect.acquireRelease(
Effect.sync(() => NodeFS.openSync(filePath, "r")),
(fd) => Effect.sync(() => NodeFS.closeSync(fd)),
);
});
it.effect("falls back to effect/config values when flags are omitted", () =>
+1 -1
View File
@@ -466,7 +466,7 @@ export const DurationFromString = Schema.String.pipe(
return Effect.succeed(duration);
}
return Effect.fail(
new SchemaIssue.InvalidValue(Option.some(value), {
new SchemaIssue.InvalidValue({
message: "Invalid duration. Use values like 5m, 1h, 30d, or 15 minutes.",
}),
);
+10
View File
@@ -10,6 +10,7 @@ import * as Option from "effect/Option";
import * as References from "effect/References";
import * as Terminal from "effect/Terminal";
import * as BootService from "../cloud/bootService.ts";
import {
acquireRelayClientForLink,
formatHeadlessAuthorizationPrompt,
@@ -63,6 +64,15 @@ it.effect("treats cancelling optional background setup as a successful skip", ()
}),
);
it.effect("keeps a successful connection when a remote service update is pending", () =>
Effect.gen(function* () {
const result = yield* recoverServiceOnboardingOffer(
Effect.fail(new BootService.BootServiceUpdatePendingError()),
);
assert.isFalse(result);
}),
);
it.effect("does not install the relay client when the user declines the managed download", () =>
Effect.gen(function* () {
let installCalls = 0;
+2
View File
@@ -185,6 +185,8 @@ export const recoverServiceOnboardingOffer = <R>(
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
BootServiceInstallError: (error) =>
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
BootServiceUpdatePendingError: (error) =>
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
}),
);
+46 -6
View File
@@ -15,7 +15,11 @@ import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawne
import * as ProcessRunner from "../processRunner.ts";
import * as BootService from "./bootService.ts";
import { pinnedRuntimePaths } from "./pinnedRuntime.ts";
import { parseServiceState } from "./serviceProtocol.ts";
import {
parseServiceState,
SERVICE_LAUNCHER_PROTOCOL,
serviceStateHasPendingUpdate,
} from "./serviceProtocol.ts";
it("keeps systemd pinned to the stable launcher rather than a versioned server", () => {
const unit = BootService.renderBootServiceUnit({
@@ -97,15 +101,24 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
const plan = yield* service.install;
expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
protocol: 1,
protocol: SERVICE_LAUNCHER_PROTOCOL,
activeVersion: "1.2.3",
});
expect(yield* fs.readFileString(plan.launcherPath)).toBe("export {};\n");
expect((yield* service.status).current).toBe(true);
yield* fs.writeFileString(
statePath,
'{"protocol":1,"activeVersion":"1.2.3","update":{"id":"u","fromVersion":"1.2.3","targetVersion":"1.2.4","status":"pending"}}',
);
// @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
const pendingState = JSON.stringify({
protocol: SERVICE_LAUNCHER_PROTOCOL,
activeVersion: "1.2.3",
update: {
id: "u",
fromVersion: "1.2.3",
targetVersion: "1.2.4",
dbPath: "/tmp/state.sqlite",
status: "pending",
},
});
yield* fs.writeFileString(statePath, pendingState);
expect((yield* service.status).current).toBe(false);
expect(yield* service.uninstall).toBe(true);
expect((yield* service.status).installed).toBe(false);
@@ -141,6 +154,33 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
}),
);
it.effect("restarts without overwriting a pending remote update", () =>
Effect.gen(function* () {
const { service, fs, statePath, commands } = yield* makeHarness();
yield* service.install;
// @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
const pendingState = JSON.stringify({
protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
activeVersion: "1.2.3",
update: {
id: "remote-update",
fromVersion: "1.2.3",
targetVersion: "1.2.4",
status: "pending",
},
});
yield* fs.writeFileString(statePath, pendingState);
commands.length = 0;
expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUpdatePendingError");
expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([
"systemctl --user stop t3code.service",
"systemctl --user restart t3code.service",
]);
}),
);
it.effect("fails closed off Linux", () =>
Effect.gen(function* () {
const { service } = yield* makeHarness("darwin");
+21 -1
View File
@@ -21,6 +21,7 @@ import {
SERVICE_LAUNCHER_PROTOCOL,
SERVICE_STATE_FILE,
parseServiceState,
serviceStateHasPendingUpdate,
type ServiceState,
} from "./serviceProtocol.ts";
@@ -110,10 +111,20 @@ export class BootServiceInstallError extends Schema.TaggedErrorClass<BootService
}
}
export class BootServiceUpdatePendingError extends Schema.TaggedErrorClass<BootServiceUpdatePendingError>()(
"BootServiceUpdatePendingError",
{},
) {
override get message(): string {
return "A remote server update is still pending. Wait for it to finish, then retry.";
}
}
export type BootServiceError =
| BootServiceUnsupportedError
| BootServiceCommandError
| BootServiceInstallError;
| BootServiceInstallError
| BootServiceUpdatePendingError;
export interface BootServiceStatus {
readonly supported: boolean;
@@ -288,6 +299,15 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
}
yield* Effect.gen(function* () {
if (installed) {
const previousStateText = yield* fs.readFileString(statePath).pipe(Effect.option);
if (
Option.isSome(previousStateText) &&
serviceStateHasPendingUpdate(previousStateText.value)
) {
return yield* new BootServiceUpdatePendingError();
}
}
yield* fs
.makeDirectory(unitDir, { recursive: true })
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
+2 -3
View File
@@ -4,7 +4,6 @@ import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
import * as Config from "effect/Config";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as SchemaIssue from "effect/SchemaIssue";
@@ -24,7 +23,7 @@ function validateRelayUrl(value: string) {
? Effect.fail(
new Config.ConfigError(
new Schema.SchemaError(
new SchemaIssue.InvalidValue(Option.some(value), {
new SchemaIssue.InvalidValue({
message: "Relay URL must be a secure absolute HTTPS origin.",
}),
),
@@ -130,7 +129,7 @@ function validateHostedAppUrl(value: string) {
return Effect.fail(
new Config.ConfigError(
new Schema.SchemaError(
new SchemaIssue.InvalidValue(Option.some(value), {
new SchemaIssue.InvalidValue({
message: "Hosted app URL must be an absolute HTTPS origin (or HTTP loopback origin).",
}),
),
+6 -2
View File
@@ -11,6 +11,7 @@ import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawne
import * as ServerConfig from "../config.ts";
import * as ProcessRunner from "../processRunner.ts";
import * as ServiceLauncherClient from "./serviceLauncherClient.ts";
import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
import * as ServerSelfUpdate from "./selfUpdate.ts";
interface HarnessOptions {
@@ -50,7 +51,11 @@ const makeHarness = Effect.fn("test.make_self_update_harness")(function* (
const result =
options.preflight === "blocked"
? { status: "blocked", version: "1.1.0", reason: "local update required" }
: { status: "ready", version: "1.1.0", launcherProtocol: 1 };
: {
status: "ready",
version: "1.1.0",
launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
};
return {
// @effect-diagnostics-next-line preferSchemaOverJson:off - fake child-process stdout.
stdout: JSON.stringify(result),
@@ -64,7 +69,6 @@ const makeHarness = Effect.fn("test.make_self_update_harness")(function* (
});
const launcher = ServiceLauncherClient.ServiceLauncherClient.of({
managed: options.managed ?? true,
trial: false,
requestUpdate:
options.requestUpdate ??
(() =>
+1 -1
View File
@@ -170,7 +170,7 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* () {
yield* reportProgress("installing");
const updateId = yield* launcher
.requestUpdate({ targetVersion })
.requestUpdate({ targetVersion, dbPath: serverConfig.dbPath })
.pipe(
Effect.mapError((error) =>
failWith(
@@ -5,6 +5,7 @@ import * as Fiber from "effect/Fiber";
import {
SERVICE_LAUNCHER_CONTEXT_ENV,
SERVICE_LAUNCHER_PROTOCOL,
type ServiceLauncherChildMessage,
type ServiceLauncherParentMessage,
} from "./serviceProtocol.ts";
@@ -53,10 +54,11 @@ it.effect("waits for the launcher to durably commit the trial update ID", () =>
id: "update-1",
fromVersion: "1.0.0",
targetVersion: "1.1.0",
dbPath: "/tmp/state.sqlite",
status: "pending" as const,
};
const host = new FakeLauncherProcess({
protocol: 1,
protocol: SERVICE_LAUNCHER_PROTOCOL,
childVersion: "1.1.0",
update: pending,
});
@@ -79,13 +81,14 @@ it.effect("waits for the launcher to durably commit the trial update ID", () =>
it.effect("returns the launcher-generated ID only after update acceptance", () =>
Effect.gen(function* () {
const host = new FakeLauncherProcess({
protocol: 1,
protocol: SERVICE_LAUNCHER_PROTOCOL,
childVersion: "1.0.0",
});
const client = yield* makeClient(host, "1.0.0");
const requested = yield* Effect.forkChild(client.requestUpdate({ targetVersion: "1.1.0" }), {
startImmediately: true,
});
const requested = yield* Effect.forkChild(
client.requestUpdate({ targetVersion: "1.1.0", dbPath: "/tmp/state.sqlite" }),
{ startImmediately: true },
);
yield* Effect.yieldNow;
host.emit({
type: "update-accepted",
@@ -97,11 +100,15 @@ it.effect("returns the launcher-generated ID only after update acceptance", () =
it.effect("preserves a launcher rejection as a distinct error", () =>
Effect.gen(function* () {
const host = new FakeLauncherProcess({ protocol: 1, childVersion: "1.0.0" });
const client = yield* makeClient(host, "1.0.0");
const requested = yield* Effect.forkChild(client.requestUpdate({ targetVersion: "1.1.0" }), {
startImmediately: true,
const host = new FakeLauncherProcess({
protocol: SERVICE_LAUNCHER_PROTOCOL,
childVersion: "1.0.0",
});
const client = yield* makeClient(host, "1.0.0");
const requested = yield* Effect.forkChild(
client.requestUpdate({ targetVersion: "1.1.0", dbPath: "/tmp/state.sqlite" }),
{ startImmediately: true },
);
yield* Effect.yieldNow;
host.emit({ type: "update-rejected", reason: "requires local update" });
expect(yield* Fiber.join(requested).pipe(Effect.flip)).toMatchObject({
@@ -115,12 +122,13 @@ it.effect("preserves a launcher rejection as a distinct error", () =>
it.effect("rejects contradictory trial context instead of leaving activation closed", () =>
Effect.gen(function* () {
const host = new FakeLauncherProcess({
protocol: 1,
protocol: SERVICE_LAUNCHER_PROTOCOL,
childVersion: "1.1.0",
update: {
id: "update-1",
fromVersion: "1.0.0",
targetVersion: "1.2.0",
dbPath: "/tmp/state.sqlite",
status: "pending",
},
});
+10 -6
View File
@@ -100,9 +100,9 @@ export class ServiceLauncherClient extends Context.Service<
ServiceLauncherClient,
{
readonly managed: boolean;
readonly trial: boolean;
readonly requestUpdate: (input: {
readonly targetVersion: string;
readonly dbPath: string;
}) => Effect.Effect<string, ServiceLauncherClientError | ServiceLauncherRejectedError>;
readonly prepareTrial: Effect.Effect<
ServerSelfUpdateOutcome | undefined,
@@ -137,8 +137,8 @@ const resolveStartup = Effect.fn("cloud.service_launcher_client.resolve_startup"
export const resolveServiceLauncherMode = Effect.fn("cloud.service_launcher_client.resolve_mode")(
function* () {
const { context, managed } = yield* resolveStartup();
return { managed, trial: context?.update?.status === "pending" };
const { managed } = yield* resolveStartup();
return { managed };
},
);
@@ -199,7 +199,7 @@ export const make = Effect.fn("cloud.service_launcher_client.make")(function* (o
}),
);
const requestUpdate = (input: { readonly targetVersion: string }) =>
const requestUpdate = (input: { readonly targetVersion: string; readonly dbPath: string }) =>
exchange(
{ type: "request-update", ...input },
(reply) => reply.type === "update-accepted" || reply.type === "update-rejected",
@@ -233,14 +233,18 @@ export const make = Effect.fn("cloud.service_launcher_client.make")(function* (o
if (reply.type !== "committed") {
return Effect.die("service launcher returned an impossible prepared response");
}
return Effect.succeed({ ...pending, status: "committed" as const });
return Effect.succeed({
id: pending.id,
fromVersion: pending.fromVersion,
targetVersion: pending.targetVersion,
status: "committed" as const,
});
}),
)
: Effect.succeed(outcome);
return ServiceLauncherClient.of({
managed,
trial: pending !== undefined,
requestUpdate,
prepareTrial,
});
+20 -41
View File
@@ -1,47 +1,26 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as NodeSqlite from "node:sqlite";
import { migrationManifest } from "../persistence/Migrations.ts";
import { runServicePreflight } from "./servicePreflight.ts";
import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
it.layer(NodeServices.layer)("service update preflight", (it) => {
it.effect("requires exact migration-manifest equality without mutating the database", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-preflight-test-" });
const databasePath = path.join(root, "state.sqlite");
const database = new NodeSqlite.DatabaseSync(databasePath);
database.exec("CREATE TABLE effect_sql_migrations (migration_id INTEGER, name TEXT)");
const insert = database.prepare(
"INSERT INTO effect_sql_migrations (migration_id, name) VALUES (?, ?)",
);
for (const [id, name] of migrationManifest) insert.run(id, name);
database.close();
expect(runServicePreflight({ databasePath, launcherProtocol: 1, version: "1.2.3" })).toEqual({
status: "ready",
version: "1.2.3",
launcherProtocol: 1,
});
const changed = new NodeSqlite.DatabaseSync(databasePath);
changed.exec("DELETE FROM effect_sql_migrations WHERE migration_id = 35");
changed.close();
const blocked = runServicePreflight({
databasePath,
launcherProtocol: 1,
version: "1.2.3",
});
expect(blocked.status).toBe("blocked");
if (blocked.status === "blocked") {
expect(blocked.reason).toContain("npx [email protected] service update");
}
it("requires the database-snapshot launcher protocol", () => {
expect(
runServicePreflight({
databasePath: "/missing/state.sqlite",
launcherProtocol: SERVICE_LAUNCHER_PROTOCOL - 1,
version: "1.2.3",
}),
);
).toMatchObject({ status: "blocked", version: "1.2.3" });
expect(
runServicePreflight({
databasePath: "/missing/state.sqlite",
launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
version: "1.2.3",
}),
).toEqual({
status: "ready",
version: "1.2.3",
launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
});
});
+1 -38
View File
@@ -1,7 +1,4 @@
import * as NodeSqlite from "node:sqlite";
import packageJson from "../../package.json" with { type: "json" };
import { migrationManifest } from "../persistence/Migrations.ts";
import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
export type ServicePreflightResult =
@@ -16,20 +13,8 @@ export type ServicePreflightResult =
readonly reason: string;
};
const localUpdateReason = (version: string) =>
`This version includes a database update and cannot be installed remotely. Run \`npx t3@${version} service update\` on the server machine.`;
const isMigrationRow = (
value: unknown,
): value is { readonly migration_id: number; readonly name: string } =>
typeof value === "object" &&
value !== null &&
"migration_id" in value &&
typeof value.migration_id === "number" &&
"name" in value &&
typeof value.name === "string";
export function runServicePreflight(input: {
/** Older servers always pass this flag when invoking a staged preflight. */
readonly databasePath: string;
readonly launcherProtocol: number;
readonly version?: string;
@@ -44,28 +29,6 @@ export function runServicePreflight(input: {
};
}
try {
const database = new NodeSqlite.DatabaseSync(input.databasePath, { readOnly: true });
try {
const rows: ReadonlyArray<unknown> = database
.prepare("SELECT migration_id, name FROM effect_sql_migrations ORDER BY migration_id")
.all();
const exact =
rows.length === migrationManifest.length &&
rows.every((row, index) => {
const expected = migrationManifest[index];
return (
isMigrationRow(row) && row.migration_id === expected?.[0] && row.name === expected?.[1]
);
});
if (!exact) return { status: "blocked", version, reason: localUpdateReason(version) };
} finally {
database.close();
}
} catch {
return { status: "blocked", version, reason: localUpdateReason(version) };
}
return { status: "ready", version, launcherProtocol: SERVICE_LAUNCHER_PROTOCOL };
}
+23 -4
View File
@@ -1,6 +1,7 @@
import type { ServerSelfUpdateOutcome } from "@t3tools/contracts";
export const SERVICE_LAUNCHER_PROTOCOL = 1 as const;
/** Protocol 2 snapshots SQLite before trials so migrations can be rolled back safely. */
export const SERVICE_LAUNCHER_PROTOCOL = 2 as const;
export const SERVICE_LAUNCHER_CONTEXT_ENV = "T3_SERVICE_LAUNCHER_CONTEXT";
export const SERVICE_LAUNCHER_FILE = "service-launcher.mjs";
export const SERVICE_STATE_FILE = "service-state.json";
@@ -9,6 +10,7 @@ export interface PendingServiceUpdate {
readonly id: string;
readonly fromVersion: string;
readonly targetVersion: string;
readonly dbPath: string;
readonly status: "pending";
}
@@ -31,6 +33,7 @@ export type ServiceLauncherChildMessage =
| {
readonly type: "request-update";
readonly targetVersion: string;
readonly dbPath: string;
}
| {
readonly type: "prepared";
@@ -78,7 +81,9 @@ export function decodeServiceUpdate(value: unknown): ServiceUpdateRecord | undef
return undefined;
}
if (status === "pending") {
return { id, fromVersion, targetVersion, status };
return typeof value.dbPath === "string" && value.dbPath.trim() !== ""
? { id, fromVersion, targetVersion, dbPath: value.dbPath, status }
: undefined;
}
if (
(status === "committed" || status === "rolled-back" || status === "failed") &&
@@ -165,6 +170,16 @@ export function parseServiceState(value: string): ServiceState | undefined {
}
}
/** Detects an in-flight update across launcher protocol versions before replacing its state. */
export function serviceStateHasPendingUpdate(value: string): boolean {
try {
const parsed: unknown = JSON.parse(value);
return isRecord(parsed) && isRecord(parsed.update) && parsed.update.status === "pending";
} catch {
return false;
}
}
export function decodeServiceLauncherContext(value: string): ServiceLauncherContext | undefined {
let parsed: unknown;
try {
@@ -202,8 +217,12 @@ export function decodeServiceLauncherChildMessage(
value: unknown,
): ServiceLauncherChildMessage | undefined {
if (!isRecord(value)) return undefined;
if (value.type === "request-update" && typeof value.targetVersion === "string") {
return { type: value.type, targetVersion: value.targetVersion };
if (
value.type === "request-update" &&
typeof value.targetVersion === "string" &&
typeof value.dbPath === "string"
) {
return { type: value.type, targetVersion: value.targetVersion, dbPath: value.dbPath };
}
return value.type === "prepared" && typeof value.updateId === "string"
? { type: value.type, updateId: value.updateId }
@@ -145,6 +145,7 @@ export const make = Effect.gen(function* () {
connectionProbe: true,
threadSettlement: true,
threadSnooze: true,
threadPinning: true,
threadTitleRegeneration: true,
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
...(serverSelfUpdate === "boot-service" ? { serverSelfUpdateProgress: true } : {}),
+3 -68
View File
@@ -14,10 +14,10 @@ import * as Option from "effect/Option";
import * as Path from "effect/Path";
import { cast } from "effect/Function";
import {
Headers,
HttpBody,
HttpClient,
HttpClientResponse,
HttpMiddleware,
HttpRouter,
HttpServerResponse,
HttpServerRequest,
@@ -30,7 +30,6 @@ import * as ServerConfig from "./config.ts";
import { ASSET_ROUTE_PREFIX, resolveAsset } from "./assets/AssetAccess.ts";
import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import * as HttpResponseCompression from "./httpCompression/HttpResponseCompression.ts";
import { traceRelayRequest } from "./cloud/traceRelayRequest.ts";
import {
annotateEnvironmentRequest,
@@ -44,74 +43,10 @@ import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./ht
const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
const DESKTOP_RENDERER_ORIGINS = ["t3code://app", "t3code-dev://app"];
const GZIP_MIN_BYTES = 1024;
function acceptsGzip(value: string | undefined): boolean {
if (!value) return false;
const accepted = new Map(
value.split(",").map((entry) => {
const [coding = "", ...parameters] = entry.trim().toLowerCase().split(";");
const quality = parameters
.map((parameter) => parameter.trim().match(/^q=(.+)$/)?.[1])
.find((parameter) => parameter !== undefined);
return [coding, quality === undefined ? 1 : Number(quality)] as const;
}),
);
return (accepted.get("gzip") ?? accepted.get("*") ?? 0) > 0;
}
function varyByAcceptEncoding(value: string | undefined): string {
if (!value) return "Accept-Encoding";
const values = new Set(value.split(",").map((entry) => entry.trim().toLowerCase()));
return values.has("*") || values.has("accept-encoding") ? value : `${value}, Accept-Encoding`;
}
const compressHttpResponse = Effect.fnUntraced(function* (
response: HttpServerResponse.HttpServerResponse,
acceptEncoding: string | undefined,
) {
const body = response.body;
if (
body._tag !== "Uint8Array" ||
body.contentLength < GZIP_MIN_BYTES ||
!body.contentType.startsWith("application/json") ||
response.headers["content-encoding"]
) {
return response;
}
const variedResponse = HttpServerResponse.setHeader(
response,
"vary",
varyByAcceptEncoding(response.headers.vary),
);
if (!acceptsGzip(acceptEncoding)) return variedResponse;
const compression = yield* HttpResponseCompression.HttpResponseCompression;
const headers = Headers.set(
Headers.remove(variedResponse.headers, "content-length"),
"content-encoding",
"gzip",
);
return compression.gzip(body.body, {
status: response.status,
statusText: response.statusText,
headers,
cookies: response.cookies,
contentType: body.contentType,
});
export const httpCompressionLayer = HttpRouter.middleware(HttpMiddleware.compression(), {
global: true,
});
export const httpCompressionLayer = HttpRouter.middleware(
(httpEffect) =>
Effect.flatMap(
Effect.all([httpEffect, HttpServerRequest.HttpServerRequest]),
([response, request]) => compressHttpResponse(response, request.headers["accept-encoding"]),
),
{ global: true },
);
export const browserApiCorsLayer = Layer.unwrap(
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
@@ -1,29 +0,0 @@
import { expect, it } from "@effect/vitest";
import * as NodeStream from "node:stream";
import * as Effect from "effect/Effect";
import * as HttpResponseCompression from "./HttpResponseCompression.ts";
it.effect("uses a native Node stream", () =>
Effect.gen(function* () {
const compression = yield* HttpResponseCompression.HttpResponseCompression;
const response = compression.gzip(new Uint8Array(), {});
expect(response.body._tag).toBe("Raw");
if (response.body._tag === "Raw") {
expect(response.body.body).toBeInstanceOf(NodeStream.Readable);
}
}).pipe(Effect.provide(HttpResponseCompression.layerNode)),
);
it.effect("uses a native Web stream for Bun", () =>
Effect.gen(function* () {
const compression = yield* HttpResponseCompression.HttpResponseCompression;
const response = compression.gzip(new Uint8Array(), {});
expect(response.body._tag).toBe("Raw");
if (response.body._tag === "Raw") {
expect(response.body.body).toBeInstanceOf(ReadableStream);
}
}).pipe(Effect.provide(HttpResponseCompression.layerBun)),
);
@@ -1,36 +0,0 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
export class HttpResponseCompression extends Context.Service<
HttpResponseCompression,
{
readonly gzip: (
body: Uint8Array,
options: HttpServerResponse.Options,
) => HttpServerResponse.HttpServerResponse;
}
>()("t3/httpCompression/HttpResponseCompression") {}
export const layerNode = Layer.effect(
HttpResponseCompression,
Effect.gen(function* () {
const NodeZlib = yield* Effect.promise(() => import("node:zlib"));
return {
gzip: (body, options) => {
const stream = NodeZlib.createGzip();
stream.end(body);
return HttpServerResponse.raw(stream, options);
},
};
}),
);
export const layerBun = Layer.succeed(HttpResponseCompression, {
gzip: (body, options) =>
HttpServerResponse.raw(
new Response(body).body!.pipeThrough(new CompressionStream("gzip")),
options,
),
});
+2 -3
View File
@@ -29,7 +29,6 @@ import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Predicate from "effect/Predicate";
import * as PubSub from "effect/PubSub";
import * as Result from "effect/Result";
@@ -68,7 +67,7 @@ export const ResolvedKeybindingFromConfig = KeybindingRule.pipe(
Effect.filterOrFail(
Predicate.isNotNull,
() =>
new SchemaIssue.InvalidValue(Option.some(rule), {
new SchemaIssue.InvalidValue({
message: "Invalid keybinding rule",
}),
),
@@ -80,7 +79,7 @@ export const ResolvedKeybindingFromConfig = KeybindingRule.pipe(
const key = encodeShortcut(resolved.shortcut);
if (!key) {
return yield* Effect.fail(
new SchemaIssue.InvalidValue(Option.some(resolved), {
new SchemaIssue.InvalidValue({
message: "Resolved shortcut cannot be encoded to key string",
}),
);
+6 -3
View File
@@ -5,7 +5,7 @@ import { EnvironmentId, PreviewTabId, ProviderInstanceId, ThreadId } from "@t3to
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
import { McpSchema, McpServer } from "effect/unstable/ai";
import { McpProtocol, McpSchema, McpServer } from "effect/unstable/ai";
import { HttpBody, HttpClient, HttpRouter, HttpServerResponse } from "effect/unstable/http";
import * as McpHttpServer from "./McpHttpServer.ts";
@@ -26,8 +26,9 @@ const invocation = {
};
const client = McpSchema.McpServerClient.of({
clientId: 1,
protocolVersion: "2025-06-18",
initializePayload: {
protocolVersion: "2025-03-26",
protocolVersion: "2025-06-18",
capabilities: {},
clientInfo: { name: "mcp-test", version: "1.0.0" },
},
@@ -103,6 +104,7 @@ it.effect("terminates HTTP MCP sessions with DELETE", () =>
name: "MCP termination test",
version: "1.0.0",
path: "/mcp",
protocols: [McpProtocol.v2025_06_18],
});
yield* HttpRouter.serve(serverLayer, {
disableListenLog: true,
@@ -239,8 +241,9 @@ it.effect("registers annotated tools and preserves authenticated request context
.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
Effect.provideService(McpSchema.McpServerClient, client),
Effect.flip,
);
expect(malformed.isError).toBe(true);
expect(malformed._tag).toBe("InvalidParams");
const snapshot = yield* server
.callTool({ name: "preview_snapshot", arguments: { tabId: alternateTabId } })
+2 -1
View File
@@ -6,7 +6,7 @@ import * as Option from "effect/Option";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import type * as Types from "effect/Types";
import { McpSchema, McpServer, Tool } from "effect/unstable/ai";
import { McpProtocol, McpSchema, McpServer, Tool } from "effect/unstable/ai";
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
import packageJson from "../../package.json" with { type: "json" };
@@ -220,6 +220,7 @@ const McpTransportLive = McpServer.layerHttp({
name: "T3 Code",
version: packageJson.version,
path: "/mcp",
protocols: [McpProtocol.v2025_06_18],
}).pipe(Layer.provide(McpAuthMiddlewareLive));
export const layer = PreviewToolkitRegistrationLive.pipe(Layer.provideMerge(McpTransportLive));
@@ -12,6 +12,19 @@ const schemaHasDescription = (schema: unknown): boolean => {
.some((members) => members.some(schemaHasDescription));
};
const schemaHasMultipleAllOfDescriptions = (schema: unknown): boolean => {
if (!schema || typeof schema !== "object") return false;
const record = schema as Record<string, unknown>;
const allOf = Array.isArray(record.allOf) ? record.allOf : [];
const descriptionCount = allOf.filter(
(member) =>
member !== null &&
typeof member === "object" &&
typeof (member as Record<string, unknown>).description === "string",
).length;
return descriptionCount > 1 || Object.values(record).some(schemaHasMultipleAllOfDescriptions);
};
it("exports provider-compatible object schemas with described parameters", () => {
for (const tool of Object.values(PreviewToolkit.tools)) {
const schema = Tool.getJsonSchema(tool) as {
@@ -27,6 +40,9 @@ it("exports provider-compatible object schemas with described parameters", () =>
expect(schema.type, `${tool.name} must export a top-level object schema`).toBe("object");
expect(schema.anyOf, `${tool.name} must not export a root anyOf`).toBeUndefined();
expect(schema.oneOf, `${tool.name} must not export a root oneOf`).toBeUndefined();
if (tool.name === "preview_navigate") {
expect(schemaHasMultipleAllOfDescriptions(schema)).toBe(false);
}
expect(
schema.properties?.tabId,
`${tool.name} must allow an explicit collaborative browser tab target`,
@@ -611,6 +611,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
pinnedAt: null,
titleRegenerationRequestId: null,
titleRegenerationStartedAt: null,
latestUserMessageAt: null,
@@ -717,6 +718,36 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
return;
}
case "thread.pinned": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) {
return;
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
pinnedAt: event.payload.pinnedAt,
updatedAt: event.payload.updatedAt,
});
return;
}
case "thread.unpinned": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) {
return;
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
pinnedAt: null,
updatedAt: event.payload.updatedAt,
});
return;
}
case "thread.meta-updated": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
@@ -312,6 +312,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
pinnedAt: null,
titleRegeneration: null,
deletedAt: null,
messages: [
@@ -427,6 +428,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
pinnedAt: null,
titleRegeneration: null,
session: {
threadId: ThreadId.make("thread-1"),
@@ -384,6 +384,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -418,6 +419,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -454,6 +456,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -890,6 +893,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -1328,6 +1332,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
titleRegeneration: mapTitleRegeneration(row),
deletedAt: row.deletedAt,
messages: messagesByThread.get(row.threadId) ?? [],
@@ -1531,6 +1536,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
titleRegeneration: mapTitleRegeneration(row),
deletedAt: row.deletedAt,
messages: [],
@@ -1665,6 +1671,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
titleRegeneration: mapTitleRegeneration(row),
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
@@ -1804,6 +1811,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
titleRegeneration: mapTitleRegeneration(row),
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
@@ -2075,6 +2083,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: threadRow.value.settledAt,
snoozedUntil: threadRow.value.snoozedUntil,
snoozedAt: threadRow.value.snoozedAt,
pinnedAt: threadRow.value.pinnedAt,
titleRegeneration: mapTitleRegeneration(threadRow.value),
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
latestUserMessageAt: threadRow.value.latestUserMessageAt,
@@ -2174,6 +2183,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: threadRow.value.settledAt,
snoozedUntil: threadRow.value.snoozedUntil,
snoozedAt: threadRow.value.snoozedAt,
pinnedAt: threadRow.value.pinnedAt,
titleRegeneration: mapTitleRegeneration(threadRow.value),
deletedAt: null,
messages: messageRows.map((row) => {
@@ -785,6 +785,123 @@ describe("ProviderCommandReactor", () => {
expect(thread?.titleRegeneration).toBeNull();
});
it("pins the first user message when regeneration context is truncated", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
const firstUserMessage = `Review subagent monitoring risks. ${"Opening context. ".repeat(200)}`;
const recentUserMessage = `LATEST FINDING: ${"implementation detail ".repeat(320)}`;
harness.generateThreadTitle.mockReturnValue(
Effect.succeed({ title: "Review subagent monitoring risks" }),
);
await harness.runEffect(
harness.engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.make("cmd-thread-title-existing-long"),
threadId: ThreadId.make("thread-1"),
title: "Generic PR review",
}),
);
await harness.runEffect(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-before-long-title-regeneration"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-before-long-title-regeneration"),
role: "user",
text: firstUserMessage,
attachments: [
{
type: "image",
id: "opening-context-image",
name: "image.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await harness.runEffect(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-middle-turn-before-long-title-regeneration"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("middle-message-before-long-title-regeneration"),
role: "user",
text: "Temporary handoff details.",
attachments: [
{
type: "image",
id: "middle-context-image",
name: "image.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: "2026-01-01T00:00:01.000Z",
}),
);
await harness.runEffect(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-recent-turn-before-long-title-regeneration"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("recent-message-before-long-title-regeneration"),
role: "user",
text: recentUserMessage,
attachments: [
{
type: "image",
id: "recent-context-image",
name: "image.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: "2026-01-01T00:00:02.000Z",
}),
);
await harness.runEffect(
harness.engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.make("cmd-thread-title-regenerate-long"),
threadId: ThreadId.make("thread-1"),
regenerateTitle: true,
}),
);
await harness.drain();
expect(harness.generateThreadTitle).toHaveBeenCalledTimes(1);
const input = harness.generateThreadTitle.mock.calls[0]?.[0];
if (!input) {
throw new Error("Expected a title generation input");
}
const message = input.message;
expect(message.startsWith("USER:\nReview subagent monitoring risks.")).toBe(true);
expect(message).toContain("[First user message truncated]");
expect(message).toContain("[Earlier content truncated]");
expect(message).toContain("image.png");
expect(message).toHaveLength(8_000);
expect(input.attachments?.map((attachment) => attachment.id)).toEqual([
"opening-context-image",
"recent-context-image",
]);
});
it("clears title regeneration state left pending across reactor startup", async () => {
const harness = await createHarness({
titleRegenerationBeforeStart: "one",
@@ -972,10 +1089,14 @@ describe("ProviderCommandReactor", () => {
expect(thread?.titleRegeneration).toBeNull();
});
it("keeps the full retained context and excludes attachments outside it", async () => {
it("pins the first user context and attachment before the retained tail", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
const retainedContext = "x".repeat(8_000);
const firstUserContext = "USER:\nOld visual issue\n[Attachments: old-issue.png]";
const truncationMarker = "[Earlier content truncated]\n\n";
const retainedContext = "x".repeat(
8_000 - firstUserContext.length - "\n\n".length - truncationMarker.length,
);
await harness.runEffect(
harness.engine.dispatch({
@@ -1040,9 +1161,14 @@ describe("ProviderCommandReactor", () => {
await harness.drain();
expect(harness.generateThreadTitle.mock.calls[0]?.[0].message).toBe(
`[Earlier content truncated]\n\n${retainedContext}`,
`${firstUserContext}\n\n${truncationMarker}${retainedContext}`,
);
expect(harness.generateThreadTitle.mock.calls[0]?.[0].attachments).toBeUndefined();
expect(harness.generateThreadTitle.mock.calls[0]?.[0].attachments).toEqual([
expect.objectContaining({
id: "old-title-context-image",
name: "old-issue.png",
}),
]);
});
it("does not overwrite a manual rename while title regeneration is running", async () => {
@@ -94,41 +94,61 @@ const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
const DEFAULT_THREAD_TITLE = "New thread";
const MAX_REGENERATION_ATTACHMENTS = 4;
const MAX_THREAD_TITLE_CONTEXT_CHARS = 8_000;
const MAX_FIRST_USER_TITLE_CONTEXT_CHARS = 2_000;
const THREAD_TITLE_CONTEXT_TRUNCATION_MARKER = "[Earlier content truncated]\n\n";
const FIRST_USER_CONTEXT_TRUNCATION_MARKER = "\n[First user message truncated]";
function formatThreadTitleContext(
messages: ReadonlyArray<{
readonly role: "user" | "assistant" | "system";
readonly text: string;
readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
}>,
type ThreadTitleMessage = {
readonly role: "user" | "assistant" | "system";
readonly text: string;
readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
};
function formatThreadTitleSection(message: ThreadTitleMessage): string | undefined {
if (message.role === "system") {
return undefined;
}
const text = message.text.trim();
const attachmentSummary = (message.attachments ?? [])
.map((attachment) => attachment.name)
.join(", ");
const contents = [
...(text.length > 0 ? [text] : []),
...(attachmentSummary.length > 0 ? [`[Attachments: ${attachmentSummary}]`] : []),
].join("\n");
return contents.length > 0 ? `${message.role.toUpperCase()}:\n${contents}` : undefined;
}
function limitFirstUserSection(section: string): string {
if (section.length <= MAX_FIRST_USER_TITLE_CONTEXT_CHARS) {
return section;
}
return `${section.slice(
0,
MAX_FIRST_USER_TITLE_CONTEXT_CHARS - FIRST_USER_CONTEXT_TRUNCATION_MARKER.length,
)}${FIRST_USER_CONTEXT_TRUNCATION_MARKER}`;
}
function collectRecentThreadTitleContext(
messages: ReadonlyArray<ThreadTitleMessage>,
maxChars: number,
): {
readonly message: string;
readonly context: string;
readonly attachments: ReadonlyArray<ChatAttachment>;
readonly truncated: boolean;
} {
let context = "";
let truncated = false;
const retainedAttachments: Array<ChatAttachment> = [];
for (const message of messages.toReversed()) {
if (message.role === "system") {
continue;
}
const text = message.text.trim();
const attachmentSummary = (message.attachments ?? [])
.map((attachment) => attachment.name)
.join(", ");
const contents = [
...(text.length > 0 ? [text] : []),
...(attachmentSummary.length > 0 ? [`[Attachments: ${attachmentSummary}]`] : []),
].join("\n");
if (contents.length === 0) {
const section = formatThreadTitleSection(message);
if (section === undefined) {
continue;
}
const section = `${message.role.toUpperCase()}:\n${contents}`;
const separator = context.length > 0 ? "\n\n" : "";
const available = MAX_THREAD_TITLE_CONTEXT_CHARS - context.length - separator.length;
const available = maxChars - context.length - separator.length;
if (section.length > available) {
if (available > 0) {
context = `${section.slice(-available)}${separator}${context}`;
@@ -141,9 +161,54 @@ function formatThreadTitleContext(
retainedAttachments.unshift(...(message.attachments ?? []));
}
return { context, attachments: retainedAttachments, truncated };
}
function formatThreadTitleContext(messages: ReadonlyArray<ThreadTitleMessage>): {
readonly message: string;
readonly attachments: ReadonlyArray<ChatAttachment>;
} {
const recent = collectRecentThreadTitleContext(messages, MAX_THREAD_TITLE_CONTEXT_CHARS);
if (!recent.truncated) {
return {
message: recent.context,
attachments: recent.attachments.slice(-MAX_REGENERATION_ATTACHMENTS),
};
}
const firstUserMessage = messages.find(
(message) => message.role === "user" && formatThreadTitleSection(message),
);
const firstUserSection = firstUserMessage
? formatThreadTitleSection(firstUserMessage)
: undefined;
if (!firstUserMessage || !firstUserSection) {
return {
message: `${THREAD_TITLE_CONTEXT_TRUNCATION_MARKER}${recent.context}`,
attachments: recent.attachments.slice(-MAX_REGENERATION_ATTACHMENTS),
};
}
const pinnedSection = limitFirstUserSection(firstUserSection);
const recentContextBudget =
MAX_THREAD_TITLE_CONTEXT_CHARS -
pinnedSection.length -
"\n\n".length -
THREAD_TITLE_CONTEXT_TRUNCATION_MARKER.length;
const retainedRecent = collectRecentThreadTitleContext(messages, recentContextBudget);
const pinnedAttachment = firstUserMessage.attachments?.[0];
const recentAttachments = retainedRecent.attachments.filter(
(attachment) => attachment.id !== pinnedAttachment?.id,
);
return {
message: truncated ? `${THREAD_TITLE_CONTEXT_TRUNCATION_MARKER}${context}` : context,
attachments: retainedAttachments.slice(-MAX_REGENERATION_ATTACHMENTS),
message: `${pinnedSection}\n\n${THREAD_TITLE_CONTEXT_TRUNCATION_MARKER}${retainedRecent.context}`,
attachments: [
...(pinnedAttachment ? [pinnedAttachment] : []),
...recentAttachments.slice(
-(MAX_REGENERATION_ATTACHMENTS - (pinnedAttachment === undefined ? 0 : 1)),
),
],
};
}
+4
View File
@@ -13,6 +13,8 @@ import {
ThreadUnsettledPayload as ContractsThreadUnsettledPayloadSchema,
ThreadSnoozedPayload as ContractsThreadSnoozedPayloadSchema,
ThreadUnsnoozedPayload as ContractsThreadUnsnoozedPayloadSchema,
ThreadPinnedPayload as ContractsThreadPinnedPayloadSchema,
ThreadUnpinnedPayload as ContractsThreadUnpinnedPayloadSchema,
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
@@ -42,6 +44,8 @@ export const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema;
export const ThreadUnsettledPayload = ContractsThreadUnsettledPayloadSchema;
export const ThreadSnoozedPayload = ContractsThreadSnoozedPayloadSchema;
export const ThreadUnsnoozedPayload = ContractsThreadUnsnoozedPayloadSchema;
export const ThreadPinnedPayload = ContractsThreadPinnedPayloadSchema;
export const ThreadUnpinnedPayload = ContractsThreadUnpinnedPayloadSchema;
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;
@@ -0,0 +1,226 @@
import {
CommandId,
ProjectId,
ProviderInstanceId,
ThreadId,
type OrchestrationReadModel,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { decideOrchestrationCommand } from "./decider.ts";
const NOW = "2026-01-01T00:00:00.000Z";
const PINNED_AT = "1969-12-30T00:00:00.000Z";
function makeReadModel(input: {
readonly pinnedAt?: string | null;
readonly archivedAt?: string | null;
readonly settledOverride?: "settled" | "active" | null;
readonly settledAt?: string | null;
readonly snoozedUntil?: string | null;
readonly snoozedAt?: string | null;
}): OrchestrationReadModel {
return {
snapshotSequence: 0,
projects: [],
threads: [
{
id: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-1"),
title: "Thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: NOW,
updatedAt: NOW,
archivedAt: input.archivedAt ?? null,
settledOverride: input.settledOverride ?? null,
settledAt: input.settledAt ?? (input.settledOverride === "settled" ? NOW : null),
snoozedUntil: input.snoozedUntil ?? null,
snoozedAt: input.snoozedAt ?? (input.snoozedUntil != null ? PINNED_AT : null),
pinnedAt: input.pinnedAt ?? null,
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
},
],
updatedAt: NOW,
};
}
it.layer(NodeServices.layer)("pinned thread decider", (it) => {
it.effect("pins a thread, stamping pinnedAt and updatedAt together", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.pin",
commandId: CommandId.make("cmd-pin"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({}),
});
const events = Array.isArray(event) ? event : [event];
expect(events).toHaveLength(1);
expect(events[0]?.type).toBe("thread.pinned");
if (events[0]?.type === "thread.pinned") {
expect(events[0].payload.pinnedAt).toBe(events[0].payload.updatedAt);
}
}),
);
it.effect("re-pinning preserves the original pinnedAt and updatedAt", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.pin",
commandId: CommandId.make("cmd-pin-again"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({ pinnedAt: PINNED_AT }),
});
const events = Array.isArray(event) ? event : [event];
expect(events[0]?.type).toBe("thread.pinned");
if (events[0]?.type === "thread.pinned") {
expect(events[0].payload.pinnedAt).toBe(PINNED_AT);
expect(events[0].payload.updatedAt).toBe(NOW);
}
}),
);
it.effect("unpins a pinned thread", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.unpin",
commandId: CommandId.make("cmd-unpin"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({ pinnedAt: PINNED_AT }),
});
const events = Array.isArray(event) ? event : [event];
expect(events[0]?.type).toBe("thread.unpinned");
if (events[0]?.type === "thread.unpinned") {
expect(events[0].payload.updatedAt).not.toBe(NOW);
}
}),
);
it.effect("unpinning an unpinned thread preserves updatedAt", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.unpin",
commandId: CommandId.make("cmd-unpin-noop"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({}),
});
const events = Array.isArray(event) ? event : [event];
expect(events[0]?.type).toBe("thread.unpinned");
if (events[0]?.type === "thread.unpinned") {
expect(events[0].payload.updatedAt).toBe(NOW);
}
}),
);
it.effect("pinning a settled thread also un-settles it", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.pin",
commandId: CommandId.make("cmd-pin-settled"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({ settledOverride: "settled" }),
});
const events = Array.isArray(event) ? event : [event];
expect(events.map((entry) => entry.type)).toEqual(["thread.pinned", "thread.unsettled"]);
const unsettled = events.find((entry) => entry.type === "thread.unsettled");
if (unsettled?.type === "thread.unsettled") {
expect(unsettled.payload.reason).toBe("user");
}
}),
);
it.effect("pinning a snoozed thread also wakes it", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.pin",
commandId: CommandId.make("cmd-pin-snoozed"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({ snoozedUntil: "1970-01-02T09:00:00.000Z" }),
});
const events = Array.isArray(event) ? event : [event];
expect(events.map((entry) => entry.type)).toEqual(["thread.pinned", "thread.unsnoozed"]);
}),
);
it.effect("pinning an unparked thread emits only thread.pinned", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.pin",
commandId: CommandId.make("cmd-pin-plain"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({}),
});
const events = Array.isArray(event) ? event : [event];
expect(events.map((entry) => entry.type)).toEqual(["thread.pinned"]);
}),
);
it.effect("settling a pinned thread also unpins it", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.settle",
commandId: CommandId.make("cmd-settle-pinned"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({ pinnedAt: PINNED_AT }),
});
const events = Array.isArray(event) ? event : [event];
expect(events.map((entry) => entry.type)).toEqual(["thread.settled", "thread.unpinned"]);
}),
);
it.effect("settling an unpinned thread emits no unpin event", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.settle",
commandId: CommandId.make("cmd-settle-unpinned"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({}),
});
const events = Array.isArray(event) ? event : [event];
expect(events.map((entry) => entry.type)).toEqual(["thread.settled"]);
}),
);
it.effect("rejects pinning an archived thread", () =>
Effect.gen(function* () {
const error = yield* decideOrchestrationCommand({
command: {
type: "thread.pin",
commandId: CommandId.make("cmd-pin-archived"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({ archivedAt: NOW }),
}).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationCommandInvariantError");
}),
);
});
+117 -2
View File
@@ -487,14 +487,14 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
// settledAt: the engine rejects zero-event commands, and bulk-settle /
// double-click must stay silent no-ops rather than surface errors.
const alreadySettled = thread.settledOverride === "settled" && thread.settledAt !== null;
return {
const settledEvent = {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.settled",
type: "thread.settled" as const,
payload: {
threadId: command.threadId,
settledAt: alreadySettled ? thread.settledAt : occurredAt,
@@ -504,6 +504,29 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
updatedAt: alreadySettled ? thread.updatedAt : occurredAt,
},
};
// Settling is "I'm done with this": it clears a pin the same way it
// parks the thread. Without this, settling a pinned thread would only
// stamp invisible state — the pin would hold the card in place until
// a separate unpin.
if (thread.pinnedAt == null) {
return settledEvent;
}
return [
settledEvent,
{
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.unpinned" as const,
payload: {
threadId: command.threadId,
updatedAt: occurredAt,
},
},
];
}
case "thread.unsettle": {
@@ -630,6 +653,98 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
case "thread.pin": {
const thread = yield* requireThreadNotArchived({
readModel,
command,
threadId: command.threadId,
});
const occurredAt = yield* nowIso;
// Re-pinning an already-pinned thread is a duplicate (double-click,
// raced clients): re-emit with the original timestamps so the
// projection is a no-op. Pinning has no lifecycle invariants — a pin
// only ever promotes visibility, so it can never hide pending work.
const existingPinnedAt = thread.pinnedAt ?? null;
const pinnedEvent = {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.pinned" as const,
payload: {
threadId: command.threadId,
pinnedAt: existingPinnedAt ?? occurredAt,
updatedAt: existingPinnedAt !== null ? thread.updatedAt : occurredAt,
},
};
// Pinning is a promotion: it clears the parked states rather than
// silently outranking them. An explicit settle un-settles (reason
// "user", same override the un-settle button stamps), and a snooze's
// return ticket is spent — the thread is on top NOW, not on Tuesday.
const promotionEvents: Array<Omit<OrchestrationEvent, "sequence">> = [];
if (thread.settledOverride === "settled") {
promotionEvents.push({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.unsettled",
payload: {
threadId: command.threadId,
reason: "user",
updatedAt: occurredAt,
},
});
}
if (thread.snoozedUntil != null) {
promotionEvents.push({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.unsnoozed",
payload: {
threadId: command.threadId,
reason: "user",
updatedAt: occurredAt,
},
});
}
return promotionEvents.length > 0 ? [pinnedEvent, ...promotionEvents] : pinnedEvent;
}
case "thread.unpin": {
const thread = yield* requireThreadNotArchived({
readModel,
command,
threadId: command.threadId,
});
// Idempotent by re-emission (see thread.settle): unpinning a thread
// that is not pinned lands on the same null state without churning
// updatedAt.
const alreadyUnpinned = thread.pinnedAt == null;
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.unpinned",
payload: {
threadId: command.threadId,
updatedAt: alreadyUnpinned ? thread.updatedAt : occurredAt,
},
};
}
case "thread.meta.update": {
const thread = yield* requireThread({
readModel,
@@ -0,0 +1,77 @@
import {
CommandId,
EventId,
ProjectId,
ThreadId,
type OrchestrationEvent,
} from "@t3tools/contracts";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { createEmptyReadModel, projectEvent } from "./projector.ts";
function makeEvent(input: {
readonly sequence: number;
readonly type: OrchestrationEvent["type"];
readonly payload: unknown;
}): OrchestrationEvent {
return {
sequence: input.sequence,
eventId: EventId.make(`event-${input.sequence}`),
type: input.type,
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
occurredAt: "2026-01-01T00:00:00.000Z",
commandId: CommandId.make(`command-${input.sequence}`),
causationEventId: null,
correlationId: null,
metadata: {},
payload: input.payload as never,
} as OrchestrationEvent;
}
it.effect("projects pin lifecycle events", () =>
Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
const created = yield* projectEvent(
createEmptyReadModel(now),
makeEvent({
sequence: 1,
type: "thread.created",
payload: {
threadId: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-1"),
title: "Thread",
modelSelection: { provider: "codex", model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
}),
);
expect(created.threads[0]?.pinnedAt ?? null).toBeNull();
const pinned = yield* projectEvent(
created,
makeEvent({
sequence: 2,
type: "thread.pinned",
payload: { threadId: ThreadId.make("thread-1"), pinnedAt: now, updatedAt: now },
}),
);
expect(pinned.threads[0]?.pinnedAt).toBe(now);
const unpinned = yield* projectEvent(
pinned,
makeEvent({
sequence: 3,
type: "thread.unpinned",
payload: { threadId: ThreadId.make("thread-1"), updatedAt: now },
}),
);
expect(unpinned.threads[0]?.pinnedAt).toBeNull();
}),
);
@@ -23,7 +23,9 @@ import {
ThreadProposedPlanUpsertedPayload,
ThreadRuntimeModeSetPayload,
ThreadSettledPayload,
ThreadPinnedPayload,
ThreadSnoozedPayload,
ThreadUnpinnedPayload,
ThreadUnarchivedPayload,
ThreadUnsettledPayload,
ThreadUnsnoozedPayload,
@@ -394,6 +396,28 @@ export function projectEvent(
})),
);
case "thread.pinned":
return decodeForEvent(ThreadPinnedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
pinnedAt: payload.pinnedAt,
updatedAt: payload.updatedAt,
}),
})),
);
case "thread.unpinned":
return decodeForEvent(ThreadUnpinnedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
pinnedAt: null,
updatedAt: payload.updatedAt,
}),
})),
);
case "thread.meta-updated":
return decodeForEvent(ThreadMetaUpdatedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
@@ -95,6 +95,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
pinnedAt: null,
latestUserMessageAt: null,
pendingApprovalCount: 0,
pendingUserInputCount: 0,
@@ -157,6 +158,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
settledAt: "2026-03-25T00:00:00.000Z",
snoozedUntil: "2026-03-26T09:00:00.000Z",
snoozedAt: "2026-03-25T00:00:00.000Z",
pinnedAt: "2026-03-25T00:00:00.000Z",
latestUserMessageAt: null,
pendingApprovalCount: 0,
pendingUserInputCount: 0,
@@ -175,6 +177,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
assert.strictEqual(row.settledAt, "2026-03-25T00:00:00.000Z");
assert.strictEqual(row.snoozedUntil, "2026-03-26T09:00:00.000Z");
assert.strictEqual(row.snoozedAt, "2026-03-25T00:00:00.000Z");
assert.strictEqual(row.pinnedAt, "2026-03-25T00:00:00.000Z");
// Un-settle to the keep-active pin and wake the snooze; confirm the
// flips persist.
@@ -184,6 +187,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
pinnedAt: null,
});
const repersisted = yield* threads.getById({
threadId: ThreadId.make("thread-settled"),
@@ -193,6 +197,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
assert.strictEqual(updated?.settledAt, null);
assert.strictEqual(updated?.snoozedUntil, null);
assert.strictEqual(updated?.snoozedAt, null);
assert.strictEqual(updated?.pinnedAt, null);
}),
);
});
@@ -47,6 +47,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
settled_at,
snoozed_until,
snoozed_at,
pinned_at,
title_regeneration_request_id,
title_regeneration_started_at,
latest_user_message_at,
@@ -72,6 +73,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
${row.settledAt},
${row.snoozedUntil},
${row.snoozedAt},
${row.pinnedAt},
${row.titleRegenerationRequestId ?? null},
${row.titleRegenerationStartedAt ?? null},
${row.latestUserMessageAt},
@@ -97,6 +99,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
settled_at = excluded.settled_at,
snoozed_until = excluded.snoozed_until,
snoozed_at = excluded.snoozed_at,
pinned_at = excluded.pinned_at,
title_regeneration_request_id = excluded.title_regeneration_request_id,
title_regeneration_started_at = excluded.title_regeneration_started_at,
latest_user_message_at = excluded.latest_user_message_at,
@@ -129,6 +132,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -163,6 +167,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
+11 -17
View File
@@ -7,7 +7,6 @@ import type { SqlError } from "effect/unstable/sql/SqlError";
import { runMigrations } from "../Migrations.ts";
import { ServerConfig } from "../../config.ts";
import * as ServiceLauncherClient from "../../cloud/serviceLauncherClient.ts";
type RuntimeSqliteLayerConfig = {
readonly filename: string;
@@ -31,28 +30,24 @@ const makeRuntimeSqliteLayer = Effect.fn("makeRuntimeSqliteLayer")(function* (
return clientModule.layer(config);
}, Layer.unwrap);
const setup = (trial: boolean) =>
Layer.effectDiscard(
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`PRAGMA foreign_keys = ON;`;
if (!trial) {
yield* sql`PRAGMA journal_mode = WAL;`;
yield* runMigrations();
}
}),
);
const setup = Layer.effectDiscard(
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`PRAGMA foreign_keys = ON;`;
yield* sql`PRAGMA journal_mode = WAL;`;
yield* runMigrations();
}),
);
export const makeSqlitePersistenceLive = Effect.fn("makeSqlitePersistenceLive")(function* (
dbPath: string,
options?: { readonly trial?: boolean },
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });
return Layer.provideMerge(
setup(options?.trial === true),
setup,
makeRuntimeSqliteLayer({
filename: dbPath,
spanAttributes: {
@@ -64,14 +59,13 @@ export const makeSqlitePersistenceLive = Effect.fn("makeSqlitePersistenceLive")(
}, Layer.unwrap);
export const SqlitePersistenceMemory = Layer.provideMerge(
setup(false),
setup,
makeRuntimeSqliteLayer({ filename: ":memory:" }),
);
export const layerConfig = Layer.unwrap(
Effect.gen(function* () {
const { dbPath } = yield* ServerConfig;
const launcher = yield* ServiceLauncherClient.resolveServiceLauncherMode();
return makeSqlitePersistenceLive(dbPath, { trial: launcher.trial });
return makeSqlitePersistenceLive(dbPath);
}),
);
@@ -48,6 +48,7 @@ import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts";
import Migration0033 from "./Migrations/033_ProjectionThreadsSettled.ts";
import Migration0034 from "./Migrations/034_ProjectionThreadsSnoozed.ts";
import Migration0035 from "./Migrations/035_ProjectionThreadTitleRegeneration.ts";
import Migration0036 from "./Migrations/036_ProjectionThreadsPinned.ts";
/**
* Migration loader with all migrations defined inline.
@@ -95,6 +96,7 @@ export const migrationEntries = [
[33, "ProjectionThreadsSettled", Migration0033],
[34, "ProjectionThreadsSnoozed", Migration0034],
[35, "ProjectionThreadTitleRegeneration", Migration0035],
[36, "ProjectionThreadsPinned", Migration0036],
] as const;
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
@@ -0,0 +1,16 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const columns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_threads)
`;
if (!columns.some((column) => column.name === "pinned_at")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN pinned_at TEXT
`;
}
});
@@ -41,6 +41,7 @@ export const ProjectionThread = Schema.Struct({
settledAt: Schema.NullOr(IsoDateTime),
snoozedUntil: Schema.NullOr(IsoDateTime),
snoozedAt: Schema.NullOr(IsoDateTime),
pinnedAt: Schema.NullOr(IsoDateTime),
titleRegenerationRequestId: Schema.optional(Schema.NullOr(CommandId)),
titleRegenerationStartedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
latestUserMessageAt: Schema.NullOr(IsoDateTime),
@@ -90,8 +90,8 @@ import {
} from "../Errors.ts";
import { type ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.UnknownFromJsonString);
const decodeUnknownJsonStringExit = Schema.decodeUnknownExit(Schema.UnknownFromJsonString);
const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.fromJsonString(Schema.Unknown));
const decodeUnknownJsonStringExit = Schema.decodeUnknownExit(Schema.fromJsonString(Schema.Unknown));
const PROVIDER = ProviderDriverKind.make("claudeAgent");
type ClaudeTextStreamKind = Extract<RuntimeContentStreamKind, "assistant_text" | "reasoning_text">;
@@ -77,7 +77,7 @@ import {
import { type CursorAdapterShape } from "../Services/CursorAdapter.ts";
import { resolveCursorAcpBaseModelId } from "./CursorProvider.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.UnknownFromJsonString);
const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.fromJsonString(Schema.Unknown));
const PROVIDER = ProviderDriverKind.make("cursor");
const CURSOR_RESUME_VERSION = 1 as const;
@@ -20,7 +20,7 @@ import {
writeBatchedMessages,
} from "./EventNdjsonLogger.ts";
const encodeUnknownJson = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
const encodeUnknownJson = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
function ownedLogPath(basePath: string, segment: string): string {
const basename = NodePath.basename(basePath);
@@ -34,7 +34,7 @@ const DEFAULT_MAX_BUFFERED_BYTES = MEBIBYTE;
const DEFAULT_MAX_BUFFERED_RECORDS = 512;
const GLOBAL_THREAD_SEGMENT = "_global";
const LOG_SCOPE = "provider-observability";
const encodeUnknownJsonString = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
const encodeUnknownJsonString = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
const transientCanonicalEventTypes = new Set([
"content.delta",
@@ -69,7 +69,7 @@ import {
import { type GrokAdapterShape } from "../Services/GrokAdapter.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.UnknownFromJsonString);
const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.fromJsonString(Schema.Unknown));
const PROVIDER = ProviderDriverKind.make("grok");
const GROK_RESUME_VERSION = 1 as const;
@@ -12,7 +12,7 @@ import type { EventNdjsonLogger } from "../Layers/EventNdjsonLogger.ts";
import { makeAcpNativeLoggerFactory } from "./AcpNativeLogging.ts";
const nodeServicesIt = it.layer(NodeServices.layer);
const encodeUnknownJson = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
const encodeUnknownJson = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
nodeServicesIt("ACP native logging", (it) => {
it.effect("records bounded request and protocol diagnostics without raw payloads", () =>
@@ -107,6 +107,25 @@ describe("CursorAcpExtension", () => {
});
});
it("falls back to the title when content is present but blank", () => {
expect(
extractTodosAsPlan({
toolCallId: "todos-2",
todos: [
{ id: "1", content: "", title: "Titled step", status: "pending" },
{ id: "2", content: " ", title: "Whitespace content", status: "in_progress" },
{ id: "3", content: "", title: "", status: "pending" },
],
merge: true,
}),
).toEqual({
plan: [
{ step: "Titled step", status: "pending" },
{ step: "Whitespace content", status: "inProgress" },
],
});
});
it("decodes Cursor list_available_models responses with per-model config options", () => {
const decoded = CursorListAvailableModelsResponse.make({
models: [
@@ -94,7 +94,10 @@ export function extractTodosAsPlan(params: typeof CursorUpdateTodosRequest.Type)
}>;
} {
const plan = params.todos.flatMap((todo) => {
const step = todo.content?.trim() ?? todo.title?.trim() ?? "";
// Fall back to the title when content is missing OR blank. `??` only
// covers a missing content, so a present-but-empty content ("" or
// whitespace) would shadow a real title and drop the step below.
const step = todo.content?.trim() || todo.title?.trim() || "";
if (step === "") {
return [];
}
+1 -1
View File
@@ -34,7 +34,7 @@ import { collectStreamAsString } from "./providerSnapshot.ts";
import * as NetService from "@t3tools/shared/Net";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.UnknownFromJsonString);
const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.fromJsonString(Schema.Unknown));
const OPENCODE_EMPTY_CONFIG_CONTENT = "{}";
const OPENCODE_SERVER_READY_PREFIX = "opencode server listening";
@@ -57,6 +57,39 @@ describe("ReviewService", () => {
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("attributes file-content workspace violations to the file-content operation", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" });
const outsideRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-outside-" });
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" });
const detectCalls: Array<{ readonly cwd: string }> = [];
const error = yield* Effect.gen(function* () {
const review = yield* ReviewService.ReviewService;
return yield* review
.getDiffFileContents({
cwd: outsideRoot,
sourceKind: "working-tree",
changeType: "change",
baseRef: "HEAD",
headRef: null,
oldPath: "file.ts",
newPath: "file.ts",
})
.pipe(Effect.flip);
}).pipe(Effect.provide(makeLayer({ workspaceRoot, baseDir, detectCalls })));
assert.strictEqual(error._tag, "VcsRepositoryDetectionError");
assert.strictEqual(error.operation, "ReviewService.getDiffFileContents");
assert.match(
"detail" in error ? error.detail : "",
/must stay within the configured workspace root/,
);
assert.deepStrictEqual(detectCalls, []);
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("allows diff preview cwd inside the configured workspace root", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
+30 -3
View File
@@ -8,6 +8,8 @@ import * as Path from "effect/Path";
import {
VcsRepositoryDetectionError,
VcsUnsupportedOperationError,
type ReviewDiffFileContentsInput,
type ReviewDiffFileContentsResult,
type ReviewDiffPreviewError,
type ReviewDiffPreviewInput,
type ReviewDiffPreviewResult,
@@ -23,6 +25,9 @@ export class ReviewService extends Context.Service<
readonly getDiffPreview: (
input: ReviewDiffPreviewInput,
) => Effect.Effect<ReviewDiffPreviewResult, ReviewDiffPreviewError>;
readonly getDiffFileContents: (
input: ReviewDiffFileContentsInput,
) => Effect.Effect<ReviewDiffFileContentsResult, ReviewDiffPreviewError>;
}
>()("t3/review/ReviewService") {}
@@ -58,6 +63,7 @@ export const make = Effect.gen(function* () {
};
const assertWorkspaceBoundCwd = Effect.fn("ReviewService.assertWorkspaceBoundCwd")(function* (
operation: "ReviewService.getDiffPreview" | "ReviewService.getDiffFileContents",
cwd: string,
) {
const [candidate, workspaceRoot, worktreesRoot] = yield* Effect.all([
@@ -71,16 +77,19 @@ export const make = Effect.gen(function* () {
}
return yield* new VcsRepositoryDetectionError({
operation: "ReviewService.getDiffPreview",
operation,
cwd,
detail: "Review diff preview cwd must stay within the configured workspace root.",
detail:
operation === "ReviewService.getDiffPreview"
? "Review diff preview cwd must stay within the configured workspace root."
: "Review diff file contents cwd must stay within the configured workspace root.",
});
});
const getDiffPreview: ReviewService["Service"]["getDiffPreview"] = Effect.fn(
"ReviewService.getDiffPreview",
)(function* (input) {
yield* assertWorkspaceBoundCwd(input.cwd);
yield* assertWorkspaceBoundCwd("ReviewService.getDiffPreview", input.cwd);
const handle = yield* vcsRegistry.detect({ cwd: input.cwd, requestedKind: "auto" });
if (!handle) {
@@ -106,8 +115,26 @@ export const make = Effect.gen(function* () {
return yield* getDriverDiffPreview(input);
});
const getDiffFileContents: ReviewService["Service"]["getDiffFileContents"] = Effect.fn(
"ReviewService.getDiffFileContents",
)(function* (input) {
yield* assertWorkspaceBoundCwd("ReviewService.getDiffFileContents", input.cwd);
const handle = yield* vcsRegistry.detect({ cwd: input.cwd, requestedKind: "auto" });
if (handle?.kind !== "git") {
return yield* new VcsUnsupportedOperationError({
operation: "ReviewService.getDiffFileContents",
kind: handle?.kind ?? "unknown",
detail: "Unchanged diff expansion currently requires a Git repository.",
});
}
return yield* git.getReviewDiffFileContents(input);
});
return ReviewService.of({
getDiffPreview,
getDiffFileContents,
});
});
+44 -3
View File
@@ -73,7 +73,6 @@ const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
import * as ServerConfig from "./config.ts";
import * as HttpResponseCompression from "./httpCompression/HttpResponseCompression.ts";
import { makeRoutesLayer } from "./server.ts";
import { resolveAvailableEditorsForConfig } from "./ws.ts";
import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";
@@ -892,7 +891,6 @@ const buildAppUnderTest = (options?: {
Layer.provideMerge(ServerSecretStore.layer),
Layer.provide(workspaceAndProjectServicesLayer),
Layer.provideMerge(FetchHttpClient.layer),
Layer.provide(HttpResponseCompression.layerNode),
Layer.provide(layerConfig),
);
@@ -3221,6 +3219,28 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
// Mirrors NodeHttpServer.layerTest, which does not expose server options,
// with the production `websocket: { perMessageDeflate: true }` setting.
const NodeHttpServerTestWithWsDeflate = HttpServer.layerTestClient.pipe(
Layer.provide(
Layer.fresh(FetchHttpClient.layer).pipe(
Layer.provide(Layer.succeed(FetchHttpClient.RequestInit)({ keepalive: false })),
),
),
Layer.provideMerge(
Layer.unwrap(
Effect.map(
Effect.promise(() => import("node:http")),
(NodeHttp) =>
NodeHttpServer.layer(NodeHttp.createServer, {
port: 0,
websocket: { perMessageDeflate: true },
}),
),
),
),
);
it.effect("negotiates permessage-deflate with clients that offer it", () =>
Effect.gen(function* () {
yield* buildAppUnderTest();
@@ -3246,7 +3266,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
const plain = yield* openSocket(false);
assert.notInclude(plain.extensions, "permessage-deflate");
}).pipe(Effect.scoped, Effect.provide(NodeHttpServer.layerTest)),
}).pipe(Effect.scoped, Effect.provide(NodeHttpServerTestWithWsDeflate)),
);
it.effect("issues short-lived websocket tickets for authenticated bearer sessions", () =>
@@ -5229,6 +5249,11 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
},
],
}),
getDiffFileContents: () =>
Effect.succeed({
oldContents: "before\n",
newContents: "after\n",
}),
},
},
});
@@ -5343,6 +5368,22 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
),
);
assert.equal(diffPreview.sources[0]?.diff, "dirty-diff");
const diffFileContents = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[WS_METHODS.reviewGetDiffFileContents]({
cwd: "/tmp/repo",
sourceKind: "working-tree",
changeType: "change",
baseRef: "HEAD",
headRef: null,
oldPath: "README.md",
newPath: "README.md",
}),
),
);
assert.equal(diffFileContents.oldContents, "before\n");
assert.equal(diffFileContents.newContents, "after\n");
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
+21 -5
View File
@@ -10,7 +10,6 @@ import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
import * as HostPowerMonitor from "./background/HostPowerMonitor.ts";
import * as ServerConfig from "./config.ts";
import * as HttpResponseCompression from "./httpCompression/HttpResponseCompression.ts";
import {
otlpTracesProxyRouteLayer,
assetRouteLayer,
@@ -182,6 +181,20 @@ const HttpServerLive = Layer.unwrap(
port: config.port,
hostname: config.host ?? "127.0.0.1",
gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
websocket: {
// Negotiate permessage-deflate with clients that offer it; clients
// that don't still get uncompressed frames on their connection. A
// dedicated compressor keeps a per-connection sliding window
// (context takeover) so the compression dictionary is shared across
// server-to-client frames. Decompression uses the shared
// decompressor: uWebSockets' dedicated decompressor path can abort
// connections (close 1006) on valid DEFLATE input — see
// https://github.com/uNetworking/uWebSockets.js/issues/633.
perMessageDeflate: {
compress: "dedicated",
decompress: "shared",
},
},
});
} else {
const [NodeHttpServer, NodeHttp] = yield* Effect.all([
@@ -192,14 +205,18 @@ const HttpServerLive = Layer.unwrap(
host: config.host ?? "127.0.0.1",
port: config.port,
gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
// Negotiate permessage-deflate with clients that offer it; clients
// that don't still get uncompressed frames on their connection.
// Context takeover stays enabled (ws default) so the compression
// window is shared across frames — that also makes small frames cheap
// to compress, so no size threshold is set (ws only honors
// `threshold` when context takeover is disabled).
websocket: { perMessageDeflate: true },
});
}
}),
);
const HttpResponseCompressionLive =
typeof Bun !== "undefined" ? HttpResponseCompression.layerBun : HttpResponseCompression.layerNode;
const PlatformServicesLive = Layer.unwrap(
Effect.gen(function* () {
if (typeof Bun !== "undefined") {
@@ -622,7 +639,6 @@ export const makeServerLayer = Layer.unwrap(
Layer.provideMerge(runtimeServicesLive),
Layer.provide(activationLayer),
Layer.provideMerge(serverRelayBrokerTracingLayer),
Layer.provideMerge(HttpResponseCompressionLive),
Layer.provideMerge(HttpServerLive),
Layer.provide(ApplicationObservabilityLive),
Layer.provideMerge(FetchHttpClient.layer),
+95 -8
View File
@@ -9,6 +9,7 @@ import {
compareExactServiceVersions,
decodeServiceState,
isExactServiceVersion,
SERVICE_LAUNCHER_PROTOCOL,
} from "./cloud/serviceProtocol.ts";
it("accepts only exact semantic versions", () => {
@@ -33,12 +34,13 @@ it("orders exact semantic versions without treating build metadata as precedence
it("rejects contradictory service state", () => {
assert.isUndefined(
decodeServiceState({
protocol: 1,
protocol: SERVICE_LAUNCHER_PROTOCOL,
activeVersion: "0.0.31",
update: {
id: "update-1",
fromVersion: "0.0.30",
targetVersion: "0.0.32",
dbPath: "/tmp/state.sqlite",
status: "pending",
},
}),
@@ -46,12 +48,26 @@ it("rejects contradictory service state", () => {
assert.isUndefined(
decodeServiceState({
protocol: 1,
protocol: SERVICE_LAUNCHER_PROTOCOL,
activeVersion: "1.0.0",
update: {
id: "update-3",
fromVersion: "1.0.0",
targetVersion: "1.1.0",
status: "pending",
},
}),
);
assert.isUndefined(
decodeServiceState({
protocol: SERVICE_LAUNCHER_PROTOCOL,
activeVersion: "1.0.0",
update: {
id: "update-2",
fromVersion: "1.0.0",
targetVersion: "0.9.0",
dbPath: "/tmp/state.sqlite",
status: "pending",
},
}),
@@ -66,7 +82,7 @@ it.layer(NodeServices.layer)("service state persistence", (it) => {
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-test-" });
const statePath = path.join(root, "runtime", "service-state.json");
const state = {
protocol: 1,
protocol: SERVICE_LAUNCHER_PROTOCOL,
activeVersion: "0.0.31",
} as const;
@@ -88,7 +104,7 @@ it.layer(NodeServices.layer)("service state persistence", (it) => {
yield* fs.writeFileString(path.join(versionDir, ".install-complete"), "1.0.0\n");
yield* Effect.promise(() =>
writeServiceState(statePath, {
protocol: 1,
protocol: SERVICE_LAUNCHER_PROTOCOL,
activeVersion: "1.0.0",
}),
);
@@ -106,6 +122,11 @@ it.layer(NodeServices.layer)("service state persistence", (it) => {
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-flow-" });
const statePath = path.join(root, "runtime", "service-state.json");
const databasePath = path.join(root, "userdata", "state.sqlite");
yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
yield* fs.writeFileString(databasePath, "before trial");
// @effect-diagnostics-next-line preferSchemaOverJson:off - embeds a path in fake child source.
const encodedDatabasePath = JSON.stringify(databasePath);
const childSource = `
const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
if (context.update?.status === "pending") {
@@ -114,7 +135,7 @@ if (context.update?.status === "pending") {
if (message.type === "committed") process.exit(0);
});
} else if (context.update === undefined) {
process.send({ type: "request-update", targetVersion: "1.1.0" });
process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
setInterval(() => {}, 1_000);
} else {
process.exit(0);
@@ -129,7 +150,7 @@ if (context.update?.status === "pending") {
}
yield* Effect.promise(() =>
writeServiceState(statePath, {
protocol: 1,
protocol: SERVICE_LAUNCHER_PROTOCOL,
activeVersion: "1.0.0",
}),
);
@@ -154,12 +175,17 @@ if (context.update?.status === "pending") {
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-rollback-" });
const statePath = path.join(root, "runtime", "service-state.json");
const databasePath = path.join(root, "userdata", "state.sqlite");
yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
yield* fs.writeFileString(databasePath, "before trial");
// @effect-diagnostics-next-line preferSchemaOverJson:off - embeds a path in fake child source.
const encodedDatabasePath = JSON.stringify(databasePath);
const childSource = `
const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
if (context.update?.status === "pending") {
process.send({ type: "prepared", updateId: "wrong-update" });
} else if (context.update === undefined) {
process.send({ type: "request-update", targetVersion: "1.1.0" });
process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
setInterval(() => {}, 1_000);
} else {
process.exit(0);
@@ -174,7 +200,7 @@ if (context.update?.status === "pending") {
}
yield* Effect.promise(() =>
writeServiceState(statePath, {
protocol: 1,
protocol: SERVICE_LAUNCHER_PROTOCOL,
activeVersion: "1.0.0",
}),
);
@@ -196,4 +222,65 @@ if (context.update?.status === "pending") {
);
}),
);
it.effect("restores the database when a migrating trial exits", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-db-" });
const statePath = path.join(root, "runtime", "service-state.json");
const databasePath = path.join(root, "userdata", "state.sqlite");
const original = "database before migration";
yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
yield* fs.writeFileString(databasePath, original);
// @effect-diagnostics-next-line preferSchemaOverJson:off - embeds a path in fake child source.
const encodedDatabasePath = JSON.stringify(databasePath);
const childSource = `
import { writeFileSync } from "node:fs";
const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
if (context.update?.status === "pending") {
writeFileSync(context.update.dbPath, "database after migration");
writeFileSync(context.update.dbPath + "-wal", "trial wal");
writeFileSync(context.update.dbPath + "-shm", "trial shm");
process.exit(1);
} else if (context.update === undefined) {
process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
setInterval(() => {}, 1_000);
} else {
process.exit(0);
}
`;
for (const version of ["1.0.0", "1.1.0"]) {
const versionDir = path.join(root, "runtime", "versions", version);
const entryPath = path.join(versionDir, "node_modules", "t3", "dist", "bin.mjs");
yield* fs.makeDirectory(path.dirname(entryPath), { recursive: true });
yield* fs.writeFileString(entryPath, childSource);
yield* fs.writeFileString(path.join(versionDir, ".install-complete"), `${version}\n`);
}
yield* Effect.promise(() =>
writeServiceState(statePath, {
protocol: SERVICE_LAUNCHER_PROTOCOL,
activeVersion: "1.0.0",
}),
);
const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
yield* Effect.promise(() =>
launcher.run().then(
() => Promise.reject(new Error("launcher unexpectedly completed")),
() => Promise.resolve(),
),
);
const state = yield* Effect.promise(() => readServiceState(statePath));
assert.equal(state.activeVersion, "1.0.0");
assert.equal(state.update?.status, "rolled-back");
assert.equal(yield* fs.readFileString(databasePath), original);
assert.isFalse(yield* fs.exists(`${databasePath}-wal`));
assert.isFalse(yield* fs.exists(`${databasePath}-shm`));
const updateId = state.update?.id;
assert.isDefined(updateId);
assert.isFalse(yield* fs.exists(path.join(root, "runtime", "db-backup", updateId)));
}),
);
});
+141 -4
View File
@@ -48,6 +48,121 @@ const runtimePaths = (baseDir: string, version: string) => {
};
};
/** SQLite persists across the main file plus its WAL and shared-memory sidecars. */
const DB_FILE_SUFFIXES = ["", "-wal", "-shm"] as const;
const RESTORE_MARKER = ".restore-pending";
const databaseBackupDir = (baseDir: string, updateId: string) =>
NodePath.join(baseDir, "runtime", "db-backup", updateId);
const databaseBackupFile = (backupDir: string, suffix: (typeof DB_FILE_SUFFIXES)[number]) =>
NodePath.join(backupDir, suffix === "" ? "database" : `database${suffix}`);
async function pathExists(target: string): Promise<boolean> {
try {
await NodeFSP.access(target);
return true;
} catch (cause) {
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") return false;
throw cause;
}
}
async function syncFile(filePath: string): Promise<void> {
const handle = await NodeFSP.open(filePath, "r");
try {
await handle.sync();
} finally {
await handle.close();
}
}
async function syncDirectory(directory: string): Promise<void> {
const handle = await NodeFSP.open(directory, "r");
try {
await handle.sync();
} finally {
await handle.close();
}
}
/**
* Snapshots the database once per update before the first trial. A completed
* backup is never overwritten because a restarted launcher may be looking at
* database writes from an earlier attempt by the same trial.
*/
async function backupDatabaseOnce(baseDir: string, pending: PendingServiceUpdate): Promise<void> {
const backupDir = databaseBackupDir(baseDir, pending.id);
if (await pathExists(backupDir)) return;
const stagingDir = `${backupDir}.staging`;
await NodeFSP.rm(stagingDir, { recursive: true, force: true });
await NodeFSP.mkdir(stagingDir, { recursive: true, mode: 0o700 });
try {
for (const suffix of DB_FILE_SUFFIXES) {
const source = `${pending.dbPath}${suffix}`;
if (suffix !== "" && !(await pathExists(source))) continue;
const destination = databaseBackupFile(stagingDir, suffix);
await NodeFSP.copyFile(source, destination);
await syncFile(destination);
}
await NodeFSP.rename(stagingDir, backupDir);
await syncDirectory(NodePath.dirname(backupDir));
} catch (cause) {
await NodeFSP.rm(stagingDir, { recursive: true, force: true }).catch(() => undefined);
throw cause;
}
}
const restoreMarkerPath = (baseDir: string, updateId: string) =>
NodePath.join(databaseBackupDir(baseDir, updateId), RESTORE_MARKER);
const databaseRestorePending = (baseDir: string, pending: PendingServiceUpdate) =>
pathExists(restoreMarkerPath(baseDir, pending.id));
/** Mark rollback before changing live files so launcher recovery cannot boot a partial restore. */
async function markDatabaseRestorePending(backupDir: string): Promise<void> {
const markerPath = NodePath.join(backupDir, RESTORE_MARKER);
if (!(await pathExists(markerPath))) {
const handle = await NodeFSP.open(markerPath, "wx", 0o600);
try {
await handle.sync();
} finally {
await handle.close();
}
await syncDirectory(backupDir);
}
}
/** Restore is retryable after any process crash while the backup directory remains. */
async function restoreDatabaseBackup(
baseDir: string,
pending: PendingServiceUpdate,
): Promise<void> {
const backupDir = databaseBackupDir(baseDir, pending.id);
if (!(await pathExists(backupDir))) return;
await markDatabaseRestorePending(backupDir);
for (const suffix of DB_FILE_SUFFIXES) {
const target = `${pending.dbPath}${suffix}`;
const source = databaseBackupFile(backupDir, suffix);
if (await pathExists(source)) {
await NodeFSP.copyFile(source, target);
await syncFile(target);
} else {
await NodeFSP.rm(target, { force: true });
}
}
await syncDirectory(NodePath.dirname(pending.dbPath));
}
async function discardDatabaseBackup(baseDir: string, updateId: string): Promise<void> {
const backupDir = databaseBackupDir(baseDir, updateId);
if (!(await pathExists(backupDir))) return;
await NodeFSP.rm(backupDir, { recursive: true, force: true });
await syncDirectory(NodePath.dirname(backupDir));
}
export async function readServiceState(filePath: string): Promise<ServiceState> {
const contents = await NodeFSP.readFile(filePath, "utf8");
const state = parseServiceState(contents);
@@ -217,9 +332,16 @@ export class Launcher {
async #recover(): Promise<void> {
const update = this.#state.update;
if (update?.status !== "pending") {
if (update !== undefined) {
await discardDatabaseBackup(this.#baseDir, update.id).catch(() => undefined);
}
await this.#startChild(this.#state.activeVersion, "active", update);
return;
}
if (await databaseRestorePending(this.#baseDir, update)) {
await this.#returnToPrevious(update, "failed", "rollback-interrupted");
return;
}
if (!(await runtimeExists(this.#baseDir, update.targetVersion))) {
await this.#returnToPrevious(update, "failed", "target-runtime-missing");
return;
@@ -228,6 +350,13 @@ export class Launcher {
}
async #startTrial(pending: PendingServiceUpdate): Promise<void> {
// The previous child is dead here, so all three SQLite files are quiescent.
try {
await backupDatabaseOnce(this.#baseDir, pending);
} catch {
await this.#returnToPrevious(pending, "failed", "db-backup-failed");
return;
}
try {
await this.#startChild(pending.targetVersion, "trial", pending);
} catch {
@@ -322,6 +451,10 @@ export class Launcher {
await reject("Remote updates must select a newer server version.");
return;
}
if (!NodePath.isAbsolute(message.dbPath)) {
await reject("The requested database path is not absolute.");
return;
}
if (!(await runtimeExists(this.#baseDir, message.targetVersion))) {
await reject("The requested target runtime is missing or incomplete.");
return;
@@ -331,6 +464,7 @@ export class Launcher {
id: NodeCrypto.randomUUID(),
fromVersion: child.version,
targetVersion: message.targetVersion,
dbPath: message.dbPath,
status: "pending",
};
const next: ServiceState = { ...this.#state, update: pending };
@@ -375,6 +509,7 @@ export class Launcher {
await writeServiceState(this.#statePath, next);
this.#state = next;
child.role = "active";
await discardDatabaseBackup(this.#baseDir, committed.id).catch(() => undefined);
await sendMessage(child.process, { type: "committed", updateId: committed.id });
}
@@ -423,6 +558,11 @@ export class Launcher {
reason: string,
child?: ManagedChild,
): Promise<void> {
if (child !== undefined) {
this.#child = null;
await terminateChild(child.process);
}
await restoreDatabaseBackup(this.#baseDir, pending);
const outcome = terminalUpdate({ pending, status, reason });
const next: ServiceState = {
...this.#state,
@@ -431,10 +571,7 @@ export class Launcher {
};
await writeServiceState(this.#statePath, next);
this.#state = next;
if (child !== undefined) {
this.#child = null;
await terminateChild(child.process);
}
await discardDatabaseBackup(this.#baseDir, pending.id).catch(() => undefined);
await this.#startChild(next.activeVersion, "active", outcome);
}
}
+62
View File
@@ -991,6 +991,61 @@ it.layer(
}),
);
it.effect("strips replayable CSI and DCS traffic while preserving setters", () =>
Effect.gen(function* () {
const { manager, ptyAdapter } = yield* createManager();
yield* manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitData("prompt ");
// DECRQM/DECRPM, XTVERSION, and kitty-keyboard CSI query/reply traffic.
process.emitData("\u001b[?2026$p\u001b[?2026;2$y\u001b[>q\u001b[?u\u001b[?31u");
// DECRQSS and XTGETTCAP query/reply traffic in 7-bit DCS form.
process.emitData("\u001bP$q m\u001b\\\u001bP1$r0m\u001b\\");
process.emitData("\u001bP+q544e\u001b\\\u001bP1+r544e=1b\u001b\\");
// The same DCS traffic in 8-bit form.
process.emitData("\u0090$q m\u009c\u00901$r0m\u009c");
process.emitData("\u0090+q544e\u009c\u00901+r544e=1b\u009c");
// Setters and cursor movement share final bytes with query families but
// have visible terminal-state value and must survive replay.
process.emitData('\u001b[!p\u001b["p\u001b[4 q\u001b[u');
process.emitData("done\n");
yield* manager.close({ threadId: "thread-1" });
const reopened = yield* manager.open(openInput());
assert.equal(reopened.history, 'prompt \u001b[!p\u001b["p\u001b[4 q\u001b[udone\n');
}),
);
it.effect("handles CSI and DCS query sequences split across output chunks", () =>
Effect.gen(function* () {
const { manager, ptyAdapter } = yield* createManager();
yield* manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitData("before ");
process.emitData("\u001b[?2026$");
process.emitData("pafter ");
process.emitData("\u001bP$q ");
process.emitData("m\u001b");
process.emitData("\\after ");
process.emitData("\u009b?3");
process.emitData("1uafter ");
process.emitData("\u0090+q544e");
process.emitData("\u009cafter\n");
yield* manager.close({ threadId: "thread-1" });
const reopened = yield* manager.open(openInput());
assert.equal(reopened.history, "before after after after after\n");
}),
);
it.effect(
"preserves clear and style control sequences while dropping chunk-split query traffic",
() =>
@@ -1345,6 +1400,8 @@ it.layer(
OWD: "/home/user/project",
PATH: `${appDir}/usr/bin:${appDir}:/usr/local/bin:/usr/bin:/bin`,
LD_LIBRARY_PATH: `${appDir}/usr/lib:/home/user/.local/lib`,
XDG_DATA_DIRS: `${appDir}/usr/share:/usr/local/share:/usr/share`,
GSETTINGS_SCHEMA_DIR: `${appDir}/usr/share/glib-2.0/schemas`,
TEST_TERMINAL_KEEP: "keep-me",
},
});
@@ -1364,6 +1421,11 @@ it.layer(
// mount segments that the runtime prepended.
expect(spawnInput.env.PATH).toBe("/usr/local/bin:/usr/bin:/bin");
expect(spawnInput.env.LD_LIBRARY_PATH).toBe("/home/user/.local/lib");
// XDG_DATA_DIRS keeps the host entries but drops the AppImage share dir.
expect(spawnInput.env.XDG_DATA_DIRS).toBe("/usr/local/share:/usr/share");
// GSETTINGS_SCHEMA_DIR pointed only at the mount, so it is removed and
// gsettings falls back to the host schema location.
expect(spawnInput.env.GSETTINGS_SCHEMA_DIR).toBeUndefined();
// Unrelated host vars still pass through untouched.
expect(spawnInput.env.TEST_TERMINAL_KEEP).toBe("keep-me");
}),
+43 -6
View File
@@ -878,9 +878,31 @@ function shouldStripCsiSequence(body: string, finalByte: string): boolean {
if (finalByte === "c" && /^[>0-9;?]*$/.test(body)) {
return true;
}
// DECRQM mode queries (…$p) and DECRPM replies (…$y): replaying a stored
// query makes the terminal answer again, and the shell echoes the answer as
// junk at the prompt. The `$` guard keeps setters like DECSTR (!p) and
// DECSCL ("p) intact.
if ((finalByte === "p" || finalByte === "y") && /^[0-9;?]*\$$/.test(body)) {
return true;
}
// XTVERSION query (>q). DECSCUSR (space-intermediate q) stays.
if (finalByte === "q" && /^>[0-9;]*$/.test(body)) {
return true;
}
// Kitty keyboard protocol query/reply (?u). Restore-cursor (bare u) stays.
if (finalByte === "u" && body.startsWith("?")) {
return true;
}
return false;
}
// DECRQSS ($q) and XTGETTCAP (+q) queries plus their replies ([01]$r / [01]+r):
// pure request/response traffic with no visual value, and replaying a stored
// query triggers a fresh reply.
function shouldStripDcsSequence(content: string): boolean {
return /^[01]?[$+][qr]/.test(content);
}
function shouldStripOscSequence(content: string): boolean {
return /^(10|11|12);(?:\?|rgb:)/.test(content);
}
@@ -981,7 +1003,10 @@ function sanitizeTerminalHistoryChunk(
}
const sequence = input.slice(index, terminatorIndex);
const content = stripStringTerminator(input.slice(index + 2, terminatorIndex));
if (nextCodePoint !== 0x5d || !shouldStripOscSequence(content)) {
const strip =
(nextCodePoint === 0x5d && shouldStripOscSequence(content)) ||
(nextCodePoint === 0x50 && shouldStripDcsSequence(content));
if (!strip) {
append(sequence);
}
index = terminatorIndex;
@@ -1024,7 +1049,10 @@ function sanitizeTerminalHistoryChunk(
}
const sequence = input.slice(index, terminatorIndex);
const content = stripStringTerminator(input.slice(index + 1, terminatorIndex));
if (codePoint !== 0x9d || !shouldStripOscSequence(content)) {
const strip =
(codePoint === 0x9d && shouldStripOscSequence(content)) ||
(codePoint === 0x90 && shouldStripDcsSequence(content));
if (!strip) {
append(sequence);
}
index = terminatorIndex;
@@ -1069,10 +1097,19 @@ function shouldExcludeTerminalEnvKey(key: string): boolean {
// They describe the AppImage itself, not the user's session, so terminals must
// not inherit them.
const APPIMAGE_RUNTIME_ENV_KEYS = ["APPIMAGE", "APPDIR", "ARGV0", "OWD"] as const;
// PATH-style variables the AppImage runtime prepends with its temporary mount
// (e.g. /tmp/.mount_T3-XXXX/usr/bin). Only the mount segments are dropped; the
// user's real entries are preserved.
const APPIMAGE_PATH_LIKE_ENV_KEYS = ["PATH", "LD_LIBRARY_PATH"] as const;
// Colon-separated search-path variables the AppImage runtime points at its
// temporary mount (e.g. /tmp/.mount_T3-XXXX/usr/bin, the bundled glib schemas,
// and an $APPDIR/usr/share XDG data entry). Only the mount segments are
// dropped; the user's real entries are preserved. When nothing but mount
// segments remain the variable is removed entirely so consumers fall back to
// their platform default (e.g. gsettings finds the host schemas instead of
// reporting "No schemas installed"). See issues #1699 and #5059.
const APPIMAGE_PATH_LIKE_ENV_KEYS = [
"PATH",
"LD_LIBRARY_PATH",
"XDG_DATA_DIRS",
"GSETTINGS_SCHEMA_DIR",
] as const;
function isPathSegmentUnderAppDir(segment: string, appDir: string): boolean {
return segment === appDir || segment.startsWith(`${appDir}/`);
@@ -264,7 +264,7 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGeneration", (it) => {
' "Reconnect failures after restart because the session state does not recover" ',
},
}),
stdinMustContain: "You write concise thread titles for coding conversations.",
stdinMustContain: "Please investigate reconnect failures after restarting the session.",
},
(textGeneration) =>
Effect.gen(function* () {
Loaded 100 of 212 files, more files were not shown because too many files have changed in this diff. Show more