Compare commits
27
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
21ef91a087 | ||
|
|
28966761e1 | ||
|
|
d58dba29c7 | ||
|
|
f2fd69d8d7 | ||
|
|
33ce2d2869 | ||
|
|
9f812dd83d | ||
|
|
34e6f78fe7 | ||
|
|
d2cb3d016f | ||
|
|
e71933771d | ||
|
|
4e4cb07265 | ||
|
|
41ebf22eea | ||
|
|
3d429662c9 | ||
|
|
7b38fb5c6b | ||
|
|
7537adc30f | ||
|
|
94696b0f54 | ||
|
|
fff6a5b028 | ||
|
|
da6e1a9678 | ||
|
|
8eca20005b | ||
|
|
2fa1fec8d8 | ||
|
|
9bd2a4c688 | ||
|
|
4fb03aff0b | ||
|
|
d7950ac153 | ||
|
|
36caf34c68 | ||
|
|
90e3778660 | ||
|
|
94331c58ec | ||
|
|
c30a6d9b99 | ||
|
|
37ae1abbe9 |
No files matched your search
@@ -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>()(
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -11,6 +11,7 @@ import type {
|
||||
DesktopPreviewPointerEvent,
|
||||
PreviewAnnotationPayload,
|
||||
PreviewAnnotationRect,
|
||||
PreviewAnnotationSubmissionResult,
|
||||
DesktopPreviewRecordingArtifact,
|
||||
DesktopPreviewRecordingFrame,
|
||||
DesktopPreviewScreenshotArtifact,
|
||||
@@ -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,
|
||||
|
||||
@@ -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 });
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
@@ -549,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;
|
||||
@@ -630,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();
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -50,6 +50,8 @@ import {
|
||||
IconMinus,
|
||||
IconNetwork,
|
||||
IconPalette,
|
||||
IconPin,
|
||||
IconPinnedOff,
|
||||
IconPlayerPlay,
|
||||
IconPlayerStopFilled,
|
||||
IconPlus,
|
||||
@@ -121,6 +123,8 @@ const ANDROID_ICON_BY_SF_SYMBOL: Partial<Record<SFSymbol, Icon>> = {
|
||||
magnifyingglass: IconSearch,
|
||||
paintbrush: IconPalette,
|
||||
"person.crop.circle": IconUserCircle,
|
||||
pin: IconPin,
|
||||
"pin.slash": IconPinnedOff,
|
||||
play: IconPlayerPlay,
|
||||
plus: IconPlus,
|
||||
"qrcode.viewfinder": IconQrcode,
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -42,6 +42,8 @@ export function HomeRouteScreen() {
|
||||
settleThread,
|
||||
snoozeThread,
|
||||
unsnoozeThread,
|
||||
pinThread,
|
||||
unpinThread,
|
||||
unsettleThread,
|
||||
} = useThreadListActions();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
@@ -155,6 +157,8 @@ export function HomeRouteScreen() {
|
||||
onSnoozeThread={snoozeThread}
|
||||
onUnsnoozeThread={unsnoozeThread}
|
||||
onUnsettleThread={unsettleThread}
|
||||
onPinThread={pinThread}
|
||||
onUnpinThread={unpinThread}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
onOpenEnvironments={() =>
|
||||
|
||||
@@ -111,6 +111,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;
|
||||
@@ -516,6 +518,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 +589,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 {
|
||||
@@ -718,6 +741,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={
|
||||
@@ -753,9 +777,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 +795,15 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
[
|
||||
handleChangeRequestState,
|
||||
handleDeleteThread,
|
||||
handlePinThread,
|
||||
handleSettleThread,
|
||||
handleSnoozeThread,
|
||||
handleUnpinThread,
|
||||
handleUnsnoozeThread,
|
||||
handleSwipeableClose,
|
||||
handleSwipeableWillOpen,
|
||||
handleUnsettleThread,
|
||||
pinningEnvironmentIds,
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
props.onArchiveThread,
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -305,6 +305,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;
|
||||
@@ -337,11 +339,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 +374,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;
|
||||
@@ -383,6 +392,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
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;
|
||||
|
||||
@@ -398,6 +408,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 +446,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 +469,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 +501,10 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
[
|
||||
handleArchive,
|
||||
handleDelete,
|
||||
handlePin,
|
||||
handleSettle,
|
||||
handleSnooze,
|
||||
handleUnpin,
|
||||
handleUnsettle,
|
||||
handleUnsnooze,
|
||||
snoozePresets,
|
||||
@@ -560,6 +595,9 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
>
|
||||
{props.projectTitle ?? props.project?.title ?? ""}
|
||||
</Text>
|
||||
{pinnedRow ? (
|
||||
<SymbolView name="pin" size={11} tintColor={pinTintColor} type="monochrome" />
|
||||
) : null}
|
||||
<Text
|
||||
className={cn(
|
||||
"text-xs tabular-nums",
|
||||
@@ -805,7 +843,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
? SLIM_MENU_ACTIONS
|
||||
: swipeActions.secondary === "snooze"
|
||||
? snoozableCardMenuActions
|
||||
: CARD_MENU_ACTIONS
|
||||
: cardMenuActions
|
||||
}
|
||||
onPressAction={handleMenuAction}
|
||||
shouldOpenOnLongPress
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -6,6 +6,7 @@ import * as NodePath from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
import { TailscaleCommandExitError } from "@t3tools/tailscale";
|
||||
import { assert, describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -22,6 +23,7 @@ import {
|
||||
DevServerNotProxiableError,
|
||||
resolveDirectPairingBaseUrl,
|
||||
resolveTailscaleLocalTarget,
|
||||
tailscaleServeFailedError,
|
||||
} from "./pair.ts";
|
||||
|
||||
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
||||
@@ -50,6 +52,45 @@ describe("pair base URL selection", () => {
|
||||
});
|
||||
|
||||
describe("pair tailscale local target", () => {
|
||||
it("surfaces the operator fix from safe structural error fields", () => {
|
||||
const cause = new TailscaleCommandExitError({
|
||||
executable: "tailscale",
|
||||
subcommand: "serve",
|
||||
argumentCount: 4,
|
||||
exitCode: 1,
|
||||
stderrLength: 24,
|
||||
stderrDiagnostic: "permission-denied",
|
||||
});
|
||||
|
||||
const failure = tailscaleServeFailedError(443, cause);
|
||||
|
||||
expect(failure).toMatchObject({
|
||||
exitCode: 1,
|
||||
stderrDiagnostic: "permission-denied",
|
||||
cause,
|
||||
});
|
||||
expect(failure.message).toBe(
|
||||
"tailscale serve failed with code 1 for HTTPS port 443: access denied. Run `sudo tailscale set --operator=$USER`, then retry.",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps Windows permission guidance free of Unix-only commands", () => {
|
||||
const cause = new TailscaleCommandExitError({
|
||||
executable: "tailscale.exe",
|
||||
subcommand: "serve",
|
||||
argumentCount: 4,
|
||||
exitCode: 1,
|
||||
stderrLength: 24,
|
||||
stderrDiagnostic: "permission-denied",
|
||||
});
|
||||
|
||||
const failure = tailscaleServeFailedError(443, cause);
|
||||
|
||||
expect(failure).toMatchObject({ executable: "tailscale.exe", cause });
|
||||
expect(failure.message).toContain("Grant this Windows user permission");
|
||||
expect(failure.message).not.toContain("sudo");
|
||||
});
|
||||
|
||||
it("proxies the dev web port for dev servers", () => {
|
||||
expect(resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://localhost:5733/" })).toEqual(
|
||||
{ localPort: 5_733 },
|
||||
@@ -205,7 +246,8 @@ describe("t3 pair", () => {
|
||||
const rendered = String(
|
||||
typeof error === "object" && error !== null && "cause" in error ? error.cause : error,
|
||||
);
|
||||
assert.include(rendered, "No running T3 Code server found.");
|
||||
assert.include(rendered, "No usable T3 Code server runtime state found.");
|
||||
assert.include(rendered, "--base-dir");
|
||||
assert.include(rendered, "npx t3 serve");
|
||||
assert.include(rendered, "npx t3 connect");
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
@@ -236,7 +278,7 @@ describe("t3 pair", () => {
|
||||
const rendered = String(
|
||||
typeof error === "object" && error !== null && "cause" in error ? error.cause : error,
|
||||
);
|
||||
assert.include(rendered, "No running T3 Code server found.");
|
||||
assert.include(rendered, "No usable T3 Code server runtime state found.");
|
||||
}),
|
||||
).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
@@ -262,7 +304,7 @@ describe("t3 pair", () => {
|
||||
const rendered = String(
|
||||
typeof error === "object" && error !== null && "cause" in error ? error.cause : error,
|
||||
);
|
||||
assert.include(rendered, "No running T3 Code server found.");
|
||||
assert.include(rendered, "No usable T3 Code server runtime state found.");
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
@@ -20,6 +20,8 @@ import {
|
||||
DEFAULT_TAILSCALE_SERVE_PORT,
|
||||
ensureTailscaleServe,
|
||||
readTailscaleStatus,
|
||||
TailscaleCommandExitError,
|
||||
TailscaleStderrDiagnostic,
|
||||
} from "@t3tools/tailscale";
|
||||
import * as Config from "effect/Config";
|
||||
import * as Console from "effect/Console";
|
||||
@@ -76,9 +78,10 @@ export class NoRunningServerError extends Schema.TaggedErrorClass<NoRunningServe
|
||||
) {
|
||||
override get message(): string {
|
||||
return [
|
||||
"No running T3 Code server found.",
|
||||
"No usable T3 Code server runtime state found.",
|
||||
...this.checkedStatePaths.map((statePath) => ` checked ${statePath}`),
|
||||
"Start one with `npx t3 serve`, or connect this machine with T3 Connect: `npx t3 connect`.",
|
||||
"If a server is running, pass its T3 home with `--base-dir`; its runtime state may be missing or stale.",
|
||||
"Otherwise start one with `npx t3 serve`, or connect this machine with T3 Connect: `npx t3 connect`.",
|
||||
].join("\n");
|
||||
}
|
||||
}
|
||||
@@ -114,13 +117,44 @@ export class ServesOtherEnvironmentError extends Schema.TaggedErrorClass<ServesO
|
||||
|
||||
export class TailscaleServeFailedError extends Schema.TaggedErrorClass<TailscaleServeFailedError>()(
|
||||
"TailscaleServeFailedError",
|
||||
{ servePort: Schema.Number, cause: Schema.Defect() },
|
||||
{
|
||||
servePort: Schema.Number,
|
||||
executable: Schema.optional(Schema.Literals(["tailscale", "tailscale.exe"])),
|
||||
exitCode: Schema.optional(Schema.Number),
|
||||
stderrDiagnostic: Schema.optional(TailscaleStderrDiagnostic),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
if (this.stderrDiagnostic === "permission-denied") {
|
||||
const exitDetail = this.exitCode === undefined ? "" : ` with code ${String(this.exitCode)}`;
|
||||
if (this.executable === "tailscale.exe") {
|
||||
return `tailscale serve failed${exitDetail} for HTTPS port ${String(this.servePort)}: access denied. Grant this Windows user permission to manage Tailscale, then retry.`;
|
||||
}
|
||||
return `tailscale serve failed${exitDetail} for HTTPS port ${String(this.servePort)}: access denied. Run \`sudo tailscale set --operator=$USER\`, then retry.`;
|
||||
}
|
||||
return `tailscale serve failed for HTTPS port ${String(this.servePort)}. Run \`tailscale serve --https=${String(this.servePort)} --bg <local-url>\` by hand to see why.`;
|
||||
}
|
||||
}
|
||||
|
||||
const isTailscaleCommandExitError = Schema.is(TailscaleCommandExitError);
|
||||
|
||||
export function tailscaleServeFailedError(
|
||||
servePort: number,
|
||||
cause: unknown,
|
||||
): TailscaleServeFailedError {
|
||||
const exitDetails = isTailscaleCommandExitError(cause)
|
||||
? {
|
||||
executable: cause.executable,
|
||||
exitCode: cause.exitCode,
|
||||
...(cause.stderrDiagnostic === undefined
|
||||
? {}
|
||||
: { stderrDiagnostic: cause.stderrDiagnostic }),
|
||||
}
|
||||
: {};
|
||||
return new TailscaleServeFailedError({ servePort, cause, ...exitDetails });
|
||||
}
|
||||
|
||||
export class ServePortOccupiedError extends Schema.TaggedErrorClass<ServePortOccupiedError>()(
|
||||
"ServePortOccupiedError",
|
||||
{ servePort: Schema.Number },
|
||||
@@ -409,11 +443,7 @@ const resolveTailscalePairingBase = Effect.fn("pair.resolveTailscalePairingBase"
|
||||
localPort: localTarget.localPort,
|
||||
servePort: input.servePort,
|
||||
...(localTarget.localHost !== undefined ? { localHost: localTarget.localHost } : {}),
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new TailscaleServeFailedError({ servePort: input.servePort, cause }),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.mapError((cause) => tailscaleServeFailedError(input.servePort, cause)));
|
||||
notes.push(
|
||||
`Tailscale Serve now maps ${baseUrl} to this server and persists across restarts. Remove it with \`tailscale serve --https=${String(input.servePort)} off\`.`,
|
||||
);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import { formatServiceStatus } from "./service.ts";
|
||||
import { formatServiceStatus, serviceDowngradeRefusal } from "./service.ts";
|
||||
|
||||
const status = {
|
||||
supported: true,
|
||||
@@ -8,6 +8,7 @@ const status = {
|
||||
current: true,
|
||||
unitPath: "/home/me/.config/systemd/user/t3code.service",
|
||||
logPath: "/home/me/.t3/userdata/logs/boot-service.log",
|
||||
installedVersion: "0.0.29",
|
||||
} as const;
|
||||
|
||||
it("reports the installed service version and host paths", () => {
|
||||
@@ -35,3 +36,42 @@ it("explains service availability without systemd", () => {
|
||||
"Supported on: Linux with systemd",
|
||||
);
|
||||
});
|
||||
|
||||
it("reports a newer installed service without recommending latest", () => {
|
||||
const output = formatServiceStatus(
|
||||
{ ...status, current: false, installedVersion: "0.0.32-nightly.1" },
|
||||
"0.0.31",
|
||||
);
|
||||
|
||||
assert.include(output, "[email protected] (newer than this [email protected] CLI)");
|
||||
assert.include(output, "npx [email protected] service update");
|
||||
assert.notInclude(output, "npx t3@latest service update");
|
||||
});
|
||||
|
||||
it("refuses service downgrades unless explicitly allowed", () => {
|
||||
const refusal = serviceDowngradeRefusal({
|
||||
installedVersion: "0.0.32-nightly.1",
|
||||
targetVersion: "0.0.31",
|
||||
allowDowngrade: false,
|
||||
});
|
||||
assert.instanceOf(refusal, Error);
|
||||
assert.deepInclude(refusal, {
|
||||
_tag: "ServiceDowngradeRefusedError",
|
||||
installedVersion: "0.0.32-nightly.1",
|
||||
targetVersion: "0.0.31",
|
||||
});
|
||||
assert.isNull(
|
||||
serviceDowngradeRefusal({
|
||||
installedVersion: "0.0.32-nightly.1",
|
||||
targetVersion: "0.0.31",
|
||||
allowDowngrade: true,
|
||||
}),
|
||||
);
|
||||
assert.isNull(
|
||||
serviceDowngradeRefusal({
|
||||
installedVersion: undefined,
|
||||
targetVersion: "0.0.31",
|
||||
allowDowngrade: false,
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,11 +1,13 @@
|
||||
import * as Console from "effect/Console";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Terminal from "effect/Terminal";
|
||||
import { Command, GlobalFlag, Prompt } from "effect/unstable/cli";
|
||||
import { Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli";
|
||||
|
||||
import packageJson from "../../package.json" with { type: "json" };
|
||||
import * as BootService from "../cloud/bootService.ts";
|
||||
import { compareExactServiceVersions } from "../cloud/serviceProtocol.ts";
|
||||
import type * as ServerConfig from "../config.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
|
||||
@@ -28,13 +30,50 @@ export type ServiceReconcileResult =
|
||||
readonly plan: BootService.BootServicePlan;
|
||||
};
|
||||
|
||||
export class ServiceDowngradeRefusedError extends Schema.TaggedErrorClass<ServiceDowngradeRefusedError>()(
|
||||
"ServiceDowngradeRefusedError",
|
||||
{
|
||||
installedVersion: Schema.String,
|
||||
targetVersion: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Refusing to replace t3@${this.installedVersion} with older t3@${this.targetVersion}. Re-run with --allow-downgrade to continue.`;
|
||||
}
|
||||
}
|
||||
|
||||
export function serviceDowngradeRefusal(input: {
|
||||
readonly installedVersion: string | undefined;
|
||||
readonly targetVersion: string;
|
||||
readonly allowDowngrade: boolean;
|
||||
}): ServiceDowngradeRefusedError | null {
|
||||
return input.installedVersion !== undefined &&
|
||||
!input.allowDowngrade &&
|
||||
compareExactServiceVersions(input.targetVersion, input.installedVersion) < 0
|
||||
? new ServiceDowngradeRefusedError({
|
||||
installedVersion: input.installedVersion,
|
||||
targetVersion: input.targetVersion,
|
||||
})
|
||||
: null;
|
||||
}
|
||||
|
||||
/** Install, update, or repair the service using the CLI version running this command. */
|
||||
export const reconcileService = Effect.fn("cli.service.reconcile")(function* () {
|
||||
export const reconcileService = Effect.fn("cli.service.reconcile")(function* (options?: {
|
||||
readonly allowDowngrade?: boolean;
|
||||
}) {
|
||||
const service = yield* BootService.BootService;
|
||||
const status = yield* service.status;
|
||||
if (status.installed && status.current) {
|
||||
return { changed: false, status } satisfies ServiceReconcileResult;
|
||||
}
|
||||
const downgradeRefusal = serviceDowngradeRefusal({
|
||||
installedVersion: status.installedVersion,
|
||||
targetVersion: packageJson.version,
|
||||
allowDowngrade: options?.allowDowngrade === true,
|
||||
});
|
||||
if (downgradeRefusal !== null) {
|
||||
return yield* downgradeRefusal;
|
||||
}
|
||||
const plan = yield* service.install;
|
||||
return {
|
||||
changed: true,
|
||||
@@ -53,9 +92,23 @@ export function formatServiceStatus(
|
||||
if (!status.installed) {
|
||||
return "T3 Code service\n Status: not installed\n Next: Run `t3 service install`.";
|
||||
}
|
||||
const installedVersion = status.installedVersion ?? cliVersion;
|
||||
if (
|
||||
!status.current &&
|
||||
status.installedVersion !== undefined &&
|
||||
compareExactServiceVersions(status.installedVersion, cliVersion) > 0
|
||||
) {
|
||||
return [
|
||||
"T3 Code service",
|
||||
` Status: installed · t3@${installedVersion} (newer than this t3@${cliVersion} CLI)`,
|
||||
` Unit: ${status.unitPath}`,
|
||||
` Logs: ${status.logPath}`,
|
||||
` Next: Use \`npx t3@${installedVersion} service update\` to repair it, or pass \`--allow-downgrade\` explicitly.`,
|
||||
].join("\n");
|
||||
}
|
||||
return [
|
||||
"T3 Code service",
|
||||
` Status: ${status.current ? `installed · t3@${cliVersion}` : "needs an update or repair"}`,
|
||||
` Status: ${status.current ? `installed · t3@${installedVersion}` : "needs an update or repair"}`,
|
||||
` Unit: ${status.unitPath}`,
|
||||
` Logs: ${status.logPath}`,
|
||||
...(status.current ? [] : [" Next: Run `npx t3@latest service update`."]),
|
||||
@@ -71,13 +124,21 @@ const runServiceCommand = Effect.fn("cli.service.run")(function* <A, E>(
|
||||
return yield* run.pipe(Effect.provide(bootServiceLayer(config)));
|
||||
});
|
||||
|
||||
const serviceInstallCommand = Command.make("install", projectLocationFlags).pipe(
|
||||
const serviceReconcileFlags = {
|
||||
...projectLocationFlags,
|
||||
allowDowngrade: Flag.boolean("allow-downgrade").pipe(
|
||||
Flag.withDescription("Allow replacing a newer installed service with this older CLI version."),
|
||||
Flag.withDefault(false),
|
||||
),
|
||||
};
|
||||
|
||||
const serviceInstallCommand = Command.make("install", serviceReconcileFlags).pipe(
|
||||
Command.withDescription("Install T3 Code as a background service for this user."),
|
||||
Command.withHandler((flags) =>
|
||||
runServiceCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const result = yield* reconcileService();
|
||||
const result = yield* reconcileService({ allowDowngrade: flags.allowDowngrade });
|
||||
if (!result.changed) {
|
||||
yield* Console.log(
|
||||
`T3 Code service is already installed with t3@${packageJson.version}.`,
|
||||
@@ -92,7 +153,7 @@ const serviceInstallCommand = Command.make("install", projectLocationFlags).pipe
|
||||
),
|
||||
);
|
||||
|
||||
const serviceUpdateCommand = Command.make("update", projectLocationFlags).pipe(
|
||||
const serviceUpdateCommand = Command.make("update", serviceReconcileFlags).pipe(
|
||||
Command.withDescription(
|
||||
"Update or repair the background service using this CLI version. Use `npx t3@latest service update` for the latest release.",
|
||||
),
|
||||
@@ -100,7 +161,7 @@ const serviceUpdateCommand = Command.make("update", projectLocationFlags).pipe(
|
||||
runServiceCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const result = yield* reconcileService();
|
||||
const result = yield* reconcileService({ allowDowngrade: flags.allowDowngrade });
|
||||
if (!result.changed) {
|
||||
yield* Console.log(`T3 Code service is already using t3@${packageJson.version}.`);
|
||||
return;
|
||||
@@ -144,7 +205,8 @@ const serviceStatusCommand = Command.make("status", projectLocationFlags).pipe(
|
||||
|
||||
export const offerServiceDuringOnboarding = Effect.gen(function* () {
|
||||
const service = yield* BootService.BootService;
|
||||
const { supported, installed, current } = yield* service.status;
|
||||
const status = yield* service.status;
|
||||
const { supported, installed, current } = status;
|
||||
if (!supported) {
|
||||
return false;
|
||||
}
|
||||
@@ -152,6 +214,18 @@ export const offerServiceDuringOnboarding = Effect.gen(function* () {
|
||||
yield* Console.log("T3 Code is already set up to run in the background on this machine.");
|
||||
return true;
|
||||
}
|
||||
if (
|
||||
installed &&
|
||||
status.installedVersion !== undefined &&
|
||||
compareExactServiceVersions(status.installedVersion, packageJson.version) > 0
|
||||
) {
|
||||
yield* Console.log(
|
||||
`A newer t3@${status.installedVersion} background service is installed; leaving it unchanged.`,
|
||||
);
|
||||
// This CLI cannot verify that the newer unit is healthy, so keep the
|
||||
// manual `serve` fallback visible instead of claiming background readiness.
|
||||
return false;
|
||||
}
|
||||
const wanted = yield* Prompt.run(
|
||||
Prompt.confirm({
|
||||
message: installed
|
||||
@@ -174,7 +248,11 @@ export const offerServiceDuringOnboarding = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
export const recoverServiceOnboardingOffer = <R>(
|
||||
offer: Effect.Effect<boolean, BootService.BootServiceError | Terminal.QuitError, R>,
|
||||
offer: Effect.Effect<
|
||||
boolean,
|
||||
BootService.BootServiceError | ServiceDowngradeRefusedError | Terminal.QuitError,
|
||||
R
|
||||
>,
|
||||
) =>
|
||||
offer.pipe(
|
||||
Effect.catchTags({
|
||||
@@ -185,6 +263,10 @@ 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)),
|
||||
ServiceDowngradeRefusedError: (error) =>
|
||||
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -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,27 @@ 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"}}',
|
||||
);
|
||||
expect(yield* service.status).toMatchObject({
|
||||
current: true,
|
||||
installedVersion: "1.2.3",
|
||||
});
|
||||
// @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);
|
||||
@@ -124,6 +140,22 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports the installed version across launcher protocol revisions", () =>
|
||||
Effect.gen(function* () {
|
||||
const { service, fs, statePath } = yield* makeHarness();
|
||||
yield* service.install;
|
||||
yield* fs.writeFileString(
|
||||
statePath,
|
||||
`{"protocol":${String(SERVICE_LAUNCHER_PROTOCOL + 1)},"activeVersion":"9.9.9"}`,
|
||||
);
|
||||
|
||||
expect(yield* service.status).toMatchObject({
|
||||
current: false,
|
||||
installedVersion: "9.9.9",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("restarts an installed service when repair fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const { service, commands, control } = yield* makeHarness();
|
||||
@@ -141,6 +173,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,6 +21,8 @@ import {
|
||||
SERVICE_LAUNCHER_PROTOCOL,
|
||||
SERVICE_STATE_FILE,
|
||||
parseServiceState,
|
||||
serviceStateActiveVersion,
|
||||
serviceStateHasPendingUpdate,
|
||||
type ServiceState,
|
||||
} from "./serviceProtocol.ts";
|
||||
|
||||
@@ -110,15 +112,26 @@ 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;
|
||||
readonly installed: boolean;
|
||||
readonly current: boolean;
|
||||
readonly installedVersion?: string;
|
||||
readonly unitPath: string;
|
||||
readonly logPath: string;
|
||||
}
|
||||
@@ -288,6 +301,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 })));
|
||||
@@ -370,9 +392,13 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
|
||||
fs.readFileString(statePath).pipe(Effect.option),
|
||||
]);
|
||||
const state = Option.isSome(stateText) ? parseServiceState(stateText.value) : undefined;
|
||||
const installedVersion = Option.isSome(stateText)
|
||||
? serviceStateActiveVersion(stateText.value)
|
||||
: undefined;
|
||||
return {
|
||||
supported: true,
|
||||
installed: true,
|
||||
...(installedVersion === undefined ? {} : { installedVersion }),
|
||||
current:
|
||||
unit === renderBootServiceUnit(plan) &&
|
||||
launcherExists &&
|
||||
|
||||
@@ -19,12 +19,19 @@ import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
|
||||
import { CLOUD_CLI_DESIRED_LINK_SECRET } from "./CliState.ts";
|
||||
import * as CliTokenManager from "./CliTokenManager.ts";
|
||||
import type { RelayLinkProofRequest } from "@t3tools/contracts/relay";
|
||||
import { CLOUD_ENDPOINT_RUNTIME_CONFIG, RELAY_URL_SECRET } from "./config.ts";
|
||||
import {
|
||||
CLOUD_ENDPOINT_RUNTIME_CONFIG,
|
||||
CLOUD_LINKED_USER_ID,
|
||||
decodeRuntimeConfig,
|
||||
RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
|
||||
RELAY_URL_SECRET,
|
||||
} from "./config.ts";
|
||||
import {
|
||||
consumeCloudReplayGuards,
|
||||
isSupportedLinkProviderKind,
|
||||
linkProofScopes,
|
||||
reconcileDesiredCloudLink,
|
||||
managedEndpointOriginsEqual,
|
||||
reconcileCloudLinkOnStartup,
|
||||
releaseManagedTunnelOnShutdown,
|
||||
} from "./http.ts";
|
||||
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
|
||||
@@ -79,6 +86,18 @@ it("preserves messages surfaced by cloud 500 responses", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("compares managed endpoint origins without hostname formatting drift", () => {
|
||||
const desired = { localHttpHost: "127.0.0.1", localHttpPort: 7331 } as const;
|
||||
|
||||
expect(managedEndpointOriginsEqual(undefined, desired)).toBe(false);
|
||||
expect(
|
||||
managedEndpointOriginsEqual({ localHttpHost: "[127.0.0.1]", localHttpPort: 7331 }, desired),
|
||||
).toBe(true);
|
||||
expect(
|
||||
managedEndpointOriginsEqual({ localHttpHost: "127.0.0.1", localHttpPort: 7332 }, desired),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
describe("consumeCloudReplayGuards", () => {
|
||||
it.effect("reports already-created guards as replay conflicts", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -172,20 +191,25 @@ describe("relay request tracing", () => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("reconcileDesiredCloudLink", () => {
|
||||
it.effect("requires stored CLI authorization without exposing an HTTP endpoint", () =>
|
||||
describe("reconcileCloudLinkOnStartup", () => {
|
||||
it.effect("restores a desired CLI link before attempting origin repair", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(reconcileDesiredCloudLink("http://127.0.0.1:3774"));
|
||||
const error = yield* Effect.flip(reconcileCloudLinkOnStartup("http://127.0.0.1:3774"));
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "EnvironmentHttpUnauthorizedError",
|
||||
message: "Run `t3 connect link` to authorize this environment.",
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provideService(
|
||||
ServerSecretStore.ServerSecretStore,
|
||||
makeSecretStore(unusedSecretStoreOperation),
|
||||
),
|
||||
Effect.provideService(ServerSecretStore.ServerSecretStore, {
|
||||
...makeSecretStore(unusedSecretStoreOperation),
|
||||
get: (name) =>
|
||||
Effect.succeed(
|
||||
name === CLOUD_CLI_DESIRED_LINK_SECRET
|
||||
? Option.some(new TextEncoder().encode("managed"))
|
||||
: Option.none(),
|
||||
),
|
||||
}),
|
||||
Effect.provideService(
|
||||
ServerEnvironment.ServerEnvironment,
|
||||
ServerEnvironment.ServerEnvironment.of({
|
||||
@@ -222,6 +246,122 @@ describe("reconcileDesiredCloudLink", () => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("reconcileManagedEndpointOrigin", () => {
|
||||
it.effect("uses the environment credential and persists the reconciled origin", () => {
|
||||
const initialSecrets: ReadonlyArray<readonly [string, string]> = [
|
||||
[
|
||||
CLOUD_ENDPOINT_RUNTIME_CONFIG,
|
||||
JSON.stringify({
|
||||
providerKind: "cloudflare_tunnel",
|
||||
connectorToken: "old-connector-token",
|
||||
}),
|
||||
],
|
||||
[RELAY_URL_SECRET, "https://relay.example.test"],
|
||||
[RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
|
||||
[CLOUD_LINKED_USER_ID, "user_123"],
|
||||
];
|
||||
const values = new Map<string, Uint8Array>(
|
||||
initialSecrets.map(([name, value]) => [name, new TextEncoder().encode(value)] as const),
|
||||
);
|
||||
const store: ServerSecretStore.ServerSecretStore["Service"] = {
|
||||
get: (name) => Effect.sync(() => Option.fromNullishOr(values.get(name))),
|
||||
set: (name, value) =>
|
||||
Effect.sync(() => {
|
||||
values.set(name, value);
|
||||
}),
|
||||
create: unusedSecretStoreOperation,
|
||||
getOrCreateRandom: unusedSecretStoreOperation,
|
||||
remove: unusedSecretStoreOperation,
|
||||
};
|
||||
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
|
||||
const applied: Array<unknown> = [];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
expect(yield* reconcileCloudLinkOnStartup("http://127.0.0.1:4555")).toBe(true);
|
||||
|
||||
expect(requests).toHaveLength(1);
|
||||
expect(requests[0]?.url).toBe(
|
||||
"https://relay.example.test/v1/environments/env_123/managed-endpoint/reconcile",
|
||||
);
|
||||
expect(requests[0]?.headers.authorization).toBe("Bearer environment-credential");
|
||||
expect(applied).toEqual([
|
||||
{
|
||||
providerKind: "cloudflare_tunnel",
|
||||
connectorToken: "fresh-connector-token",
|
||||
tunnelId: "tunnel-123",
|
||||
tunnelName: "tunnel-name",
|
||||
origin: { localHttpHost: "127.0.0.1", localHttpPort: 4555 },
|
||||
},
|
||||
]);
|
||||
const persisted = decodeRuntimeConfig(
|
||||
new TextDecoder().decode(values.get(CLOUD_ENDPOINT_RUNTIME_CONFIG)),
|
||||
);
|
||||
expect(Option.getOrNull(persisted)?.origin).toEqual({
|
||||
localHttpHost: "127.0.0.1",
|
||||
localHttpPort: 4555,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provideService(ServerSecretStore.ServerSecretStore, store),
|
||||
Effect.provideService(
|
||||
ServerEnvironment.ServerEnvironment,
|
||||
ServerEnvironment.ServerEnvironment.of({
|
||||
getEnvironmentId: Effect.succeed(EnvironmentId.make("env_123")),
|
||||
getDescriptor: unusedSecretStoreOperation(),
|
||||
}),
|
||||
),
|
||||
Effect.provideService(
|
||||
ManagedEndpointRuntime.CloudManagedEndpointRuntime,
|
||||
ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({
|
||||
applyConfig: (config) =>
|
||||
Effect.sync(() => {
|
||||
applied.push(config);
|
||||
return {
|
||||
status: "running",
|
||||
providerKind: "cloudflare_tunnel",
|
||||
pid: 123,
|
||||
} as const;
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Effect.provideService(
|
||||
EnvironmentAuth.EnvironmentAuth,
|
||||
EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]),
|
||||
),
|
||||
Effect.provideService(
|
||||
CliTokenManager.CloudCliTokenManager,
|
||||
CliTokenManager.CloudCliTokenManager.of({
|
||||
get: unusedSecretStoreOperation(),
|
||||
getExisting: unusedSecretStoreOperation(),
|
||||
hasCredential: unusedSecretStoreOperation(),
|
||||
store: unusedSecretStoreOperation,
|
||||
clear: unusedSecretStoreOperation(),
|
||||
}),
|
||||
),
|
||||
Effect.provideService(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make((request) =>
|
||||
Effect.sync(() => {
|
||||
requests.push(request);
|
||||
return HttpClientResponse.fromWeb(
|
||||
request,
|
||||
Response.json({
|
||||
endpointRuntime: {
|
||||
providerKind: "cloudflare_tunnel",
|
||||
connectorToken: "fresh-connector-token",
|
||||
tunnelId: "tunnel-123",
|
||||
tunnelName: "tunnel-name",
|
||||
origin: { localHttpHost: "127.0.0.1", localHttpPort: 4555 },
|
||||
},
|
||||
}),
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.provide(NodeServices.layer),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("releaseManagedTunnelOnShutdown", () => {
|
||||
const cliToken: CliTokenManager.PersistedToken = {
|
||||
accessToken: "cli-access-token",
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
RelayEnvironmentConfigRequest,
|
||||
RelayEnvironmentLinkChallengeResponse,
|
||||
RelayEnvironmentLinkResponse,
|
||||
RelayManagedEndpointReconcileResponse,
|
||||
RelayEnvironmentMintResponseProofPayload,
|
||||
type RelayEnvironmentMintResponse as RelayEnvironmentMintResponseShape,
|
||||
RelayEnvironmentLinkProof,
|
||||
@@ -62,6 +63,7 @@ import {
|
||||
CLOUD_ENDPOINT_RUNTIME_CONFIG,
|
||||
CLOUD_LINKED_USER_ID,
|
||||
CLOUD_MINT_PUBLIC_KEY,
|
||||
decodeRuntimeConfig,
|
||||
encodeEndpointRuntimeConfigJson,
|
||||
PUBLISH_AGENT_ACTIVITY_SECRET,
|
||||
RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
|
||||
@@ -627,6 +629,115 @@ export const reconcileDesiredCloudLink = Effect.fn("environment.cloud.reconcileD
|
||||
},
|
||||
);
|
||||
|
||||
function managedEndpointOriginFromLocalUrl(localUrl: URL): RelayManagedEndpointOrigin {
|
||||
return {
|
||||
localHttpHost: localUrl.hostname,
|
||||
localHttpPort: endpointRequestPort(localUrl),
|
||||
};
|
||||
}
|
||||
|
||||
export function managedEndpointOriginsEqual(
|
||||
left: RelayManagedEndpointOrigin | undefined,
|
||||
right: RelayManagedEndpointOrigin,
|
||||
): boolean {
|
||||
return (
|
||||
left !== undefined &&
|
||||
normalizeHostname(left.localHttpHost) === normalizeHostname(right.localHttpHost) &&
|
||||
left.localHttpPort === right.localHttpPort
|
||||
);
|
||||
}
|
||||
|
||||
const reconcileManagedEndpointOriginWith = Effect.fn(
|
||||
"environment.cloud.reconcileManagedEndpointOriginWith",
|
||||
)(function* (dependencies: CloudHttpDependencies, localOrigin: string) {
|
||||
const localUrl = yield* Effect.try({
|
||||
try: () => new URL(localOrigin),
|
||||
catch: () =>
|
||||
new EnvironmentHttpBadRequestError({
|
||||
message: "Could not resolve local environment origin.",
|
||||
}),
|
||||
});
|
||||
if (localUrl.origin !== localOrigin) {
|
||||
return yield* new EnvironmentHttpBadRequestError({
|
||||
message: "Could not resolve local environment origin.",
|
||||
});
|
||||
}
|
||||
const desiredOrigin = managedEndpointOriginFromLocalUrl(localUrl);
|
||||
const storedConfigBytes = yield* dependencies.secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG);
|
||||
const storedConfig = Option.isSome(storedConfigBytes)
|
||||
? decodeRuntimeConfig(bytesToString(storedConfigBytes.value))
|
||||
: Option.none();
|
||||
if (Option.isSome(storedConfigBytes) && Option.isNone(storedConfig)) {
|
||||
return yield* new EnvironmentHttpInternalServerError({
|
||||
message: "Stored managed endpoint runtime configuration is invalid.",
|
||||
});
|
||||
}
|
||||
const config = Option.getOrNull(storedConfig);
|
||||
const desiredManagedLink =
|
||||
(yield* readCliDesiredCloudLink) && (yield* readCliDesiredLinkMode) === "managed";
|
||||
if (config?.providerKind !== "cloudflare_tunnel" && !desiredManagedLink) {
|
||||
return false;
|
||||
}
|
||||
if (managedEndpointOriginsEqual(config?.origin, desiredOrigin)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const relayUrl = yield* dependencies.secrets.get(RELAY_URL_SECRET);
|
||||
const environmentCredential = yield* dependencies.secrets.get(
|
||||
RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
|
||||
);
|
||||
const cloudUserId = yield* dependencies.secrets.get(CLOUD_LINKED_USER_ID);
|
||||
if (
|
||||
Option.isNone(relayUrl) ||
|
||||
Option.isNone(environmentCredential) ||
|
||||
Option.isNone(cloudUserId)
|
||||
) {
|
||||
return yield* new EnvironmentHttpUnauthorizedError({
|
||||
message: "This managed environment is missing its T3 Connect credentials. Link it again.",
|
||||
});
|
||||
}
|
||||
|
||||
const environmentId = yield* dependencies.environment.getEnvironmentId;
|
||||
const response = yield* relayClientRequest(dependencies, {
|
||||
url: `${bytesToString(relayUrl.value)}/v1/environments/${encodeURIComponent(environmentId)}/managed-endpoint/reconcile`,
|
||||
token: bytesToString(environmentCredential.value),
|
||||
payload: {
|
||||
cloudUserId: bytesToString(cloudUserId.value),
|
||||
origin: desiredOrigin,
|
||||
},
|
||||
schema: RelayManagedEndpointReconcileResponse,
|
||||
});
|
||||
const status = yield* dependencies.endpointRuntime.applyConfig(response.endpointRuntime);
|
||||
if (status.status !== "running") {
|
||||
return yield* new EnvironmentCloudEndpointUnavailableError({
|
||||
message: "Managed endpoint runtime could not be started after origin reconciliation.",
|
||||
endpointRuntimeStatus: status,
|
||||
});
|
||||
}
|
||||
const encoded = yield* encodeEndpointRuntimeConfigJson(response.endpointRuntime);
|
||||
yield* dependencies.secrets.set(CLOUD_ENDPOINT_RUNTIME_CONFIG, stringToBytes(encoded));
|
||||
return true;
|
||||
});
|
||||
|
||||
export const reconcileManagedEndpointOrigin = Effect.fn(
|
||||
"environment.cloud.reconcileManagedEndpointOrigin",
|
||||
)(function* (localOrigin: string) {
|
||||
return yield* reconcileManagedEndpointOriginWith(yield* cloudHttpDependencies, localOrigin);
|
||||
});
|
||||
|
||||
/** Restores CLI-desired links first, then repairs origin drift for links that
|
||||
are owned by web or mobile and therefore have no CLI desired-link marker. */
|
||||
export const reconcileCloudLinkOnStartup = Effect.fn(
|
||||
"environment.cloud.reconcileCloudLinkOnStartup",
|
||||
)(function* (localOrigin: string) {
|
||||
const dependencies = yield* cloudHttpDependencies;
|
||||
if (yield* readCliDesiredCloudLink) {
|
||||
yield* reconcileDesiredCloudLinkWith(dependencies, localOrigin);
|
||||
return true;
|
||||
}
|
||||
return yield* reconcileManagedEndpointOriginWith(dependencies, localOrigin);
|
||||
});
|
||||
|
||||
// Cloudflare bills per provisioned tunnel, so an environment that goes offline
|
||||
// must not leave its tunnel behind. Releasing deletes only the tunnel — the
|
||||
// relay keeps the link and its hostname reservation, and the next startup's
|
||||
@@ -641,11 +752,11 @@ export const releaseManagedTunnelOnShutdown = Effect.fn(
|
||||
if (Option.isNone(runtimeConfig)) {
|
||||
return false;
|
||||
}
|
||||
// Only CLI-desired managed links release on shutdown, because the startup
|
||||
// reconcile that provisions the replacement tunnel only runs for them. A
|
||||
// link installed by a web/mobile client comes back after a restart by
|
||||
// reapplying the stored connector token — it has no boot-time re-provision
|
||||
// path — so its tunnel must survive the restart. (Unlink still deletes it.)
|
||||
// Only CLI-desired managed links release on shutdown. Their desired-link
|
||||
// marker lets startup re-provision after this function removes the dead
|
||||
// runtime config. Web/mobile links have no equivalent marker, so they keep
|
||||
// the tunnel and stored connector token across restarts. (Unlink still
|
||||
// deletes it.)
|
||||
if (!(yield* readCliDesiredCloudLink) || (yield* readCliDesiredLinkMode) !== "managed") {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -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 ??
|
||||
(() =>
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
@@ -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,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 };
|
||||
}
|
||||
|
||||
|
||||
@@ -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,30 @@ 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;
|
||||
}
|
||||
}
|
||||
|
||||
/** Reads the active version across launcher protocol revisions for downgrade protection. */
|
||||
export function serviceStateActiveVersion(value: string): string | undefined {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(value);
|
||||
return isRecord(parsed) &&
|
||||
typeof parsed.activeVersion === "string" &&
|
||||
isExactServiceVersion(parsed.activeVersion)
|
||||
? parsed.activeVersion
|
||||
: undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function decodeServiceLauncherContext(value: string): ServiceLauncherContext | undefined {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
@@ -202,8 +231,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 } : {}),
|
||||
|
||||
@@ -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)),
|
||||
),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -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",
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -5249,6 +5249,11 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
},
|
||||
],
|
||||
}),
|
||||
getDiffFileContents: () =>
|
||||
Effect.succeed({
|
||||
oldContents: "before\n",
|
||||
newContents: "after\n",
|
||||
}),
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -5363,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)),
|
||||
);
|
||||
|
||||
|
||||
@@ -83,13 +83,12 @@ import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
|
||||
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
|
||||
import {
|
||||
connectHttpApiLayer,
|
||||
reconcileDesiredCloudLink,
|
||||
reconcileCloudLinkOnStartup,
|
||||
releaseManagedTunnelOnShutdown,
|
||||
} from "./cloud/http.ts";
|
||||
import { serverRelayBrokerTracingLayer } from "./cloud/relayTracing.ts";
|
||||
import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts";
|
||||
import * as CloudCliTokenManager from "./cloud/CliTokenManager.ts";
|
||||
import * as CloudCliState from "./cloud/CliState.ts";
|
||||
import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";
|
||||
import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";
|
||||
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
|
||||
@@ -579,12 +578,11 @@ export const makeServerLayer = Layer.unwrap(
|
||||
Effect.asVoid,
|
||||
),
|
||||
);
|
||||
if (!(yield* CloudCliState.readCliDesiredCloudLink)) return;
|
||||
const server = yield* HttpServer.HttpServer;
|
||||
const address = server.address;
|
||||
if (typeof address === "string" || !("port" in address)) return;
|
||||
yield* Effect.sleep("250 millis").pipe(
|
||||
Effect.andThen(reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`)),
|
||||
Effect.andThen(reconcileCloudLinkOnStartup(`http://127.0.0.1:${address.port}`)),
|
||||
Effect.retry({
|
||||
while: (error) =>
|
||||
error._tag !== "EnvironmentHttpBadRequestError" &&
|
||||
@@ -597,9 +595,11 @@ export const makeServerLayer = Layer.unwrap(
|
||||
Schedule.upTo({ duration: "10 minutes" }),
|
||||
),
|
||||
}),
|
||||
Effect.tap(() => Effect.logInfo("T3 Connect desired link reconciled on startup")),
|
||||
Effect.tap((reconciled) =>
|
||||
reconciled ? Effect.logInfo("T3 Connect link reconciled on startup") : Effect.void,
|
||||
),
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("Failed to reconcile T3 Connect desired link on startup", {
|
||||
Effect.logWarning("Failed to reconcile T3 Connect link on startup", {
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
|
||||
import * as Console from "effect/Console";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
@@ -36,11 +37,14 @@ import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
|
||||
import * as ProviderSessionReaper from "./provider/Services/ProviderSessionReaper.ts";
|
||||
import { forkParked } from "./serverActivation.ts";
|
||||
import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";
|
||||
import { BOOT_SERVICE_UNIT_ENV, BOOT_SERVICE_UNIT_FILE } from "./cloud/bootService.ts";
|
||||
import {
|
||||
formatHeadlessServeOutput,
|
||||
formatManagedHeadlessServeOutput,
|
||||
formatHostForUrl,
|
||||
isWildcardHost,
|
||||
issueHeadlessServeAccessInfo,
|
||||
resolveHeadlessServeConnectionString,
|
||||
} from "./startupAccess.ts";
|
||||
|
||||
export class ServerRuntimeStartupError extends Schema.TaggedErrorClass<ServerRuntimeStartupError>()(
|
||||
@@ -307,6 +311,9 @@ export const make = (options?: StartupOptions) =>
|
||||
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
|
||||
const hostEnvironment = yield* HostProcessEnvironment;
|
||||
const managedServiceStartup =
|
||||
launcher.managed || hostEnvironment[BOOT_SERVICE_UNIT_ENV] === BOOT_SERVICE_UNIT_FILE;
|
||||
|
||||
const commandGate = yield* makeCommandGate;
|
||||
const httpListening = yield* Deferred.make<void>();
|
||||
@@ -406,11 +413,10 @@ export const make = (options?: StartupOptions) =>
|
||||
Effect.ignoreCause({ log: true }),
|
||||
);
|
||||
if (serverConfig.startupPresentation === "headless") {
|
||||
const accessInfo = yield* issueHeadlessServeAccessInfo();
|
||||
yield* runStartupPhase(
|
||||
"headless.output",
|
||||
Console.log(formatHeadlessServeOutput(accessInfo)),
|
||||
);
|
||||
const output = managedServiceStartup
|
||||
? formatManagedHeadlessServeOutput(yield* resolveHeadlessServeConnectionString)
|
||||
: formatHeadlessServeOutput(yield* issueHeadlessServeAccessInfo());
|
||||
yield* runStartupPhase("headless.output", Console.log(output));
|
||||
} else {
|
||||
const startupBrowserTarget = yield* resolveStartupBrowserTarget;
|
||||
if (serverConfig.mode !== "desktop") {
|
||||
|
||||
@@ -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)));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { assert, expect, it } from "@effect/vitest";
|
||||
import {
|
||||
buildPairingUrl,
|
||||
formatHeadlessServeOutput,
|
||||
formatManagedHeadlessServeOutput,
|
||||
renderTerminalQrCode,
|
||||
resolveHeadlessConnectionHost,
|
||||
resolveHeadlessConnectionString,
|
||||
@@ -77,3 +78,14 @@ it("formats headless serve output with the connection string, token, pairing url
|
||||
expect(output).toContain("Pairing URL: http://192.168.1.42:3773/pair#token=PAIRCODE");
|
||||
assert.isTrue(output.includes("█") || output.includes("▀") || output.includes("▄"));
|
||||
});
|
||||
|
||||
it("formats managed service output without mintable pairing material", () => {
|
||||
const output = formatManagedHeadlessServeOutput("http://127.0.0.1:3773");
|
||||
|
||||
expect(output).toContain("Connection string: http://127.0.0.1:3773");
|
||||
expect(output).toContain("Run `npx t3 pair` to create a pairing URL.");
|
||||
expect(output).not.toContain("Token:");
|
||||
expect(output).not.toContain("Pairing URL:");
|
||||
expect(output).not.toContain("#token=");
|
||||
assert.isFalse(output.includes("█") || output.includes("▀") || output.includes("▄"));
|
||||
});
|
||||
@@ -130,14 +130,26 @@ export const formatHeadlessServeOutput = (accessInfo: HeadlessServeAccessInfo):
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
export const issueHeadlessServeAccessInfo = Effect.fn("issueHeadlessServeAccessInfo")(function* () {
|
||||
export const formatManagedHeadlessServeOutput = (connectionString: string): string =>
|
||||
[
|
||||
"T3 Code server is ready.",
|
||||
`Connection string: ${connectionString}`,
|
||||
"Run `npx t3 pair` to create a pairing URL.",
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
export const resolveHeadlessServeConnectionString = Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const httpServer = yield* HttpServer.HttpServer;
|
||||
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
|
||||
const connectionString = resolveHeadlessConnectionString(
|
||||
return resolveHeadlessConnectionString(
|
||||
serverConfig.host,
|
||||
resolveListeningPort(httpServer.address, serverConfig.port),
|
||||
);
|
||||
});
|
||||
|
||||
export const issueHeadlessServeAccessInfo = Effect.fn("issueHeadlessServeAccessInfo")(function* () {
|
||||
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
|
||||
const connectionString = yield* resolveHeadlessServeConnectionString;
|
||||
const issued = yield* serverAuth.issueStartupPairingCredential();
|
||||
|
||||
return {
|
||||
|
||||
@@ -1400,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",
|
||||
},
|
||||
});
|
||||
@@ -1419,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");
|
||||
}),
|
||||
|
||||
@@ -1097,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* () {
|
||||
|
||||
@@ -7,7 +7,12 @@ import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { type CodexSettings, type ModelSelection } from "@t3tools/contracts";
|
||||
import {
|
||||
type CodexSettings,
|
||||
DEFAULT_TEXT_GENERATION_REASONING_EFFORT,
|
||||
type ModelSelection,
|
||||
TextGenerationError,
|
||||
} from "@t3tools/contracts";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
import { resolveSpawnCommand } from "@t3tools/shared/shell";
|
||||
|
||||
@@ -15,7 +20,6 @@ import { resolveAttachmentPath } from "../attachmentStore.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import { expandHomePath } from "../pathExpansion.ts";
|
||||
import { codexExecLaunchArgs, resolveCodexLaunchArgs } from "../provider/Layers/codexLaunchArgs.ts";
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
import * as TextGeneration from "./TextGeneration.ts";
|
||||
import {
|
||||
buildBranchNamePrompt,
|
||||
@@ -33,7 +37,6 @@ import {
|
||||
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
|
||||
import { getCodexServiceTierOptionValue } from "../codexModelOptions.ts";
|
||||
|
||||
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
|
||||
const CODEX_TIMEOUT_MS = 180_000;
|
||||
const encodeJsonString = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
|
||||
/**
|
||||
@@ -178,7 +181,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
||||
const launchArgs = resolveCodexLaunchArgs(codexConfig.launchArgs, resolvedEnvironment);
|
||||
const reasoningEffort =
|
||||
getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ??
|
||||
CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
|
||||
DEFAULT_TEXT_GENERATION_REASONING_EFFORT;
|
||||
const serviceTier = getCodexServiceTierOptionValue(modelSelection);
|
||||
const spawnCommand = yield* resolveSpawnCommand(
|
||||
codexConfig.binaryPath || "codex",
|
||||
|
||||
@@ -154,6 +154,18 @@ describe("buildThreadTitlePrompt", () => {
|
||||
expect(result.prompt).toContain("User message:");
|
||||
expect(result.prompt).toContain("Investigate reconnect regressions after session restore");
|
||||
expect(result.prompt).not.toContain("Attachment metadata:");
|
||||
expect(result.prompt).toContain(
|
||||
"Generate a title that will help the user recognize this T3 Code thread weeks later.",
|
||||
);
|
||||
expect(result.prompt).toContain(
|
||||
"Title the subject and outcome. Discard incidental instructions.",
|
||||
);
|
||||
expect(result.prompt).toContain(
|
||||
"Name the product change, not the mock, plan, report, branch, or PR used to produce it.",
|
||||
);
|
||||
expect(result.prompt).not.toContain(
|
||||
"Title should summarize the user's request, not restate it verbatim.",
|
||||
);
|
||||
});
|
||||
|
||||
it("includes attachment metadata when attachments are provided", () => {
|
||||
@@ -183,12 +195,17 @@ describe("buildThreadTitlePrompt", () => {
|
||||
});
|
||||
|
||||
expect(result.prompt).toContain(
|
||||
"The user requested a new title based on the contents of this thread.",
|
||||
"Regenerate the title for an existing T3 Code thread so the user can recognize it weeks later.",
|
||||
);
|
||||
expect(result.prompt).toContain('The previous title was "Investigate reconnect regressions".');
|
||||
expect(result.prompt).toContain("better represents the current state of the thread");
|
||||
expect(result.prompt).toContain(
|
||||
"Capture the thread's intent, not a PR number or other superficial detail.",
|
||||
"Read the USER messages first. Identify the latest explicit durable goal.",
|
||||
);
|
||||
expect(result.prompt).toContain(
|
||||
"Do not promote one assistant finding into the thread subject unless the user adopts it as a new goal.",
|
||||
);
|
||||
expect(result.prompt).toContain(
|
||||
'A subagent-monitoring review that finds a Codex roster bug remains "Review Subagent Monitoring Risks,"',
|
||||
);
|
||||
expect(result.prompt).toContain("Thread contents:");
|
||||
expect(result.prompt).toContain("The remaining issue is stale session state");
|
||||
|
||||
@@ -152,23 +152,10 @@ interface PromptFromMessageInput {
|
||||
responseShape: string;
|
||||
rules: ReadonlyArray<string>;
|
||||
message: string;
|
||||
messageLabel?: string | undefined;
|
||||
preserveMessageEnd?: boolean | undefined;
|
||||
attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||
additionalInstructions?: string | undefined;
|
||||
}
|
||||
|
||||
function preserveMessageEnd(message: string): string {
|
||||
const alreadyTruncated = message.startsWith(EARLIER_CONTENT_TRUNCATION_MARKER);
|
||||
const contents = alreadyTruncated
|
||||
? message.slice(EARLIER_CONTENT_TRUNCATION_MARKER.length)
|
||||
: message;
|
||||
if (!alreadyTruncated && contents.length <= 8_000) {
|
||||
return contents;
|
||||
}
|
||||
return `${EARLIER_CONTENT_TRUNCATION_MARKER}${contents.slice(-8_000)}`;
|
||||
}
|
||||
|
||||
function buildPromptFromMessage(input: PromptFromMessageInput): string {
|
||||
const attachmentLines = (input.attachments ?? []).map(
|
||||
(attachment) => `- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
|
||||
@@ -180,10 +167,8 @@ function buildPromptFromMessage(input: PromptFromMessageInput): string {
|
||||
"Rules:",
|
||||
...input.rules.map((rule) => `- ${rule}`),
|
||||
"",
|
||||
`${input.messageLabel ?? "User message"}:`,
|
||||
input.preserveMessageEnd
|
||||
? preserveMessageEnd(input.message)
|
||||
: limitSection(input.message, 8_000),
|
||||
"User message:",
|
||||
limitSection(input.message, 8_000),
|
||||
...policyInstruction(input.additionalInstructions),
|
||||
];
|
||||
if (attachmentLines.length > 0) {
|
||||
@@ -229,42 +214,102 @@ export interface ThreadTitlePromptInput {
|
||||
policy?: TextGenerationPolicy | undefined;
|
||||
}
|
||||
|
||||
// Keep shared editorial rules in these two prompts in sync. Regeneration
|
||||
// intentionally adds guidance for thread history and the previous title.
|
||||
const INITIAL_THREAD_TITLE_PROMPT = `Generate a title that will help the user recognize this T3 Code thread weeks later.
|
||||
Return JSON with exactly one key: title.
|
||||
|
||||
Before answering, silently reduce the request to:
|
||||
- Subject: What system, feature, or problem is this really about?
|
||||
- Outcome: What does the user ultimately want to understand or change?
|
||||
- Incidental instructions: What only describes how the agent should do the work?
|
||||
|
||||
Title the subject and outcome. Discard incidental instructions.
|
||||
|
||||
Editorial rules:
|
||||
- 3-8 words, fewer than 40 characters.
|
||||
- Use a compact noun phrase or clear action phrase.
|
||||
- Capture the umbrella goal when the request lists several symptoms or steps.
|
||||
- Name the product change, not the mock, plan, report, branch, or PR used to produce it.
|
||||
- Models, subagents, tools, output formats, and monitoring instructions do not belong in the title unless they are themselves the topic.
|
||||
- For reviews, name what is being reviewed and the relevant concern. Avoid generic titles such as "Review PR 123" when linked or attached context reveals the subject.
|
||||
- For research, name the question domain rather than the requested research process.
|
||||
- Do not claim the work is complete.
|
||||
- Do not copy and truncate the user's message.
|
||||
- Avoid project names already visible in the UI, quotes, labels, filler, and trailing punctuation.
|
||||
- Use attached images as primary context for UI issues.
|
||||
- When a URL or attachment is the only source of the subject, use available tools to inspect it. If it cannot be resolved, remain accurate rather than guessing.`;
|
||||
|
||||
function regenerateThreadTitlePrompt(previousTitle: string): string {
|
||||
return `Regenerate the title for an existing T3 Code thread so the user can recognize it weeks later.
|
||||
The previous title was ${JSON.stringify(previousTitle)}.
|
||||
Return JSON with exactly one key: title.
|
||||
|
||||
Determine the title in this order:
|
||||
1. Read the USER messages first. Identify the latest explicit durable goal. The original subject remains the subject until the user clearly changes what the thread is about.
|
||||
2. Use ASSISTANT messages to resolve vague links, unnamed code, and discovered product nouns. Do not promote one assistant finding into the thread subject unless the user adopts it as a new goal.
|
||||
3. Compare that subject with the previous title. Preserve accurate scope words, especially when earlier content is truncated. Replace the previous title when it is generic, artifact-based, a completion update, or contradicted by the thread.
|
||||
4. Title the durable subject and desired outcome, not the current workflow state.
|
||||
|
||||
Editorial rules:
|
||||
- 3-8 words, fewer than 40 characters.
|
||||
- Use a compact noun phrase or clear action phrase.
|
||||
- Preserve the umbrella subject when later messages focus on one finding, provider, platform, or implementation detail.
|
||||
- A thread progressing through research, planning, implementation, review, CI, merge, and monitoring has usually not changed subjects.
|
||||
- Ignore deliverables and operations such as mocks, plans, HTML, branches, PRs, tests, CI, commits, merging, and monitoring unless they are the actual topic.
|
||||
- Models, subagents, tools, output formats, and monitoring instructions do not belong in the title unless they are themselves the topic.
|
||||
- Treat final operational follow-ups and assistant completion summaries as weak evidence of subject.
|
||||
- For reviews, name the reviewed feature or system and its durable concern, not one finding from the review.
|
||||
- For research, name the question domain rather than the research process.
|
||||
- Do not claim the work is complete.
|
||||
- Do not copy and truncate a thread message.
|
||||
- Avoid project names already visible in the UI, PR numbers, quotes, labels, filler, and trailing punctuation.
|
||||
- Use attached images as primary context for UI issues.
|
||||
- When a URL or attachment is the only source of the subject, use available tools to inspect it. If it cannot be resolved, remain accurate rather than guessing.
|
||||
- Return a meaningfully improved title, not a cosmetic paraphrase of the previous title.
|
||||
|
||||
Examples of the distinction:
|
||||
- A subagent-monitoring review that finds a Codex roster bug remains "Review Subagent Monitoring Risks," not "Codex Roster Bug Review."
|
||||
- A vague failing-test request later identified as a lazy thread-feed mismatch becomes "Fix Lazy Thread Feed Test," not "Prevent Mobile Feed Regressions."
|
||||
- A QR-sharing overhaul that ends with CI and merge work remains about QR sharing, not the PR lifecycle.`;
|
||||
}
|
||||
|
||||
function preserveMessageEnd(message: string): string {
|
||||
const alreadyTruncated = message.startsWith(EARLIER_CONTENT_TRUNCATION_MARKER);
|
||||
const contents = alreadyTruncated
|
||||
? message.slice(EARLIER_CONTENT_TRUNCATION_MARKER.length)
|
||||
: message;
|
||||
if (!alreadyTruncated && contents.length <= 8_000) {
|
||||
return contents;
|
||||
}
|
||||
return `${EARLIER_CONTENT_TRUNCATION_MARKER}${contents.slice(-8_000)}`;
|
||||
}
|
||||
|
||||
function threadTitlePromptSuffix(input: ThreadTitlePromptInput): string {
|
||||
const additionalInstructions = policyInstruction(input.policy?.threadTitleInstructions);
|
||||
const attachmentLines = (input.attachments ?? []).map(
|
||||
(attachment) => `- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
|
||||
);
|
||||
|
||||
let suffix = "";
|
||||
if (additionalInstructions.length > 0) {
|
||||
suffix = `\n${additionalInstructions.join("\n")}`;
|
||||
}
|
||||
if (attachmentLines.length > 0) {
|
||||
suffix += `\n\nAttachment metadata:\n${limitSection(attachmentLines.join("\n"), 4_000)}`;
|
||||
}
|
||||
return suffix;
|
||||
}
|
||||
|
||||
export function buildThreadTitlePrompt(input: ThreadTitlePromptInput) {
|
||||
const isRegeneration = input.previousTitle !== undefined;
|
||||
const prompt = buildPromptFromMessage({
|
||||
instruction: isRegeneration
|
||||
? [
|
||||
"You write concise thread titles for coding conversations.",
|
||||
"The user requested a new title based on the contents of this thread.",
|
||||
`The previous title was ${JSON.stringify(input.previousTitle)}.`,
|
||||
"Come up with a new title that better represents the current state of the thread.",
|
||||
].join("\n")
|
||||
: "You write concise thread titles for coding conversations.",
|
||||
responseShape: "Return a JSON object with key: title.",
|
||||
rules: [
|
||||
isRegeneration
|
||||
? "Title should summarize the thread's current state, not just its initial request."
|
||||
: "Title should summarize the user's request, not restate it verbatim.",
|
||||
...(isRegeneration
|
||||
? [
|
||||
"Capture the thread's intent, not a PR number or other superficial detail.",
|
||||
"Return a different title from the previous title.",
|
||||
]
|
||||
: []),
|
||||
"Keep it short and specific (3-8 words).",
|
||||
"Avoid quotes, filler, prefixes, and trailing punctuation.",
|
||||
"If images are attached, use them as primary context for visual/UI issues.",
|
||||
],
|
||||
message: input.message,
|
||||
...(isRegeneration
|
||||
? {
|
||||
messageLabel: "Thread contents",
|
||||
preserveMessageEnd: true,
|
||||
}
|
||||
: {}),
|
||||
attachments: input.attachments,
|
||||
additionalInstructions: input.policy?.threadTitleInstructions,
|
||||
});
|
||||
let prompt: string;
|
||||
if (input.previousTitle === undefined) {
|
||||
const message = limitSection(input.message, 8_000);
|
||||
prompt = `${INITIAL_THREAD_TITLE_PROMPT}\n\nUser message:\n${message}${threadTitlePromptSuffix(input)}`;
|
||||
} else {
|
||||
const message = preserveMessageEnd(input.message);
|
||||
prompt = `${regenerateThreadTitlePrompt(input.previousTitle)}\n\nThread contents:\n${message}${threadTitlePromptSuffix(input)}`;
|
||||
}
|
||||
const outputSchema = Schema.Struct({
|
||||
title: Schema.String,
|
||||
});
|
||||
|
||||
@@ -20,6 +20,8 @@ import {
|
||||
type VcsCreateWorktreeResult,
|
||||
type ReviewDiffPreviewInput,
|
||||
type ReviewDiffPreviewResult,
|
||||
type ReviewDiffFileContentsInput,
|
||||
type ReviewDiffFileContentsResult,
|
||||
type VcsInitInput,
|
||||
type VcsListRefsInput,
|
||||
type VcsListRefsResult,
|
||||
@@ -221,6 +223,9 @@ export class GitVcsDriver extends Context.Service<
|
||||
readonly getReviewDiffPreview: (
|
||||
input: ReviewDiffPreviewInput,
|
||||
) => Effect.Effect<ReviewDiffPreviewResult, GitCommandError>;
|
||||
readonly getReviewDiffFileContents: (
|
||||
input: ReviewDiffFileContentsInput,
|
||||
) => Effect.Effect<ReviewDiffFileContentsResult, GitCommandError>;
|
||||
readonly readConfigValue: (
|
||||
cwd: string,
|
||||
key: string,
|
||||
|
||||
@@ -14,7 +14,7 @@ import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { GitCommandError } from "@t3tools/contracts";
|
||||
import { GitCommandError, type ReviewDiffFileContentsInput } from "@t3tools/contracts";
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { makeGitVcsDriverCore, splitNullSeparatedGitStdoutPaths } from "./GitVcsDriverCore.ts";
|
||||
import * as GitVcsDriver from "./GitVcsDriver.ts";
|
||||
@@ -78,6 +78,20 @@ const writeTextFile = (
|
||||
yield* fileSystem.writeFileString(filePath, contents);
|
||||
});
|
||||
|
||||
const makeReviewDiffFileContentsInput = (
|
||||
cwd: string,
|
||||
overrides: Partial<Omit<ReviewDiffFileContentsInput, "cwd">> = {},
|
||||
): ReviewDiffFileContentsInput => ({
|
||||
cwd,
|
||||
sourceKind: "working-tree",
|
||||
changeType: "change",
|
||||
baseRef: "HEAD",
|
||||
headRef: null,
|
||||
oldPath: "README.md",
|
||||
newPath: "README.md",
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const git = (
|
||||
cwd: string,
|
||||
args: ReadonlyArray<string>,
|
||||
@@ -803,6 +817,107 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("loads full file contents for working-tree diff expansion", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(cwd);
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
const pathService = yield* Path.Path;
|
||||
yield* writeTextFile(cwd, "nested/.keep", "");
|
||||
yield* writeTextFile(cwd, "README.md", "# changed\nunchanged context\n");
|
||||
|
||||
const contents = yield* driver.getReviewDiffFileContents(
|
||||
makeReviewDiffFileContentsInput(pathService.join(cwd, "nested")),
|
||||
);
|
||||
|
||||
assert.strictEqual(contents.oldContents, "# test\n");
|
||||
assert.strictEqual(contents.newContents, "# changed\nunchanged context\n");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("attributes working-tree filesystem failures to the failing operation", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(cwd);
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
|
||||
const error = yield* driver
|
||||
.getReviewDiffFileContents(
|
||||
makeReviewDiffFileContentsInput(cwd, {
|
||||
changeType: "new",
|
||||
oldPath: "missing.ts",
|
||||
newPath: "missing.ts",
|
||||
}),
|
||||
)
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.deepInclude(error, {
|
||||
_tag: "GitCommandError",
|
||||
operation: "GitVcsDriver.getReviewDiffFileContents.workingTree.fs.realPath",
|
||||
command: "fs.realPath",
|
||||
cwd,
|
||||
detail: "Could not resolve diff file 'missing.ts'.",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("loads new and deleted files without reading their missing side", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(cwd);
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const pathService = yield* Path.Path;
|
||||
yield* writeTextFile(cwd, "added.ts", "export const added = true;\n");
|
||||
yield* fileSystem.remove(pathService.join(cwd, "README.md"));
|
||||
|
||||
const [added, deleted] = yield* Effect.all([
|
||||
driver.getReviewDiffFileContents(
|
||||
makeReviewDiffFileContentsInput(cwd, {
|
||||
changeType: "new",
|
||||
oldPath: "added.ts",
|
||||
newPath: "added.ts",
|
||||
}),
|
||||
),
|
||||
driver.getReviewDiffFileContents(
|
||||
makeReviewDiffFileContentsInput(cwd, { changeType: "deleted" }),
|
||||
),
|
||||
]);
|
||||
|
||||
assert.deepStrictEqual(added, {
|
||||
oldContents: "",
|
||||
newContents: "export const added = true;\n",
|
||||
});
|
||||
assert.deepStrictEqual(deleted, {
|
||||
oldContents: "# test\n",
|
||||
newContents: "",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("loads merge-base and head contents for branch diff expansion", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
const { initialBranch } = yield* initRepoWithCommit(cwd);
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
yield* git(cwd, ["checkout", "-b", "feature/context"]);
|
||||
yield* writeTextFile(cwd, "README.md", "# branch change\nunchanged context\n");
|
||||
yield* git(cwd, ["add", "README.md"]);
|
||||
yield* git(cwd, ["commit", "-m", "change readme"]);
|
||||
|
||||
const contents = yield* driver.getReviewDiffFileContents(
|
||||
makeReviewDiffFileContentsInput(cwd, {
|
||||
sourceKind: "branch-range",
|
||||
baseRef: initialBranch,
|
||||
headRef: "feature/context",
|
||||
}),
|
||||
);
|
||||
|
||||
assert.strictEqual(contents.oldContents, "# test\n");
|
||||
assert.strictEqual(contents.newContents, "# branch change\nunchanged context\n");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("repository status", () => {
|
||||
|
||||
@@ -21,6 +21,7 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
GitCommandError,
|
||||
type ReviewDiffFileContentsInput,
|
||||
type ReviewDiffPreviewInput,
|
||||
type ReviewDiffPreviewSource,
|
||||
type VcsRef,
|
||||
@@ -46,6 +47,7 @@ const RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES = 19_000;
|
||||
const RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES = 59_000;
|
||||
const REVIEW_DIFF_PATCH_MAX_OUTPUT_BYTES = 120_000;
|
||||
const REVIEW_UNTRACKED_DIFF_MAX_OUTPUT_BYTES = 80_000;
|
||||
const REVIEW_DIFF_FILE_MAX_OUTPUT_BYTES = 1024 * 1024;
|
||||
const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 120_000;
|
||||
const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
|
||||
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
|
||||
@@ -2270,6 +2272,163 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
};
|
||||
});
|
||||
|
||||
const reviewDiffFileError = (
|
||||
input: ReviewDiffFileContentsInput,
|
||||
detail: string,
|
||||
cause?: unknown,
|
||||
) =>
|
||||
new GitCommandError({
|
||||
operation: "GitVcsDriver.getReviewDiffFileContents",
|
||||
command: "git",
|
||||
cwd: input.cwd,
|
||||
detail,
|
||||
...(cause === undefined ? {} : { cause }),
|
||||
});
|
||||
|
||||
const isPathWithinRoot = (root: string, candidate: string) => {
|
||||
const relative = path.relative(root, candidate);
|
||||
return (
|
||||
relative === "" ||
|
||||
(relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
|
||||
);
|
||||
};
|
||||
|
||||
const readReviewFileAtRevision = Effect.fn("readReviewFileAtRevision")(function* (
|
||||
input: ReviewDiffFileContentsInput,
|
||||
revision: string,
|
||||
relativePath: string,
|
||||
) {
|
||||
const result = yield* executeGit(
|
||||
"GitVcsDriver.getReviewDiffFileContents.revision",
|
||||
input.cwd,
|
||||
["show", `${revision}:${relativePath}`],
|
||||
{ maxOutputBytes: REVIEW_DIFF_FILE_MAX_OUTPUT_BYTES },
|
||||
);
|
||||
if (result.stdout.includes("\0")) {
|
||||
return yield* reviewDiffFileError(input, `Cannot expand binary file '${relativePath}'.`);
|
||||
}
|
||||
return result.stdout;
|
||||
});
|
||||
|
||||
const readWorkingTreeReviewFile = Effect.fn("readWorkingTreeReviewFile")(function* (
|
||||
input: ReviewDiffFileContentsInput,
|
||||
repositoryRoot: string,
|
||||
) {
|
||||
const fileError = (stage: string, detail: string, cause?: unknown) =>
|
||||
new GitCommandError({
|
||||
operation: `GitVcsDriver.getReviewDiffFileContents.workingTree.${stage}`,
|
||||
command: stage,
|
||||
cwd: input.cwd,
|
||||
detail,
|
||||
...(cause === undefined ? {} : { cause }),
|
||||
});
|
||||
const requestedPath = path.resolve(repositoryRoot, input.newPath);
|
||||
if (!isPathWithinRoot(repositoryRoot, requestedPath)) {
|
||||
return yield* fileError(
|
||||
"path.resolve",
|
||||
`Diff file '${input.newPath}' resolves outside the review workspace.`,
|
||||
);
|
||||
}
|
||||
|
||||
const [realRepositoryRoot, realTarget] = yield* Effect.all([
|
||||
fileSystem.realPath(repositoryRoot),
|
||||
fileSystem.realPath(requestedPath),
|
||||
]).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
fileError("fs.realPath", `Could not resolve diff file '${input.newPath}'.`, cause),
|
||||
),
|
||||
);
|
||||
if (!isPathWithinRoot(realRepositoryRoot, realTarget)) {
|
||||
return yield* fileError(
|
||||
"fs.realPath",
|
||||
`Diff file '${input.newPath}' resolves outside the review workspace.`,
|
||||
);
|
||||
}
|
||||
|
||||
const info = yield* fileSystem
|
||||
.stat(realTarget)
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
fileError("fs.stat", `Could not inspect diff file '${input.newPath}'.`, cause),
|
||||
),
|
||||
);
|
||||
if (info.type !== "File") {
|
||||
return yield* fileError("fs.stat", `Diff path '${input.newPath}' is not a file.`);
|
||||
}
|
||||
if (info.size > BigInt(REVIEW_DIFF_FILE_MAX_OUTPUT_BYTES)) {
|
||||
return yield* fileError(
|
||||
"fs.stat",
|
||||
`Diff file '${input.newPath}' exceeds the 1 MB expansion limit.`,
|
||||
);
|
||||
}
|
||||
|
||||
const bytes = yield* fileSystem
|
||||
.readFile(realTarget)
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
fileError("fs.readFile", `Could not read diff file '${input.newPath}'.`, cause),
|
||||
),
|
||||
);
|
||||
if (bytes.includes(0)) {
|
||||
return yield* fileError("fs.readFile", `Cannot expand binary file '${input.newPath}'.`);
|
||||
}
|
||||
return new TextDecoder("utf-8").decode(bytes);
|
||||
});
|
||||
|
||||
const getReviewDiffFileContents = Effect.fn("getReviewDiffFileContents")(function* (
|
||||
input: ReviewDiffFileContentsInput,
|
||||
) {
|
||||
if (input.sourceKind === "working-tree") {
|
||||
const repositoryRoot = yield* runGitStdout(
|
||||
"GitVcsDriver.getReviewDiffFileContents.repositoryRoot",
|
||||
input.cwd,
|
||||
["rev-parse", "--show-toplevel"],
|
||||
).pipe(Effect.map((value) => value.trim()));
|
||||
if (repositoryRoot.length === 0) {
|
||||
return yield* reviewDiffFileError(input, "Could not resolve the Git repository root.");
|
||||
}
|
||||
const [oldContents, newContents] = yield* Effect.all(
|
||||
[
|
||||
input.changeType === "new"
|
||||
? Effect.succeed("")
|
||||
: readReviewFileAtRevision(input, input.baseRef ?? "HEAD", input.oldPath),
|
||||
input.changeType === "deleted"
|
||||
? Effect.succeed("")
|
||||
: readWorkingTreeReviewFile(input, repositoryRoot),
|
||||
],
|
||||
{ concurrency: 2 },
|
||||
);
|
||||
return { oldContents, newContents };
|
||||
}
|
||||
|
||||
if (!input.baseRef || !input.headRef) {
|
||||
return yield* reviewDiffFileError(
|
||||
input,
|
||||
"Branch diff file expansion requires both base and head refs.",
|
||||
);
|
||||
}
|
||||
const mergeBase = yield* runGitStdout(
|
||||
"GitVcsDriver.getReviewDiffFileContents.mergeBase",
|
||||
input.cwd,
|
||||
["merge-base", input.baseRef, input.headRef],
|
||||
).pipe(Effect.map((value) => value.trim()));
|
||||
if (mergeBase.length === 0) {
|
||||
return yield* reviewDiffFileError(input, "Could not resolve the branch comparison base.");
|
||||
}
|
||||
const [oldContents, newContents] = yield* Effect.all(
|
||||
[
|
||||
input.changeType === "new"
|
||||
? Effect.succeed("")
|
||||
: readReviewFileAtRevision(input, mergeBase, input.oldPath),
|
||||
input.changeType === "deleted"
|
||||
? Effect.succeed("")
|
||||
: readReviewFileAtRevision(input, input.headRef, input.newPath),
|
||||
],
|
||||
{ concurrency: 2 },
|
||||
);
|
||||
return { oldContents, newContents };
|
||||
});
|
||||
|
||||
const readConfigValue: GitVcsDriver.GitVcsDriver["Service"]["readConfigValue"] = (cwd, key) =>
|
||||
runGitStdout("GitVcsDriver.readConfigValue", cwd, ["config", "--get", key], true).pipe(
|
||||
Effect.map((stdout) => stdout.trim()),
|
||||
@@ -2903,6 +3062,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
pullCurrentBranch: (cwd) => withListRefsInvalidation(cwd, pullCurrentBranch(cwd)),
|
||||
readRangeContext,
|
||||
getReviewDiffPreview,
|
||||
getReviewDiffFileContents,
|
||||
readConfigValue,
|
||||
listRefs,
|
||||
createWorktree: (input) => withListRefsInvalidation(input.cwd, createWorktree(input)),
|
||||
|
||||
@@ -1854,6 +1854,12 @@ const makeWsRpcLayer = (
|
||||
observeRpcEffect(WS_METHODS.reviewGetDiffPreview, review.getDiffPreview(input), {
|
||||
"rpc.aggregate": "review",
|
||||
}),
|
||||
[WS_METHODS.reviewGetDiffFileContents]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.reviewGetDiffFileContents,
|
||||
review.getDiffFileContents(input),
|
||||
{ "rpc.aggregate": "review" },
|
||||
),
|
||||
[WS_METHODS.terminalOpen]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), {
|
||||
"rpc.aggregate": "terminal",
|
||||
|
||||
+1
-8
@@ -47,14 +47,7 @@
|
||||
body {
|
||||
background: #ffffff;
|
||||
color: #262626;
|
||||
font-family:
|
||||
"DM Sans Variable",
|
||||
"DM Sans",
|
||||
-apple-system,
|
||||
BlinkMacSystemFont,
|
||||
"Segoe UI",
|
||||
system-ui,
|
||||
sans-serif;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;
|
||||
}
|
||||
|
||||
html.dark body {
|
||||
|
||||
@@ -20,8 +20,6 @@
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@effect/atom-react": "catalog:",
|
||||
"@fontsource-variable/dm-sans": "^5.2.8",
|
||||
"@fontsource/jetbrains-mono": "^5.2.8",
|
||||
"@formkit/auto-animate": "^0.9.0",
|
||||
"@legendapp/list": "3.2.0",
|
||||
"@lexical/react": "^0.41.0",
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
clampCodeFontSize,
|
||||
clampInterfaceFontSize,
|
||||
clampPromptFontSize,
|
||||
DEFAULT_CODE_FONT_STACK,
|
||||
DEFAULT_SANS_FONT_STACK,
|
||||
appearanceFontStack,
|
||||
cssFontFamilies,
|
||||
resolveDefaultFamilyLabel,
|
||||
} from "./appearanceFonts";
|
||||
|
||||
describe("cssFontFamilies", () => {
|
||||
it("returns null for effectively empty input", () => {
|
||||
expect(cssFontFamilies("")).toBeNull();
|
||||
expect(cssFontFamilies(" ")).toBeNull();
|
||||
expect(cssFontFamilies(" , , ")).toBeNull();
|
||||
});
|
||||
|
||||
it("quotes names with spaces and keeps single idents bare", () => {
|
||||
expect(cssFontFamilies("Fira Code")).toBe('"Fira Code"');
|
||||
expect(cssFontFamilies("monospace")).toBe("monospace");
|
||||
expect(cssFontFamilies('"Comic Mono"')).toBe('"Comic Mono"');
|
||||
});
|
||||
|
||||
it("normalizes comma-separated lists and strips embedded quotes", () => {
|
||||
expect(cssFontFamilies(" Fira Code , Menlo ")).toBe('"Fira Code", Menlo');
|
||||
expect(cssFontFamilies('Bad"Name')).toBe('"BadName"');
|
||||
});
|
||||
|
||||
it("quotes names that are not single CSS idents", () => {
|
||||
expect(cssFontFamilies("3270 Nerd Font")).toBe('"3270 Nerd Font"');
|
||||
expect(cssFontFamilies("M+ 1m")).toBe('"M+ 1m"');
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveDefaultFamilyLabel", () => {
|
||||
it("skips generic keywords and returns null for a stack of only generics", () => {
|
||||
expect(resolveDefaultFamilyLabel("system-ui, sans-serif")).toBeNull();
|
||||
expect(resolveDefaultFamilyLabel("ui-monospace, monospace")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("appearanceFontStack", () => {
|
||||
it("prepends the custom family to the default stack", () => {
|
||||
expect(appearanceFontStack("Fira Code", DEFAULT_CODE_FONT_STACK)).toBe(
|
||||
`"Fira Code", ${DEFAULT_CODE_FONT_STACK}`,
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to the default stack when unset", () => {
|
||||
expect(appearanceFontStack("", DEFAULT_SANS_FONT_STACK)).toBe(DEFAULT_SANS_FONT_STACK);
|
||||
});
|
||||
});
|
||||
|
||||
describe("font size clamping", () => {
|
||||
it("keeps sizes inside the ranges the UI can absorb", () => {
|
||||
expect(clampInterfaceFontSize(16)).toBe(16);
|
||||
expect(clampInterfaceFontSize(2)).toBe(12);
|
||||
expect(clampInterfaceFontSize(96)).toBe(20);
|
||||
expect(clampPromptFontSize(40)).toBe(20);
|
||||
expect(clampCodeFontSize(1)).toBe(10);
|
||||
});
|
||||
|
||||
it("rounds fractional values and falls back for unusable input", () => {
|
||||
expect(clampCodeFontSize(13.4)).toBe(13);
|
||||
expect(clampInterfaceFontSize(Number.NaN)).toBe(16);
|
||||
expect(clampPromptFontSize(Number.POSITIVE_INFINITY)).toBe(14);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,352 @@
|
||||
/**
|
||||
* Font preferences from Settings → Appearance, applied as CSS custom
|
||||
* properties. The default stacks mirror the `--font-sans` / `--font-mono`
|
||||
* definitions in `index.css`; a custom family is always prepended to the
|
||||
* matching default stack so glyph coverage never regresses.
|
||||
*/
|
||||
|
||||
import {
|
||||
DEFAULT_CODE_FONT_SIZE,
|
||||
DEFAULT_INTERFACE_FONT_SIZE,
|
||||
DEFAULT_PROMPT_FONT_SIZE,
|
||||
MAX_CODE_FONT_SIZE,
|
||||
MAX_INTERFACE_FONT_SIZE,
|
||||
MAX_PROMPT_FONT_SIZE,
|
||||
MIN_CODE_FONT_SIZE,
|
||||
MIN_INTERFACE_FONT_SIZE,
|
||||
MIN_PROMPT_FONT_SIZE,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
export const DEFAULT_SANS_FONT_STACK =
|
||||
'-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif';
|
||||
|
||||
// Concrete names first: some engines alias `ui-monospace` to the
|
||||
// proportional system UI font, which would break every code surface.
|
||||
export const DEFAULT_CODE_FONT_STACK =
|
||||
'"SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace';
|
||||
|
||||
function quoteFontFamilyName(name: string): string {
|
||||
const bare = name.trim();
|
||||
if (bare.length === 0) return "";
|
||||
// Already quoted, or a single ident that needs no quoting.
|
||||
if (/^(['"]).*\1$/.test(bare)) return bare;
|
||||
if (/^[a-zA-Z][a-zA-Z0-9-]*$/.test(bare)) return bare;
|
||||
return `"${bare.replaceAll('"', "")}"`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a user-entered family (single name or comma-separated list) into a
|
||||
* safe CSS font-family list, or null when the input is effectively empty.
|
||||
*/
|
||||
export function cssFontFamilies(input: string): string | null {
|
||||
const families = input
|
||||
.split(",")
|
||||
.map(quoteFontFamilyName)
|
||||
.filter((name) => name.length > 0);
|
||||
return families.length > 0 ? families.join(", ") : null;
|
||||
}
|
||||
|
||||
/** The full stack a preference resolves to: custom families before the default. */
|
||||
export function appearanceFontStack(custom: string, defaultStack: string): string {
|
||||
const families = cssFontFamilies(custom);
|
||||
return families === null ? defaultStack : `${families}, ${defaultStack}`;
|
||||
}
|
||||
|
||||
export interface AppearanceFontPreferences {
|
||||
readonly sans: string;
|
||||
readonly code: string;
|
||||
readonly composer: string;
|
||||
readonly sizeInterface: number;
|
||||
readonly sizePrompt: number;
|
||||
readonly sizeCode: number;
|
||||
/** Grayscale `antialiased` rendering; false keeps the heavier platform default. */
|
||||
readonly smoothing: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply the preferences to the root element. Unset families remove the
|
||||
* override so the stylesheet defaults (and theme changes) stay in charge.
|
||||
*
|
||||
* Sizes are always written: the interface size drives the root font size (and
|
||||
* with it every rem-based dimension), while the prompt and code sizes stay in
|
||||
* absolute pixels so they do not scale twice.
|
||||
*/
|
||||
export function applyAppearanceFontVariables(
|
||||
root: HTMLElement,
|
||||
preferences: AppearanceFontPreferences,
|
||||
): void {
|
||||
const families: ReadonlyArray<readonly [variable: string, custom: string, fallback: string]> = [
|
||||
["--font-sans", preferences.sans, DEFAULT_SANS_FONT_STACK],
|
||||
["--font-mono", preferences.code, DEFAULT_CODE_FONT_STACK],
|
||||
// The composer falls back to whatever the sans preference resolves to.
|
||||
["--font-composer", preferences.composer, "var(--font-sans)"],
|
||||
];
|
||||
for (const [variable, custom, fallback] of families) {
|
||||
const list = cssFontFamilies(custom);
|
||||
if (list === null) {
|
||||
root.style.removeProperty(variable);
|
||||
} else {
|
||||
root.style.setProperty(variable, `${list}, ${fallback}`);
|
||||
}
|
||||
}
|
||||
|
||||
root.style.fontSize = `${clampInterfaceFontSize(preferences.sizeInterface)}px`;
|
||||
root.style.setProperty("--font-size-prompt", `${clampPromptFontSize(preferences.sizePrompt)}px`);
|
||||
const code = clampCodeFontSize(preferences.sizeCode);
|
||||
root.style.setProperty("--font-size-code", `${code}px`);
|
||||
// The @pierre/diffs surfaces read their own hook for code text.
|
||||
root.style.setProperty("--diffs-font-size", `${code}px`);
|
||||
|
||||
// Inherited from the root; only macOS engines honor the property, so no
|
||||
// platform gate is needed here. Smoothing on means grayscale `antialiased`
|
||||
// (thinner strokes); off restores the platform default, which macOS renders
|
||||
// with heavier stem darkening.
|
||||
if (preferences.smoothing) {
|
||||
root.style.setProperty("-webkit-font-smoothing", "antialiased");
|
||||
} else {
|
||||
root.style.removeProperty("-webkit-font-smoothing");
|
||||
}
|
||||
}
|
||||
|
||||
function clampFontSize(value: number, minimum: number, maximum: number, fallback: number): number {
|
||||
if (!Number.isFinite(value)) return fallback;
|
||||
return Math.min(maximum, Math.max(minimum, Math.round(value)));
|
||||
}
|
||||
|
||||
export function clampInterfaceFontSize(value: number): number {
|
||||
return clampFontSize(
|
||||
value,
|
||||
MIN_INTERFACE_FONT_SIZE,
|
||||
MAX_INTERFACE_FONT_SIZE,
|
||||
DEFAULT_INTERFACE_FONT_SIZE,
|
||||
);
|
||||
}
|
||||
|
||||
export function clampPromptFontSize(value: number): number {
|
||||
return clampFontSize(value, MIN_PROMPT_FONT_SIZE, MAX_PROMPT_FONT_SIZE, DEFAULT_PROMPT_FONT_SIZE);
|
||||
}
|
||||
|
||||
export function clampCodeFontSize(value: number): number {
|
||||
return clampFontSize(value, MIN_CODE_FONT_SIZE, MAX_CODE_FONT_SIZE, DEFAULT_CODE_FONT_SIZE);
|
||||
}
|
||||
|
||||
const FONT_PROBE_TEXT = "mmmmmmmmMMWli1O0@# fjord";
|
||||
let fontProbeContext: CanvasRenderingContext2D | null | undefined;
|
||||
|
||||
function probeWidth(fontList: string): number | null {
|
||||
if (fontProbeContext === undefined) {
|
||||
fontProbeContext = document.createElement("canvas").getContext("2d");
|
||||
}
|
||||
if (fontProbeContext === null) return null;
|
||||
fontProbeContext.font = `16px ${fontList}`;
|
||||
return fontProbeContext.measureText(FONT_PROBE_TEXT).width;
|
||||
}
|
||||
|
||||
/**
|
||||
* Canvas metric probing instead of document.fonts.check(): check() reports
|
||||
* true for families that are not installed at all (nothing needs loading), so
|
||||
* it cannot filter the dropdown. A family exists when falling back to at
|
||||
* least one generic changes the measured advance.
|
||||
*/
|
||||
export function isFontFamilyAvailable(family: string): boolean {
|
||||
const families = cssFontFamilies(family);
|
||||
if (families === null) return false;
|
||||
if (/^(system-ui|sans-serif|serif|monospace|ui-monospace)$/i.test(families)) return true;
|
||||
try {
|
||||
for (const generic of ["monospace", "serif", "sans-serif"]) {
|
||||
const baseline = probeWidth(generic);
|
||||
const candidate = probeWidth(`${families}, ${generic}`);
|
||||
if (baseline === null || candidate === null) return false;
|
||||
if (candidate !== baseline) return true;
|
||||
}
|
||||
return false;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a family renders every character on the same advance. Cell-grid
|
||||
* surfaces (the terminal) require this: a proportional face draws its text
|
||||
* narrower than the lattice the cursor and selection are placed on, which
|
||||
* reads as ragged gaps and a cursor stranded to the right of the text.
|
||||
*
|
||||
* Unmeasurable environments answer true, so a missing canvas never blocks a
|
||||
* legitimate font.
|
||||
*/
|
||||
export function isMonospaceFamily(family: string): boolean {
|
||||
const families = cssFontFamilies(family);
|
||||
if (families === null) return true;
|
||||
try {
|
||||
if (fontProbeContext === undefined) {
|
||||
fontProbeContext = document.createElement("canvas").getContext("2d");
|
||||
}
|
||||
if (fontProbeContext === null) return true;
|
||||
// Fall back to a generic mono so an absent face measures as monospace and
|
||||
// is left for the normal fallback chain to resolve.
|
||||
fontProbeContext.font = `32px ${families}, monospace`;
|
||||
const narrow = fontProbeContext.measureText("i").width;
|
||||
const wide = fontProbeContext.measureText("M").width;
|
||||
if (!Number.isFinite(narrow) || !Number.isFinite(wide) || wide === 0) return true;
|
||||
return Math.abs(wide - narrow) < 0.5;
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Nameable faces the platform generics commonly map to, likeliest first.
|
||||
// Pixel-comparing a generic against these names the actual face; Apple's own
|
||||
// UI fonts are deliberately not CSS-nameable, so a miss on an Apple platform
|
||||
// identifies San Francisco itself.
|
||||
const SANS_GENERIC_CANDIDATES = [
|
||||
"Segoe UI",
|
||||
"Roboto",
|
||||
"Noto Sans",
|
||||
"Ubuntu",
|
||||
"Cantarell",
|
||||
"DejaVu Sans",
|
||||
"Liberation Sans",
|
||||
"Helvetica Neue",
|
||||
"Arial",
|
||||
] as const;
|
||||
const MONO_GENERIC_CANDIDATES = [
|
||||
"Menlo",
|
||||
"Consolas",
|
||||
"Cascadia Mono",
|
||||
"DejaVu Sans Mono",
|
||||
"Ubuntu Mono",
|
||||
"Liberation Mono",
|
||||
"Noto Sans Mono",
|
||||
"Roboto Mono",
|
||||
"Monaco",
|
||||
"Courier New",
|
||||
] as const;
|
||||
|
||||
const GENERIC_PROBE_TEXT = "RagIl10O@ fjord quiz";
|
||||
|
||||
/**
|
||||
* Advance width of the probe text laid out by the DOM - not canvas, whose
|
||||
* generic-family mapping diverges from real rendering (this engine draws
|
||||
* `ui-monospace` as the proportional UI font on canvas but not in CSS).
|
||||
* Identical widths at this size mean the same face for practical purposes.
|
||||
*/
|
||||
function measureDomProbeWidth(fontFamily: string): number | null {
|
||||
try {
|
||||
const body = document.body;
|
||||
if (!body) return null;
|
||||
const span = document.createElement("span");
|
||||
span.style.cssText =
|
||||
"position:absolute;left:-9999px;top:0;visibility:hidden;white-space:pre;font-size:100px;";
|
||||
span.style.fontFamily = fontFamily;
|
||||
span.textContent = GENERIC_PROBE_TEXT;
|
||||
body.appendChild(span);
|
||||
const width = span.getBoundingClientRect().width;
|
||||
span.remove();
|
||||
return width > 0 ? width : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function widthsMatch(left: number, right: number): boolean {
|
||||
return Math.abs(left - right) < 0.01;
|
||||
}
|
||||
|
||||
/**
|
||||
* Name the concrete face a generic keyword renders as, by measuring the
|
||||
* generic against nameable candidates. Null when the face cannot be
|
||||
* identified (and the platform gives no definitional answer).
|
||||
*/
|
||||
function resolveGenericFamilyLabel(generic: string): string | null {
|
||||
const lower = generic.toLowerCase();
|
||||
if (lower === "serif") return null;
|
||||
const monoLike = lower === "ui-monospace" || lower === "monospace";
|
||||
const genericWidth = measureDomProbeWidth(generic);
|
||||
if (genericWidth === null) return null;
|
||||
for (const candidate of monoLike ? MONO_GENERIC_CANDIDATES : SANS_GENERIC_CANDIDATES) {
|
||||
if (!isFontFamilyAvailable(candidate)) continue;
|
||||
const candidateWidth = measureDomProbeWidth(`"${candidate}"`);
|
||||
if (candidateWidth !== null && widthsMatch(genericWidth, candidateWidth)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
// No nameable face matched; on Apple platforms that means one of the San
|
||||
// Francisco faces, which CSS cannot name. Comparing against -apple-system
|
||||
// tells the UI face apart from SF Mono.
|
||||
if (/mac|iphone|ipad|ipod/i.test(navigator.platform)) {
|
||||
const systemWidth = measureDomProbeWidth("-apple-system");
|
||||
if (systemWidth !== null && widthsMatch(genericWidth, systemWidth)) return "SF Pro";
|
||||
return monoLike ? "SF Mono" : "SF Pro";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The first family of a default stack that will actually render - what the
|
||||
* "Default" choice means on this machine. Concrete names are probed for
|
||||
* availability; generic keywords are resolved to the face they draw with
|
||||
* where identifiable. Null when nothing can be named.
|
||||
*/
|
||||
export function resolveDefaultFamilyLabel(stack: string): string | null {
|
||||
for (const raw of stack.split(",")) {
|
||||
const family = raw.trim().replace(/^(['"])(.*)\1$/, "$2");
|
||||
if (family.length === 0) continue;
|
||||
if (
|
||||
/^(system-ui|sans-serif|serif|monospace|ui-monospace|-apple-system|BlinkMacSystemFont)$/i.test(
|
||||
family,
|
||||
)
|
||||
) {
|
||||
const resolved = resolveGenericFamilyLabel(family);
|
||||
if (resolved !== null) return resolved;
|
||||
continue;
|
||||
}
|
||||
if (isFontFamilyAvailable(family)) return family;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface InstalledFontFamiliesResult {
|
||||
readonly families: readonly string[];
|
||||
/**
|
||||
* "unsupported" - the engine has no Local Font Access API (Safari,
|
||||
* Firefox); "denied" - the API exists but the user declined the permission
|
||||
* prompt. Both fall back to the curated catalog.
|
||||
*/
|
||||
readonly status: "granted" | "denied" | "unsupported";
|
||||
}
|
||||
|
||||
let installedFamiliesCache: InstalledFontFamiliesResult | null = null;
|
||||
|
||||
/**
|
||||
* Every installed family via the Local Font Access API (Chromium and
|
||||
* Electron). Call from a user gesture: the first call raises the browser's
|
||||
* local-fonts permission prompt. A denial is not cached, so reopening the
|
||||
* picker can ask again after the user changes the site setting.
|
||||
*/
|
||||
export async function queryInstalledFontFamilies(): Promise<InstalledFontFamiliesResult> {
|
||||
if (installedFamiliesCache !== null) return installedFamiliesCache;
|
||||
const query = (
|
||||
window as Window & {
|
||||
queryLocalFonts?: () => Promise<ReadonlyArray<{ readonly family: string }>>;
|
||||
}
|
||||
).queryLocalFonts;
|
||||
if (typeof query !== "function") {
|
||||
installedFamiliesCache = { families: [], status: "unsupported" };
|
||||
return installedFamiliesCache;
|
||||
}
|
||||
try {
|
||||
const fonts = await query.call(window);
|
||||
const families = [...new Set(fonts.map((font) => font.family))]
|
||||
// Dot-prefixed families are macOS-internal UI faces; selecting one is
|
||||
// never intended and most refuse to render for web content anyway.
|
||||
.filter((family) => !family.startsWith("."))
|
||||
.sort((left, right) => left.localeCompare(right));
|
||||
// A denied permission check resolves with an empty list instead of
|
||||
// throwing; no machine has zero fonts, so treat empty as denied.
|
||||
if (families.length === 0) return { families: [], status: "denied" };
|
||||
installedFamiliesCache = { families, status: "granted" };
|
||||
return installedFamiliesCache;
|
||||
} catch {
|
||||
return { families: [], status: "denied" };
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
HistoryIcon,
|
||||
MonitorIcon,
|
||||
} from "lucide-react";
|
||||
import { memo, useCallback, useMemo } from "react";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
|
||||
import { useProject, useThread, useThreadShellsForProjectRefs } from "../state/entities";
|
||||
@@ -214,6 +214,98 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Collapse the strip's labels to icons only when the text no longer fits.
|
||||
*
|
||||
* Hidden labels stay measurable (they collapse to invisible absolute boxes,
|
||||
* which keep their natural width), so the required width can be recomputed in
|
||||
* either state on every pass - no remembered widths that could go stale or
|
||||
* latch the strip compact. A small hysteresis keeps the boundary from
|
||||
* flapping between states.
|
||||
*/
|
||||
const COMPACT_EXPAND_HYSTERESIS_PX = 16;
|
||||
|
||||
function useLabelsOverflow(element: HTMLDivElement | null): boolean {
|
||||
const [overflows, setOverflows] = useState(false);
|
||||
// A render-synced mirror instead of useEffectEvent: the compiler memoizes
|
||||
// the event callback, which left observers reading the first render's null
|
||||
// element forever.
|
||||
const stateRef = useRef({ element, overflows });
|
||||
stateRef.current = { element, overflows };
|
||||
|
||||
const measure = useCallback(() => {
|
||||
const { element: current, overflows: compact } = stateRef.current;
|
||||
if (!current) return;
|
||||
const available = current.clientWidth;
|
||||
if (available === 0) return;
|
||||
// flex-1 stretches the groups to fill the strip, so their own boxes always
|
||||
// measure "full". Sum the laid-out content instead, skipping hidden form
|
||||
// artifacts and absolutely-positioned nodes (the compact-hidden labels).
|
||||
const contentWidth = (parent: Element): number => {
|
||||
const gap = Number.parseFloat(getComputedStyle(parent).columnGap) || 0;
|
||||
let width = 0;
|
||||
let counted = 0;
|
||||
for (const child of parent.children) {
|
||||
if (!(child instanceof HTMLElement)) continue;
|
||||
if (child.offsetWidth <= 1) continue;
|
||||
const position = getComputedStyle(child).position;
|
||||
if (position === "absolute" || position === "fixed") continue;
|
||||
width += child.offsetWidth;
|
||||
counted += 1;
|
||||
}
|
||||
return width + gap * Math.max(0, counted - 1);
|
||||
};
|
||||
const stripGap = Number.parseFloat(getComputedStyle(current).columnGap) || 0;
|
||||
let needed = 0;
|
||||
let groups = 0;
|
||||
for (const child of current.children) {
|
||||
if (!(child instanceof HTMLElement) || child.offsetWidth <= 1) continue;
|
||||
needed += contentWidth(child);
|
||||
groups += 1;
|
||||
}
|
||||
needed += stripGap * Math.max(0, groups - 1);
|
||||
for (const label of current.querySelectorAll<HTMLElement>("[data-composer-label]")) {
|
||||
// The clipping can happen below the marker (SelectValue truncates
|
||||
// internally), where the outer span's scrollWidth matches its clipped
|
||||
// box. The text's real width is the largest scrollWidth in the subtree.
|
||||
let textWidth = label.scrollWidth;
|
||||
for (const inner of label.querySelectorAll<HTMLElement>("*")) {
|
||||
textWidth = Math.max(textWidth, inner.scrollWidth);
|
||||
}
|
||||
if (compact) {
|
||||
// Compact: the label is squeezed to zero width but keeps reporting
|
||||
// the full width it would need when expanded.
|
||||
needed += textWidth;
|
||||
} else {
|
||||
// Expanded: the label is in flow; only the clipped remainder is
|
||||
// missing from the content sum.
|
||||
needed += Math.max(0, textWidth - label.clientWidth);
|
||||
}
|
||||
}
|
||||
setOverflows(compact ? needed > available - COMPACT_EXPAND_HYSTERESIS_PX : needed > available);
|
||||
}, []);
|
||||
|
||||
// Label widths can change without the strip box moving (font family or
|
||||
// size preferences), so re-measure on every render as well as on resize
|
||||
// and font loads.
|
||||
useEffect(() => {
|
||||
measure();
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!element) return;
|
||||
const observer = new ResizeObserver(measure);
|
||||
observer.observe(element);
|
||||
document.fonts.addEventListener("loadingdone", measure);
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
document.fonts.removeEventListener("loadingdone", measure);
|
||||
};
|
||||
}, [element, measure]);
|
||||
|
||||
return overflows;
|
||||
}
|
||||
|
||||
export const BranchToolbar = memo(function BranchToolbar({
|
||||
environmentId,
|
||||
threadId,
|
||||
@@ -300,11 +392,17 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
canPickEnvironment: showEnvironmentPicker,
|
||||
});
|
||||
const isMobile = useIsMobile();
|
||||
const [stripElement, setStripElement] = useState<HTMLDivElement | null>(null);
|
||||
const labelsOverflow = useLabelsOverflow(stripElement);
|
||||
|
||||
if (!hasActiveThread || !activeProject) return null;
|
||||
|
||||
return (
|
||||
<div className="chat-composer-context-strip -mt-4 mx-auto flex w-[calc(100%-2.75rem)] max-w-[calc(48rem-2.75rem)] items-center gap-2 ps-1 pe-2 pt-5 pb-1">
|
||||
<div
|
||||
ref={setStripElement}
|
||||
data-compact={labelsOverflow ? "" : undefined}
|
||||
className="chat-composer-context-strip group/composer-context -mt-4 mx-auto flex w-[calc(100%-2.75rem)] max-w-[calc(48rem-2.75rem)] items-center gap-2 ps-1 pe-2 pt-5 pb-1"
|
||||
>
|
||||
{isMobile ? (
|
||||
<MobileRunContextSelector
|
||||
envLocked={envLocked}
|
||||
|
||||
@@ -749,7 +749,12 @@ export function BranchToolbarBranchSelector({
|
||||
disabled={isInitialBranchesLoadPending || isBranchActionPending}
|
||||
>
|
||||
<GitBranchIcon className="size-3 shrink-0 opacity-70" />
|
||||
<span className="min-w-0 max-w-[240px] truncate">{triggerLabel}</span>
|
||||
<span
|
||||
data-composer-label
|
||||
className="min-w-0 max-w-[240px] truncate transition-[max-width,opacity] duration-300 ease-out group-data-[compact]/composer-context:max-w-0 group-data-[compact]/composer-context:opacity-0"
|
||||
>
|
||||
{triggerLabel}
|
||||
</span>
|
||||
<ChevronDownIcon className="size-3 shrink-0 opacity-50" />
|
||||
</ComboboxTrigger>
|
||||
</span>
|
||||
|
||||
@@ -82,7 +82,7 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
|
||||
<SelectTrigger
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
className="shrink-0 font-medium"
|
||||
className="min-w-0 shrink font-medium"
|
||||
aria-label="Workspace"
|
||||
>
|
||||
{effectiveEnvMode === "worktree" ? (
|
||||
@@ -92,7 +92,12 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
|
||||
) : (
|
||||
<FolderIcon className="size-3" />
|
||||
)}
|
||||
<SelectValue />
|
||||
<span
|
||||
data-composer-label
|
||||
className="min-w-0 max-w-[240px] truncate transition-[max-width,opacity] duration-300 ease-out group-data-[compact]/composer-context:max-w-0 group-data-[compact]/composer-context:opacity-0"
|
||||
>
|
||||
<SelectValue />
|
||||
</span>
|
||||
</SelectTrigger>
|
||||
<SelectPopup>
|
||||
<SelectGroup>
|
||||
|
||||
@@ -49,7 +49,12 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
|
||||
) : (
|
||||
<CloudIcon className="size-3 shrink-0" />
|
||||
)}
|
||||
<span className="truncate">{activeEnvironment?.label ?? "Run on"}</span>
|
||||
<span
|
||||
data-composer-label
|
||||
className="min-w-0 max-w-[240px] truncate transition-[max-width,opacity] duration-300 ease-out group-data-[compact]/composer-context:max-w-0 group-data-[compact]/composer-context:opacity-0"
|
||||
>
|
||||
{activeEnvironment?.label ?? "Run on"}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -72,7 +77,12 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
|
||||
) : (
|
||||
<CloudIcon className="size-3 shrink-0" />
|
||||
)}
|
||||
<SelectValue />
|
||||
<span
|
||||
data-composer-label
|
||||
className="min-w-0 max-w-[240px] truncate transition-[max-width,opacity] duration-300 ease-out group-data-[compact]/composer-context:max-w-0 group-data-[compact]/composer-context:opacity-0"
|
||||
>
|
||||
<SelectValue />
|
||||
</span>
|
||||
</SelectTrigger>
|
||||
<SelectPopup>
|
||||
<SelectGroup>
|
||||
|
||||
@@ -1363,6 +1363,9 @@ function ChatMarkdown({
|
||||
},
|
||||
[createAssetUrl, openPreview, preparedConnection, threadRef],
|
||||
);
|
||||
/* eslint-disable react/no-unstable-nested-components -- ReactMarkdown requires component
|
||||
* renderers that close over this message's metadata. useMemo keeps them stable until that
|
||||
* metadata changes. */
|
||||
const markdownComponents = useMemo<Components>(() => {
|
||||
const fileLinkChip = (
|
||||
fileLinkMeta: MarkdownFileLinkMeta,
|
||||
@@ -1593,6 +1596,7 @@ function ChatMarkdown({
|
||||
text,
|
||||
threadRef,
|
||||
]);
|
||||
/* eslint-enable react/no-unstable-nested-components */
|
||||
|
||||
return (
|
||||
<div
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
type ProjectScript,
|
||||
type ProjectId,
|
||||
type ProviderApprovalDecision,
|
||||
type PreviewAnnotationPayload,
|
||||
ProviderInstanceId,
|
||||
type ServerProvider,
|
||||
type ResolvedKeybindingsConfig,
|
||||
@@ -298,10 +299,12 @@ import {
|
||||
} from "./ui/alert-dialog";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
import { ServerUpdateAction, ServerUpdateProgress } from "./ServerUpdateAction";
|
||||
import { APP_STAGE_LABEL, APP_VERSION } from "../branding";
|
||||
import {
|
||||
buildVersionMismatchDismissalKey,
|
||||
dismissVersionMismatch,
|
||||
isVersionMismatchDismissed,
|
||||
resolveCompatibilityChannelMismatch,
|
||||
resolveServerConfigVersionMismatch,
|
||||
resolveServerSelfUpdateCapability,
|
||||
serverUpdateGuidance,
|
||||
@@ -1907,6 +1910,14 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
unavailableConnection !== null &&
|
||||
(unavailableConnection.phase === "connecting" ||
|
||||
unavailableConnection.phase === "reconnecting");
|
||||
const compatibilityChannelMismatch =
|
||||
unavailableConnection?.blockedReason === "unsupported"
|
||||
? resolveCompatibilityChannelMismatch({
|
||||
clientVersion: APP_VERSION,
|
||||
clientStageLabel: APP_STAGE_LABEL,
|
||||
serverVersion: unavailableConnection.serverVersion,
|
||||
})
|
||||
: null;
|
||||
// Reconnecting to a version-skewed server with no update in flight
|
||||
// usually means the server is restarting mid-update and a refresh wiped
|
||||
// the in-memory update state. Fold the reconnect and version banners
|
||||
@@ -1933,6 +1944,59 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
title: `${unavailableConnection.phase === "connecting" ? "Connecting" : "Reconnecting"} to ${activeEnvironmentUnavailableState.label}`,
|
||||
description: "It may be finishing an update. One moment.",
|
||||
});
|
||||
} else if (compatibilityChannelMismatch) {
|
||||
items.push({
|
||||
id: `environment-unavailable:${activeEnvironmentUnavailableState.environmentId}`,
|
||||
variant: "error",
|
||||
icon: <TriangleAlertIcon />,
|
||||
title: "Client and server channels differ",
|
||||
description: (
|
||||
<div className="mt-1 min-w-0 space-y-2">
|
||||
<p>
|
||||
{compatibilityChannelMismatch.newerSide === "server"
|
||||
? `This client is older. Update it to match the ${compatibilityChannelMismatch.serverChannel} server.`
|
||||
: compatibilityChannelMismatch.newerSide === "client"
|
||||
? `The server is older. Update it to match this ${compatibilityChannelMismatch.clientChannel} client.`
|
||||
: "Pick Stable or Nightly for both installations."}
|
||||
</p>
|
||||
<div className="grid grid-cols-[3rem_minmax(0,1fr)_auto] gap-x-3 gap-y-1.5 border-y border-current/15 py-2 text-xs">
|
||||
<span className="text-muted-foreground">Client</span>
|
||||
<code className="truncate text-foreground">
|
||||
{compatibilityChannelMismatch.clientVersion}
|
||||
</code>
|
||||
<span className="font-medium text-foreground">
|
||||
{compatibilityChannelMismatch.clientChannel}
|
||||
</span>
|
||||
<span className="text-muted-foreground">Server</span>
|
||||
<code className="truncate text-foreground">
|
||||
{compatibilityChannelMismatch.serverVersion}
|
||||
</code>
|
||||
<span className="font-medium text-foreground">
|
||||
{compatibilityChannelMismatch.serverChannel}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
actions: (
|
||||
<>
|
||||
{compatibilityChannelMismatch.newerSide === "client" ? (
|
||||
<ServerUpdateAction
|
||||
environmentId={activeEnvironmentUnavailableState.environmentId}
|
||||
serverLabel={`${activeEnvironmentUnavailableState.label} server`}
|
||||
selfUpdate={null}
|
||||
targetVersion={compatibilityChannelMismatch.clientVersion}
|
||||
/>
|
||||
) : null}
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() => void navigate({ to: "/settings/connections" })}
|
||||
>
|
||||
Connections
|
||||
</Button>
|
||||
</>
|
||||
),
|
||||
});
|
||||
} else {
|
||||
items.push({
|
||||
id: `environment-unavailable:${activeEnvironmentUnavailableState.environmentId}`,
|
||||
@@ -1971,7 +2035,10 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
serverUpdateEnvironmentId &&
|
||||
!reconnectingThroughVersionSkew &&
|
||||
(serverUpdateState.status !== "idle" ||
|
||||
(showVersionMismatchBanner && versionMismatch && versionMismatchDismissKey))
|
||||
(compatibilityChannelMismatch === null &&
|
||||
showVersionMismatchBanner &&
|
||||
versionMismatch &&
|
||||
versionMismatchDismissKey))
|
||||
) {
|
||||
const updateInProgress = serverUpdateState.status === "running";
|
||||
const updateFailed = serverUpdateState.status === "failed";
|
||||
@@ -4561,8 +4628,24 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
],
|
||||
);
|
||||
|
||||
const onSend = async (e?: { preventDefault: () => void }) => {
|
||||
const onSend = async (
|
||||
e?: { preventDefault: () => void },
|
||||
directAnnotation?: {
|
||||
annotation: PreviewAnnotationPayload;
|
||||
image: ComposerImageAttachment | null;
|
||||
},
|
||||
) => {
|
||||
e?.preventDefault();
|
||||
const notifyDirectAnnotationAttached = () => {
|
||||
if (!directAnnotation) return;
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "info",
|
||||
title: "Annotation attached to draft",
|
||||
description: "Sending is unavailable right now. Finish the current action, then send.",
|
||||
}),
|
||||
);
|
||||
};
|
||||
if (
|
||||
!activeThread ||
|
||||
isSendBusy ||
|
||||
@@ -4570,19 +4653,28 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
threadDetailLoading ||
|
||||
activeEnvironmentUnavailable ||
|
||||
sendInFlightRef.current
|
||||
)
|
||||
) {
|
||||
notifyDirectAnnotationAttached();
|
||||
return;
|
||||
}
|
||||
if (activePendingProgress) {
|
||||
if (directAnnotation) {
|
||||
notifyDirectAnnotationAttached();
|
||||
return;
|
||||
}
|
||||
onAdvanceActivePendingUserInput();
|
||||
return;
|
||||
}
|
||||
const sendCtx = composerRef.current?.getSendContext();
|
||||
if (!sendCtx?.providerAvailable) return;
|
||||
if (!sendCtx?.providerAvailable) {
|
||||
notifyDirectAnnotationAttached();
|
||||
return;
|
||||
}
|
||||
const {
|
||||
images: composerImages,
|
||||
images: sendContextImages,
|
||||
terminalContexts: composerTerminalContexts,
|
||||
elementContexts: composerElementContexts,
|
||||
previewAnnotations: composerPreviewAnnotations,
|
||||
previewAnnotations: sendContextPreviewAnnotations,
|
||||
reviewComments: composerReviewComments,
|
||||
selectedProvider: ctxSelectedProvider,
|
||||
selectedModel: ctxSelectedModel,
|
||||
@@ -4590,6 +4682,26 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
selectedPromptEffort: ctxSelectedPromptEffort,
|
||||
selectedModelSelection: ctxSelectedModelSelection,
|
||||
} = sendCtx;
|
||||
const composerImages =
|
||||
directAnnotation?.image &&
|
||||
!sendContextImages.some((image) => image.id === directAnnotation.image?.id)
|
||||
? [...sendContextImages, directAnnotation.image]
|
||||
: sendContextImages;
|
||||
const composerPreviewAnnotations =
|
||||
directAnnotation &&
|
||||
!sendContextPreviewAnnotations.some(
|
||||
(annotation) => annotation.id === directAnnotation.annotation.id,
|
||||
)
|
||||
? [
|
||||
...sendContextPreviewAnnotations,
|
||||
{
|
||||
...directAnnotation.annotation,
|
||||
screenshot: directAnnotation.annotation.screenshot
|
||||
? { ...directAnnotation.annotation.screenshot, dataUrl: "" }
|
||||
: null,
|
||||
},
|
||||
]
|
||||
: sendContextPreviewAnnotations;
|
||||
const promptForSend = promptRef.current;
|
||||
const {
|
||||
trimmedPrompt: trimmed,
|
||||
@@ -4605,7 +4717,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
composerPreviewAnnotations.length +
|
||||
composerReviewComments.length,
|
||||
});
|
||||
if (showPlanFollowUpPrompt && activeProposedPlan) {
|
||||
if (!directAnnotation && showPlanFollowUpPrompt && activeProposedPlan) {
|
||||
const followUp = resolvePlanFollowUpSubmission({
|
||||
draftText: trimmed,
|
||||
planMarkdown: activeProposedPlan.planMarkdown,
|
||||
@@ -5648,7 +5760,14 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
/>
|
||||
);
|
||||
const panelLayoutControls = (
|
||||
<div className="workspace-titlebar-controls z-50 mr-px gap-1 [-webkit-app-region:no-drag]">
|
||||
<div
|
||||
className={cn(
|
||||
"workspace-titlebar-controls z-50 gap-1 [-webkit-app-region:no-drag]",
|
||||
rightPanelOpen && !shouldUsePlanSidebarSheet
|
||||
? "right-2 wco:right-[var(--workspace-controls-right)]"
|
||||
: "mr-px",
|
||||
)}
|
||||
>
|
||||
{rightPanelOpen && !shouldUsePlanSidebarSheet ? (
|
||||
<RightPanelMaximizeControl
|
||||
maximized={rightPanelMaximized}
|
||||
@@ -5667,6 +5786,9 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
tabId={activeRightPanelSurface.resourceId}
|
||||
configuredUrls={configuredPreviewUrls}
|
||||
visible
|
||||
onSendAnnotation={(annotation, image) => {
|
||||
void onSend(undefined, { annotation, image });
|
||||
}}
|
||||
/>
|
||||
</Suspense>
|
||||
) : activeRightPanelSurface?.kind === "terminal" ? (
|
||||
|
||||
@@ -138,9 +138,20 @@ import {
|
||||
buildSidebarProjectPickerEntries,
|
||||
buildSidebarProjectSnapshots,
|
||||
} from "../sidebarProjectGrouping";
|
||||
import type { Project } from "../types";
|
||||
|
||||
const EMPTY_BROWSE_ENTRIES: FilesystemBrowseResult["entries"] = [];
|
||||
|
||||
function projectFavicon(project: Project) {
|
||||
return (
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
cwd={project.workspaceRoot}
|
||||
className={ITEM_ICON_CLASS}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function getLocalFileManagerName(platform: string): string {
|
||||
if (isMacPlatform(platform)) {
|
||||
return "Finder";
|
||||
@@ -924,13 +935,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
group?.memberProjects.flatMap((member) => [member.title, member.workspaceRoot]) ?? []
|
||||
);
|
||||
},
|
||||
icon: (project) => (
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
cwd={project.workspaceRoot}
|
||||
className={ITEM_ICON_CLASS}
|
||||
/>
|
||||
),
|
||||
icon: projectFavicon,
|
||||
runProject: openProjectFromSearch,
|
||||
}),
|
||||
[openProjectFromSearch, pickerProjects, projectGroupByTargetKey],
|
||||
@@ -948,13 +953,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
group?.memberProjects.flatMap((member) => [member.title, member.workspaceRoot]) ?? []
|
||||
);
|
||||
},
|
||||
icon: (project) => (
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
cwd={project.workspaceRoot}
|
||||
className={ITEM_ICON_CLASS}
|
||||
/>
|
||||
),
|
||||
icon: projectFavicon,
|
||||
runProject: async (project) => {
|
||||
const group = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`);
|
||||
const contextualRefBelongsToGroup =
|
||||
|
||||
@@ -1747,12 +1747,14 @@ function ComposerPromptEditorInner({
|
||||
|
||||
return (
|
||||
<ComposerTerminalContextActionsContext value={terminalContextActions}>
|
||||
<div className="relative">
|
||||
<div className="composer-editor-surface relative">
|
||||
<PlainTextPlugin
|
||||
contentEditable={
|
||||
<ContentEditable
|
||||
className={cn(
|
||||
"block max-h-50 min-h-17.5 w-full overflow-y-auto whitespace-pre-wrap wrap-break-word bg-transparent text-[16px] leading-relaxed text-foreground focus:outline-none sm:text-[14px]",
|
||||
// The size comes from .composer-editor-surface so Settings -> Appearance
|
||||
// can drive it; keep everything else here.
|
||||
"block max-h-50 min-h-17.5 w-full overflow-y-auto whitespace-pre-wrap wrap-break-word bg-transparent leading-relaxed text-foreground focus:outline-none",
|
||||
className,
|
||||
)}
|
||||
data-testid="composer-editor"
|
||||
@@ -1763,7 +1765,7 @@ function ComposerPromptEditorInner({
|
||||
}
|
||||
placeholder={
|
||||
terminalContexts.length > 0 ? null : (
|
||||
<div className="pointer-events-none absolute inset-0 text-[16px] leading-relaxed text-muted-foreground/35 sm:text-[14px]">
|
||||
<div className="pointer-events-none absolute inset-0 leading-relaxed text-muted-foreground/35">
|
||||
{placeholder}
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type { FileDiffContentsLoader } from "@pierre/diffs";
|
||||
import { useParams } from "@tanstack/react-router";
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
@@ -15,6 +16,7 @@ import {
|
||||
ChevronsUpDownIcon,
|
||||
Columns2Icon,
|
||||
PilcrowIcon,
|
||||
RefreshCwIcon,
|
||||
Rows3Icon,
|
||||
SearchIcon,
|
||||
TextWrapIcon,
|
||||
@@ -67,6 +69,7 @@ import {
|
||||
} from "./ui/menu";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
import { useEnvironmentQuery } from "../state/query";
|
||||
import { useAtomCommand } from "../state/use-atom-command";
|
||||
import { serverEnvironment } from "../state/server";
|
||||
import { reviewEnvironment } from "../state/review";
|
||||
import { vcsEnvironment } from "../state/vcs";
|
||||
@@ -91,9 +94,9 @@ const DIFF_PANEL_UNSAFE_CSS = `
|
||||
[data-virtualizer-buffer] {
|
||||
--diffs-header-font-family: var(--font-sans) !important;
|
||||
--diffs-font-family: var(--font-mono) !important;
|
||||
--diffs-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
|
||||
--diffs-light-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
|
||||
--diffs-dark-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
|
||||
--diffs-bg: var(--background) !important;
|
||||
--diffs-light-bg: var(--background) !important;
|
||||
--diffs-dark-bg: var(--background) !important;
|
||||
--diffs-token-light-bg: transparent;
|
||||
--diffs-token-dark-bg: transparent;
|
||||
|
||||
@@ -102,13 +105,25 @@ const DIFF_PANEL_UNSAFE_CSS = `
|
||||
--diffs-bg-separator-override: color-mix(in srgb, var(--background) 95%, var(--foreground));
|
||||
--diffs-bg-buffer-override: color-mix(in srgb, var(--background) 90%, var(--foreground));
|
||||
|
||||
--diffs-bg-addition-override: color-mix(in srgb, var(--background) 92%, var(--success));
|
||||
--diffs-bg-addition-number-override: color-mix(in srgb, var(--background) 88%, var(--success));
|
||||
--diffs-bg-addition-override: light-dark(
|
||||
color-mix(in srgb, var(--background) 50%, var(--success)),
|
||||
color-mix(in srgb, var(--background) 70%, var(--success))
|
||||
);
|
||||
--diffs-bg-addition-number-override: light-dark(
|
||||
color-mix(in srgb, var(--background) 35%, var(--success)),
|
||||
color-mix(in srgb, var(--background) 60%, var(--success))
|
||||
);
|
||||
--diffs-bg-addition-hover-override: color-mix(in srgb, var(--background) 85%, var(--success));
|
||||
--diffs-bg-addition-emphasis-override: color-mix(in srgb, var(--background) 80%, var(--success));
|
||||
|
||||
--diffs-bg-deletion-override: color-mix(in srgb, var(--background) 92%, var(--destructive));
|
||||
--diffs-bg-deletion-number-override: color-mix(in srgb, var(--background) 88%, var(--destructive));
|
||||
--diffs-bg-deletion-override: light-dark(
|
||||
color-mix(in srgb, var(--background) 50%, var(--destructive)),
|
||||
color-mix(in srgb, var(--background) 70%, var(--destructive))
|
||||
);
|
||||
--diffs-bg-deletion-number-override: light-dark(
|
||||
color-mix(in srgb, var(--background) 35%, var(--destructive)),
|
||||
color-mix(in srgb, var(--background) 60%, var(--destructive))
|
||||
);
|
||||
--diffs-bg-deletion-hover-override: color-mix(in srgb, var(--background) 85%, var(--destructive));
|
||||
--diffs-bg-deletion-emphasis-override: color-mix(
|
||||
in srgb,
|
||||
@@ -119,9 +134,66 @@ const DIFF_PANEL_UNSAFE_CSS = `
|
||||
background-color: var(--diffs-bg) !important;
|
||||
}
|
||||
|
||||
:is(
|
||||
[data-line],
|
||||
[data-line-annotation],
|
||||
[data-merge-conflict],
|
||||
[data-merge-conflict-actions],
|
||||
[data-no-newline]
|
||||
)[data-selected-line] {
|
||||
--diffs-line-bg: light-dark(
|
||||
color-mix(
|
||||
in lab,
|
||||
var(--background) 88%,
|
||||
color-mix(in srgb, var(--background) 50%, var(--diffs-modified-base))
|
||||
),
|
||||
color-mix(
|
||||
in lab,
|
||||
var(--background) 80%,
|
||||
color-mix(in srgb, var(--background) 70%, var(--diffs-modified-base))
|
||||
)
|
||||
) !important;
|
||||
}
|
||||
|
||||
:is([data-gutter-buffer], [data-column-number])[data-selected-line] {
|
||||
--diffs-line-bg: light-dark(
|
||||
color-mix(
|
||||
in lab,
|
||||
var(--background) 91%,
|
||||
color-mix(in srgb, var(--background) 35%, var(--diffs-modified-base))
|
||||
),
|
||||
color-mix(
|
||||
in lab,
|
||||
var(--background) 85%,
|
||||
color-mix(in srgb, var(--background) 60%, var(--diffs-modified-base))
|
||||
)
|
||||
) !important;
|
||||
}
|
||||
|
||||
[data-indicators="bars"]
|
||||
:is([data-column-number], [data-gutter-buffer="annotation"])[data-selected-line] {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
[data-indicators="bars"]
|
||||
:is([data-column-number], [data-gutter-buffer="annotation"])[data-selected-line]::before {
|
||||
position: absolute !important;
|
||||
inset-block: 0 !important;
|
||||
inset-inline-start: 0 !important;
|
||||
display: block !important;
|
||||
width: 4px !important;
|
||||
min-width: 4px !important;
|
||||
max-width: 4px !important;
|
||||
height: auto !important;
|
||||
padding: 0 !important;
|
||||
content: "" !important;
|
||||
background-color: var(--diffs-modified-base) !important;
|
||||
background-image: none !important;
|
||||
}
|
||||
|
||||
[data-file-info] {
|
||||
background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important;
|
||||
border-block-color: var(--border) !important;
|
||||
background-color: var(--background) !important;
|
||||
border-block-color: transparent !important;
|
||||
color: var(--foreground) !important;
|
||||
}
|
||||
|
||||
@@ -129,14 +201,103 @@ const DIFF_PANEL_UNSAFE_CSS = `
|
||||
position: sticky !important;
|
||||
top: 0;
|
||||
z-index: 4;
|
||||
background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important;
|
||||
border-bottom: 1px solid var(--border) !important;
|
||||
background-color: var(--background) !important;
|
||||
border-bottom-color: transparent !important;
|
||||
align-items: center !important;
|
||||
font-family: var(--font-sans) !important;
|
||||
font-size: 12px !important;
|
||||
line-height: 1 !important;
|
||||
min-height: 32px !important;
|
||||
padding-block: 6px !important;
|
||||
padding-inline: 8px 12px !important;
|
||||
}
|
||||
|
||||
[data-diffs-header]:hover {
|
||||
background-color: color-mix(in srgb, var(--background) 97%, var(--foreground)) !important;
|
||||
}
|
||||
|
||||
:is([data-separator="line-info"], [data-separator="line-info-basic"]) {
|
||||
height: 24px !important;
|
||||
margin-block: 0 !important;
|
||||
background-color: var(--background) !important;
|
||||
}
|
||||
|
||||
:is([data-separator="line-info"], [data-separator="line-info-basic"])
|
||||
[data-separator-wrapper] {
|
||||
padding-inline: 8px 12px !important;
|
||||
background-color: transparent !important;
|
||||
}
|
||||
|
||||
:is([data-separator="line-info"], [data-separator="line-info-basic"])
|
||||
[data-separator-content] {
|
||||
gap: 8px;
|
||||
padding-inline: 0 !important;
|
||||
background-color: transparent !important;
|
||||
color: color-mix(in srgb, var(--foreground) 52%, var(--background)) !important;
|
||||
font-family: var(--font-sans) !important;
|
||||
font-size: 11px !important;
|
||||
text-decoration: none !important;
|
||||
}
|
||||
|
||||
:is([data-separator="line-info"], [data-separator="line-info-basic"])
|
||||
[data-unmodified-lines] {
|
||||
display: flex !important;
|
||||
min-width: 0;
|
||||
flex: 1 1 auto;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
:is([data-separator="line-info"], [data-separator="line-info-basic"])
|
||||
[data-unmodified-lines]::before,
|
||||
:is([data-separator="line-info"], [data-separator="line-info-basic"])
|
||||
[data-unmodified-lines]::after {
|
||||
width: auto;
|
||||
height: 1px;
|
||||
flex: 1 1 auto;
|
||||
content: "";
|
||||
background-color: color-mix(in srgb, var(--background) 92%, var(--foreground));
|
||||
}
|
||||
|
||||
:is([data-separator="line-info"], [data-separator="line-info-basic"])[data-expand-index]
|
||||
[data-separator-wrapper] {
|
||||
grid-template-columns: 0 minmax(0, 1fr) !important;
|
||||
}
|
||||
|
||||
:is([data-separator="line-info"], [data-separator="line-info-basic"])[data-expand-index]
|
||||
[data-separator-content] {
|
||||
grid-column: 2 !important;
|
||||
}
|
||||
|
||||
:is([data-separator="line-info"], [data-separator="line-info-basic"])
|
||||
[data-expand-button] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
:is([data-separator="line-info"], [data-separator="line-info-basic"]):has(
|
||||
[data-expand-button]
|
||||
)
|
||||
[data-separator-content] {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
:is([data-separator="line-info"], [data-separator="line-info-basic"]):has(
|
||||
[data-expand-button]
|
||||
):hover
|
||||
[data-separator-content] {
|
||||
color: color-mix(in srgb, var(--foreground) 76%, var(--background)) !important;
|
||||
}
|
||||
|
||||
:is([data-separator="line-info"], [data-separator="line-info-basic"]):has(
|
||||
[data-expand-button]
|
||||
):hover
|
||||
[data-unmodified-lines]::before,
|
||||
:is([data-separator="line-info"], [data-separator="line-info-basic"]):has(
|
||||
[data-expand-button]
|
||||
):hover
|
||||
[data-unmodified-lines]::after {
|
||||
background-color: color-mix(in srgb, var(--background) 84%, var(--foreground));
|
||||
}
|
||||
|
||||
[data-diffs-header] [data-header-content] {
|
||||
@@ -205,7 +366,12 @@ export default function DiffPanel({
|
||||
scopeKey: null,
|
||||
fileKeys: EMPTY_COLLAPSED_DIFF_FILE_KEYS,
|
||||
}));
|
||||
const [codeViewRevision, setCodeViewRevision] = useState(0);
|
||||
const codeViewRef = useRef<AnnotatableCodeViewHandle>(null);
|
||||
const lastCompletedTurnRefreshRef = useRef<{
|
||||
readonly threadKey: string | null;
|
||||
readonly turnId: TurnId | null;
|
||||
} | null>(null);
|
||||
|
||||
const routeThreadRef = useParams({
|
||||
strict: false,
|
||||
@@ -230,6 +396,7 @@ export default function DiffPanel({
|
||||
activeThread?.environmentId ?? null,
|
||||
serverConfig?.availableEditors ?? [],
|
||||
);
|
||||
const getDiffFileContents = useAtomCommand(reviewEnvironment.diffFileContents);
|
||||
const gitStatusQuery = useEnvironmentQuery(
|
||||
activeThread !== null && activeThread !== undefined && activeCwd != null
|
||||
? vcsEnvironment.status({
|
||||
@@ -298,6 +465,7 @@ export default function DiffPanel({
|
||||
const collapseScopeKey = routeThreadRef
|
||||
? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}:${reviewSectionId}`
|
||||
: null;
|
||||
const codeViewMountKey = `${collapseScopeKey ?? reviewSectionId}:${codeViewRevision}`;
|
||||
const collapsedDiffFileKeys =
|
||||
collapsedDiffFiles.scopeKey === collapseScopeKey
|
||||
? collapsedDiffFiles.fileKeys
|
||||
@@ -360,9 +528,93 @@ export default function DiffPanel({
|
||||
const branchDiffPreview = shouldRetryBranchDiffAtEnvironmentCwd
|
||||
? fallbackBranchDiffPreview
|
||||
: primaryBranchDiffPreview;
|
||||
const refreshBranchDiffPreview = branchDiffPreview.refresh;
|
||||
const canRefreshGitDiff =
|
||||
isGitRepo && selectedTurnId === null && activeThread != null && activeCwd != null;
|
||||
const activeThreadRefreshKey = routeThreadRef
|
||||
? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}`
|
||||
: null;
|
||||
|
||||
useEffect(() => {
|
||||
if (!canRefreshGitDiff) return;
|
||||
const refreshOnFocus = () => refreshBranchDiffPreview();
|
||||
window.addEventListener("focus", refreshOnFocus);
|
||||
return () => window.removeEventListener("focus", refreshOnFocus);
|
||||
}, [canRefreshGitDiff, refreshBranchDiffPreview]);
|
||||
|
||||
useEffect(() => {
|
||||
const current = {
|
||||
threadKey: activeThreadRefreshKey,
|
||||
turnId: latestTurn?.turnId ?? null,
|
||||
};
|
||||
const previous = lastCompletedTurnRefreshRef.current;
|
||||
if (!canRefreshGitDiff) {
|
||||
return;
|
||||
}
|
||||
if (previous === null || previous.threadKey !== current.threadKey) {
|
||||
lastCompletedTurnRefreshRef.current = current;
|
||||
return;
|
||||
}
|
||||
if (previous.turnId === current.turnId) return;
|
||||
refreshBranchDiffPreview();
|
||||
lastCompletedTurnRefreshRef.current = current;
|
||||
}, [activeThreadRefreshKey, canRefreshGitDiff, latestTurn?.turnId, refreshBranchDiffPreview]);
|
||||
|
||||
const selectedGitSource = branchDiffPreview.data?.sources.find(
|
||||
(source) => source.kind === (selectedGitScope === "unstaged" ? "working-tree" : "branch-range"),
|
||||
);
|
||||
const loadDiffFiles = useMemo<FileDiffContentsLoader | undefined>(() => {
|
||||
const preview = branchDiffPreview.data;
|
||||
if (selectedTurnId !== null || !activeThread || !preview || !selectedGitSource) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const source = selectedGitSource;
|
||||
return async (fileDiff) => {
|
||||
const newPath = resolveFileDiffPath(fileDiff);
|
||||
const oldPath = fileDiff.prevName
|
||||
? resolveFileDiffPath({ ...fileDiff, name: fileDiff.prevName })
|
||||
: newPath;
|
||||
const result = await getDiffFileContents({
|
||||
environmentId: activeThread.environmentId,
|
||||
input: {
|
||||
cwd: preview.cwd,
|
||||
sourceKind: source.kind,
|
||||
changeType: fileDiff.type,
|
||||
baseRef: source.baseRef,
|
||||
headRef: source.headRef,
|
||||
oldPath,
|
||||
newPath,
|
||||
},
|
||||
});
|
||||
if (result._tag !== "Success") {
|
||||
throw squashAtomCommandFailure(result);
|
||||
}
|
||||
|
||||
const newFile = {
|
||||
name: newPath,
|
||||
contents: result.value.newContents,
|
||||
cacheKey: `${source.diffHash}:new:${newPath}`,
|
||||
};
|
||||
if (fileDiff.type === "rename-pure") {
|
||||
return { oldFile: null, newFile };
|
||||
}
|
||||
return {
|
||||
oldFile: {
|
||||
name: oldPath,
|
||||
contents: result.value.oldContents,
|
||||
cacheKey: `${source.diffHash}:old:${oldPath}`,
|
||||
},
|
||||
newFile,
|
||||
};
|
||||
};
|
||||
}, [
|
||||
activeThread,
|
||||
branchDiffPreview.data,
|
||||
getDiffFileContents,
|
||||
selectedGitSource,
|
||||
selectedTurnId,
|
||||
]);
|
||||
const localBranchRefs = useEnvironmentQuery(
|
||||
selectedTurnId === null &&
|
||||
selectedGitScope === "branch" &&
|
||||
@@ -439,10 +691,17 @@ export default function DiffPanel({
|
||||
}),
|
||||
);
|
||||
}, [renderablePatch]);
|
||||
const renderableFileEntries = useMemo(
|
||||
() =>
|
||||
renderableFiles.map((fileDiff) => ({
|
||||
fileDiff,
|
||||
fileKey: buildFileDiffRenderKey(fileDiff),
|
||||
})),
|
||||
[renderableFiles],
|
||||
);
|
||||
const codeViewFiles = useMemo(
|
||||
() =>
|
||||
renderableFiles.map((fileDiff) => {
|
||||
const fileKey = buildFileDiffRenderKey(fileDiff);
|
||||
renderableFileEntries.map(({ fileDiff, fileKey }) => {
|
||||
return {
|
||||
fileDiff,
|
||||
filePath: resolveFileDiffPath(fileDiff),
|
||||
@@ -450,18 +709,19 @@ export default function DiffPanel({
|
||||
collapsed: collapsedDiffFileKeys.has(fileKey),
|
||||
};
|
||||
}),
|
||||
[collapsedDiffFileKeys, renderableFiles],
|
||||
[collapsedDiffFileKeys, renderableFileEntries],
|
||||
);
|
||||
const diffFileKeys = useMemo(() => codeViewFiles.map((file) => file.fileKey), [codeViewFiles]);
|
||||
const allDiffFilesCollapsed = areAllDiffFilesCollapsed(diffFileKeys, collapsedDiffFileKeys);
|
||||
const diffLineStat = useMemo(() => getDiffLineStat(renderableFiles), [renderableFiles]);
|
||||
const selectedDiffFileKey = selectedFilePath
|
||||
? (codeViewFiles.find((candidate) => candidate.filePath === selectedFilePath)?.fileKey ?? null)
|
||||
: null;
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedFilePath) return;
|
||||
const file = codeViewFiles.find((candidate) => candidate.filePath === selectedFilePath);
|
||||
if (!file) return;
|
||||
codeViewRef.current?.scrollTo({ type: "item", id: file.fileKey, align: "start" });
|
||||
}, [codeViewFiles, selectedFilePath, selectedFileRevealRequestId]);
|
||||
if (!selectedDiffFileKey) return;
|
||||
codeViewRef.current?.scrollTo({ type: "item", id: selectedDiffFileKey, align: "start" });
|
||||
}, [codeViewMountKey, selectedDiffFileKey, selectedFileRevealRequestId]);
|
||||
|
||||
const openDiffFile = useCallback(
|
||||
(filePath: string) => {
|
||||
@@ -506,6 +766,7 @@ export default function DiffPanel({
|
||||
);
|
||||
|
||||
const toggleDiffFileCollapse = useCallback(() => {
|
||||
setCodeViewRevision((current) => current + 1);
|
||||
setCollapsedDiffFiles((current) => {
|
||||
const currentKeys =
|
||||
current.scopeKey === collapseScopeKey ? current.fileKeys : EMPTY_COLLAPSED_DIFF_FILE_KEYS;
|
||||
@@ -724,23 +985,45 @@ export default function DiffPanel({
|
||||
layout="inline"
|
||||
/>
|
||||
)}
|
||||
{canRefreshGitDiff && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-sm"
|
||||
variant="ghost"
|
||||
aria-label={branchDiffPreview.isPending ? "Refreshing diff" : "Refresh diff"}
|
||||
onClick={refreshBranchDiffPreview}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<RefreshCwIcon
|
||||
className={cn("size-3.5", branchDiffPreview.isPending && "animate-spin")}
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
{branchDiffPreview.isPending ? "Refreshing diff…" : "Refresh diff"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
{codeViewFiles.length > 0 && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="outline"
|
||||
size="icon-sm"
|
||||
variant="ghost"
|
||||
aria-label={allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
|
||||
onClick={toggleDiffFileCollapse}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{allDiffFilesCollapsed ? (
|
||||
<ChevronsUpDownIcon className="size-3" />
|
||||
<ChevronsUpDownIcon className="size-3.5" />
|
||||
) : (
|
||||
<ChevronsDownUpIcon className="size-3" />
|
||||
<ChevronsDownUpIcon className="size-3.5" />
|
||||
)}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
@@ -749,9 +1032,8 @@ export default function DiffPanel({
|
||||
</Tooltip>
|
||||
)}
|
||||
<ToggleGroup
|
||||
className="shrink-0"
|
||||
variant="outline"
|
||||
size="xs"
|
||||
className="shrink-0 gap-1"
|
||||
size="sm"
|
||||
value={[diffRenderMode]}
|
||||
onValueChange={(value) => {
|
||||
const next = value[0];
|
||||
@@ -760,11 +1042,11 @@ export default function DiffPanel({
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Toggle aria-label="Stacked diff view" value="stacked">
|
||||
<Rows3Icon className="size-3" />
|
||||
<Toggle aria-label="Stacked diff view" value="stacked" variant="ghost">
|
||||
<Rows3Icon className="size-3.5" />
|
||||
</Toggle>
|
||||
<Toggle aria-label="Split diff view" value="split">
|
||||
<Columns2Icon className="size-3" />
|
||||
<Toggle aria-label="Split diff view" value="split" variant="ghost">
|
||||
<Columns2Icon className="size-3.5" />
|
||||
</Toggle>
|
||||
</ToggleGroup>
|
||||
<Tooltip>
|
||||
@@ -772,8 +1054,8 @@ export default function DiffPanel({
|
||||
render={
|
||||
<Toggle
|
||||
aria-label={wordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"}
|
||||
variant="outline"
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
pressed={wordWrap}
|
||||
onPressedChange={(pressed) => {
|
||||
setWordWrap(Boolean(pressed));
|
||||
@@ -781,7 +1063,7 @@ export default function DiffPanel({
|
||||
/>
|
||||
}
|
||||
>
|
||||
<TextWrapIcon className="size-3" />
|
||||
<TextWrapIcon className="size-3.5" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
{wordWrap ? "Disable line wrapping" : "Enable line wrapping"}
|
||||
@@ -794,8 +1076,8 @@ export default function DiffPanel({
|
||||
aria-label={
|
||||
diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"
|
||||
}
|
||||
variant="outline"
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
pressed={diffIgnoreWhitespace}
|
||||
onPressedChange={(pressed) => {
|
||||
setDiffIgnoreWhitespace(Boolean(pressed));
|
||||
@@ -803,7 +1085,7 @@ export default function DiffPanel({
|
||||
/>
|
||||
}
|
||||
>
|
||||
<PilcrowIcon className="size-3" />
|
||||
<PilcrowIcon className="size-3.5" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
{diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
|
||||
@@ -875,8 +1157,9 @@ export default function DiffPanel({
|
||||
}}
|
||||
>
|
||||
<AnnotatableCodeView
|
||||
viewerRef={codeViewRef}
|
||||
key={collapseScopeKey ?? reviewSectionId}
|
||||
viewerRef={codeViewRef}
|
||||
codeViewKey={codeViewMountKey}
|
||||
className="diff-render-surface h-full min-h-0 overflow-auto"
|
||||
files={codeViewFiles}
|
||||
sectionId={reviewSectionId}
|
||||
@@ -891,7 +1174,7 @@ export default function DiffPanel({
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
"inline-flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-sm border-0 bg-transparent p-0 transition-colors hover:bg-foreground/10 focus-visible:outline-hidden",
|
||||
"-ms-0.5 inline-flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-sm border-0 bg-transparent p-0 transition-colors hover:bg-foreground/10 focus-visible:outline-hidden",
|
||||
getDiffCollapseIconClassName(fileDiff),
|
||||
)}
|
||||
aria-label={collapsed ? `Expand ${filePath}` : `Collapse ${filePath}`}
|
||||
@@ -923,8 +1206,14 @@ export default function DiffPanel({
|
||||
themeType: resolvedTheme as DiffThemeType,
|
||||
unsafeCSS: DIFF_PANEL_UNSAFE_CSS,
|
||||
stickyHeaders: true,
|
||||
itemMetrics: { diffHeaderHeight: 33 },
|
||||
layout: { paddingTop: 0, paddingBottom: 8, gap: 8 },
|
||||
...(loadDiffFiles ? { loadDiffFiles } : {}),
|
||||
itemMetrics: {
|
||||
diffHeaderHeight: 32,
|
||||
hunkSeparatorHeight: 24,
|
||||
paddingTop: 0,
|
||||
paddingBottom: 0,
|
||||
},
|
||||
layout: { paddingTop: 0, paddingBottom: 0, gap: 0 },
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -10,7 +10,8 @@ export type DiffPanelMode = "inline" | "sheet" | "sidebar" | "embedded";
|
||||
function getDiffPanelHeaderRowClassName(mode: DiffPanelMode) {
|
||||
const shouldUseDragRegion = isElectron && mode !== "sheet" && mode !== "embedded";
|
||||
return cn(
|
||||
"flex items-center justify-between gap-2 px-4",
|
||||
"flex items-center justify-between gap-2",
|
||||
mode === "embedded" ? "px-2" : "px-4",
|
||||
shouldUseDragRegion
|
||||
? "drag-region h-[52px] border-b border-border wco:h-[env(titlebar-area-height)] wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]"
|
||||
: "surface-subheader",
|
||||
@@ -59,30 +60,53 @@ export function DiffPanelHeaderSkeleton() {
|
||||
);
|
||||
}
|
||||
|
||||
export function DiffPanelLoadingState(props: { label: string }) {
|
||||
function DiffFileHeaderSkeleton({ titleClassName }: { titleClassName: string }) {
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col p-2">
|
||||
<div
|
||||
className="flex min-h-0 flex-1 flex-col overflow-hidden rounded-md border border-border/60 bg-card/25"
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
aria-label={props.label}
|
||||
>
|
||||
<div className="flex items-center gap-2 border-b border-border/50 px-3 py-2">
|
||||
<Skeleton className="h-4 w-32 rounded-full" />
|
||||
<Skeleton className="ml-auto h-4 w-20 rounded-full" />
|
||||
</div>
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-4 px-3 py-4">
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-3 w-full rounded-full" />
|
||||
<Skeleton className="h-3 w-full rounded-full" />
|
||||
<Skeleton className="h-3 w-10/12 rounded-full" />
|
||||
<Skeleton className="h-3 w-11/12 rounded-full" />
|
||||
<Skeleton className="h-3 w-9/12 rounded-full" />
|
||||
</div>
|
||||
<span className="sr-only">{props.label}</span>
|
||||
</div>
|
||||
<div className="flex h-8 items-center gap-2 px-2 pr-3">
|
||||
<div className="flex size-5 shrink-0 items-center justify-center">
|
||||
<Skeleton className="size-2.5 rounded-[2px]" />
|
||||
</div>
|
||||
<Skeleton className="size-5 shrink-0 rounded-md" />
|
||||
<Skeleton className={cn("h-3 rounded-full", titleClassName)} />
|
||||
<div className="ml-auto flex shrink-0 items-center gap-2">
|
||||
<Skeleton className="h-3 w-5 rounded-full" />
|
||||
<Skeleton className="h-3 w-5 rounded-full" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DiffCodeLineSkeleton({ contentClassName }: { contentClassName: string }) {
|
||||
return (
|
||||
<div className="flex items-center gap-3">
|
||||
<Skeleton className="h-2.5 w-5 shrink-0 rounded-full" />
|
||||
<Skeleton className={cn("h-2.5 rounded-full", contentClassName)} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function DiffPanelLoadingState(props: { label: string }) {
|
||||
return (
|
||||
<div
|
||||
className="min-h-0 flex-1 overflow-hidden bg-background"
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
aria-label={props.label}
|
||||
>
|
||||
<DiffFileHeaderSkeleton titleClassName="w-1/2 max-w-64" />
|
||||
<div className="flex h-6 items-center gap-2 px-2 pr-3">
|
||||
<div className="h-px flex-1 bg-border/40" />
|
||||
<Skeleton className="h-2.5 w-24 rounded-full" />
|
||||
<div className="h-px flex-1 bg-border/40" />
|
||||
</div>
|
||||
<div className="space-y-2 px-3 py-2">
|
||||
<DiffCodeLineSkeleton contentClassName="w-2/3" />
|
||||
<DiffCodeLineSkeleton contentClassName="w-4/5" />
|
||||
<DiffCodeLineSkeleton contentClassName="w-3/5" />
|
||||
</div>
|
||||
<DiffFileHeaderSkeleton titleClassName="w-2/5 max-w-52" />
|
||||
<DiffFileHeaderSkeleton titleClassName="w-3/5 max-w-72" />
|
||||
<span className="sr-only">{props.label}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -221,14 +221,14 @@ function surfaceTitle(
|
||||
function PreviewFavicon({ url }: { url: string | null }) {
|
||||
const faviconUrl = faviconUrlForOrigin(url, 32);
|
||||
const [failedUrl, setFailedUrl] = useState<string | null>(null);
|
||||
if (!faviconUrl || failedUrl === faviconUrl) return <Globe2 className="size-3.5 shrink-0" />;
|
||||
if (!faviconUrl || failedUrl === faviconUrl) return <Globe2 className="size-3 shrink-0" />;
|
||||
return (
|
||||
<img
|
||||
src={faviconUrl}
|
||||
alt=""
|
||||
aria-hidden
|
||||
draggable={false}
|
||||
className="size-3.5 shrink-0 rounded-sm"
|
||||
className="size-3 shrink-0 rounded-sm"
|
||||
onError={() => setFailedUrl(faviconUrl)}
|
||||
/>
|
||||
);
|
||||
@@ -250,22 +250,22 @@ function SurfaceIcon({
|
||||
return <PreviewFavicon url={url} />;
|
||||
}
|
||||
case "diff":
|
||||
return <FileDiff className="size-3.5 shrink-0" />;
|
||||
return <FileDiff className="size-3 shrink-0" />;
|
||||
case "files":
|
||||
return <Files className="size-3.5 shrink-0" />;
|
||||
return <Files className="size-3 shrink-0" />;
|
||||
case "file":
|
||||
return (
|
||||
<PierreEntryIcon
|
||||
pathValue={surface.relativePath}
|
||||
kind="file"
|
||||
theme={theme}
|
||||
className="size-3.5"
|
||||
className="size-3"
|
||||
/>
|
||||
);
|
||||
case "terminal":
|
||||
return <TerminalSquare className="size-3.5 shrink-0" />;
|
||||
return <TerminalSquare className="size-3 shrink-0" />;
|
||||
case "plan":
|
||||
return <ClipboardList className="size-3.5 shrink-0" />;
|
||||
return <ClipboardList className="size-3 shrink-0" />;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -358,7 +358,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
|
||||
<div
|
||||
className={cn(
|
||||
"workspace-topbar gap-1 pl-2",
|
||||
!ownsDesktopTitleBar && "[--workspace-topbar-height:--spacing(11)]",
|
||||
props.mode !== "inline" && "[--workspace-topbar-height:--spacing(11)]",
|
||||
props.mode === "inline" ? "pr-28" : "pr-3",
|
||||
ownsDesktopTitleBar && "wco:pr-[calc(var(--workspace-native-controls-inset)+6rem)]",
|
||||
props.mode === "inline" && props.maximized && COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
|
||||
@@ -385,62 +385,57 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
|
||||
onAuxClick={(event) => handleTabAuxClick(event, surface)}
|
||||
onContextMenu={(event) => void handleTabContextMenu(event, surface)}
|
||||
className={cn(
|
||||
"group flex h-7 min-w-25 max-w-44 shrink-0 items-center gap-1.5 rounded-md px-2 text-sm",
|
||||
"group/tab flex h-6 max-w-36 shrink-0 items-center gap-0.5 rounded-md pr-2 pl-1.5 text-xs",
|
||||
active
|
||||
? "bg-accent text-foreground"
|
||||
: "text-muted-foreground hover:bg-accent/60 hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="group/close relative flex size-4 shrink-0 items-center justify-center rounded-sm hover:bg-muted"
|
||||
aria-label={`Close ${title}`}
|
||||
onClick={() => props.onCloseSurface(surface)}
|
||||
>
|
||||
<span className="relative flex size-3 items-center justify-center group-hover/tab:hidden group-focus-visible/close:hidden">
|
||||
<SurfaceIcon
|
||||
surface={surface}
|
||||
sessions={props.previewSessions}
|
||||
theme={resolvedTheme}
|
||||
/>
|
||||
{pending ? (
|
||||
<span
|
||||
className="absolute -right-0.5 -bottom-0.5 size-1.5 rounded-full bg-current"
|
||||
aria-hidden
|
||||
/>
|
||||
) : null}
|
||||
</span>
|
||||
<X className="hidden size-3 group-hover/tab:block group-focus-visible/close:block" />
|
||||
</button>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
className="flex min-w-0 flex-1 items-center gap-1.5"
|
||||
className="flex min-w-0 items-center"
|
||||
onClick={() => props.onActivate(surface)}
|
||||
>
|
||||
<SurfaceIcon
|
||||
surface={surface}
|
||||
sessions={props.previewSessions}
|
||||
theme={resolvedTheme}
|
||||
/>
|
||||
<span className="truncate">{title}</span>
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup>{title}</TooltipPopup>
|
||||
</Tooltip>
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
"relative flex size-4 shrink-0 items-center justify-center rounded hover:bg-muted focus:opacity-100",
|
||||
pending ? "opacity-100" : "opacity-0 group-hover:opacity-100",
|
||||
)}
|
||||
aria-label={`Close ${title}`}
|
||||
onClick={() => props.onCloseSurface(surface)}
|
||||
>
|
||||
{pending ? (
|
||||
<>
|
||||
<span
|
||||
className="size-2 rounded-full bg-current group-hover:hidden"
|
||||
aria-hidden
|
||||
/>
|
||||
<X className="hidden size-3 group-hover:block" />
|
||||
</>
|
||||
) : (
|
||||
<X className="size-3" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{props.surfaces.length > 0 ? (
|
||||
<Menu>
|
||||
<MenuTrigger
|
||||
className="relative inline-flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
className="relative inline-flex size-6 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
aria-label="Add panel surface"
|
||||
>
|
||||
<Plus className="size-4" />
|
||||
<Plus className="size-3.5" />
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="start" side="bottom" sideOffset={6} className="min-w-44">
|
||||
<SurfaceMenuItem
|
||||
@@ -478,7 +473,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
|
||||
</ScrollArea>
|
||||
{props.layoutControls}
|
||||
</div>
|
||||
<div className="flex min-h-0 flex-1 flex-col">
|
||||
<div className="flex min-h-0 flex-1 flex-col" data-right-panel-surface-content>
|
||||
{props.activeSurfaceId === null ? (
|
||||
<RightPanelEmptyState
|
||||
onAddBrowser={props.onAddBrowser}
|
||||
|
||||
@@ -16,8 +16,12 @@ import { resolveServerBackedAppStageLabel } from "../branding.logic";
|
||||
export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
|
||||
export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 100;
|
||||
// Visible sidebar rows are prewarmed into the thread-detail cache so opening a
|
||||
// nearby thread usually reuses an already-hot subscription.
|
||||
export const SIDEBAR_THREAD_PREWARM_LIMIT = 10;
|
||||
// nearby thread usually reuses an already-hot subscription. Each prewarmed
|
||||
// thread holds a live, fully hydrated detail subscription (all messages and
|
||||
// activities, growing as agents work) for as long as the row stays visible,
|
||||
// so this limit is a direct renderer-heap and server-load multiplier — keep
|
||||
// it small; cold opens still render instantly from the cached snapshot.
|
||||
export const SIDEBAR_THREAD_PREWARM_LIMIT = 3;
|
||||
|
||||
type SidebarProject = {
|
||||
id: string;
|
||||
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
GitBranchIcon,
|
||||
EllipsisIcon,
|
||||
MessageSquareIcon,
|
||||
PinIcon,
|
||||
PlusIcon,
|
||||
SearchIcon,
|
||||
ServerIcon,
|
||||
@@ -394,6 +395,11 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
|
||||
settlementSupported: boolean;
|
||||
// Same contract for thread.snooze/unsnooze.
|
||||
snoozeSupported: boolean;
|
||||
// Renders the pin glyph. Pinned cards keep the full settle/snooze quick
|
||||
// actions: settling clears the pin server-side, and snoozing hides the
|
||||
// card until wake with the pin intact underneath. Pin/unpin themselves
|
||||
// live in the context menu only.
|
||||
isPinned: boolean;
|
||||
// Compact wake countdown ("2h") for rows in the snoozed shelf.
|
||||
snoozeWakeLabelText: string | null;
|
||||
// When a snooze ended (timer or early wake); drives the Woke pill until
|
||||
@@ -757,7 +763,9 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
|
||||
type="button"
|
||||
onClick={handlePrClick}
|
||||
className={cn(
|
||||
"shrink-0 font-mono text-xs hover:underline",
|
||||
// Sidebar chrome follows the interface font; tabular digits keep the
|
||||
// number from reflowing as PR states stream in.
|
||||
"shrink-0 text-xs tabular-nums hover:underline",
|
||||
variant === "slim" && variantAction === "unsettle"
|
||||
? props.isActive
|
||||
? "text-muted-foreground/70"
|
||||
@@ -937,6 +945,13 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
|
||||
) : (
|
||||
<span className="flex-1" />
|
||||
)}
|
||||
{props.isPinned ? (
|
||||
<PinIcon
|
||||
aria-label="Pinned"
|
||||
role="img"
|
||||
className="size-3 shrink-0 text-muted-foreground/65"
|
||||
/>
|
||||
) : null}
|
||||
{/* The visible state owns this slot's width: status at rest,
|
||||
actions on hover/keyboard focus or while the popover is open. Keeping
|
||||
the hidden state out of flow lets the project label reclaim
|
||||
@@ -1184,8 +1199,15 @@ export default function SidebarV2() {
|
||||
const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete);
|
||||
const sidebarProjectSortOrder = useClientSettings((s) => s.sidebarProjectSortOrder);
|
||||
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
|
||||
const { settleThread, unsettleThread, snoozeThread, unsnoozeThread, deleteThread } =
|
||||
useThreadActions();
|
||||
const {
|
||||
settleThread,
|
||||
unsettleThread,
|
||||
snoozeThread,
|
||||
unsnoozeThread,
|
||||
pinThread,
|
||||
unpinThread,
|
||||
deleteThread,
|
||||
} = useThreadActions();
|
||||
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
|
||||
reportFailure: false,
|
||||
});
|
||||
@@ -1562,76 +1584,91 @@ export default function SidebarV2() {
|
||||
// merging, no optimistic holds. Archived threads remain hidden here —
|
||||
// archive keeps its original "remove from sidebar" meaning.
|
||||
const serverConfigs = useAtomValue(environmentServerConfigsAtom);
|
||||
const { activeThreads, snoozedThreads, settledThreads, snoozeNow } = useMemo(() => {
|
||||
const now = `${nowMinute}:00.000Z`;
|
||||
// Snooze classification uses a REAL clock, not the quantized minute:
|
||||
// wake times are second-precise and a woken thread must not linger on
|
||||
// the shelf for the rest of the minute. snoozeWakeTick re-runs this
|
||||
// memo exactly at the next wake boundary.
|
||||
void snoozeWakeTick;
|
||||
const preciseNow = new Date().toISOString();
|
||||
const visible = threads.filter(
|
||||
(thread) =>
|
||||
thread.archivedAt === null &&
|
||||
(scopedProjectKeys === null ||
|
||||
scopedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`)),
|
||||
);
|
||||
const active: EnvironmentThreadShell[] = [];
|
||||
const snoozed: EnvironmentThreadShell[] = [];
|
||||
const settled: EnvironmentThreadShell[] = [];
|
||||
for (const thread of visible) {
|
||||
// Threads on servers without the settlement capability (old server,
|
||||
// or descriptor not loaded yet) never classify as settled: the user
|
||||
// could neither un-settle nor pin them, so auto-settling them would
|
||||
// strand rows in a tail with no working affordances.
|
||||
const supportsSettlement =
|
||||
serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSettlement === true;
|
||||
const supportsSnooze =
|
||||
serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true;
|
||||
const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
|
||||
const changeRequestState = changeRequestStateByKey.get(threadKey) ?? null;
|
||||
// Snooze outranks settled classification: an explicitly snoozed thread
|
||||
// belongs to the shelf even if it would also auto-settle (the shelf's
|
||||
// wake time is a stronger statement about when it matters again).
|
||||
if (supportsSnooze && effectiveSnoozed(thread, { now: preciseNow })) {
|
||||
snoozed.push(thread);
|
||||
} else if (
|
||||
supportsSettlement &&
|
||||
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
|
||||
) {
|
||||
settled.push(thread);
|
||||
} else {
|
||||
active.push(thread);
|
||||
const { pinnedThreads, activeThreads, snoozedThreads, settledThreads, snoozeNow } =
|
||||
useMemo(() => {
|
||||
const now = `${nowMinute}:00.000Z`;
|
||||
// Snooze classification uses a REAL clock, not the quantized minute:
|
||||
// wake times are second-precise and a woken thread must not linger on
|
||||
// the shelf for the rest of the minute. snoozeWakeTick re-runs this
|
||||
// memo exactly at the next wake boundary.
|
||||
void snoozeWakeTick;
|
||||
const preciseNow = new Date().toISOString();
|
||||
const visible = threads.filter(
|
||||
(thread) =>
|
||||
thread.archivedAt === null &&
|
||||
(scopedProjectKeys === null ||
|
||||
scopedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`)),
|
||||
);
|
||||
const pinned: EnvironmentThreadShell[] = [];
|
||||
const active: EnvironmentThreadShell[] = [];
|
||||
const snoozed: EnvironmentThreadShell[] = [];
|
||||
const settled: EnvironmentThreadShell[] = [];
|
||||
for (const thread of visible) {
|
||||
// Threads on servers without the settlement capability (old server,
|
||||
// or descriptor not loaded yet) never classify as settled: the user
|
||||
// could neither un-settle nor pin them, so auto-settling them would
|
||||
// strand rows in a tail with no working affordances.
|
||||
const supportsSettlement =
|
||||
serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSettlement ===
|
||||
true;
|
||||
const supportsSnooze =
|
||||
serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true;
|
||||
const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
|
||||
const changeRequestState = changeRequestStateByKey.get(threadKey) ?? null;
|
||||
// Snooze outranks everything, including a pin: "hide until Tuesday"
|
||||
// temporarily suspends "keep on top". The pin survives underneath —
|
||||
// pinned cards are creation-ordered, so on wake the thread reappears
|
||||
// at its original spot in the pinned block. (For unpinned threads
|
||||
// this is also the snooze-beats-auto-settle rule: the wake time is a
|
||||
// stronger statement about when the thread matters again.)
|
||||
if (supportsSnooze && effectiveSnoozed(thread, { now: preciseNow })) {
|
||||
snoozed.push(thread);
|
||||
// A pin otherwise overrides the lifecycle: pinned threads never
|
||||
// auto-settle out of sight. (The decider clears settled state on
|
||||
// pin and the pin on settle, so pin-vs-settled conflicts only
|
||||
// arise from stale or raced writes.)
|
||||
} else if (thread.pinnedAt != null) {
|
||||
pinned.push(thread);
|
||||
} else if (
|
||||
supportsSettlement &&
|
||||
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
|
||||
) {
|
||||
settled.push(thread);
|
||||
} else {
|
||||
active.push(thread);
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
activeThreads: sortThreadsForSidebarV2(active),
|
||||
// Soonest wake first: "what comes back next" is the shelf's question.
|
||||
snoozedThreads: snoozed.toSorted(
|
||||
(left, right) =>
|
||||
firstValidTimestampMs(left.snoozedUntil ?? null) -
|
||||
firstValidTimestampMs(right.snoozedUntil ?? null),
|
||||
),
|
||||
settledThreads: sortSettledThreadsForSidebarV2(settled),
|
||||
snoozeNow: preciseNow,
|
||||
};
|
||||
}, [
|
||||
autoSettleAfterDays,
|
||||
changeRequestStateByKey,
|
||||
nowMinute,
|
||||
scopedProjectKeys,
|
||||
serverConfigs,
|
||||
snoozeWakeTick,
|
||||
threads,
|
||||
]);
|
||||
return {
|
||||
// Same static creation order as the inbox: a pin freezes prominence,
|
||||
// it does not introduce a new ordering scheme.
|
||||
pinnedThreads: sortThreadsForSidebarV2(pinned),
|
||||
activeThreads: sortThreadsForSidebarV2(active),
|
||||
// Soonest wake first: "what comes back next" is the shelf's question.
|
||||
snoozedThreads: snoozed.toSorted(
|
||||
(left, right) =>
|
||||
firstValidTimestampMs(left.snoozedUntil ?? null) -
|
||||
firstValidTimestampMs(right.snoozedUntil ?? null),
|
||||
),
|
||||
settledThreads: sortSettledThreadsForSidebarV2(settled),
|
||||
snoozeNow: preciseNow,
|
||||
};
|
||||
}, [
|
||||
autoSettleAfterDays,
|
||||
changeRequestStateByKey,
|
||||
nowMinute,
|
||||
scopedProjectKeys,
|
||||
serverConfigs,
|
||||
snoozeWakeTick,
|
||||
threads,
|
||||
]);
|
||||
|
||||
const threadSearchInputRef = useRef<HTMLInputElement>(null);
|
||||
const [threadSearchQuery, setThreadSearchQuery] = useState("");
|
||||
const [activeSearchResultIndex, setActiveSearchResultIndex] = useState(0);
|
||||
const isSearchingThreads = threadSearchQuery.trim().length > 0;
|
||||
const searchableThreads = useMemo(
|
||||
() => [...activeThreads, ...snoozedThreads, ...settledThreads],
|
||||
[activeThreads, settledThreads, snoozedThreads],
|
||||
() => [...pinnedThreads, ...activeThreads, ...snoozedThreads, ...settledThreads],
|
||||
[activeThreads, pinnedThreads, settledThreads, snoozedThreads],
|
||||
);
|
||||
const threadSearchResults = useMemo(
|
||||
() => searchSidebarThreadsByTitle(searchableThreads, threadSearchQuery),
|
||||
@@ -1735,8 +1772,8 @@ export default function SidebarV2() {
|
||||
}, [routeThreadKey, snoozedShelfExpanded, snoozedThreads]);
|
||||
|
||||
const orderedThreads = useMemo(
|
||||
() => [...activeThreads, ...visibleSnoozedThreads, ...renderedSettledThreads],
|
||||
[activeThreads, visibleSnoozedThreads, renderedSettledThreads],
|
||||
() => [...pinnedThreads, ...activeThreads, ...visibleSnoozedThreads, ...renderedSettledThreads],
|
||||
[pinnedThreads, activeThreads, visibleSnoozedThreads, renderedSettledThreads],
|
||||
);
|
||||
const orderedThreadKeys = useMemo(
|
||||
() =>
|
||||
@@ -2038,6 +2075,42 @@ export default function SidebarV2() {
|
||||
},
|
||||
[unsnoozeThread],
|
||||
);
|
||||
const attemptPin = useCallback(
|
||||
(threadRef: ScopedThreadRef) => {
|
||||
void (async () => {
|
||||
const result = await pinThread(threadRef);
|
||||
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to pin thread",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
})();
|
||||
},
|
||||
[pinThread],
|
||||
);
|
||||
const attemptUnpin = useCallback(
|
||||
(threadRef: ScopedThreadRef) => {
|
||||
void (async () => {
|
||||
const result = await unpinThread(threadRef);
|
||||
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to unpin thread",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
})();
|
||||
},
|
||||
[unpinThread],
|
||||
);
|
||||
// One snooze per thread at a time — same double-dispatch guard as settle.
|
||||
const snoozingThreadKeysRef = useRef(new Set<string>());
|
||||
const attemptSnooze = useCallback(
|
||||
@@ -2201,7 +2274,8 @@ export default function SidebarV2() {
|
||||
// Post-settle navigation must skip threads settling in this same
|
||||
// batch — they are all leaving the card block together. Rows that
|
||||
// are already explicitly settled are skipped: nothing to do on a
|
||||
// valid mixed selection.
|
||||
// valid mixed selection. Pinned rows ARE included: the decider
|
||||
// clears the pin as part of settling, so they park like the rest.
|
||||
const coSettlingKeys = new Set(threadKeys);
|
||||
for (const threadKey of threadKeys) {
|
||||
const thread = threadByKeyRef.current.get(threadKey);
|
||||
@@ -2298,12 +2372,15 @@ export default function SidebarV2() {
|
||||
true;
|
||||
const supportsSnooze =
|
||||
serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true;
|
||||
const supportsPinning =
|
||||
serverConfigs.get(thread.environmentId)?.environment.capabilities.threadPinning === true;
|
||||
const supportsTitleRegeneration =
|
||||
serverConfigs.get(thread.environmentId)?.environment.capabilities
|
||||
.threadTitleRegeneration === true;
|
||||
const isRegeneratingTitle = thread.titleRegeneration != null;
|
||||
const isSettled = settledThreadKeysRef.current.has(threadKey);
|
||||
const isSnoozed = snoozedThreadKeysRef.current.has(threadKey);
|
||||
const isPinned = thread.pinnedAt != null;
|
||||
// Presets resolve at menu-open time (same as the popover).
|
||||
const snoozePresets = resolveSnoozePresets(new Date());
|
||||
const clicked = await settlePromise(() =>
|
||||
@@ -2317,6 +2394,16 @@ export default function SidebarV2() {
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(supportsPinning
|
||||
? [
|
||||
isPinned
|
||||
? { id: "unpin", label: "Unpin thread" }
|
||||
: { id: "pin", label: "Pin thread" },
|
||||
]
|
||||
: []),
|
||||
// Both lifecycle actions stay available on pinned threads:
|
||||
// settling clears the pin ("done" beats "keep on top"), and
|
||||
// snoozing hides the card until wake with the pin intact.
|
||||
...(supportsSettlement
|
||||
? [
|
||||
isSettled
|
||||
@@ -2398,6 +2485,12 @@ export default function SidebarV2() {
|
||||
case "unsnooze":
|
||||
attemptUnsnooze(threadRef);
|
||||
return;
|
||||
case "pin":
|
||||
attemptPin(threadRef);
|
||||
return;
|
||||
case "unpin":
|
||||
attemptUnpin(threadRef);
|
||||
return;
|
||||
case "rename":
|
||||
startThreadRename(threadRef, thread.title);
|
||||
return;
|
||||
@@ -2472,8 +2565,10 @@ export default function SidebarV2() {
|
||||
})();
|
||||
},
|
||||
[
|
||||
attemptPin,
|
||||
attemptSettle,
|
||||
attemptSnooze,
|
||||
attemptUnpin,
|
||||
attemptUnsettle,
|
||||
attemptUnsnooze,
|
||||
confirmThreadDelete,
|
||||
@@ -2828,7 +2923,7 @@ export default function SidebarV2() {
|
||||
{(() => {
|
||||
const renderThreadRow = (
|
||||
thread: EnvironmentThreadShell,
|
||||
section: "active" | "snoozed" | "settled",
|
||||
section: "pinned" | "active" | "snoozed" | "settled",
|
||||
) => {
|
||||
const threadKey = scopedThreadKey(
|
||||
scopeThreadRef(thread.environmentId, thread.id),
|
||||
@@ -2837,7 +2932,7 @@ export default function SidebarV2() {
|
||||
// row: every other thread is a full card. Density comes
|
||||
// from users (or the auto rules) actually parking work,
|
||||
// not from the sidebar second-guessing what still matters.
|
||||
const isCard = section === "active";
|
||||
const isCard = section === "active" || section === "pinned";
|
||||
const rowVariant = isCard ? "card" : "slim";
|
||||
return (
|
||||
<SidebarV2Row
|
||||
@@ -2868,6 +2963,7 @@ export default function SidebarV2() {
|
||||
serverConfigs.get(thread.environmentId)?.environment.capabilities
|
||||
.threadSnooze === true
|
||||
}
|
||||
isPinned={section === "pinned"}
|
||||
snoozeWakeLabelText={
|
||||
section === "snoozed" && thread.snoozedUntil != null
|
||||
? snoozeWakeLabel(thread.snoozedUntil, {
|
||||
@@ -2910,9 +3006,25 @@ export default function SidebarV2() {
|
||||
/>
|
||||
);
|
||||
};
|
||||
const items: ReactNode[] = activeThreads.map((thread) =>
|
||||
renderThreadRow(thread, "active"),
|
||||
// Pinned block: full cards above the inbox, closed by a
|
||||
// thin divider (the pin glyphs carry the meaning, so no
|
||||
// header text). Vanishes entirely at count 0.
|
||||
const items: ReactNode[] = pinnedThreads.map((thread) =>
|
||||
renderThreadRow(thread, "pinned"),
|
||||
);
|
||||
if (pinnedThreads.length > 0) {
|
||||
items.push(
|
||||
<li
|
||||
key="pinned-divider"
|
||||
aria-hidden
|
||||
data-testid="sidebar-v2-pinned-divider"
|
||||
className="mx-2.5 my-1.5 h-px list-none bg-sidebar-border/60"
|
||||
/>,
|
||||
);
|
||||
}
|
||||
for (const thread of activeThreads) {
|
||||
items.push(renderThreadRow(thread, "active"));
|
||||
}
|
||||
// Snoozed shelf: between the inbox and Settled — out of the
|
||||
// way, never gone. The header always renders while anything
|
||||
// is snoozed (the count is the whole footprint when
|
||||
@@ -3004,7 +3116,11 @@ export default function SidebarV2() {
|
||||
</TooltipProvider>
|
||||
) : null}
|
||||
{!isSearchingThreads &&
|
||||
activeThreads.length + snoozedThreads.length + settledThreads.length === 0 ? (
|
||||
pinnedThreads.length +
|
||||
activeThreads.length +
|
||||
snoozedThreads.length +
|
||||
settledThreads.length ===
|
||||
0 ? (
|
||||
<div className="flex flex-col items-center gap-2 px-2 py-6 text-center text-xs text-muted-foreground/60">
|
||||
{projects.length === 0 ? (
|
||||
<>
|
||||
|
||||
@@ -56,6 +56,7 @@ import {
|
||||
type ThreadTerminalGroup,
|
||||
} from "../types";
|
||||
import { readLocalApi } from "~/localApi";
|
||||
import { useClientSettings } from "../hooks/useSettings";
|
||||
import { useAttachedTerminalSession } from "../state/terminalSessions";
|
||||
import { serverEnvironment } from "../state/server";
|
||||
import { previewEnvironment } from "../state/preview";
|
||||
@@ -131,7 +132,13 @@ function normalizeComputedColor(value: string | null | undefined, fallback: stri
|
||||
return value ?? fallback;
|
||||
}
|
||||
|
||||
function terminalThemeFromApp(mountElement?: HTMLElement | null): GhosttyTheme {
|
||||
/** The surface treats an omitted family or size as "use the built-in default". */
|
||||
function terminalFontOptions(family: string, size: number): { family?: string; size: number } {
|
||||
const trimmed = family.trim();
|
||||
return trimmed.length > 0 ? { family: trimmed, size } : { size };
|
||||
}
|
||||
|
||||
export function terminalThemeFromApp(mountElement?: HTMLElement | null): GhosttyTheme {
|
||||
const isDark = document.documentElement.classList.contains("dark");
|
||||
const fallbackBackground = isDark ? "rgb(14, 18, 24)" : "rgb(255, 255, 255)";
|
||||
const fallbackForeground = isDark ? "rgb(237, 241, 247)" : "rgb(28, 33, 41)";
|
||||
@@ -305,6 +312,13 @@ export function TerminalViewport({
|
||||
onAddTerminalContext(selection);
|
||||
});
|
||||
const readTerminalLabel = useEffectEvent(() => terminalLabel);
|
||||
// The terminal inherits the monospace (code) preference unless it has an
|
||||
// override of its own, so one font choice drives every mono surface.
|
||||
const terminalFontFamily = useClientSettings(
|
||||
(settings) => settings.fontFamilyTerminal.trim() || settings.fontFamilyCode,
|
||||
);
|
||||
const terminalFontSize = useClientSettings((settings) => settings.fontSizeTerminal);
|
||||
const terminalFontRef = useRef({ family: terminalFontFamily, size: terminalFontSize });
|
||||
const terminalSession = useAttachedTerminalSession({
|
||||
environmentId,
|
||||
terminal: {
|
||||
@@ -367,6 +381,13 @@ export function TerminalViewport({
|
||||
keybindingsRef.current = keybindings;
|
||||
}, [keybindings]);
|
||||
|
||||
useEffect(() => {
|
||||
const current = terminalFontRef.current;
|
||||
if (current.family === terminalFontFamily && current.size === terminalFontSize) return;
|
||||
terminalFontRef.current = { family: terminalFontFamily, size: terminalFontSize };
|
||||
void terminalRef.current?.setFont(terminalFontOptions(terminalFontFamily, terminalFontSize));
|
||||
}, [terminalFontFamily, terminalFontSize]);
|
||||
|
||||
useEffect(() => {
|
||||
const mount = containerRef.current;
|
||||
if (!mount) return;
|
||||
@@ -378,8 +399,10 @@ export function TerminalViewport({
|
||||
let setupCleanups: Array<() => void> = [];
|
||||
|
||||
const setup = async (): Promise<(() => void) | null> => {
|
||||
const setupFont = terminalFontRef.current;
|
||||
const terminalOptions: GhosttyTerminalSurfaceOptions = {
|
||||
theme: terminalThemeFromApp(mount),
|
||||
font: terminalFontOptions(setupFont.family, setupFont.size),
|
||||
onData: (data) => handleData(data),
|
||||
onResize: (cols, rows) => void resizeTerminal(cols, rows),
|
||||
onSelectionChange: () => handleSelectionChange(),
|
||||
@@ -397,6 +420,13 @@ export function TerminalViewport({
|
||||
terminal.setTheme(terminalThemeFromApp(mount));
|
||||
setupTerminal = terminal;
|
||||
terminalRef.current = terminal;
|
||||
// Client settings hydrate asynchronously; a font preference that landed
|
||||
// while the surface was loading found terminalRef null, so its setFont
|
||||
// was dropped. Re-apply whatever is current once the terminal exists.
|
||||
const currentFont = terminalFontRef.current;
|
||||
if (currentFont.family !== setupFont.family || currentFont.size !== setupFont.size) {
|
||||
void terminal.setFont(terminalFontOptions(currentFont.family, currentFont.size));
|
||||
}
|
||||
const latestSession = latestSessionRef.current;
|
||||
previousSessionRef.current = latestSession;
|
||||
if (latestSession.buffer.length > 0) terminal.resetAndWrite(latestSession.buffer);
|
||||
|
||||
@@ -777,7 +777,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
onLayout={updateModelListScrollFades}
|
||||
onScroll={updateModelListScrollFades}
|
||||
className={cn(
|
||||
"model-picker-list h-full overflow-x-hidden overscroll-y-contain py-1.5 [--fade-size:1.5rem]",
|
||||
"model-picker-list scrollbar-gutter-stable h-full overflow-x-hidden overscroll-y-contain py-1.5 [--fade-size:1.5rem]",
|
||||
showTopScrollFade && "model-picker-list-scroll-fade-top",
|
||||
showBottomScrollFade && "model-picker-list-scroll-fade-bottom",
|
||||
)}
|
||||
|
||||
@@ -44,6 +44,15 @@ describe("ProviderStatusBanner", () => {
|
||||
expect(markup).toContain("absolute top-2 right-2");
|
||||
});
|
||||
|
||||
it("renders on a glass surface so the timeline never reads through the banner", () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<ProviderStatusBanner status={warningProvider()} onDismiss={() => {}} />,
|
||||
);
|
||||
|
||||
expect(markup).toContain("alert-glass");
|
||||
expect(markup).toContain('data-variant="warning"');
|
||||
});
|
||||
|
||||
it("labels error dismiss controls with the correct severity", () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<ProviderStatusBanner
|
||||
|
||||
@@ -46,11 +46,12 @@ export const ProviderStatusBanner = memo(function ProviderStatusBanner({
|
||||
<div className="pointer-events-auto mx-auto w-fit max-w-[calc(100%-2rem)] pt-3">
|
||||
<div
|
||||
className={cn(
|
||||
"relative inline-flex items-center gap-3 rounded-xl border py-3 ps-3.5 pe-10 text-card-foreground text-sm",
|
||||
"alert-glass relative inline-flex items-center gap-3 rounded-xl border py-3 ps-3.5 pe-10 text-card-foreground text-sm",
|
||||
status.status === "warning"
|
||||
? "border-warning/32 bg-warning/4 [&_svg]:text-warning"
|
||||
: "border-destructive/32 bg-destructive/4 text-destructive-foreground [&_svg]:text-destructive",
|
||||
? "border-warning/32 [&_svg]:text-warning"
|
||||
: "border-destructive/32 text-destructive-foreground [&_svg]:text-destructive",
|
||||
)}
|
||||
data-variant={status.status === "warning" ? "warning" : "error"}
|
||||
role="alert"
|
||||
>
|
||||
<InfoIcon className="size-4 shrink-0" aria-hidden />
|
||||
|
||||
@@ -1,20 +1,23 @@
|
||||
// Chip metrics are in em so the pills scale with the text they sit in (the
|
||||
// composer honors the prompt font-size preference). The chat variant pins the
|
||||
// original 12px, where every em value resolves to the same pixels as before.
|
||||
const INLINE_CHIP_CLASS_NAME =
|
||||
"inline-flex max-w-full items-center gap-1 rounded-md border border-border/70 bg-accent/40 px-1.5 py-px font-medium text-[12px] leading-[1.1] text-foreground align-middle";
|
||||
"inline-flex max-w-full items-center gap-[0.33em] rounded-[0.5em] border border-border/70 bg-accent/40 px-[0.5em] py-[0.08em] font-medium leading-[1.1] text-foreground align-middle";
|
||||
|
||||
export const CHAT_INLINE_CHIP_CLASS_NAME = INLINE_CHIP_CLASS_NAME;
|
||||
export const CHAT_INLINE_CHIP_CLASS_NAME = `${INLINE_CHIP_CLASS_NAME} text-[12px]`;
|
||||
|
||||
export const COMPOSER_INLINE_CHIP_CLASS_NAME = `${INLINE_CHIP_CLASS_NAME} select-none`;
|
||||
export const COMPOSER_INLINE_CHIP_CLASS_NAME = `${INLINE_CHIP_CLASS_NAME} text-[0.86em] select-none`;
|
||||
|
||||
export const COMPOSER_INLINE_CHIP_ICON_CLASS_NAME = "size-3.5 shrink-0 opacity-85";
|
||||
export const COMPOSER_INLINE_CHIP_ICON_CLASS_NAME = "size-[1.17em] shrink-0 opacity-85";
|
||||
|
||||
export const CHAT_INLINE_CHIP_LABEL_CLASS_NAME = "truncate leading-tight";
|
||||
|
||||
export const COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME = `${CHAT_INLINE_CHIP_LABEL_CLASS_NAME} select-none`;
|
||||
|
||||
export const COMPOSER_INLINE_SKILL_CHIP_CLASS_NAME =
|
||||
"inline-flex max-w-full select-none items-center gap-1 rounded-md border border-fuchsia-500/25 bg-fuchsia-500/12 px-1.5 py-px font-medium text-[12px] leading-[1.1] text-fuchsia-700 align-middle dark:text-fuchsia-300";
|
||||
"inline-flex max-w-full select-none items-center gap-[0.33em] rounded-[0.5em] border border-fuchsia-500/25 bg-fuchsia-500/12 px-[0.5em] py-[0.08em] font-medium text-[0.86em] leading-[1.1] text-fuchsia-700 align-middle dark:text-fuchsia-300";
|
||||
|
||||
export const SKILL_CHIP_ICON_SVG = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.85" stroke-linecap="round" stroke-linejoin="round"><path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z"/><path d="m3.3 7 8.7 5 8.7-5"/><path d="M12 22V12"/></svg>`;
|
||||
export const SKILL_CHIP_ICON_SVG = `<svg width="100%" height="100%" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.85" stroke-linecap="round" stroke-linejoin="round"><path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z"/><path d="m3.3 7 8.7 5 8.7-5"/><path d="M12 22V12"/></svg>`;
|
||||
|
||||
export const COMPOSER_INLINE_CHIP_DISMISS_BUTTON_CLASS_NAME =
|
||||
"ml-0.5 inline-flex size-3.5 shrink-0 cursor-pointer items-center justify-center rounded-sm text-muted-foreground/72 transition-colors hover:bg-foreground/6 hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring";
|
||||
"ml-[0.17em] inline-flex size-[1.17em] shrink-0 cursor-pointer items-center justify-center rounded-sm text-muted-foreground/72 transition-colors hover:bg-foreground/6 hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring";
|
||||
@@ -0,0 +1,59 @@
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
const testState = vi.hoisted(() => ({
|
||||
codeViewOptions: null as Record<string, unknown> | null,
|
||||
}));
|
||||
|
||||
vi.mock("@pierre/diffs/react", () => ({
|
||||
CodeView: (props: { options: Record<string, unknown> }) => {
|
||||
testState.codeViewOptions = props.options;
|
||||
return null;
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/composerDraftStore", () => ({
|
||||
useComposerDraftStore: (selector: (store: Record<string, unknown>) => unknown) =>
|
||||
selector({
|
||||
addReviewComment: vi.fn(),
|
||||
removeReviewComment: vi.fn(),
|
||||
getComposerDraft: () => undefined,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../files/LocalCommentAnnotation", () => ({
|
||||
LocalCommentAnnotation: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("../files/fileCommentAnnotations", () => ({
|
||||
nextFileCommentId: () => "comment-test",
|
||||
}));
|
||||
|
||||
import { AnnotatableCodeView } from "./AnnotatableCodeView";
|
||||
|
||||
describe("AnnotatableCodeView", () => {
|
||||
beforeEach(() => {
|
||||
testState.codeViewOptions = null;
|
||||
});
|
||||
|
||||
it("opens comments from Pierre's gutter action without ending line selection", () => {
|
||||
renderToStaticMarkup(
|
||||
<AnnotatableCodeView
|
||||
codeViewKey="test-view"
|
||||
files={[]}
|
||||
sectionId="working-tree"
|
||||
sectionTitle="Working tree"
|
||||
composerDraftTarget={"draft-test" as never}
|
||||
options={{}}
|
||||
renderHeaderPrefix={() => null}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(testState.codeViewOptions).toMatchObject({
|
||||
enableGutterUtility: true,
|
||||
enableLineSelection: true,
|
||||
onGutterUtilityClick: expect.any(Function),
|
||||
});
|
||||
expect(testState.codeViewOptions).not.toHaveProperty("onLineSelectionEnd");
|
||||
});
|
||||
});
|
||||
@@ -71,6 +71,7 @@ function appendAnnotationEntry(
|
||||
}
|
||||
|
||||
interface AnnotatableCodeViewProps {
|
||||
codeViewKey: string;
|
||||
files: ReadonlyArray<{
|
||||
fileDiff: FileDiffMetadata;
|
||||
filePath: string;
|
||||
@@ -95,6 +96,7 @@ interface DiffSelectionContext {
|
||||
}
|
||||
|
||||
export function AnnotatableCodeView({
|
||||
codeViewKey,
|
||||
files,
|
||||
sectionId,
|
||||
sectionTitle,
|
||||
@@ -117,6 +119,7 @@ export function AnnotatableCodeView({
|
||||
fileKey: string;
|
||||
annotation: DiffCommentLineAnnotation;
|
||||
} | null>(null);
|
||||
const [draftText, setDraftText] = useState("");
|
||||
|
||||
const filesByKey = useMemo(() => new Map(files.map((file) => [file.fileKey, file])), [files]);
|
||||
const items = useMemo<CodeViewDiffItem<DiffCommentAnnotationGroup>[]>(
|
||||
@@ -167,6 +170,7 @@ export function AnnotatableCodeView({
|
||||
setSelectedLines(null);
|
||||
if (draft?.annotation.metadata.entries.some((entry) => entry.id === entryId)) {
|
||||
setDraft(null);
|
||||
setDraftText("");
|
||||
} else {
|
||||
removeReviewComment(composerDraftTarget, entryId);
|
||||
}
|
||||
@@ -193,6 +197,7 @@ export function AnnotatableCodeView({
|
||||
if (comment) addReviewComment(composerDraftTarget, comment);
|
||||
setSelectedLines(null);
|
||||
setDraft(null);
|
||||
setDraftText("");
|
||||
},
|
||||
[addReviewComment, composerDraftTarget, draft, filesByKey, sectionId, sectionTitle],
|
||||
);
|
||||
@@ -215,6 +220,7 @@ export function AnnotatableCodeView({
|
||||
text: "",
|
||||
});
|
||||
if (!comment) return;
|
||||
setDraftText("");
|
||||
setDraft({
|
||||
fileKey: item.id,
|
||||
annotation: {
|
||||
@@ -232,6 +238,7 @@ export function AnnotatableCodeView({
|
||||
const hasOpenComment = draft !== null;
|
||||
return (
|
||||
<CodeView<DiffCommentAnnotationGroup>
|
||||
key={codeViewKey}
|
||||
{...(viewerRef ? { ref: viewerRef } : {})}
|
||||
{...(className ? { className } : {})}
|
||||
items={items}
|
||||
@@ -241,28 +248,34 @@ export function AnnotatableCodeView({
|
||||
...options,
|
||||
enableGutterUtility: !hasOpenComment,
|
||||
enableLineSelection: !hasOpenComment,
|
||||
onLineSelectionEnd: beginComment,
|
||||
onGutterUtilityClick: beginComment,
|
||||
}}
|
||||
renderHeaderPrefix={(item) =>
|
||||
item.type === "diff"
|
||||
? renderHeaderPrefix(item.fileDiff, item.id, item.collapsed === true)
|
||||
: null
|
||||
}
|
||||
renderAnnotation={(annotation) => (
|
||||
<div className="py-1">
|
||||
{annotation.metadata.entries.map((entry) => (
|
||||
<LocalCommentAnnotation
|
||||
key={entry.id}
|
||||
kind={entry.kind}
|
||||
rangeLabel={entry.rangeLabel}
|
||||
text={entry.text}
|
||||
onCancel={() => removeEntry(entry.id)}
|
||||
onComment={(text) => submitEntry(entry.id, text)}
|
||||
onDelete={() => removeEntry(entry.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
renderAnnotation={(annotation) => {
|
||||
const hasDraft = annotation.metadata.entries.some((entry) => entry.kind === "draft");
|
||||
return (
|
||||
<div
|
||||
className={hasDraft ? "py-1" : "divide-y divide-border/30 border-y border-border/30"}
|
||||
>
|
||||
{annotation.metadata.entries.map((entry) => (
|
||||
<LocalCommentAnnotation
|
||||
key={entry.id}
|
||||
kind={entry.kind}
|
||||
rangeLabel={entry.rangeLabel}
|
||||
text={entry.kind === "draft" ? draftText : entry.text}
|
||||
onTextChange={setDraftText}
|
||||
onCancel={() => removeEntry(entry.id)}
|
||||
onComment={(text) => submitEntry(entry.id, text)}
|
||||
onDelete={() => removeEntry(entry.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { LocalCommentAnnotation } from "./LocalCommentAnnotation";
|
||||
|
||||
const callbacks = {
|
||||
onTextChange: vi.fn(),
|
||||
onCancel: vi.fn(),
|
||||
onComment: vi.fn(),
|
||||
onDelete: vi.fn(),
|
||||
};
|
||||
|
||||
describe("LocalCommentAnnotation", () => {
|
||||
it("renders the draft composer directly in the selected diff", () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<LocalCommentAnnotation kind="draft" rangeLabel="+78" text="" {...callbacks} />,
|
||||
);
|
||||
|
||||
expect(markup).toContain("font-sans");
|
||||
expect(markup).not.toContain("chat-composer-glass");
|
||||
expect(markup).not.toContain("font-mono");
|
||||
expect(markup).not.toContain("Local comment");
|
||||
expect(markup).not.toContain("on +78");
|
||||
expect(markup).toContain("⌘/Ctrl Enter to send");
|
||||
expect(markup).toContain("Add a comment…");
|
||||
expect(markup).toContain(">Comment</button>");
|
||||
expect(markup).toContain("autofocus");
|
||||
const textareaControl = markup.match(/<span[^>]*data-slot="textarea-control"[^>]*>/)?.[0];
|
||||
expect(textareaControl).toBeDefined();
|
||||
expect(textareaControl).not.toContain("ring-ring");
|
||||
expect(markup).toContain("cursor-text");
|
||||
});
|
||||
|
||||
it("renders a saved comment without a nested card or redundant range label", () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<LocalCommentAnnotation
|
||||
kind="comment"
|
||||
rangeLabel="+78"
|
||||
text="Please keep this branch explicit."
|
||||
{...callbacks}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain("font-sans");
|
||||
expect(markup).not.toContain("chat-composer-glass");
|
||||
expect(markup).not.toContain("on +78");
|
||||
expect(markup).toContain("Please keep this branch explicit.");
|
||||
expect(markup).toContain('aria-label="Delete comment"');
|
||||
expect(markup).toContain("border-s-2");
|
||||
expect(markup).toContain("bg-primary/[0.045]");
|
||||
expect(markup).toContain("lucide-message-circle");
|
||||
});
|
||||
|
||||
it("renders draft text owned by the annotation wrapper", () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<LocalCommentAnnotation
|
||||
kind="draft"
|
||||
rangeLabel="+78"
|
||||
text="Keep this unsaved draft"
|
||||
{...callbacks}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain("Keep this unsaved draft");
|
||||
});
|
||||
});
|
||||
@@ -8,6 +8,7 @@ interface LocalCommentAnnotationProps {
|
||||
kind: "draft" | "comment";
|
||||
rangeLabel: string;
|
||||
text: string;
|
||||
onTextChange?: (text: string) => void;
|
||||
onCancel: () => void;
|
||||
onComment: (text: string) => void;
|
||||
onDelete: () => void;
|
||||
@@ -16,32 +17,34 @@ interface LocalCommentAnnotationProps {
|
||||
export function LocalCommentAnnotation({
|
||||
kind,
|
||||
rangeLabel,
|
||||
text: savedText,
|
||||
text,
|
||||
onTextChange,
|
||||
onCancel,
|
||||
onComment,
|
||||
onDelete,
|
||||
}: LocalCommentAnnotationProps) {
|
||||
const [text, setText] = useState("");
|
||||
const [localDraftText, setLocalDraftText] = useState("");
|
||||
const displayedText = kind === "draft" && !onTextChange ? localDraftText : text;
|
||||
|
||||
if (kind === "comment") {
|
||||
return (
|
||||
<div
|
||||
data-file-comment-annotation
|
||||
className="mx-3 my-2 rounded-xl border border-border/70 bg-background p-3 shadow-sm"
|
||||
className="group/comment flex min-w-0 items-start gap-2.5 border-s-2 border-primary/55 bg-primary/[0.045] px-3 py-2.5 font-sans text-foreground"
|
||||
contentEditable={false}
|
||||
onPointerDown={(event) => event.stopPropagation()}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<MessageCircle className="size-4 text-muted-foreground" />
|
||||
<span className="text-xs font-medium">Local comment</span>
|
||||
<span className="ml-auto text-[11px] text-muted-foreground">{rangeLabel}</span>
|
||||
<Button variant="ghost" size="icon-xs" aria-label="Delete comment" onClick={onDelete}>
|
||||
<Trash2 className="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
<p className="mt-2 whitespace-pre-wrap text-sm leading-relaxed text-foreground">
|
||||
{savedText}
|
||||
</p>
|
||||
<MessageCircle className="mt-0.5 size-3.5 shrink-0 text-primary/70" aria-hidden="true" />
|
||||
<p className="min-w-0 flex-1 whitespace-pre-wrap text-[13px] leading-5">{displayedText}</p>
|
||||
<Button
|
||||
className="-my-1 -mr-1 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover/comment:opacity-100 focus-visible:opacity-100 max-sm:opacity-100"
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
aria-label="Delete comment"
|
||||
onClick={onDelete}
|
||||
>
|
||||
<Trash2 className="size-3" />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -49,39 +52,49 @@ export function LocalCommentAnnotation({
|
||||
return (
|
||||
<div
|
||||
data-file-comment-annotation
|
||||
className="mx-3 my-2 rounded-xl border border-border/70 bg-background p-3 shadow-lg"
|
||||
className="px-3 py-2 font-sans text-foreground"
|
||||
contentEditable={false}
|
||||
onPointerDown={(event) => event.stopPropagation()}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<MessageCircle className="size-4 text-muted-foreground" />
|
||||
<span className="text-sm font-medium">Local comment</span>
|
||||
</div>
|
||||
<div className="mt-1 text-xs text-muted-foreground">Comment on lines {rangeLabel}</div>
|
||||
<Textarea
|
||||
autoFocus
|
||||
className="mt-3"
|
||||
unstyled
|
||||
className="relative inline-flex w-full rounded-md border border-border/50 bg-background/20 font-sans text-foreground transition-colors focus-within:border-border/70 [&_[data-slot=textarea]]:min-h-12 [&_[data-slot=textarea]]:cursor-text [&_[data-slot=textarea]]:px-2.5 [&_[data-slot=textarea]]:py-1.5 [&_[data-slot=textarea]]:font-sans [&_[data-slot=textarea]]:text-xs [&_[data-slot=textarea]]:leading-5 max-sm:[&_[data-slot=textarea]]:min-h-12"
|
||||
size="sm"
|
||||
value={text}
|
||||
placeholder="Request change"
|
||||
value={displayedText}
|
||||
placeholder="Add a comment…"
|
||||
aria-label={`Comment on lines ${rangeLabel}`}
|
||||
onChange={(event) => setText(event.target.value)}
|
||||
onChange={(event) => (onTextChange ?? setLocalDraftText)(event.target.value)}
|
||||
onFocus={(event) => {
|
||||
const end = event.currentTarget.value.length;
|
||||
event.currentTarget.setSelectionRange(end, end);
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
onCancel();
|
||||
}
|
||||
if ((event.metaKey || event.ctrlKey) && event.key === "Enter" && text.trim()) {
|
||||
if ((event.metaKey || event.ctrlKey) && event.key === "Enter" && displayedText.trim()) {
|
||||
event.preventDefault();
|
||||
onComment(text.trim());
|
||||
onComment(displayedText.trim());
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<div className="mt-3 flex justify-end gap-2">
|
||||
<Button variant="ghost" size="sm" onClick={onCancel}>
|
||||
<div className="mt-1.5 flex items-center gap-1">
|
||||
<span className="mr-auto text-[10px] text-muted-foreground/70">⌘/Ctrl Enter to send</span>
|
||||
<Button
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
onClick={onCancel}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button size="sm" disabled={!text.trim()} onClick={() => onComment(text.trim())}>
|
||||
<Button
|
||||
size="xs"
|
||||
disabled={!displayedText.trim()}
|
||||
onClick={() => onComment(displayedText.trim())}
|
||||
>
|
||||
Comment
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { PreviewChromeRow } from "./PreviewChromeRow";
|
||||
|
||||
describe("PreviewChromeRow", () => {
|
||||
it("shows the complete URL while the address bar is not focused", () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<PreviewChromeRow
|
||||
url="https://example.com/dashboard?mode=edit&tab=1#notes"
|
||||
loading={false}
|
||||
loadProgress={0}
|
||||
canGoBack={false}
|
||||
canGoForward={false}
|
||||
refreshDisabled={false}
|
||||
onBack={vi.fn()}
|
||||
onForward={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
onSubmit={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain('value="https://example.com/dashboard?mode=edit&tab=1#notes"');
|
||||
});
|
||||
});
|
||||
@@ -23,7 +23,6 @@ import { cn } from "~/lib/utils";
|
||||
|
||||
interface Props {
|
||||
url: string;
|
||||
displayUrl?: string | undefined;
|
||||
loading: boolean;
|
||||
loadProgress: number;
|
||||
canGoBack: boolean;
|
||||
@@ -65,7 +64,6 @@ const NOOP = () => {};
|
||||
|
||||
export function PreviewChromeRow({
|
||||
url,
|
||||
displayUrl,
|
||||
loading,
|
||||
loadProgress,
|
||||
canGoBack,
|
||||
@@ -172,7 +170,7 @@ export function PreviewChromeRow({
|
||||
render={
|
||||
<InputGroupInput
|
||||
ref={inputRef}
|
||||
value={inputFocused ? draft : (displayUrl ?? url)}
|
||||
value={inputFocused ? draft : url}
|
||||
className={cn(
|
||||
onOpenInBrowser &&
|
||||
!inputFocused &&
|
||||
@@ -203,7 +201,6 @@ export function PreviewChromeRow({
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{!inputFocused && displayUrl ? <TooltipPopup>{url}</TooltipPopup> : null}
|
||||
</Tooltip>
|
||||
{onOpenInBrowser && !inputFocused ? (
|
||||
<InputGroupAddon
|
||||
|
||||
Loaded 100 of 171 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user