Compare commits
25
Commits
No files matched your search
@@ -0,0 +1,79 @@
|
||||
---
|
||||
name: add-dark-mode
|
||||
description: Add dark mode with colors, shadows, and surfaces handled the way a designer would.
|
||||
---
|
||||
|
||||
# Add Dark Mode
|
||||
|
||||
Use this when the user wants to add dark mode support to an existing UI.
|
||||
|
||||
## Activation
|
||||
|
||||
### Use For
|
||||
|
||||
- adding dark mode to a page, section, component, or site
|
||||
- improving an existing dark mode treatment
|
||||
- converting a light-mode-only UI to support dark mode
|
||||
|
||||
### Do Not Use For
|
||||
|
||||
- brand-new design or layout work
|
||||
- standalone image dark-mode conversion
|
||||
- responsive behavior, component organization, or general visual polish without dark mode
|
||||
|
||||
## Load First
|
||||
|
||||
- No companion files are required.
|
||||
- Dark-mode design guidance is inline below.
|
||||
|
||||
## Progress Updates
|
||||
|
||||
Keep the user informed so longer runs do not look stuck.
|
||||
|
||||
- One-line status update before each major phase.
|
||||
- Concrete and lightweight: what you are doing now, not verbose logs.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Inspect the existing UI and project Tailwind conventions.
|
||||
2. Convert markup to include appropriate dark-mode classes.
|
||||
3. Audit rasterized images for dark-mode variants.
|
||||
4. For each rasterized image that needs a dark-mode variant, hand off to `dark-mode-image`, which MUST load and use the `imagegen` skill before creating or editing image assets.
|
||||
5. Save generated dark-mode images alongside the originals and wire them into the dark-mode UI.
|
||||
|
||||
## Dark Mode Rules
|
||||
|
||||
### Design Rules
|
||||
|
||||
- Dark mode is about maintaining the same contrast ratios as light mode, not simply inverting colors
|
||||
- Dark mode doesn't need to preserve every detail of the light mode design — it just needs to look good
|
||||
- Default dark mode to follow the operating system's `prefers-color-scheme` setting (Tailwind's built-in `dark:` behavior); only add a manual toggle when the user explicitly asks for one
|
||||
- Remove all shadows in dark mode — use `dark:shadow-none`
|
||||
- On dark-mode-only sites, add the `scheme-only-dark` class to `<html>` or the top-level element — ensures native elements like scrollbars, form controls, and `color-scheme` render in dark mode
|
||||
|
||||
### Component Rules
|
||||
|
||||
- Never keep large branded/colored panels in dark mode; instead use the same background color and add a light divider between sections
|
||||
- Style cards only slightly lighter than the page background (e.g. `dark:bg-gray-900` on a `dark:bg-gray-950` page); add a `dark:inset-ring dark:inset-ring-white/5` for definition
|
||||
- Make decorative quote marks in testimonials very faint (e.g. `dark:text-white/5`)
|
||||
- Never use multiple heading text colors in dark mode (e.g. dark gray + brand color); use a single light color like `white` or `gray-100` for all heading text
|
||||
|
||||
### Raster Image Rules
|
||||
|
||||
- When adding or improving dark mode, audit the page for rasterized images that need dark-mode versions: photos, screenshots, product mockups, decorative backgrounds, textures, and rasterized illustrations
|
||||
- Never use CSS filters (`invert`, `brightness`, `contrast`, `opacity`) as the final dark-mode treatment for raster images; always create real dark-mode image files
|
||||
- Generate dark-mode raster image variants with the `dark-mode-image` skill, which MUST load and use the `imagegen` skill before creating or editing any raster image assets
|
||||
|
||||
### SVG Rules
|
||||
|
||||
- For inline `<svg>` elements, style dark mode with Tailwind `dark:*` classes (e.g. `dark:fill-*`, `dark:stroke-*`, `dark:text-*`)
|
||||
- For external SVG files referenced via `<img>`, always create a dark-mode version alongside the original (e.g. `logo.svg` and `logo-dark.svg`); never substitute CSS filters (`invert`, `brightness`) or opacity adjustments for a true dark variant
|
||||
|
||||
## Guardrails
|
||||
|
||||
- Do not generate, edit, or replace raster image assets directly from this skill; `dark-mode-image` owns that work and MUST use the `imagegen` skill.
|
||||
- Require the `dark-mode-image` + `imagegen` handoff even when the image change seems simple, decorative, or incidental.
|
||||
|
||||
## Verify
|
||||
|
||||
- Check light and dark modes for contrast, missing variants, and images that still assume a light background.
|
||||
@@ -13,7 +13,7 @@ jobs:
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: useblacksmith/checkout@v1
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
@@ -46,7 +46,7 @@ jobs:
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: useblacksmith/checkout@v1
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
@@ -88,7 +88,7 @@ jobs:
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: useblacksmith/checkout@v1
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
|
||||
@@ -37,7 +37,7 @@ jobs:
|
||||
ALCHEMY_TELEMETRY_DISABLED: "1"
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: useblacksmith/checkout@v1
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
|
||||
@@ -31,7 +31,7 @@ jobs:
|
||||
|
||||
- name: Checkout
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: useblacksmith/checkout@v1
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
|
||||
@@ -54,7 +54,7 @@ jobs:
|
||||
|
||||
- name: Checkout
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: useblacksmith/checkout@v1
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
|
||||
@@ -76,7 +76,7 @@ jobs:
|
||||
T3_SHOWCASE_ANDROID_ABI: x86_64
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: useblacksmith/checkout@v1
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
|
||||
@@ -35,7 +35,7 @@ jobs:
|
||||
has_changes: ${{ steps.check.outputs.has_changes }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: useblacksmith/checkout@v1
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -81,7 +81,7 @@ jobs:
|
||||
ref: ${{ github.sha }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: useblacksmith/checkout@v1
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -189,7 +189,7 @@ jobs:
|
||||
CLERK_CLI_OAUTH_CLIENT_ID: ${{ vars.CLERK_CLI_OAUTH_CLIENT_ID }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: useblacksmith/checkout@v1
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
@@ -266,7 +266,7 @@ jobs:
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: useblacksmith/checkout@v1
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
fetch-depth: 0
|
||||
@@ -678,7 +678,7 @@ jobs:
|
||||
owner: ${{ github.repository_owner }}
|
||||
|
||||
- name: Checkout
|
||||
uses: useblacksmith/checkout@v1
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
@@ -799,7 +799,7 @@ jobs:
|
||||
VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: useblacksmith/checkout@v1
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
@@ -909,7 +909,7 @@ jobs:
|
||||
owner: ${{ github.repository_owner }}
|
||||
|
||||
- name: Checkout
|
||||
uses: useblacksmith/checkout@v1
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: main
|
||||
fetch-depth: 0
|
||||
@@ -982,7 +982,7 @@ jobs:
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: useblacksmith/checkout@v1
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
|
||||
@@ -54,8 +54,6 @@ There's no public docs site yet, checkout the miscellaneous markdown files in [d
|
||||
## Documentation
|
||||
|
||||
- [Getting started](./docs/getting-started/quick-start.md)
|
||||
- [Remote access](./docs/user/remote-access.md)
|
||||
- [Keeping T3 Code in sync](./docs/user/server-updates.md)
|
||||
- [Architecture overview](./docs/architecture/overview.md)
|
||||
- [Provider guides](./docs/providers/codex.md)
|
||||
- [Operations](./docs/operations/ci.md)
|
||||
|
||||
@@ -50,7 +50,6 @@ export const PREVIEW_ZOOM_IN_CHANNEL = "desktop:preview-zoom-in";
|
||||
export const PREVIEW_ZOOM_OUT_CHANNEL = "desktop:preview-zoom-out";
|
||||
export const PREVIEW_RESET_ZOOM_CHANNEL = "desktop:preview-reset-zoom";
|
||||
export const PREVIEW_HARD_RELOAD_CHANNEL = "desktop:preview-hard-reload";
|
||||
export const PREVIEW_SET_COLOR_SCHEME_CHANNEL = "desktop:preview-set-color-scheme";
|
||||
export const PREVIEW_OPEN_DEVTOOLS_CHANNEL = "desktop:preview-open-devtools";
|
||||
export const PREVIEW_CLEAR_COOKIES_CHANNEL = "desktop:preview-clear-cookies";
|
||||
export const PREVIEW_CLEAR_CACHE_CHANNEL = "desktop:preview-clear-cache";
|
||||
|
||||
@@ -13,7 +13,6 @@ import {
|
||||
DesktopPreviewRecordingSaveInputSchema,
|
||||
DesktopPreviewRegisterWebviewInputSchema,
|
||||
DesktopPreviewScreenshotArtifactSchema,
|
||||
DesktopPreviewSetColorSchemeInputSchema,
|
||||
DesktopPreviewTabInputSchema,
|
||||
DesktopPreviewWebviewConfigSchema,
|
||||
PreviewAnnotationPayloadSchema,
|
||||
@@ -139,15 +138,6 @@ export const hardReload = tabMethod(
|
||||
"desktop.ipc.preview.hardReload",
|
||||
(manager, tabId) => manager.hardReload(tabId),
|
||||
);
|
||||
export const setColorScheme = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_SET_COLOR_SCHEME_CHANNEL,
|
||||
payload: DesktopPreviewSetColorSchemeInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.setColorScheme")(function* ({ tabId, colorScheme }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.setColorScheme(tabId, colorScheme);
|
||||
}),
|
||||
});
|
||||
export const openDevTools = tabMethod(
|
||||
IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL,
|
||||
"desktop.ipc.preview.openDevTools",
|
||||
@@ -356,7 +346,6 @@ export const methods = [
|
||||
zoomOut,
|
||||
resetZoom,
|
||||
hardReload,
|
||||
setColorScheme,
|
||||
openDevTools,
|
||||
clearCookies,
|
||||
clearCache,
|
||||
|
||||
@@ -160,8 +160,6 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
zoomOut: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_ZOOM_OUT_CHANNEL, { tabId }),
|
||||
resetZoom: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_RESET_ZOOM_CHANNEL, { tabId }),
|
||||
hardReload: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_HARD_RELOAD_CHANNEL, { tabId }),
|
||||
setColorScheme: (tabId, colorScheme) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_SET_COLOR_SCHEME_CHANNEL, { tabId, colorScheme }),
|
||||
openDevTools: (tabId) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL, { tabId }),
|
||||
clearCookies: () => ipcRenderer.invoke(IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL),
|
||||
|
||||
@@ -365,79 +365,6 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("emulates prefers-color-scheme and re-applies it across webview swaps", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const makeWebContents = (id: number) => {
|
||||
const sendCommand = vi.fn(async () => undefined);
|
||||
return {
|
||||
sendCommand,
|
||||
wc: {
|
||||
id,
|
||||
isDestroyed: () => false,
|
||||
isDevToolsOpened: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "https://example.com",
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand,
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never,
|
||||
};
|
||||
};
|
||||
const first = makeWebContents(42);
|
||||
fromId.mockReturnValue(first.wc);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_scheme");
|
||||
yield* manager.registerWebview("tab_scheme", 42);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* manager.setColorScheme("tab_scheme", "dark");
|
||||
|
||||
expect(first.sendCommand).toHaveBeenCalledWith("Emulation.setEmulatedMedia", {
|
||||
features: [{ name: "prefers-color-scheme", value: "dark" }],
|
||||
});
|
||||
expect(states.at(-1)?.colorScheme).toBe("dark");
|
||||
|
||||
const replacement = makeWebContents(43);
|
||||
fromId.mockReturnValue(replacement.wc);
|
||||
yield* manager.registerWebview("tab_scheme", 43);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(replacement.sendCommand).toHaveBeenCalledWith("Emulation.setEmulatedMedia", {
|
||||
features: [{ name: "prefers-color-scheme", value: "dark" }],
|
||||
});
|
||||
expect(states.at(-1)?.colorScheme).toBe("dark");
|
||||
|
||||
yield* manager.setColorScheme("tab_scheme", "system");
|
||||
|
||||
expect(replacement.sendCommand).toHaveBeenCalledWith("Emulation.setEmulatedMedia", {
|
||||
features: [{ name: "prefers-color-scheme", value: "" }],
|
||||
});
|
||||
expect(states.at(-1)?.colorScheme).toBe("system");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("keeps a main-frame load failure visible until a retry starts", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
*/
|
||||
import type {
|
||||
DesktopPreviewAnnotationTheme,
|
||||
DesktopPreviewColorScheme,
|
||||
DesktopPreviewPointerEvent,
|
||||
PreviewAnnotationPayload,
|
||||
PreviewAnnotationRect,
|
||||
@@ -85,7 +84,6 @@ export interface PreviewTabState {
|
||||
canGoBack: boolean;
|
||||
canGoForward: boolean;
|
||||
zoomFactor: number;
|
||||
colorScheme: DesktopPreviewColorScheme;
|
||||
controller: "human" | "agent" | "none";
|
||||
updatedAt: string;
|
||||
}
|
||||
@@ -1290,7 +1288,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
zoomFactor: DEFAULT_ZOOM_FACTOR,
|
||||
colorScheme: "system",
|
||||
controller: "none",
|
||||
updatedAt,
|
||||
};
|
||||
@@ -1323,7 +1320,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
zoomFactor: DEFAULT_ZOOM_FACTOR,
|
||||
colorScheme: "system",
|
||||
controller: "none",
|
||||
updatedAt,
|
||||
};
|
||||
@@ -1390,7 +1386,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
wc.getZoomFactor(),
|
||||
);
|
||||
yield* attachListeners(tabId, wc);
|
||||
runFork(restoreControlSession(tabId, wc));
|
||||
runFork(ensureControlSession(wc).pipe(Effect.ignore));
|
||||
const registeredAt = yield* currentIso;
|
||||
const registration = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
|
||||
const current = tabs.get(tabId);
|
||||
@@ -1461,7 +1457,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
canGoBack: current?.canGoBack ?? false,
|
||||
canGoForward: current?.canGoForward ?? false,
|
||||
zoomFactor: current?.zoomFactor ?? DEFAULT_ZOOM_FACTOR,
|
||||
colorScheme: current?.colorScheme ?? "system",
|
||||
controller: current?.controller ?? "none",
|
||||
updatedAt,
|
||||
};
|
||||
@@ -1530,7 +1525,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
yield* detachControlSession(wc.id);
|
||||
yield* attempt({ operation: "openDevTools", tabId, webContentsId: wc.id }, () => {
|
||||
wc.once("devtools-closed", () => {
|
||||
if (!wc.isDestroyed()) runFork(restoreControlSession(tabId, wc));
|
||||
if (!wc.isDestroyed()) runFork(ensureControlSession(wc).pipe(Effect.ignore));
|
||||
});
|
||||
wc.openDevTools({ mode: "detach" });
|
||||
});
|
||||
@@ -1689,65 +1684,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
yield* update(tabId, { zoomFactor: next });
|
||||
});
|
||||
|
||||
// Emulated media lives on the CDP debugger session, not the WebContents, so
|
||||
// it is lost whenever the session detaches (webview swap, DevTools
|
||||
// open/close) and must be re-applied after every (re)attach.
|
||||
const applyColorScheme = Effect.fn("PreviewManager.applyColorScheme")(function* (
|
||||
tabId: string,
|
||||
wc: Electron.WebContents,
|
||||
colorScheme: DesktopPreviewColorScheme,
|
||||
) {
|
||||
yield* ensureControlSession(wc);
|
||||
yield* attemptPromise({ operation: "applyColorScheme", tabId, webContentsId: wc.id }, () =>
|
||||
wc.debugger.sendCommand("Emulation.setEmulatedMedia", {
|
||||
features: [
|
||||
{
|
||||
name: "prefers-color-scheme",
|
||||
// An empty value clears the override so the page follows the OS.
|
||||
value: colorScheme === "system" ? "" : colorScheme,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// Re-establish the control session after a detach, restoring any
|
||||
// color-scheme override the tab carries. The scheme is read after the
|
||||
// session attaches so a concurrent setColorScheme is not overwritten with
|
||||
// a stale snapshot.
|
||||
const restoreControlSession = (tabId: string, wc: Electron.WebContents) =>
|
||||
ensureControlSession(wc).pipe(
|
||||
Effect.andThen(SynchronizedRef.get(tabsRef)),
|
||||
Effect.flatMap((tabs) => {
|
||||
const colorScheme = tabs.get(tabId)?.colorScheme ?? "system";
|
||||
return colorScheme === "system" ? Effect.void : applyColorScheme(tabId, wc, colorScheme);
|
||||
}),
|
||||
Effect.ignore,
|
||||
);
|
||||
|
||||
const setColorScheme = Effect.fn("PreviewManager.setColorScheme")(function* (
|
||||
tabId: string,
|
||||
colorScheme: DesktopPreviewColorScheme,
|
||||
) {
|
||||
const tab = (yield* SynchronizedRef.get(tabsRef)).get(tabId);
|
||||
if (!tab) {
|
||||
return yield* new PreviewTabNotFoundError({ tabId });
|
||||
}
|
||||
if (tab.colorScheme !== colorScheme) {
|
||||
// Record the choice even when the CDP call below can't run yet (no
|
||||
// webview, DevTools holding the debugger) — it is re-applied on the
|
||||
// next control-session (re)attach.
|
||||
yield* update(tabId, { colorScheme });
|
||||
}
|
||||
// Re-read after the update: registerWebview may have swapped the guest
|
||||
// in the meantime and the override must land on the current one.
|
||||
const webContentsId = (yield* SynchronizedRef.get(tabsRef)).get(tabId)?.webContentsId;
|
||||
if (webContentsId == null) return;
|
||||
const wc = webContents.fromId(webContentsId);
|
||||
if (!wc || wc.isDestroyed()) return;
|
||||
yield* applyColorScheme(tabId, wc, colorScheme);
|
||||
});
|
||||
|
||||
const captureScreenshot = Effect.fn("PreviewManager.captureScreenshot")(function* (
|
||||
tabId: string,
|
||||
) {
|
||||
@@ -2590,7 +2526,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
revealArtifact,
|
||||
saveRecording,
|
||||
setAnnotationTheme,
|
||||
setColorScheme,
|
||||
setMainWindow,
|
||||
startRecording,
|
||||
stopRecording,
|
||||
@@ -2895,10 +2830,6 @@ export class PreviewManager extends Context.Service<
|
||||
readonly zoomOut: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly resetZoom: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly hardReload: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly setColorScheme: (
|
||||
tabId: string,
|
||||
colorScheme: DesktopPreviewColorScheme,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly openDevTools: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly clearCookies: () => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly clearCache: () => Effect.Effect<void, PreviewManagerError>;
|
||||
@@ -2990,7 +2921,6 @@ export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
zoomOut: operations.zoomOut,
|
||||
resetZoom: operations.resetZoom,
|
||||
hardReload: operations.hardReload,
|
||||
setColorScheme: operations.setColorScheme,
|
||||
openDevTools: operations.openDevTools,
|
||||
clearCookies: Effect.fn("PreviewManager.clearCookies")(function* () {
|
||||
yield* browserSession
|
||||
|
||||
@@ -19,7 +19,6 @@ const clientSettings: ClientSettings = {
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
diffIgnoreWhitespace: true,
|
||||
favorites: [],
|
||||
glassOpacity: 80,
|
||||
providerModelPreferences: {},
|
||||
sidebarAutoSettleAfterDays: 3,
|
||||
sidebarProjectGroupingMode: "repository_path",
|
||||
|
||||
@@ -10,7 +10,6 @@
|
||||
"typecheck": "astro check"
|
||||
},
|
||||
"dependencies": {
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"astro": "^7.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
import type { APIRoute } from "astro";
|
||||
|
||||
import { buildT3ProjectFileJsonSchema } from "@t3tools/shared/t3ProjectFile";
|
||||
|
||||
// Rendered at build time; published at https://t3.codes/schema/t3.json so
|
||||
// t3.json files can reference it via "$schema" for editor/LSP support.
|
||||
export const GET: APIRoute = () =>
|
||||
new Response(`${JSON.stringify(buildT3ProjectFileJsonSchema(), null, 2)}\n`, {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { VercelConfig } from "@vercel/config/v1";
|
||||
|
||||
export const config: VercelConfig = {
|
||||
installCommand: "npm install -g vite-plus && vp install --filter '@t3tools/marketing...'",
|
||||
installCommand: "npm install -g vite-plus && vp install --filter '@t3tools/marketing'",
|
||||
buildCommand: "vp run --filter @t3tools/marketing build",
|
||||
outputDirectory: "dist",
|
||||
};
|
||||
+5
-19
@@ -13,10 +13,7 @@ import { ConfirmDialogHost } from "./components/ConfirmDialogHost";
|
||||
import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";
|
||||
import { prepareNativeShowcaseCapture } from "./features/showcase/nativeShowcaseScene";
|
||||
import { IncomingShareProvider } from "./features/sharing/IncomingShareProvider";
|
||||
import {
|
||||
AppearancePreferencesProvider,
|
||||
useAppearancePreferences,
|
||||
} from "./features/settings/appearance/AppearancePreferencesProvider";
|
||||
import { AppearancePreferencesProvider } from "./features/settings/appearance/AppearancePreferencesProvider";
|
||||
import { RootStack } from "./Stack";
|
||||
import { appAtomRegistry } from "./state/atom-registry";
|
||||
import { OverlayPortalHost } from "./components/OverlayPortal";
|
||||
@@ -29,10 +26,6 @@ if (process.env.EXPO_PUBLIC_SHOWCASE === "1") {
|
||||
prepareNativeShowcaseCapture();
|
||||
}
|
||||
|
||||
void SplashScreen.preventAutoHideAsync().catch(() => {
|
||||
// The native module can be unavailable in non-native test environments.
|
||||
});
|
||||
|
||||
const appLinking = {
|
||||
prefixes: [Linking.createURL("/"), "t3code://", "t3code-dev://", "t3code-preview://"],
|
||||
// The Expo dev client launches the app via
|
||||
@@ -47,25 +40,18 @@ const appLinking = {
|
||||
|
||||
const Navigation = createStaticNavigation(RootStack);
|
||||
|
||||
function SplashScreenCoordinator() {
|
||||
const { isReady } = useAppearancePreferences();
|
||||
|
||||
useEffect(() => {
|
||||
if (isReady) void SplashScreen.hide();
|
||||
}, [isReady]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const colorScheme = useColorScheme();
|
||||
const statusBarBg = useThemeColor("--color-status-bar");
|
||||
|
||||
useEffect(() => {
|
||||
SplashScreen.hide();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<RegistryContext.Provider value={appAtomRegistry}>
|
||||
<CloudAuthProvider>
|
||||
<AppearancePreferencesProvider>
|
||||
<SplashScreenCoordinator />
|
||||
<GestureHandlerRootView className="flex-1">
|
||||
<KeyboardProvider statusBarTranslucent>
|
||||
<SafeAreaProvider>
|
||||
|
||||
@@ -33,7 +33,7 @@ import { clearComposerDraftsEnvironment } from "../state/use-composer-drafts";
|
||||
import { connectionStorageLayer } from "./storage";
|
||||
|
||||
function networkStatus(state: Network.NetworkState): "unknown" | "offline" | "online" {
|
||||
if (state.isConnected === false) {
|
||||
if (state.isConnected === false || state.isInternetReachable === false) {
|
||||
return "offline";
|
||||
}
|
||||
if (state.isConnected === true) {
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import type { EnvironmentId, SidebarThreadSortOrder } from "@t3tools/contracts";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
SidebarProjectGroupingMode,
|
||||
SidebarThreadSortOrder,
|
||||
} from "@t3tools/contracts";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
@@ -24,6 +28,7 @@ import {
|
||||
} from "./home-list-filter-menu";
|
||||
import {
|
||||
hasCustomHomeListOptions,
|
||||
PROJECT_GROUPING_OPTIONS,
|
||||
PROJECT_SORT_OPTIONS,
|
||||
THREAD_SORT_OPTIONS,
|
||||
} from "./home-list-options";
|
||||
@@ -38,11 +43,13 @@ export function HomeHeader(props: {
|
||||
readonly selectedProjectKey: string | null;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
readonly threadSortOrder: SidebarThreadSortOrder;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
readonly onSearchQueryChange: (query: string) => void;
|
||||
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
|
||||
readonly onProjectChange: (projectKey: string | null) => void;
|
||||
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
|
||||
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
|
||||
readonly onProjectGroupingModeChange: (mode: SidebarProjectGroupingMode) => void;
|
||||
readonly onOpenSettings: () => void;
|
||||
readonly onStartNewTask: () => void;
|
||||
}) {
|
||||
@@ -136,10 +143,20 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
state: checkedMenuState(props.threadSortOrder === option.value),
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "project-grouping",
|
||||
title: "Group projects",
|
||||
subactions: PROJECT_GROUPING_OPTIONS.map((option) => ({
|
||||
id: `project-grouping:${option.value}`,
|
||||
title: option.label,
|
||||
state: checkedMenuState(props.projectGroupingMode === option.value),
|
||||
})),
|
||||
},
|
||||
] satisfies MenuAction[])),
|
||||
],
|
||||
[
|
||||
props.environments,
|
||||
props.projectGroupingMode,
|
||||
props.projectSortOrder,
|
||||
props.projects,
|
||||
props.selectedEnvironmentId,
|
||||
@@ -193,6 +210,13 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
props.onThreadSortOrderChange(threadSort.value);
|
||||
return;
|
||||
}
|
||||
|
||||
const grouping = PROJECT_GROUPING_OPTIONS.find(
|
||||
(option) => id === `project-grouping:${option.value}`,
|
||||
);
|
||||
if (grouping) {
|
||||
props.onProjectGroupingModeChange(grouping.value);
|
||||
}
|
||||
},
|
||||
[props],
|
||||
);
|
||||
@@ -385,6 +409,10 @@ function IosHomeHeader(props: HomeHeaderProps) {
|
||||
title="Thread list options"
|
||||
separateBackground
|
||||
>
|
||||
<NativeHeaderToolbar.MenuAction onPress={props.onOpenSettings}>
|
||||
<NativeHeaderToolbar.Label>Settings</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
|
||||
<NativeHeaderToolbar.Menu title="Environment">
|
||||
<NativeHeaderToolbar.Label>Environment</NativeHeaderToolbar.Label>
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
@@ -452,6 +480,20 @@ function IosHomeHeader(props: HomeHeaderProps) {
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
))}
|
||||
</NativeHeaderToolbar.Menu>
|
||||
|
||||
<NativeHeaderToolbar.Menu title="Group projects">
|
||||
<NativeHeaderToolbar.Label>Group projects</NativeHeaderToolbar.Label>
|
||||
{PROJECT_GROUPING_OPTIONS.map((option) => (
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
key={option.value}
|
||||
isOn={props.projectGroupingMode === option.value}
|
||||
onPress={() => props.onProjectGroupingModeChange(option.value)}
|
||||
subtitle={option.subtitle}
|
||||
>
|
||||
<NativeHeaderToolbar.Label>{option.label}</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
))}
|
||||
</NativeHeaderToolbar.Menu>
|
||||
</NativeHeaderToolbar.Menu>
|
||||
<NativeHeaderToolbar.Spacer width={8} sharesBackground={false} />
|
||||
<NativeHeaderToolbar.SearchBarSlot />
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useNavigation } from "@react-navigation/native";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
@@ -15,7 +16,6 @@ import { AndroidHomeFabLayout } from "./AndroidHomeFab";
|
||||
import { HomeScreen } from "./HomeScreen";
|
||||
import { HomeHeader } from "./HomeHeader";
|
||||
import { useHomeListOptions } from "./home-list-options";
|
||||
import { buildHomeProjectScopes } from "./homeThreadList";
|
||||
import { usePendingTaskListActions } from "./usePendingTaskListActions";
|
||||
import { useThreadListActions } from "./useThreadListActions";
|
||||
|
||||
@@ -54,6 +54,7 @@ export function HomeRouteScreen() {
|
||||
const {
|
||||
options: listOptions,
|
||||
setSelectedEnvironmentId,
|
||||
setProjectGroupingMode,
|
||||
setProjectSortOrder,
|
||||
setThreadSortOrder,
|
||||
} = useHomeListOptions(availableEnvironmentIds);
|
||||
@@ -61,15 +62,16 @@ export function HomeRouteScreen() {
|
||||
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
|
||||
const projectFilterOptions = useMemo(
|
||||
() =>
|
||||
buildHomeProjectScopes({
|
||||
projects,
|
||||
environmentId: selectedEnvironmentId,
|
||||
projectGroupingMode: listOptions.projectGroupingMode,
|
||||
}).map((scope) => ({
|
||||
key: scope.key,
|
||||
label: scope.title,
|
||||
})),
|
||||
[listOptions.projectGroupingMode, projects, selectedEnvironmentId],
|
||||
projects
|
||||
.filter(
|
||||
(project) =>
|
||||
selectedEnvironmentId === null || project.environmentId === selectedEnvironmentId,
|
||||
)
|
||||
.map((project) => ({
|
||||
key: scopedProjectKey(project.environmentId, project.id),
|
||||
label: project.title,
|
||||
})),
|
||||
[projects, selectedEnvironmentId],
|
||||
);
|
||||
useEffect(() => {
|
||||
if (
|
||||
@@ -117,9 +119,11 @@ export function HomeRouteScreen() {
|
||||
selectedProjectKey={selectedProjectKey}
|
||||
projectSortOrder={listOptions.projectSortOrder}
|
||||
threadSortOrder={listOptions.threadSortOrder}
|
||||
projectGroupingMode={listOptions.projectGroupingMode}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
|
||||
onProjectGroupingModeChange={setProjectGroupingMode}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
|
||||
@@ -142,6 +146,7 @@ export function HomeRouteScreen() {
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
|
||||
}
|
||||
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
|
||||
onProjectGroupingModeChange={setProjectGroupingMode}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
onSelectThread={(thread) => {
|
||||
|
||||
@@ -15,15 +15,17 @@ import type {
|
||||
import { useAtomSet, useAtomValue } from "@effect/atom-react";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { ActivityIndicator, FlatList, Platform, Pressable, View } from "react-native";
|
||||
import { ActivityIndicator, FlatList, Platform, Pressable, ScrollView, View } from "react-native";
|
||||
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { EmptyState } from "../../components/EmptyState";
|
||||
import { ProjectFavicon } from "../../components/ProjectFavicon";
|
||||
import type { WorkspaceState } from "../../state/workspaceModel";
|
||||
import type { SavedRemoteConnection } from "../../lib/connection";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
|
||||
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
|
||||
@@ -52,12 +54,7 @@ import {
|
||||
type HomeGroupDisplayState,
|
||||
type HomeListItem,
|
||||
} from "./homeListItems";
|
||||
import {
|
||||
buildHomeProjectScopes,
|
||||
buildHomeThreadGroups,
|
||||
sortHomeProjectScopes,
|
||||
type HomeProjectSortOrder,
|
||||
} from "./homeThreadList";
|
||||
import { buildHomeThreadGroups, type HomeProjectSortOrder } from "./homeThreadList";
|
||||
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "./thread-swipe-actions";
|
||||
import { WorkspaceConnectionStatus } from "./WorkspaceConnectionStatus";
|
||||
import { shouldShowWorkspaceConnectionStatus } from "./workspace-connection-status";
|
||||
@@ -82,6 +79,7 @@ interface HomeScreenProps {
|
||||
readonly onProjectChange: (projectKey: string | null) => void;
|
||||
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
|
||||
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
|
||||
readonly onProjectGroupingModeChange: (mode: SidebarProjectGroupingMode) => void;
|
||||
readonly onAddConnection: () => void;
|
||||
readonly onOpenEnvironments: () => void;
|
||||
readonly onOpenSettings: () => void;
|
||||
@@ -245,69 +243,43 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
onScrollBeginDrag: handleScrollBeginDrag,
|
||||
});
|
||||
|
||||
const projectScopes = useMemo(
|
||||
() =>
|
||||
buildHomeProjectScopes({
|
||||
projects: props.projects,
|
||||
environmentId: props.selectedEnvironmentId,
|
||||
projectGroupingMode: props.projectGroupingMode,
|
||||
}),
|
||||
[props.projectGroupingMode, props.projects, props.selectedEnvironmentId],
|
||||
);
|
||||
const selectedProjectScope = useMemo(
|
||||
const scopedProject = useMemo(
|
||||
() =>
|
||||
props.selectedProjectKey === null
|
||||
? null
|
||||
: (projectScopes.find(
|
||||
(scope) =>
|
||||
scope.key === props.selectedProjectKey ||
|
||||
scope.projectRefs.some(
|
||||
(projectRef) =>
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId) ===
|
||||
props.selectedProjectKey,
|
||||
),
|
||||
: (props.projects.find(
|
||||
(project) =>
|
||||
scopedProjectKey(project.environmentId, project.id) === props.selectedProjectKey &&
|
||||
(props.selectedEnvironmentId === null ||
|
||||
project.environmentId === props.selectedEnvironmentId),
|
||||
) ?? null),
|
||||
[projectScopes, props.selectedProjectKey],
|
||||
);
|
||||
const selectedProjectRefKeys = useMemo(
|
||||
() =>
|
||||
selectedProjectScope === null
|
||||
? null
|
||||
: new Set(
|
||||
selectedProjectScope.projectRefs.map((projectRef) =>
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
|
||||
),
|
||||
),
|
||||
[selectedProjectScope],
|
||||
[props.projects, props.selectedEnvironmentId, props.selectedProjectKey],
|
||||
);
|
||||
const scopedProjects = useMemo(
|
||||
() =>
|
||||
selectedProjectRefKeys === null
|
||||
? props.projects
|
||||
: props.projects.filter((project) =>
|
||||
selectedProjectRefKeys.has(scopedProjectKey(project.environmentId, project.id)),
|
||||
),
|
||||
[props.projects, selectedProjectRefKeys],
|
||||
() => (scopedProject === null ? props.projects : [scopedProject]),
|
||||
[props.projects, scopedProject],
|
||||
);
|
||||
const scopedThreads = useMemo(
|
||||
() =>
|
||||
selectedProjectRefKeys === null
|
||||
scopedProject === null
|
||||
? props.threads
|
||||
: props.threads.filter((thread) =>
|
||||
selectedProjectRefKeys.has(scopedProjectKey(thread.environmentId, thread.projectId)),
|
||||
: props.threads.filter(
|
||||
(thread) =>
|
||||
thread.environmentId === scopedProject.environmentId &&
|
||||
thread.projectId === scopedProject.id,
|
||||
),
|
||||
[props.threads, selectedProjectRefKeys],
|
||||
[props.threads, scopedProject],
|
||||
);
|
||||
const scopedPendingTasks = useMemo(
|
||||
() =>
|
||||
selectedProjectRefKeys === null
|
||||
scopedProject === null
|
||||
? props.pendingTasks
|
||||
: props.pendingTasks.filter((pendingTask) =>
|
||||
selectedProjectRefKeys.has(
|
||||
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
|
||||
),
|
||||
: props.pendingTasks.filter(
|
||||
(pendingTask) =>
|
||||
pendingTask.message.environmentId === scopedProject.environmentId &&
|
||||
pendingTask.creation.projectId === scopedProject.id,
|
||||
),
|
||||
[props.pendingTasks, selectedProjectRefKeys],
|
||||
[props.pendingTasks, scopedProject],
|
||||
);
|
||||
|
||||
const projectGroups = useMemo(
|
||||
@@ -362,64 +334,23 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
}, [props.projects]);
|
||||
|
||||
const v2ProjectScopeKey = props.selectedProjectKey;
|
||||
const setV2ProjectScopeKey = props.onProjectChange;
|
||||
const v2ScopeProjects = useMemo(
|
||||
() =>
|
||||
sortHomeProjectScopes({
|
||||
scopes: projectScopes,
|
||||
threads: props.threads,
|
||||
pendingTasks: props.pendingTasks,
|
||||
projectSortOrder: props.projectSortOrder,
|
||||
}),
|
||||
[
|
||||
props.pendingTasks,
|
||||
props.projects,
|
||||
props.projectSortOrder,
|
||||
props.selectedEnvironmentId,
|
||||
props.threads,
|
||||
projectScopes,
|
||||
],
|
||||
props.selectedEnvironmentId === null
|
||||
? props.projects
|
||||
: props.projects.filter((project) => project.environmentId === props.selectedEnvironmentId),
|
||||
[props.projects, props.selectedEnvironmentId],
|
||||
);
|
||||
const v2ScopedProjectGroup = useMemo(
|
||||
const v2ScopedProject = useMemo(
|
||||
() =>
|
||||
v2ProjectScopeKey === null
|
||||
? null
|
||||
: (v2ScopeProjects.find(
|
||||
(scope) =>
|
||||
scope.key === v2ProjectScopeKey ||
|
||||
scope.projectRefs.some(
|
||||
(projectRef) =>
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId) ===
|
||||
v2ProjectScopeKey,
|
||||
),
|
||||
(project) => scopedProjectKey(project.environmentId, project.id) === v2ProjectScopeKey,
|
||||
) ?? null),
|
||||
[v2ProjectScopeKey, v2ScopeProjects],
|
||||
);
|
||||
const v2ProjectTitleByProjectKey = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
v2ScopeProjects.flatMap((scope) =>
|
||||
scope.projectRefs.map(
|
||||
(projectRef) =>
|
||||
[
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
|
||||
scope.title,
|
||||
] as const,
|
||||
),
|
||||
),
|
||||
),
|
||||
[v2ScopeProjects],
|
||||
);
|
||||
const v2ScopedProjectKeys = useMemo(
|
||||
() =>
|
||||
v2ScopedProjectGroup === null
|
||||
? null
|
||||
: new Set(
|
||||
v2ScopedProjectGroup.projectRefs.map((projectRef) =>
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
|
||||
),
|
||||
),
|
||||
[v2ScopedProjectGroup],
|
||||
);
|
||||
// Thread List v2 (beta): one flat list in creation order, no grouping.
|
||||
// Settled threads collapse into a recency tail below the card block.
|
||||
// Settled threads stay in the live shell stream (settled ≠ archived), so
|
||||
@@ -500,7 +431,13 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
return buildThreadListV2Items({
|
||||
threads: props.threads.filter((thread) => thread.archivedAt === null),
|
||||
environmentId: props.selectedEnvironmentId,
|
||||
projectRefs: v2ScopedProjectGroup === null ? null : v2ScopedProjectGroup.projectRefs,
|
||||
projectRef:
|
||||
v2ScopedProject === null
|
||||
? null
|
||||
: {
|
||||
environmentId: v2ScopedProject.environmentId,
|
||||
projectId: v2ScopedProject.id,
|
||||
},
|
||||
searchQuery: props.searchQuery,
|
||||
changeRequestStateByKey,
|
||||
settlementEnvironmentIds,
|
||||
@@ -516,7 +453,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
props.selectedEnvironmentId,
|
||||
props.threads,
|
||||
threadListV2Enabled,
|
||||
v2ScopedProjectGroup,
|
||||
v2ScopedProject,
|
||||
]);
|
||||
const threadListV2Items = threadListV2Layout.items;
|
||||
|
||||
@@ -530,9 +467,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
projectByKey.get(scopedProjectKey(item.thread.environmentId, item.thread.projectId)) ??
|
||||
null
|
||||
}
|
||||
projectTitle={v2ProjectTitleByProjectKey.get(
|
||||
scopedProjectKey(item.thread.environmentId, item.thread.projectId),
|
||||
)}
|
||||
providerDriver={
|
||||
serverConfigs
|
||||
.get(item.thread.environmentId)
|
||||
@@ -576,7 +510,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
props.savedConnectionsById,
|
||||
serverConfigs,
|
||||
settlementEnvironmentIds,
|
||||
v2ProjectTitleByProjectKey,
|
||||
],
|
||||
);
|
||||
const v2KeyExtractor = useCallback(
|
||||
@@ -766,10 +699,9 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
(pendingTask) =>
|
||||
(props.selectedEnvironmentId === null ||
|
||||
pendingTask.message.environmentId === props.selectedEnvironmentId) &&
|
||||
(v2ScopedProjectKeys === null ||
|
||||
v2ScopedProjectKeys.has(
|
||||
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
|
||||
)) &&
|
||||
(v2ScopedProject === null ||
|
||||
(pendingTask.message.environmentId === v2ScopedProject.environmentId &&
|
||||
pendingTask.creation.projectId === v2ScopedProject.id)) &&
|
||||
(v2SearchQuery.length === 0 || pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
|
||||
);
|
||||
// Project scoping lives in the header filter menu (no inline chip row on
|
||||
@@ -796,9 +728,9 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
const listEmpty = !hasResults ? (
|
||||
hasSearchQuery ? (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
) : selectedProjectScope !== null ? (
|
||||
) : scopedProject !== null ? (
|
||||
<EmptyState
|
||||
title={`No threads in ${selectedProjectScope.title}`}
|
||||
title={`No threads in ${scopedProject.title}`}
|
||||
detail="Choose another project or create a new task."
|
||||
/>
|
||||
) : selectedEnvironmentLabel ? (
|
||||
@@ -818,9 +750,9 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
const v2ListEmpty =
|
||||
v2PendingTasks.length > 0 ? null : hasSearchQuery ? (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
) : v2ScopedProjectGroup !== null ? (
|
||||
) : v2ScopedProject !== null ? (
|
||||
<EmptyState
|
||||
title={`No threads in ${v2ScopedProjectGroup.title}`}
|
||||
title={`No threads in ${v2ScopedProject.title}`}
|
||||
detail="Choose another project or create a new task."
|
||||
/>
|
||||
) : (
|
||||
|
||||
@@ -15,16 +15,17 @@ describe("buildHomeListFilterMenu", () => {
|
||||
selectedProjectKey: "environment-1:project-1",
|
||||
projectSortOrder: "updated_at",
|
||||
threadSortOrder: "updated_at",
|
||||
projectGroupingMode: "repository",
|
||||
onEnvironmentChange: vi.fn(),
|
||||
onProjectChange,
|
||||
onProjectSortOrderChange: vi.fn(),
|
||||
onThreadSortOrderChange: vi.fn(),
|
||||
onProjectGroupingModeChange: vi.fn(),
|
||||
});
|
||||
|
||||
const projectMenu = menu.items.find(
|
||||
(item) => item.type === "submenu" && item.title === "Project",
|
||||
);
|
||||
expect(menu.items.some((item) => item.title === "Settings")).toBe(false);
|
||||
expect(projectMenu).toMatchObject({
|
||||
type: "submenu",
|
||||
items: [
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
import type { EnvironmentId, SidebarThreadSortOrder } from "@t3tools/contracts";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
SidebarProjectGroupingMode,
|
||||
SidebarThreadSortOrder,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import type { HomeProjectSortOrder } from "./homeThreadList";
|
||||
import { PROJECT_SORT_OPTIONS, THREAD_SORT_OPTIONS } from "./home-list-options";
|
||||
import {
|
||||
PROJECT_GROUPING_OPTIONS,
|
||||
PROJECT_SORT_OPTIONS,
|
||||
THREAD_SORT_OPTIONS,
|
||||
} from "./home-list-options";
|
||||
|
||||
export interface HomeListFilterMenuEnvironment {
|
||||
readonly environmentId: EnvironmentId;
|
||||
@@ -39,10 +47,13 @@ export function buildHomeListFilterMenu(props: {
|
||||
readonly selectedProjectKey: string | null;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
readonly threadSortOrder: SidebarThreadSortOrder;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
|
||||
readonly onProjectChange: (projectKey: string | null) => void;
|
||||
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
|
||||
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
|
||||
readonly onProjectGroupingModeChange: (mode: SidebarProjectGroupingMode) => void;
|
||||
readonly onOpenSettings?: () => void;
|
||||
/** False hides the sort/group submenus. Thread List v2 uses a fixed
|
||||
creation-order layout, so offering those controls while it silently
|
||||
ignores them would be a lie; the environment filter still applies. */
|
||||
@@ -50,6 +61,14 @@ export function buildHomeListFilterMenu(props: {
|
||||
}): HomeListFilterMenu {
|
||||
const items: Array<HomeListFilterMenuAction | HomeListFilterMenuSubmenu> = [];
|
||||
|
||||
if (props.onOpenSettings) {
|
||||
items.push({
|
||||
type: "action",
|
||||
title: "Settings",
|
||||
onPress: props.onOpenSettings,
|
||||
});
|
||||
}
|
||||
|
||||
items.push({
|
||||
type: "submenu",
|
||||
title: "Environment",
|
||||
@@ -117,6 +136,17 @@ export function buildHomeListFilterMenu(props: {
|
||||
onPress: () => props.onThreadSortOrderChange(option.value),
|
||||
})),
|
||||
},
|
||||
{
|
||||
type: "submenu",
|
||||
title: "Group projects",
|
||||
items: PROJECT_GROUPING_OPTIONS.map((option) => ({
|
||||
type: "action",
|
||||
title: option.label,
|
||||
subtitle: option.subtitle,
|
||||
state: props.projectGroupingMode === option.value ? "on" : "off",
|
||||
onPress: () => props.onProjectGroupingModeChange(option.value),
|
||||
})),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -13,6 +14,7 @@ const defaults: HomeListOptions = {
|
||||
? "updated_at"
|
||||
: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
threadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
projectGroupingMode: DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
|
||||
};
|
||||
|
||||
describe("home list options", () => {
|
||||
@@ -20,10 +22,11 @@ describe("home list options", () => {
|
||||
expect(hasCustomHomeListOptions(defaults)).toBe(false);
|
||||
});
|
||||
|
||||
it("marks environment filters as customized", () => {
|
||||
it("marks environment filters and grouping changes as customized", () => {
|
||||
expect(
|
||||
hasCustomHomeListOptions({ ...defaults, selectedEnvironmentId: "environment-1" as never }),
|
||||
).toBe(true);
|
||||
expect(hasCustomHomeListOptions({ ...defaults, projectGroupingMode: "separate" })).toBe(true);
|
||||
expect(
|
||||
hasCustomHomeListOptions({ ...defaults, selectedProjectKey: "environment-1:project-1" }),
|
||||
).toBe(true);
|
||||
|
||||
@@ -4,6 +4,7 @@ import type {
|
||||
SidebarThreadSortOrder,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -25,18 +26,9 @@ export interface HomeListOptions {
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
readonly threadSortOrder: SidebarThreadSortOrder;
|
||||
}
|
||||
|
||||
export interface ResolvedHomeListOptions extends HomeListOptions {
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
}
|
||||
|
||||
export function resolveProjectGroupingMode(
|
||||
projectGroupingEnabled: boolean | undefined,
|
||||
): SidebarProjectGroupingMode {
|
||||
return projectGroupingEnabled === false ? "separate" : "repository";
|
||||
}
|
||||
|
||||
export const PROJECT_SORT_OPTIONS: ReadonlyArray<{
|
||||
readonly value: HomeProjectSortOrder;
|
||||
readonly label: string;
|
||||
@@ -53,6 +45,28 @@ export const THREAD_SORT_OPTIONS: ReadonlyArray<{
|
||||
{ value: "created_at", label: "Created at" },
|
||||
];
|
||||
|
||||
export const PROJECT_GROUPING_OPTIONS: ReadonlyArray<{
|
||||
readonly value: SidebarProjectGroupingMode;
|
||||
readonly label: string;
|
||||
readonly subtitle: string;
|
||||
}> = [
|
||||
{
|
||||
value: "repository",
|
||||
label: "Group by repository",
|
||||
subtitle: "Combine matching repositories across environments",
|
||||
},
|
||||
{
|
||||
value: "repository_path",
|
||||
label: "Group by repository path",
|
||||
subtitle: "Combine only matching paths within a repository",
|
||||
},
|
||||
{
|
||||
value: "separate",
|
||||
label: "Keep separate",
|
||||
subtitle: "Show every project path separately",
|
||||
},
|
||||
];
|
||||
|
||||
function defaultHomeListOptions(): HomeListOptions {
|
||||
return {
|
||||
selectedEnvironmentId: null,
|
||||
@@ -61,34 +75,26 @@ function defaultHomeListOptions(): HomeListOptions {
|
||||
? "updated_at"
|
||||
: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
threadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
projectGroupingMode: DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
|
||||
};
|
||||
}
|
||||
|
||||
interface HomeListOptionsContextValue {
|
||||
readonly options: HomeListOptions;
|
||||
readonly setOptions: Dispatch<SetStateAction<HomeListOptions>>;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
}
|
||||
|
||||
const HomeListOptionsContext = createContext<HomeListOptionsContextValue | null>(null);
|
||||
|
||||
/** Keeps list preferences stable while the app moves between compact and split shells. */
|
||||
export function HomeListOptionsProvider({
|
||||
children,
|
||||
projectGroupingMode,
|
||||
}: PropsWithChildren<{ readonly projectGroupingMode: SidebarProjectGroupingMode }>) {
|
||||
export function HomeListOptionsProvider({ children }: PropsWithChildren) {
|
||||
const [options, setOptions] = useState<HomeListOptions>(defaultHomeListOptions);
|
||||
const value = useMemo(
|
||||
() => ({ options, setOptions, projectGroupingMode }),
|
||||
[options, projectGroupingMode],
|
||||
);
|
||||
const value = useMemo(() => ({ options, setOptions }), [options]);
|
||||
return createElement(HomeListOptionsContext, { value }, children);
|
||||
}
|
||||
|
||||
export function hasCustomHomeListOptions(
|
||||
options: HomeListOptions & {
|
||||
readonly selectedProjectKey?: string | null;
|
||||
},
|
||||
options: HomeListOptions & { readonly selectedProjectKey?: string | null },
|
||||
): boolean {
|
||||
const defaultProjectSortOrder =
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER === "manual"
|
||||
@@ -98,7 +104,8 @@ export function hasCustomHomeListOptions(
|
||||
options.selectedEnvironmentId !== null ||
|
||||
(options.selectedProjectKey !== null && options.selectedProjectKey !== undefined) ||
|
||||
options.projectSortOrder !== defaultProjectSortOrder ||
|
||||
options.threadSortOrder !== DEFAULT_SIDEBAR_THREAD_SORT_ORDER
|
||||
options.threadSortOrder !== DEFAULT_SIDEBAR_THREAD_SORT_ORDER ||
|
||||
options.projectGroupingMode !== DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE
|
||||
);
|
||||
}
|
||||
|
||||
@@ -112,14 +119,10 @@ export function useHomeListOptions(availableEnvironmentIds: ReadonlySet<Environm
|
||||
availableEnvironmentIds.has(options.selectedEnvironmentId)
|
||||
? options.selectedEnvironmentId
|
||||
: null;
|
||||
const availableOptions =
|
||||
const resolvedOptions =
|
||||
selectedEnvironmentId === options.selectedEnvironmentId
|
||||
? options
|
||||
: { ...options, selectedEnvironmentId };
|
||||
const resolvedOptions: ResolvedHomeListOptions = {
|
||||
...availableOptions,
|
||||
projectGroupingMode: shared?.projectGroupingMode ?? "repository",
|
||||
};
|
||||
|
||||
const setSelectedEnvironmentId = useCallback((value: EnvironmentId | null) => {
|
||||
setOptions((current) => ({ ...current, selectedEnvironmentId: value }));
|
||||
@@ -130,10 +133,15 @@ export function useHomeListOptions(availableEnvironmentIds: ReadonlySet<Environm
|
||||
const setThreadSortOrder = useCallback((value: SidebarThreadSortOrder) => {
|
||||
setOptions((current) => ({ ...current, threadSortOrder: value }));
|
||||
}, []);
|
||||
const setProjectGroupingMode = useCallback((value: SidebarProjectGroupingMode) => {
|
||||
setOptions((current) => ({ ...current, projectGroupingMode: value }));
|
||||
}, []);
|
||||
|
||||
return {
|
||||
options: resolvedOptions,
|
||||
setSelectedEnvironmentId,
|
||||
setProjectSortOrder,
|
||||
setThreadSortOrder,
|
||||
setProjectGroupingMode,
|
||||
} as const;
|
||||
}
|
||||
@@ -5,11 +5,7 @@ import type {
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
buildHomeProjectScopes,
|
||||
buildHomeThreadGroups,
|
||||
sortHomeProjectScopes,
|
||||
} from "./homeThreadList";
|
||||
import { buildHomeThreadGroups } from "./homeThreadList";
|
||||
|
||||
function makeProject(
|
||||
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
|
||||
@@ -71,346 +67,6 @@ function buildGroups(
|
||||
}
|
||||
|
||||
describe("buildHomeThreadGroups", () => {
|
||||
it("builds one v2 scope for the same repository across environments", () => {
|
||||
const localEnvironmentId = EnvironmentId.make("environment-local");
|
||||
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
|
||||
const repositoryIdentity = {
|
||||
canonicalKey: "github.com/pingdotgg/t3code",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: "[email protected]:pingdotgg/t3code.git",
|
||||
},
|
||||
};
|
||||
const projects = [
|
||||
makeProject({
|
||||
environmentId: localEnvironmentId,
|
||||
id: ProjectId.make("project-local"),
|
||||
title: "t3code",
|
||||
repositoryIdentity,
|
||||
}),
|
||||
makeProject({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ProjectId.make("project-remote"),
|
||||
title: "t3code",
|
||||
repositoryIdentity,
|
||||
}),
|
||||
];
|
||||
|
||||
const scopes = buildHomeProjectScopes({
|
||||
projects,
|
||||
environmentId: null,
|
||||
projectGroupingMode: "repository",
|
||||
});
|
||||
|
||||
expect(scopes).toHaveLength(1);
|
||||
expect(scopes[0]?.title).toBe("t3code");
|
||||
expect(scopes[0]?.projects).toEqual(projects);
|
||||
expect(scopes[0]?.projectRefs).toEqual(
|
||||
projects.map((project) => ({
|
||||
environmentId: project.environmentId,
|
||||
projectId: project.id,
|
||||
})),
|
||||
);
|
||||
});
|
||||
|
||||
it("routes stale duplicate project refs through the canonical repository group", () => {
|
||||
const localEnvironmentId = EnvironmentId.make("environment-local");
|
||||
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
|
||||
const repositoryIdentity = {
|
||||
canonicalKey: "github.com/pingdotgg/t3code",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: "[email protected]:pingdotgg/t3code.git",
|
||||
},
|
||||
};
|
||||
const local = makeProject({
|
||||
id: ProjectId.make("project-local"),
|
||||
environmentId: localEnvironmentId,
|
||||
title: "t3code",
|
||||
workspaceRoot: "/workspaces/t3code",
|
||||
repositoryIdentity,
|
||||
});
|
||||
const stale = makeProject({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ProjectId.make("project-stale"),
|
||||
title: "t3code",
|
||||
workspaceRoot: "/remote/t3code",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
});
|
||||
const canonicalRemote = makeProject({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ProjectId.make("project-canonical-remote"),
|
||||
title: "t3code",
|
||||
workspaceRoot: "/remote/t3code/",
|
||||
repositoryIdentity,
|
||||
updatedAt: "2026-06-02T00:00:00.000Z",
|
||||
});
|
||||
const projects = [local, stale, canonicalRemote];
|
||||
const staleThread = makeThread({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ThreadId.make("thread-stale-project-ref"),
|
||||
projectId: stale.id,
|
||||
title: "Still visible",
|
||||
updatedAt: "2026-06-03T00:00:00.000Z",
|
||||
});
|
||||
|
||||
const scopes = buildHomeProjectScopes({
|
||||
projects,
|
||||
environmentId: null,
|
||||
projectGroupingMode: "repository",
|
||||
});
|
||||
const groups = buildGroups(projects, [staleThread]);
|
||||
|
||||
expect(scopes).toHaveLength(1);
|
||||
expect(scopes[0]?.projects.map((project) => project.id)).toEqual([
|
||||
local.id,
|
||||
canonicalRemote.id,
|
||||
]);
|
||||
expect(scopes[0]?.projectRefs.map((projectRef) => projectRef.projectId)).toEqual([
|
||||
local.id,
|
||||
stale.id,
|
||||
canonicalRemote.id,
|
||||
]);
|
||||
expect(groups).toHaveLength(1);
|
||||
expect(groups[0]?.threads.map((thread) => thread.id)).toEqual([staleThread.id]);
|
||||
expect(groups[0]?.newThreadTarget?.id).toBe(canonicalRemote.id);
|
||||
});
|
||||
|
||||
it("keeps repository identity from an older duplicate when the freshness winner lacks it", () => {
|
||||
const localEnvironmentId = EnvironmentId.make("environment-local");
|
||||
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
|
||||
const repositoryIdentity = {
|
||||
canonicalKey: "github.com/pingdotgg/t3code",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: "[email protected]:pingdotgg/t3code.git",
|
||||
},
|
||||
};
|
||||
const projects = [
|
||||
makeProject({
|
||||
environmentId: localEnvironmentId,
|
||||
id: ProjectId.make("project-local"),
|
||||
title: "t3code",
|
||||
repositoryIdentity,
|
||||
}),
|
||||
makeProject({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ProjectId.make("project-remote-with-identity"),
|
||||
title: "t3code",
|
||||
workspaceRoot: "/remote/t3code",
|
||||
repositoryIdentity,
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
}),
|
||||
makeProject({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ProjectId.make("project-remote-fresh"),
|
||||
title: "t3code",
|
||||
workspaceRoot: "/remote/t3code/",
|
||||
updatedAt: "2026-06-02T00:00:00.000Z",
|
||||
}),
|
||||
];
|
||||
|
||||
const scopes = buildHomeProjectScopes({
|
||||
projects,
|
||||
environmentId: null,
|
||||
projectGroupingMode: "repository",
|
||||
});
|
||||
|
||||
expect(scopes).toHaveLength(1);
|
||||
expect(scopes[0]?.representative.id).toBe(ProjectId.make("project-local"));
|
||||
expect(scopes[0]?.projects.map((project) => project.id)).toContain(
|
||||
ProjectId.make("project-remote-fresh"),
|
||||
);
|
||||
expect(scopes[0]?.projectRefs).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("sorts v2 project scopes by their grouped thread activity", () => {
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const olderProject = makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make("project-older"),
|
||||
title: "Older project",
|
||||
});
|
||||
const newerProject = makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make("project-newer"),
|
||||
title: "Newer project",
|
||||
});
|
||||
const scopes = buildHomeProjectScopes({
|
||||
projects: [newerProject, olderProject],
|
||||
environmentId: null,
|
||||
projectGroupingMode: "separate",
|
||||
});
|
||||
|
||||
expect(
|
||||
sortHomeProjectScopes({
|
||||
scopes,
|
||||
threads: [
|
||||
makeThread({
|
||||
environmentId,
|
||||
id: ThreadId.make("thread-older-project"),
|
||||
projectId: olderProject.id,
|
||||
title: "Most recently active",
|
||||
updatedAt: "2026-06-03T00:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
environmentId,
|
||||
id: ThreadId.make("thread-newer-project"),
|
||||
projectId: newerProject.id,
|
||||
title: "Less recently active",
|
||||
updatedAt: "2026-06-02T00:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
pendingTasks: [],
|
||||
projectSortOrder: "updated_at",
|
||||
}).map((scope) => scope.representative.id),
|
||||
).toEqual([olderProject.id, newerProject.id]);
|
||||
});
|
||||
|
||||
it("sorts invalid project creation timestamps after valid ones", () => {
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const invalidProject = makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make("project-invalid"),
|
||||
title: "A invalid timestamp",
|
||||
createdAt: "invalid",
|
||||
});
|
||||
const validProject = makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make("project-valid"),
|
||||
title: "Z valid timestamp",
|
||||
createdAt: "2026-06-02T00:00:00.000Z",
|
||||
});
|
||||
const scopes = buildHomeProjectScopes({
|
||||
projects: [invalidProject, validProject],
|
||||
environmentId: null,
|
||||
projectGroupingMode: "separate",
|
||||
});
|
||||
|
||||
expect(
|
||||
sortHomeProjectScopes({
|
||||
scopes,
|
||||
threads: [],
|
||||
pendingTasks: [],
|
||||
projectSortOrder: "created_at",
|
||||
}).map((scope) => scope.representative.id),
|
||||
).toEqual([validProject.id, invalidProject.id]);
|
||||
});
|
||||
|
||||
it("uses the freshest member when a grouped scope has no activity", () => {
|
||||
const localEnvironmentId = EnvironmentId.make("environment-local");
|
||||
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
|
||||
const repositoryIdentity = {
|
||||
canonicalKey: "github.com/pingdotgg/t3code",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: "[email protected]:pingdotgg/t3code.git",
|
||||
},
|
||||
};
|
||||
const olderMember = makeProject({
|
||||
environmentId: localEnvironmentId,
|
||||
id: ProjectId.make("project-older-member"),
|
||||
title: "t3code",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
repositoryIdentity,
|
||||
});
|
||||
const newerMember = makeProject({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ProjectId.make("project-newer-member"),
|
||||
title: "t3code",
|
||||
updatedAt: "2026-06-03T00:00:00.000Z",
|
||||
repositoryIdentity,
|
||||
});
|
||||
const otherProject = makeProject({
|
||||
environmentId: localEnvironmentId,
|
||||
id: ProjectId.make("project-other"),
|
||||
title: "other",
|
||||
updatedAt: "2026-06-02T00:00:00.000Z",
|
||||
});
|
||||
const scopes = buildHomeProjectScopes({
|
||||
projects: [olderMember, newerMember, otherProject],
|
||||
environmentId: null,
|
||||
projectGroupingMode: "repository",
|
||||
});
|
||||
|
||||
expect(
|
||||
sortHomeProjectScopes({
|
||||
scopes,
|
||||
threads: [],
|
||||
pendingTasks: [],
|
||||
projectSortOrder: "updated_at",
|
||||
})[0]?.key,
|
||||
).toBe(scopes.find((scope) => scope.projects.length === 2)?.key);
|
||||
});
|
||||
|
||||
it("does not merge unrelated repositories that share a title", () => {
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const projects = ["one", "two"].map((name) =>
|
||||
makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make(`project-${name}`),
|
||||
title: "app",
|
||||
repositoryIdentity: {
|
||||
canonicalKey: `github.com/example/${name}`,
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: `[email protected]:example/${name}.git`,
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(
|
||||
buildHomeProjectScopes({
|
||||
projects,
|
||||
environmentId: null,
|
||||
projectGroupingMode: "repository",
|
||||
}),
|
||||
).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("uses the repository label for a singleton repository scope", () => {
|
||||
const project = makeProject({
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
id: ProjectId.make("project-1"),
|
||||
title: "local-worktree-name",
|
||||
repositoryIdentity: {
|
||||
canonicalKey: "github.com/pingdotgg/t3code",
|
||||
displayName: "codething-mvp",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: "[email protected]:pingdotgg/t3code.git",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const scopes = buildHomeProjectScopes({
|
||||
projects: [project],
|
||||
environmentId: null,
|
||||
projectGroupingMode: "repository",
|
||||
});
|
||||
const groups = buildGroups(
|
||||
[project],
|
||||
[
|
||||
makeThread({
|
||||
environmentId: project.environmentId,
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: project.id,
|
||||
title: "Thread",
|
||||
}),
|
||||
],
|
||||
);
|
||||
|
||||
expect(scopes[0]?.title).toBe("codething-mvp");
|
||||
expect(groups[0]?.title).toBe("codething-mvp");
|
||||
});
|
||||
|
||||
it("sorts the newest thread first regardless of snapshot order", () => {
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const project = makeProject({
|
||||
|
||||
@@ -1,20 +1,14 @@
|
||||
import {
|
||||
deriveLogicalProjectKey,
|
||||
derivePhysicalProjectKey,
|
||||
deriveProjectGroupLabel,
|
||||
} from "@t3tools/client-runtime/state/project-grouping";
|
||||
import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import {
|
||||
getThreadSortTimestamp,
|
||||
sortThreads,
|
||||
toSortableTimestamp,
|
||||
} from "@t3tools/client-runtime/state/thread-sort";
|
||||
import { getThreadSortTimestamp, sortThreads } from "@t3tools/client-runtime/state/thread-sort";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
ScopedProjectRef,
|
||||
SidebarProjectGroupingMode,
|
||||
SidebarProjectSortOrder,
|
||||
SidebarThreadSortOrder,
|
||||
@@ -28,161 +22,6 @@ import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
|
||||
export type HomeProjectSortOrder = Exclude<SidebarProjectSortOrder, "manual">;
|
||||
|
||||
export interface HomeProjectScope {
|
||||
readonly key: string;
|
||||
readonly title: string;
|
||||
readonly representative: EnvironmentProject;
|
||||
readonly projects: ReadonlyArray<EnvironmentProject>;
|
||||
readonly projectRefs: ReadonlyArray<ScopedProjectRef>;
|
||||
}
|
||||
|
||||
function getProjectFreshnessTimestamp(project: EnvironmentProject): number {
|
||||
return toSortableTimestamp(project.updatedAt) ?? toSortableTimestamp(project.createdAt) ?? 0;
|
||||
}
|
||||
|
||||
function getProjectSortTimestamp(
|
||||
project: EnvironmentProject,
|
||||
sortOrder: HomeProjectSortOrder,
|
||||
): number {
|
||||
return sortOrder === "created_at"
|
||||
? (toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY)
|
||||
: (toSortableTimestamp(project.updatedAt) ??
|
||||
toSortableTimestamp(project.createdAt) ??
|
||||
Number.NEGATIVE_INFINITY);
|
||||
}
|
||||
|
||||
export function buildHomeProjectScopes(input: {
|
||||
readonly projects: ReadonlyArray<EnvironmentProject>;
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
}): ReadonlyArray<HomeProjectScope> {
|
||||
const projects = input.projects.filter(
|
||||
(project) => input.environmentId === null || project.environmentId === input.environmentId,
|
||||
);
|
||||
const projectsByPhysicalKey = new Map<string, EnvironmentProject[]>();
|
||||
for (const project of projects) {
|
||||
const physicalKey = derivePhysicalProjectKey(project);
|
||||
const existing = projectsByPhysicalKey.get(physicalKey);
|
||||
if (existing) existing.push(project);
|
||||
else projectsByPhysicalKey.set(physicalKey, [project]);
|
||||
}
|
||||
|
||||
const winnersByPhysicalKey = new Map<
|
||||
string,
|
||||
{ readonly key: string; readonly project: EnvironmentProject }
|
||||
>();
|
||||
for (const [physicalKey, members] of projectsByPhysicalKey) {
|
||||
const project = members.reduce((winner, candidate) => {
|
||||
const freshnessDelta =
|
||||
getProjectFreshnessTimestamp(candidate) - getProjectFreshnessTimestamp(winner);
|
||||
return freshnessDelta > 0 || (freshnessDelta === 0 && candidate.id > winner.id)
|
||||
? candidate
|
||||
: winner;
|
||||
});
|
||||
const identitySource = members.find((member) => member.repositoryIdentity !== null) ?? project;
|
||||
winnersByPhysicalKey.set(physicalKey, {
|
||||
key: deriveLogicalProjectKey(identitySource, { groupingMode: input.projectGroupingMode }),
|
||||
project,
|
||||
});
|
||||
}
|
||||
|
||||
const groups = new Map<string, EnvironmentProject[]>();
|
||||
for (const { key, project } of winnersByPhysicalKey.values()) {
|
||||
const existing = groups.get(key);
|
||||
if (existing) existing.push(project);
|
||||
else groups.set(key, [project]);
|
||||
}
|
||||
|
||||
const projectRefsByGroup = new Map<string, ScopedProjectRef[]>();
|
||||
const seenProjectRefs = new Set<string>();
|
||||
for (const project of projects) {
|
||||
const refKey = scopedProjectKey(project.environmentId, project.id);
|
||||
if (seenProjectRefs.has(refKey)) continue;
|
||||
seenProjectRefs.add(refKey);
|
||||
|
||||
const key =
|
||||
winnersByPhysicalKey.get(derivePhysicalProjectKey(project))?.key ??
|
||||
deriveLogicalProjectKey(project, { groupingMode: input.projectGroupingMode });
|
||||
const refs = projectRefsByGroup.get(key);
|
||||
const projectRef = { environmentId: project.environmentId, projectId: project.id };
|
||||
if (refs) refs.push(projectRef);
|
||||
else projectRefsByGroup.set(key, [projectRef]);
|
||||
}
|
||||
|
||||
return Array.from(groups, ([key, projects]) => {
|
||||
const representative = projects[0]!;
|
||||
return {
|
||||
key,
|
||||
title: deriveProjectGroupLabel({ representative, members: projects }),
|
||||
representative,
|
||||
projects,
|
||||
projectRefs: projectRefsByGroup.get(key) ?? [],
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function sortHomeProjectScopes(input: {
|
||||
readonly scopes: ReadonlyArray<HomeProjectScope>;
|
||||
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
readonly pendingTasks: ReadonlyArray<PendingNewTask>;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
}): ReadonlyArray<HomeProjectScope> {
|
||||
const scopeKeyByProjectRef = new Map(
|
||||
input.scopes.flatMap((scope) =>
|
||||
scope.projectRefs.map(
|
||||
(projectRef) =>
|
||||
[scopedProjectKey(projectRef.environmentId, projectRef.projectId), scope.key] as const,
|
||||
),
|
||||
),
|
||||
);
|
||||
const latestActivityByScope = new Map<string, number>();
|
||||
const recordActivity = (scopeKey: string | undefined, timestamp: number) => {
|
||||
if (!scopeKey || !Number.isFinite(timestamp)) return;
|
||||
latestActivityByScope.set(
|
||||
scopeKey,
|
||||
Math.max(latestActivityByScope.get(scopeKey) ?? Number.NEGATIVE_INFINITY, timestamp),
|
||||
);
|
||||
};
|
||||
|
||||
for (const thread of input.threads) {
|
||||
if (thread.archivedAt !== null) continue;
|
||||
recordActivity(
|
||||
scopeKeyByProjectRef.get(scopedProjectKey(thread.environmentId, thread.projectId)),
|
||||
getThreadSortTimestamp(thread, input.projectSortOrder),
|
||||
);
|
||||
}
|
||||
for (const pendingTask of input.pendingTasks) {
|
||||
recordActivity(
|
||||
scopeKeyByProjectRef.get(
|
||||
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
|
||||
),
|
||||
Date.parse(pendingTask.message.createdAt),
|
||||
);
|
||||
}
|
||||
|
||||
return Arr.sort(
|
||||
input.scopes,
|
||||
Order.mapInput(
|
||||
Order.Struct({
|
||||
timestamp: Order.flip(Order.Number),
|
||||
title: Order.String,
|
||||
key: Order.String,
|
||||
}),
|
||||
(scope: HomeProjectScope) => ({
|
||||
timestamp:
|
||||
latestActivityByScope.get(scope.key) ??
|
||||
Math.max(
|
||||
...scope.projects.map((project) =>
|
||||
getProjectSortTimestamp(project, input.projectSortOrder),
|
||||
),
|
||||
),
|
||||
title: scope.title,
|
||||
key: scope.key,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Default home view only surfaces threads active within this window, to keep the
|
||||
* screen compact while keeping recent work visible.
|
||||
@@ -264,18 +103,22 @@ export function buildHomeThreadGroups(input: {
|
||||
const groups = new Map<string, MutableHomeThreadGroup>();
|
||||
const groupKeyByProjectKey = new Map<string, string>();
|
||||
|
||||
for (const scope of buildHomeProjectScopes(input)) {
|
||||
groups.set(scope.key, {
|
||||
key: scope.key,
|
||||
projects: [...scope.projects],
|
||||
pendingTasks: [],
|
||||
threads: [],
|
||||
for (const project of input.projects) {
|
||||
if (input.environmentId !== null && project.environmentId !== input.environmentId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const groupKey = deriveLogicalProjectKey(project, {
|
||||
groupingMode: input.projectGroupingMode,
|
||||
});
|
||||
for (const projectRef of scope.projectRefs) {
|
||||
groupKeyByProjectKey.set(
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
|
||||
scope.key,
|
||||
);
|
||||
const physicalKey = scopedProjectKey(project.environmentId, project.id);
|
||||
groupKeyByProjectKey.set(physicalKey, groupKey);
|
||||
|
||||
const existing = groups.get(groupKey);
|
||||
if (existing) {
|
||||
existing.projects.push(project);
|
||||
} else {
|
||||
groups.set(groupKey, { key: groupKey, projects: [project], pendingTasks: [], threads: [] });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -343,7 +186,10 @@ export function buildHomeThreadGroups(input: {
|
||||
continue;
|
||||
}
|
||||
|
||||
const title = deriveProjectGroupLabel({ representative, members: group.projects });
|
||||
const title =
|
||||
group.projects.length > 1
|
||||
? deriveProjectGroupLabel({ representative, members: group.projects })
|
||||
: representative.title;
|
||||
const groupMatches =
|
||||
query.length === 0 ||
|
||||
title.toLocaleLowerCase().includes(query) ||
|
||||
@@ -369,21 +215,19 @@ export function buildHomeThreadGroups(input: {
|
||||
? selectRecentThreads(sortedThreads, input.threadSortOrder, now)
|
||||
: sortedThreads;
|
||||
|
||||
// A stale project id still resolves to the canonical member with the same
|
||||
// environment/path, so quick creation follows the machine with the newest activity.
|
||||
const lastActiveProject = Arr.head(sortedThreads).pipe(
|
||||
Option.flatMap((thread) =>
|
||||
Arr.findFirst(
|
||||
input.projects,
|
||||
(project) =>
|
||||
project.environmentId === thread.environmentId && project.id === thread.projectId,
|
||||
),
|
||||
// Sorted newest-first, so the first thread whose project is a group member
|
||||
// marks the machine the user last worked on.
|
||||
const lastActiveProject = Arr.findFirst(sortedThreads, (thread) =>
|
||||
group.projects.some(
|
||||
(project) =>
|
||||
project.environmentId === thread.environmentId && project.id === thread.projectId,
|
||||
),
|
||||
Option.flatMap((threadProject) =>
|
||||
).pipe(
|
||||
Option.flatMap((thread) =>
|
||||
Arr.findFirst(
|
||||
group.projects,
|
||||
(project) =>
|
||||
derivePhysicalProjectKey(project) === derivePhysicalProjectKey(threadProject),
|
||||
project.environmentId === thread.environmentId && project.id === thread.projectId,
|
||||
),
|
||||
),
|
||||
Option.getOrNull,
|
||||
|
||||
@@ -36,8 +36,6 @@ import { AppText as Text } from "../../components/AppText";
|
||||
const ACTION_ITEM_WIDTH = 58;
|
||||
const ACTION_CIRCLE_SIZE = 36;
|
||||
const ACTION_ICON_SIZE = 15;
|
||||
const COMPACT_ACTION_CIRCLE_SIZE = 28;
|
||||
const COMPACT_ACTION_ICON_SIZE = 13;
|
||||
|
||||
export const THREAD_SWIPE_ACTIONS_WIDTH = ACTION_ITEM_WIDTH * 2;
|
||||
export const THREAD_SWIPE_SPRING = {
|
||||
@@ -165,9 +163,6 @@ export function useSwipeableScrollGate(options?: {
|
||||
export function ThreadSwipeable(props: {
|
||||
readonly backgroundColor: ColorValue;
|
||||
readonly children: (close: () => void) => ReactNode;
|
||||
/** Uses action visuals that fit inside compact 44pt rows. The press target
|
||||
* still spans the row's full height and width. */
|
||||
readonly compactActions?: boolean;
|
||||
readonly containerStyle?: StyleProp<ViewStyle>;
|
||||
/** Disables NEW swipe activations (e.g. while the list scrolls). */
|
||||
readonly enabled?: boolean;
|
||||
@@ -263,7 +258,6 @@ export function ThreadSwipeable(props: {
|
||||
renderRightActions={(_progress, translation, methods) => (
|
||||
<ThreadSwipeActions
|
||||
backgroundColor={props.backgroundColor}
|
||||
compact={props.compactActions === true}
|
||||
fullSwipeAction={props.fullSwipeAction ?? "delete"}
|
||||
fullSwipeThreshold={fullSwipeThreshold}
|
||||
onDelete={props.onDelete}
|
||||
@@ -291,7 +285,6 @@ export function ThreadSwipeable(props: {
|
||||
function SwipeActionButton(props: {
|
||||
readonly accessibilityLabel: string;
|
||||
readonly backgroundColor: string;
|
||||
readonly compact: boolean;
|
||||
readonly entryRange: readonly [number, number];
|
||||
readonly fullSwipeThreshold: number;
|
||||
readonly icon: ComponentProps<typeof SymbolView>["name"];
|
||||
@@ -300,8 +293,6 @@ function SwipeActionButton(props: {
|
||||
readonly stretchesOnFullSwipe: boolean;
|
||||
readonly translation: SharedValue<number>;
|
||||
}) {
|
||||
const circleSize = props.compact ? COMPACT_ACTION_CIRCLE_SIZE : ACTION_CIRCLE_SIZE;
|
||||
const iconSize = props.compact ? COMPACT_ACTION_ICON_SIZE : ACTION_ICON_SIZE;
|
||||
const actionStyle = useAnimatedStyle(() => {
|
||||
const reveal = Math.max(-props.translation.value, 0);
|
||||
const entryProgress = interpolate(reveal, props.entryRange, [0, 1], Extrapolation.CLAMP);
|
||||
@@ -333,7 +324,7 @@ function SwipeActionButton(props: {
|
||||
|
||||
return {
|
||||
transform: [{ translateX: -stretch }],
|
||||
width: circleSize + stretch,
|
||||
width: ACTION_CIRCLE_SIZE + stretch,
|
||||
};
|
||||
});
|
||||
const iconStyle = useAnimatedStyle(() => {
|
||||
@@ -395,13 +386,13 @@ function SwipeActionButton(props: {
|
||||
width: "100%",
|
||||
})}
|
||||
>
|
||||
<View style={{ height: circleSize, width: circleSize }}>
|
||||
<View style={{ height: ACTION_CIRCLE_SIZE, width: ACTION_CIRCLE_SIZE }}>
|
||||
<Animated.View
|
||||
style={[
|
||||
{
|
||||
backgroundColor: props.backgroundColor,
|
||||
borderRadius: 999,
|
||||
height: circleSize,
|
||||
height: ACTION_CIRCLE_SIZE,
|
||||
left: 0,
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
@@ -413,25 +404,25 @@ function SwipeActionButton(props: {
|
||||
style={[
|
||||
{
|
||||
alignItems: "center",
|
||||
height: circleSize,
|
||||
height: ACTION_CIRCLE_SIZE,
|
||||
justifyContent: "center",
|
||||
left: 0,
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
width: circleSize,
|
||||
width: ACTION_CIRCLE_SIZE,
|
||||
},
|
||||
iconStyle,
|
||||
]}
|
||||
>
|
||||
<SymbolView name={props.icon} size={iconSize} tintColor="#ffffff" type="monochrome" />
|
||||
<SymbolView
|
||||
name={props.icon}
|
||||
size={ACTION_ICON_SIZE}
|
||||
tintColor="#ffffff"
|
||||
type="monochrome"
|
||||
/>
|
||||
</Animated.View>
|
||||
</View>
|
||||
<Animated.View
|
||||
style={[
|
||||
{ height: 14, justifyContent: "center", paddingTop: props.compact ? 0 : 2 },
|
||||
labelStyle,
|
||||
]}
|
||||
>
|
||||
<Animated.View style={[{ paddingTop: 2 }, labelStyle]}>
|
||||
<Text className="text-3xs font-t3-medium text-foreground-muted" numberOfLines={1}>
|
||||
{props.label}
|
||||
</Text>
|
||||
@@ -443,7 +434,6 @@ function SwipeActionButton(props: {
|
||||
|
||||
export function ThreadSwipeActions(props: {
|
||||
readonly backgroundColor: ColorValue;
|
||||
readonly compact: boolean;
|
||||
readonly fullSwipeAction?: "delete" | "primary";
|
||||
readonly fullSwipeThreshold: number;
|
||||
readonly onDelete: () => void;
|
||||
@@ -476,7 +466,6 @@ export function ThreadSwipeActions(props: {
|
||||
<SwipeActionButton
|
||||
accessibilityLabel={props.primaryAction.accessibilityLabel}
|
||||
backgroundColor="#007aff"
|
||||
compact={props.compact}
|
||||
entryRange={[ACTION_ITEM_WIDTH * 0.55, THREAD_SWIPE_ACTIONS_WIDTH * 0.85]}
|
||||
fullSwipeThreshold={props.fullSwipeThreshold}
|
||||
icon={props.primaryAction.icon}
|
||||
@@ -488,7 +477,6 @@ export function ThreadSwipeActions(props: {
|
||||
<SwipeActionButton
|
||||
accessibilityLabel={`Delete ${props.threadTitle}`}
|
||||
backgroundColor="#ff2d55"
|
||||
compact={props.compact}
|
||||
entryRange={[8, ACTION_ITEM_WIDTH * 0.72]}
|
||||
fullSwipeThreshold={props.fullSwipeThreshold}
|
||||
icon="trash"
|
||||
|
||||
@@ -2,8 +2,7 @@ import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import { EnvironmentId, ThreadId, type SidebarProjectGroupingMode } from "@t3tools/contracts";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { useFocusEffect } from "@react-navigation/native";
|
||||
import {
|
||||
NavigationContext,
|
||||
@@ -23,7 +22,6 @@ import {
|
||||
} from "react";
|
||||
import { useWindowDimensions, View } from "react-native";
|
||||
import Animated, { useAnimatedStyle, useSharedValue, withTiming } from "react-native-reanimated";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
|
||||
import {
|
||||
deriveFileInspectorPaneLayout,
|
||||
@@ -36,12 +34,11 @@ import {
|
||||
} from "../../lib/layout";
|
||||
import { resolveThreadSelectionNavigationAction } from "../../lib/adaptive-navigation";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { mobilePreferencesAtom } from "../../state/preferences";
|
||||
import {
|
||||
parseActiveThreadPath,
|
||||
useHardwareKeyboardCommand,
|
||||
} from "../keyboard/hardwareKeyboardCommands";
|
||||
import { HomeListOptionsProvider, resolveProjectGroupingMode } from "../home/home-list-options";
|
||||
import { HomeListOptionsProvider } from "../home/home-list-options";
|
||||
import { ThreadNavigationSidebar } from "../threads/ThreadNavigationSidebar";
|
||||
import { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation";
|
||||
import { WorkspaceInspectorPane } from "./workspace-inspector-pane";
|
||||
@@ -187,31 +184,6 @@ export function AdaptiveWorkspaceLayout(props: {
|
||||
readonly children: ReactNode;
|
||||
readonly pathname: string;
|
||||
}) {
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
if (!AsyncResult.isSuccess(preferencesResult)) {
|
||||
return AsyncResult.isFailure(preferencesResult) ? (
|
||||
<AdaptiveWorkspaceLayoutContent {...props} projectGroupingMode="repository" />
|
||||
) : null;
|
||||
}
|
||||
return (
|
||||
<AdaptiveWorkspaceLayoutContent
|
||||
{...props}
|
||||
projectGroupingMode={resolveProjectGroupingMode(
|
||||
preferencesResult.value.projectGroupingEnabled,
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AdaptiveWorkspaceLayoutContent(
|
||||
props: {
|
||||
readonly children: ReactNode;
|
||||
readonly pathname: string;
|
||||
} & {
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
},
|
||||
) {
|
||||
const projectGroupingMode = props.projectGroupingMode;
|
||||
const { width, height } = useWindowDimensions();
|
||||
const pathname = props.pathname;
|
||||
const navigation = useNavigation();
|
||||
@@ -502,7 +474,7 @@ function AdaptiveWorkspaceLayoutContent(
|
||||
);
|
||||
|
||||
return (
|
||||
<HomeListOptionsProvider projectGroupingMode={projectGroupingMode}>
|
||||
<HomeListOptionsProvider>
|
||||
<AdaptiveWorkspaceContext.Provider value={contextValue}>
|
||||
<View testID="adaptive-workspace-layout" className="flex-1 flex-row">
|
||||
{shouldRenderPrimarySidebar && layout.listPaneWidth !== null ? (
|
||||
|
||||
@@ -119,8 +119,6 @@ function LocalSettingsRouteScreen() {
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<GeneralSettingsSection />
|
||||
|
||||
<SettingsSection title="Appearance">
|
||||
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
|
||||
</SettingsSection>
|
||||
@@ -506,8 +504,6 @@ function ConfiguredSettingsRouteScreen() {
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<GeneralSettingsSection />
|
||||
|
||||
<SettingsSection title="Appearance">
|
||||
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
|
||||
</SettingsSection>
|
||||
@@ -522,25 +518,6 @@ function ConfiguredSettingsRouteScreen() {
|
||||
);
|
||||
}
|
||||
|
||||
function GeneralSettingsSection() {
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
|
||||
const projectGroupingEnabled = AsyncResult.isSuccess(preferencesResult)
|
||||
? preferencesResult.value.projectGroupingEnabled !== false
|
||||
: true;
|
||||
|
||||
return (
|
||||
<SettingsSection title="General">
|
||||
<SettingsSwitchRow
|
||||
icon="folder"
|
||||
label="Project Grouping"
|
||||
value={projectGroupingEnabled}
|
||||
onValueChange={(value) => savePreferences({ projectGroupingEnabled: value })}
|
||||
/>
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Device-local beta toggles. Mobile has no client-settings sync, so this is
|
||||
* the counterpart of web's Settings → Beta backed by mobile preferences.
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import { ActivityIndicator, Pressable, StyleSheet, useColorScheme, View } from "react-native";
|
||||
import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated";
|
||||
import { ActivityIndicator, Pressable, View } from "react-native";
|
||||
import Animated, { FadeIn, FadeOut } from "react-native-reanimated";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
@@ -11,9 +10,6 @@ import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import type { GitActionProgress } from "../../state/use-vcs-action-state";
|
||||
|
||||
const OVERLAY_LAYOUT_TRANSITION = LinearTransition.duration(220);
|
||||
const AnimatedLiquidGlassView = Animated.createAnimatedComponent(LiquidGlassView);
|
||||
|
||||
export function GitActionProgressOverlay(props: {
|
||||
readonly progress: GitActionProgress;
|
||||
readonly onDismiss: () => void;
|
||||
@@ -49,7 +45,7 @@ export function GitActionProgressOverlay(props: {
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
entering={isLiquidGlassSupported ? undefined : FadeIn.duration(200)}
|
||||
entering={FadeIn.duration(200)}
|
||||
exiting={FadeOut.duration(150)}
|
||||
className="absolute inset-x-3 z-[100]"
|
||||
style={{ top: insets.top + 48 }}
|
||||
@@ -65,11 +61,16 @@ export function GitActionProgressOverlay(props: {
|
||||
function OverlayContent(props: { readonly progress: GitActionProgress }) {
|
||||
const { progress } = props;
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const glassBorder = useThemeColor("--color-header-border");
|
||||
const glassTint = useThemeColor("--color-glass-tint");
|
||||
const isDarkMode = useColorScheme() === "dark";
|
||||
const content = (
|
||||
<>
|
||||
|
||||
const bgClass =
|
||||
progress.phase === "error"
|
||||
? "bg-red-50 dark:bg-red-950/80 border-red-200 dark:border-red-800"
|
||||
: "bg-card border-border";
|
||||
|
||||
return (
|
||||
<View
|
||||
className={`flex-row items-center gap-2.5 rounded-2xl border px-3.5 py-3 shadow-lg shadow-black/10 ${bgClass}`}
|
||||
>
|
||||
<OverlayIcon phase={progress.phase} iconColor={iconColor} />
|
||||
|
||||
<View className="flex-1 gap-0.5">
|
||||
@@ -88,56 +89,7 @@ function OverlayContent(props: { readonly progress: GitActionProgress }) {
|
||||
{progress.prUrl ? (
|
||||
<SymbolView name="arrow.up.right" size={13} tintColor={iconColor} type="monochrome" />
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
|
||||
if (isLiquidGlassSupported) {
|
||||
return (
|
||||
<Animated.View
|
||||
layout={OVERLAY_LAYOUT_TRANSITION}
|
||||
style={{
|
||||
backgroundColor: glassTint,
|
||||
borderColor: glassBorder,
|
||||
borderCurve: "continuous",
|
||||
borderRadius: 26,
|
||||
borderWidth: StyleSheet.hairlineWidth,
|
||||
overflow: "hidden",
|
||||
}}
|
||||
>
|
||||
<AnimatedLiquidGlassView
|
||||
colorScheme={isDarkMode ? "dark" : "light"}
|
||||
effect="regular"
|
||||
interactive
|
||||
layout={OVERLAY_LAYOUT_TRANSITION}
|
||||
style={{
|
||||
borderCurve: "continuous",
|
||||
borderRadius: 26,
|
||||
overflow: "hidden",
|
||||
}}
|
||||
>
|
||||
<Animated.View
|
||||
entering={FadeIn.delay(60).duration(140)}
|
||||
className="flex-row items-center gap-2.5 px-3.5 py-3"
|
||||
>
|
||||
{content}
|
||||
</Animated.View>
|
||||
</AnimatedLiquidGlassView>
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
|
||||
const bgClass =
|
||||
progress.phase === "error"
|
||||
? "bg-red-50 dark:bg-red-950/80 border-red-200 dark:border-red-800"
|
||||
: "bg-card border-border";
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
layout={OVERLAY_LAYOUT_TRANSITION}
|
||||
className={`flex-row items-center gap-2.5 rounded-[26px] border border-continuous px-3.5 py-3 shadow-lg shadow-black/10 ${bgClass}`}
|
||||
>
|
||||
{content}
|
||||
</Animated.View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -582,13 +582,10 @@ export function NewTaskDraftScreen(props: {
|
||||
? "Approve actions"
|
||||
: flow.runtimeMode === "auto-accept-edits"
|
||||
? "Auto-accept edits"
|
||||
: flow.runtimeMode === "auto"
|
||||
? "Auto"
|
||||
: "Full access",
|
||||
: "Full access",
|
||||
subactions: [
|
||||
{ id: "options:runtime:approval-required", title: "Approve actions" },
|
||||
{ id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" },
|
||||
{ id: "options:runtime:auto", title: "Auto" },
|
||||
{ id: "options:runtime:full-access", title: "Full access" },
|
||||
].map((option) => {
|
||||
const value = option.id.replace("options:runtime:", "");
|
||||
|
||||
@@ -638,13 +638,10 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
? "Approve actions"
|
||||
: currentRuntimeMode === "auto-accept-edits"
|
||||
? "Auto-accept edits"
|
||||
: currentRuntimeMode === "auto"
|
||||
? "Auto"
|
||||
: "Full access",
|
||||
: "Full access",
|
||||
subactions: [
|
||||
{ id: "options:runtime:approval-required", title: "Approve actions" },
|
||||
{ id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" },
|
||||
{ id: "options:runtime:auto", title: "Auto" },
|
||||
{ id: "options:runtime:full-access", title: "Full access" },
|
||||
].map((option) => {
|
||||
const value = option.id.replace("options:runtime:", "");
|
||||
|
||||
@@ -33,6 +33,7 @@ import { useSavedRemoteConnections } from "../../state/use-remote-environment-re
|
||||
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
|
||||
import {
|
||||
hasCustomHomeListOptions,
|
||||
PROJECT_GROUPING_OPTIONS,
|
||||
PROJECT_SORT_OPTIONS,
|
||||
THREAD_SORT_OPTIONS,
|
||||
useHomeListOptions,
|
||||
@@ -47,7 +48,7 @@ import {
|
||||
type HomeGroupDisplayState,
|
||||
type HomeListItem,
|
||||
} from "../home/homeListItems";
|
||||
import { buildHomeProjectScopes, buildHomeThreadGroups } from "../home/homeThreadList";
|
||||
import { buildHomeThreadGroups } from "../home/homeThreadList";
|
||||
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "../home/thread-swipe-actions";
|
||||
import { usePendingTaskListActions } from "../home/usePendingTaskListActions";
|
||||
import { useThreadListActions } from "../home/useThreadListActions";
|
||||
@@ -216,47 +217,36 @@ function ThreadNavigationSidebarPane(
|
||||
() => new Set(environments.map((environment) => environment.environmentId)),
|
||||
[environments],
|
||||
);
|
||||
const { options, setSelectedEnvironmentId, setProjectSortOrder, setThreadSortOrder } =
|
||||
useHomeListOptions(availableEnvironmentIds);
|
||||
const {
|
||||
options,
|
||||
setSelectedEnvironmentId,
|
||||
setProjectGroupingMode,
|
||||
setProjectSortOrder,
|
||||
setThreadSortOrder,
|
||||
} = useHomeListOptions(availableEnvironmentIds);
|
||||
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
|
||||
const projectScopes = useMemo(
|
||||
() =>
|
||||
buildHomeProjectScopes({
|
||||
projects,
|
||||
environmentId: options.selectedEnvironmentId,
|
||||
projectGroupingMode: options.projectGroupingMode,
|
||||
}),
|
||||
[options.projectGroupingMode, options.selectedEnvironmentId, projects],
|
||||
);
|
||||
const projectFilterOptions = useMemo(
|
||||
() =>
|
||||
projectScopes.map((scope) => ({
|
||||
key: scope.key,
|
||||
label: scope.title,
|
||||
})),
|
||||
[projectScopes],
|
||||
projects
|
||||
.filter(
|
||||
(project) =>
|
||||
options.selectedEnvironmentId === null ||
|
||||
project.environmentId === options.selectedEnvironmentId,
|
||||
)
|
||||
.map((project) => ({
|
||||
key: scopedProjectKey(project.environmentId, project.id),
|
||||
label: project.title,
|
||||
})),
|
||||
[options.selectedEnvironmentId, projects],
|
||||
);
|
||||
const projectTitleByProjectKey = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
projectScopes.flatMap((scope) =>
|
||||
scope.projectRefs.map(
|
||||
(projectRef) =>
|
||||
[
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
|
||||
scope.title,
|
||||
] as const,
|
||||
),
|
||||
),
|
||||
),
|
||||
[projectScopes],
|
||||
);
|
||||
const selectedProjectScope = useMemo(
|
||||
const selectedProject = useMemo(
|
||||
() =>
|
||||
selectedProjectKey === null
|
||||
? null
|
||||
: (projectScopes.find((scope) => scope.key === selectedProjectKey) ?? null),
|
||||
[projectScopes, selectedProjectKey],
|
||||
: (projects.find(
|
||||
(project) => scopedProjectKey(project.environmentId, project.id) === selectedProjectKey,
|
||||
) ?? null),
|
||||
[projects, selectedProjectKey],
|
||||
);
|
||||
useEffect(() => {
|
||||
if (
|
||||
@@ -266,45 +256,31 @@ function ThreadNavigationSidebarPane(
|
||||
setSelectedProjectKey(null);
|
||||
}
|
||||
}, [projectFilterOptions, selectedProjectKey]);
|
||||
const selectedProjectRefs = useMemo(
|
||||
() =>
|
||||
selectedProjectScope === null
|
||||
? null
|
||||
: new Set(
|
||||
selectedProjectScope.projectRefs.map((projectRef) =>
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
|
||||
),
|
||||
),
|
||||
[selectedProjectScope],
|
||||
);
|
||||
const scopedProjects = useMemo(
|
||||
() =>
|
||||
selectedProjectRefs === null
|
||||
? projects
|
||||
: projects.filter((project) =>
|
||||
selectedProjectRefs.has(scopedProjectKey(project.environmentId, project.id)),
|
||||
),
|
||||
[projects, selectedProjectRefs],
|
||||
() => (selectedProject === null ? projects : [selectedProject]),
|
||||
[projects, selectedProject],
|
||||
);
|
||||
const scopedThreads = useMemo(
|
||||
() =>
|
||||
selectedProjectRefs === null
|
||||
selectedProject === null
|
||||
? threads
|
||||
: threads.filter((thread) =>
|
||||
selectedProjectRefs.has(scopedProjectKey(thread.environmentId, thread.projectId)),
|
||||
: threads.filter(
|
||||
(thread) =>
|
||||
thread.environmentId === selectedProject.environmentId &&
|
||||
thread.projectId === selectedProject.id,
|
||||
),
|
||||
[selectedProjectRefs, threads],
|
||||
[selectedProject, threads],
|
||||
);
|
||||
const scopedPendingTasks = useMemo(
|
||||
() =>
|
||||
selectedProjectRefs === null
|
||||
selectedProject === null
|
||||
? pendingTasks
|
||||
: pendingTasks.filter((pendingTask) =>
|
||||
selectedProjectRefs.has(
|
||||
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
|
||||
),
|
||||
: pendingTasks.filter(
|
||||
(pendingTask) =>
|
||||
pendingTask.message.environmentId === selectedProject.environmentId &&
|
||||
pendingTask.creation.projectId === selectedProject.id,
|
||||
),
|
||||
[pendingTasks, selectedProjectRefs],
|
||||
[pendingTasks, selectedProject],
|
||||
);
|
||||
const groups = useMemo(
|
||||
() =>
|
||||
@@ -425,7 +401,13 @@ function ThreadNavigationSidebarPane(
|
||||
return buildThreadListV2Items({
|
||||
threads: threads.filter((thread) => thread.archivedAt === null),
|
||||
environmentId: options.selectedEnvironmentId,
|
||||
projectRefs: selectedProjectScope === null ? null : selectedProjectScope.projectRefs,
|
||||
projectRef:
|
||||
selectedProject === null
|
||||
? null
|
||||
: {
|
||||
environmentId: selectedProject.environmentId,
|
||||
projectId: selectedProject.id,
|
||||
},
|
||||
searchQuery: props.searchQuery,
|
||||
changeRequestStateByKey,
|
||||
settlementEnvironmentIds,
|
||||
@@ -441,7 +423,7 @@ function ThreadNavigationSidebarPane(
|
||||
settlementEnvironmentIds,
|
||||
threadListV2Enabled,
|
||||
threads,
|
||||
selectedProjectScope,
|
||||
selectedProject,
|
||||
]);
|
||||
const listItems = useMemo<readonly SidebarListItem[]>(() => {
|
||||
if (!threadListV2Enabled) return listLayout.items;
|
||||
@@ -455,10 +437,9 @@ function ThreadNavigationSidebarPane(
|
||||
(pendingTask) =>
|
||||
(options.selectedEnvironmentId === null ||
|
||||
pendingTask.message.environmentId === options.selectedEnvironmentId) &&
|
||||
(selectedProjectRefs === null ||
|
||||
selectedProjectRefs.has(
|
||||
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
|
||||
)) &&
|
||||
(selectedProject === null ||
|
||||
(pendingTask.message.environmentId === selectedProject.environmentId &&
|
||||
pendingTask.creation.projectId === selectedProject.id)) &&
|
||||
(v2SearchQuery.length === 0 ||
|
||||
pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
|
||||
);
|
||||
@@ -488,7 +469,7 @@ function ThreadNavigationSidebarPane(
|
||||
options.selectedEnvironmentId,
|
||||
pendingTasks,
|
||||
props.searchQuery,
|
||||
selectedProjectRefs,
|
||||
selectedProject,
|
||||
threadListV2Enabled,
|
||||
threadListV2Layout,
|
||||
]);
|
||||
@@ -560,6 +541,16 @@ function ThreadNavigationSidebarPane(
|
||||
state: options.threadSortOrder === option.value ? "on" : "off",
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "project-grouping",
|
||||
title: "Group projects",
|
||||
subactions: PROJECT_GROUPING_OPTIONS.map((option) => ({
|
||||
id: `project-grouping:${option.value}`,
|
||||
title: option.label,
|
||||
subtitle: option.subtitle,
|
||||
state: options.projectGroupingMode === option.value ? "on" : "off",
|
||||
})),
|
||||
},
|
||||
] satisfies MenuAction[])),
|
||||
],
|
||||
[environments, options, projectFilterOptions, selectedProjectKey, threadListV2Enabled],
|
||||
@@ -603,10 +594,15 @@ function ThreadNavigationSidebarPane(
|
||||
setThreadSortOrder(threadSort.value);
|
||||
return;
|
||||
}
|
||||
const grouping = PROJECT_GROUPING_OPTIONS.find(
|
||||
(option) => `project-grouping:${option.value}` === event,
|
||||
);
|
||||
if (grouping) setProjectGroupingMode(grouping.value);
|
||||
},
|
||||
[
|
||||
environments,
|
||||
projectFilterOptions,
|
||||
setProjectGroupingMode,
|
||||
setProjectSortOrder,
|
||||
setSelectedEnvironmentId,
|
||||
setThreadSortOrder,
|
||||
@@ -743,7 +739,6 @@ function ThreadNavigationSidebarPane(
|
||||
variant={item.item.variant}
|
||||
showSettledDivider={item.item.showSettledDivider}
|
||||
project={projectByKey.get(scopeKey) ?? null}
|
||||
projectTitle={projectTitleByProjectKey.get(scopeKey)}
|
||||
providerDriver={
|
||||
serverConfigs
|
||||
.get(thread.environmentId)
|
||||
@@ -873,7 +868,6 @@ function ThreadNavigationSidebarPane(
|
||||
openPendingTask,
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
projectTitleByProjectKey,
|
||||
props.onNewThreadInProject,
|
||||
props.selectedThreadKey,
|
||||
props.width,
|
||||
@@ -904,10 +898,12 @@ function ThreadNavigationSidebarPane(
|
||||
selectedProjectKey,
|
||||
projectSortOrder: options.projectSortOrder,
|
||||
threadSortOrder: options.threadSortOrder,
|
||||
projectGroupingMode: options.projectGroupingMode,
|
||||
onEnvironmentChange: setSelectedEnvironmentId,
|
||||
onProjectChange: setSelectedProjectKey,
|
||||
onProjectSortOrderChange: setProjectSortOrder,
|
||||
onThreadSortOrderChange: setThreadSortOrder,
|
||||
onProjectGroupingModeChange: setProjectGroupingMode,
|
||||
listOrganization: !threadListV2Enabled,
|
||||
}),
|
||||
[
|
||||
@@ -915,6 +911,7 @@ function ThreadNavigationSidebarPane(
|
||||
options,
|
||||
projectFilterOptions,
|
||||
selectedProjectKey,
|
||||
setProjectGroupingMode,
|
||||
setProjectSortOrder,
|
||||
setSelectedEnvironmentId,
|
||||
setThreadSortOrder,
|
||||
@@ -936,8 +933,8 @@ function ThreadNavigationSidebarPane(
|
||||
? "Loading threads…"
|
||||
: props.searchQuery.trim().length > 0
|
||||
? "No matching threads"
|
||||
: selectedProjectScope !== null
|
||||
? `No threads in ${selectedProjectScope.title}`
|
||||
: selectedProject !== null
|
||||
? `No threads in ${selectedProject.title}`
|
||||
: "No threads yet"}
|
||||
</Text>
|
||||
);
|
||||
|
||||
@@ -90,7 +90,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly variant: "card" | "slim";
|
||||
readonly showSettledDivider: boolean;
|
||||
readonly project: EnvironmentProject | null;
|
||||
readonly projectTitle?: string;
|
||||
readonly providerDriver: string | null;
|
||||
/** Which machine hosts the thread. Null when only one environment is
|
||||
connected — repeating the same label on every row is noise. Mirrors
|
||||
@@ -220,7 +219,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
size={15}
|
||||
projectTitle={props.projectTitle ?? props.project.title}
|
||||
projectTitle={props.project.title}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
/>
|
||||
) : null}
|
||||
@@ -231,7 +230,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.projectTitle ?? props.project?.title ?? ""}
|
||||
{props.project?.title ?? ""}
|
||||
</Text>
|
||||
<Text
|
||||
className={cn(
|
||||
@@ -394,7 +393,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
size={15}
|
||||
projectTitle={props.projectTitle ?? props.project.title}
|
||||
projectTitle={props.project.title}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
/>
|
||||
</View>
|
||||
@@ -426,7 +425,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
{props.showSettledDivider ? <ThreadListV2SettledDivider pane={props.pane} /> : null}
|
||||
<ThreadSwipeable
|
||||
backgroundColor={sidebarPane ? drawerColor : screenColor}
|
||||
compactActions={variant === "slim"}
|
||||
containerStyle={
|
||||
sidebarPane ? { borderRadius: SIDEBAR_V2_ROW_RADIUS, overflow: "hidden" } : undefined
|
||||
}
|
||||
|
||||
@@ -166,36 +166,13 @@ describe("buildThreadListV2Items", () => {
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
projectRefs: [{ environmentId, projectId: ProjectId.make("project-1") }],
|
||||
projectRef: { environmentId, projectId: ProjectId.make("project-1") },
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.thread.id)).toEqual(["included"]);
|
||||
});
|
||||
|
||||
it("scopes the flat list to every environment member of a logical project", () => {
|
||||
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
|
||||
const { items } = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("local"), title: "Local" }),
|
||||
makeThread({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ThreadId.make("remote"),
|
||||
title: "Remote",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
projectRefs: [
|
||||
{ environmentId, projectId: ProjectId.make("project-1") },
|
||||
{ environmentId: remoteEnvironmentId, projectId: ProjectId.make("project-1") },
|
||||
],
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.thread.id)).toEqual(["local", "remote"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildThreadListV2Items settled paging", () => {
|
||||
|
||||
@@ -95,10 +95,10 @@ export interface ThreadListV2Layout {
|
||||
export function buildThreadListV2Items(input: {
|
||||
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly projectRefs?: ReadonlyArray<{
|
||||
readonly projectRef?: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly projectId: ProjectId;
|
||||
}> | null;
|
||||
} | null;
|
||||
readonly searchQuery: string;
|
||||
/** Per-row PR state reported up by visible rows ("env:threadId" keys). */
|
||||
readonly changeRequestStateByKey?: ReadonlyMap<string, "open" | "closed" | "merged">;
|
||||
@@ -115,9 +115,6 @@ export function buildThreadListV2Items(input: {
|
||||
const now = input.now ?? new Date().toISOString();
|
||||
const autoSettleAfterDays = input.autoSettleAfterDays ?? 3;
|
||||
const query = input.searchQuery.trim().toLocaleLowerCase();
|
||||
const projectKeys = input.projectRefs
|
||||
? new Set(input.projectRefs.map((ref) => `${ref.environmentId}:${ref.projectId}`))
|
||||
: null;
|
||||
|
||||
const active: EnvironmentThreadShell[] = [];
|
||||
const settled: EnvironmentThreadShell[] = [];
|
||||
@@ -125,7 +122,11 @@ export function buildThreadListV2Items(input: {
|
||||
// Callers pass live (unarchived) shells; settled threads are among them
|
||||
// and partition into the tail via effectiveSettled.
|
||||
if (input.environmentId !== null && thread.environmentId !== input.environmentId) continue;
|
||||
if (projectKeys !== null && !projectKeys.has(`${thread.environmentId}:${thread.projectId}`)) {
|
||||
if (
|
||||
input.projectRef != null &&
|
||||
(thread.environmentId !== input.projectRef.environmentId ||
|
||||
thread.projectId !== input.projectRef.projectId)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if (query.length > 0 && !thread.title.toLocaleLowerCase().includes(query)) continue;
|
||||
|
||||
@@ -22,7 +22,6 @@ export interface Preferences {
|
||||
readonly codeWordBreak?: boolean;
|
||||
readonly connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
|
||||
readonly collapsedProjectGroups?: readonly string[];
|
||||
readonly projectGroupingEnabled?: boolean;
|
||||
/**
|
||||
* Device-local mirror of the web beta's `sidebarV2Enabled`. Mobile has no
|
||||
* client-settings sync, so the flat v2 thread list is opted into per
|
||||
@@ -78,7 +77,6 @@ function sanitizePreferences(parsed: Preferences): Preferences {
|
||||
codeWordBreak?: boolean;
|
||||
connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
|
||||
collapsedProjectGroups?: readonly string[];
|
||||
projectGroupingEnabled?: boolean;
|
||||
threadListV2Enabled?: boolean;
|
||||
} = {};
|
||||
|
||||
@@ -106,9 +104,6 @@ function sanitizePreferences(parsed: Preferences): Preferences {
|
||||
(key): key is string => typeof key === "string",
|
||||
);
|
||||
}
|
||||
if (typeof parsed.projectGroupingEnabled === "boolean") {
|
||||
preferences.projectGroupingEnabled = parsed.projectGroupingEnabled;
|
||||
}
|
||||
if (typeof parsed.threadListV2Enabled === "boolean") {
|
||||
preferences.threadListV2Enabled = parsed.threadListV2Enabled;
|
||||
}
|
||||
|
||||
@@ -31,8 +31,7 @@
|
||||
"@opencode-ai/sdk": "^1.3.15",
|
||||
"@pierre/diffs": "catalog:",
|
||||
"effect": "catalog:",
|
||||
"node-pty": "^1.1.0",
|
||||
"yaml": "catalog:"
|
||||
"node-pty": "^1.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/vitest": "catalog:",
|
||||
|
||||
+55
-40
@@ -12,8 +12,7 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
DEVELOPMENT_ICON_OVERRIDES,
|
||||
resolveWebAssetBrandForPackageVersion,
|
||||
resolveWebIconOverrides,
|
||||
PUBLISH_ICON_OVERRIDES,
|
||||
} from "../../../scripts/lib/brand-assets.ts";
|
||||
import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
|
||||
import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
|
||||
@@ -82,34 +81,50 @@ const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Stan
|
||||
}
|
||||
});
|
||||
|
||||
const preparePublishIcons = Effect.fn("preparePublishIcons")(function* (
|
||||
interface PublishIconBackup {
|
||||
readonly targetPath: string;
|
||||
readonly backupPath: string;
|
||||
}
|
||||
|
||||
const applyPublishIconOverrides = Effect.fn("applyPublishIconOverrides")(function* (
|
||||
repoRoot: string,
|
||||
serverDir: string,
|
||||
version: string,
|
||||
) {
|
||||
const path = yield* Path.Path;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const brand = resolveWebAssetBrandForPackageVersion(version);
|
||||
const icons = resolveWebIconOverrides(brand, "dist/client").map((override) => ({
|
||||
sourcePath: path.join(repoRoot, override.sourceRelativePath),
|
||||
targetPath: path.join(serverDir, override.targetRelativePath),
|
||||
}));
|
||||
const backups: PublishIconBackup[] = [];
|
||||
|
||||
for (const icon of icons) {
|
||||
if (!(yield* fs.exists(icon.sourcePath))) {
|
||||
return yield* new ServerCliPublishIconSourceMissingError({ sourcePath: icon.sourcePath });
|
||||
for (const override of PUBLISH_ICON_OVERRIDES) {
|
||||
const sourcePath = path.join(repoRoot, override.sourceRelativePath);
|
||||
const targetPath = path.join(serverDir, override.targetRelativePath);
|
||||
const backupPath = `${targetPath}.publish-bak`;
|
||||
|
||||
if (!(yield* fs.exists(sourcePath))) {
|
||||
return yield* new ServerCliPublishIconSourceMissingError({ sourcePath });
|
||||
}
|
||||
if (!(yield* fs.exists(icon.targetPath))) {
|
||||
return yield* new ServerCliPublishIconTargetMissingError({ targetPath: icon.targetPath });
|
||||
if (!(yield* fs.exists(targetPath))) {
|
||||
return yield* new ServerCliPublishIconTargetMissingError({ targetPath });
|
||||
}
|
||||
|
||||
yield* fs.copyFile(targetPath, backupPath);
|
||||
yield* fs.copyFile(sourcePath, targetPath);
|
||||
backups.push({ targetPath, backupPath });
|
||||
}
|
||||
|
||||
return yield* Effect.forEach(icons, (icon) =>
|
||||
Effect.all({
|
||||
original: fs.readFile(icon.targetPath),
|
||||
publish: fs.readFile(icon.sourcePath),
|
||||
}).pipe(Effect.map((contents) => ({ ...icon, ...contents }))),
|
||||
);
|
||||
yield* Effect.log("[cli] Applied publish icon overrides to dist/client");
|
||||
return backups as ReadonlyArray<PublishIconBackup>;
|
||||
});
|
||||
|
||||
const restorePublishIconOverrides = Effect.fn("restorePublishIconOverrides")(function* (
|
||||
backups: ReadonlyArray<PublishIconBackup>,
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
for (const backup of backups) {
|
||||
if (!(yield* fs.exists(backup.backupPath))) {
|
||||
continue;
|
||||
}
|
||||
yield* fs.rename(backup.backupPath, backup.targetPath);
|
||||
}
|
||||
});
|
||||
|
||||
const applyDevelopmentIconOverrides = Effect.fn("applyDevelopmentIconOverrides")(function* (
|
||||
@@ -221,6 +236,7 @@ const publishCmd = Command.make(
|
||||
const repoRoot = yield* RepoRoot;
|
||||
const serverDir = path.join(repoRoot, "apps/server");
|
||||
const packageJsonPath = path.join(serverDir, "package.json");
|
||||
const backupPath = `${packageJsonPath}.bak`;
|
||||
|
||||
// Assert build assets exist
|
||||
for (const relPath of ["dist/bin.mjs", "dist/client/index.html"]) {
|
||||
@@ -231,7 +247,7 @@ const publishCmd = Command.make(
|
||||
}
|
||||
|
||||
yield* Effect.acquireUseRelease(
|
||||
// Acquire: resolve publish metadata and read every original before mutation.
|
||||
// Acquire: backup package.json, resolve catalog dependencies, and strip devDependencies/scripts
|
||||
Effect.gen(function* () {
|
||||
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
|
||||
const workspaceConfig = yield* readWorkspaceConfig();
|
||||
@@ -257,22 +273,19 @@ const publishCmd = Command.make(
|
||||
),
|
||||
};
|
||||
|
||||
return {
|
||||
packageJsonString: yield* encodePackageJson(pkg),
|
||||
originalPackageJson: yield* fs.readFile(packageJsonPath),
|
||||
icons: yield* preparePublishIcons(repoRoot, serverDir, version),
|
||||
};
|
||||
const original = yield* fs.readFileString(packageJsonPath);
|
||||
const packageJsonString = yield* encodePackageJson(pkg);
|
||||
yield* fs.writeFileString(backupPath, original);
|
||||
yield* fs.writeFileString(packageJsonPath, `${packageJsonString}\n`);
|
||||
yield* Effect.log("[cli] Prepared package.json for publish");
|
||||
|
||||
const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
|
||||
return { iconBackups };
|
||||
}),
|
||||
// Use: pnpm publish from the workspace root so pnpm-only workspace
|
||||
// config, including override selectors, is interpreted correctly.
|
||||
(resource) =>
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
yield* fs.writeFileString(packageJsonPath, `${resource.packageJsonString}\n`);
|
||||
for (const icon of resource.icons) {
|
||||
yield* fs.writeFile(icon.targetPath, icon.publish);
|
||||
}
|
||||
yield* Effect.log("[cli] Applied package metadata and publish icon overrides");
|
||||
|
||||
const args = createVpPmPublishArgs(config);
|
||||
const spawnCommand = yield* resolveSpawnCommand("vp", ["pm", ...args]);
|
||||
|
||||
@@ -286,14 +299,16 @@ const publishCmd = Command.make(
|
||||
}),
|
||||
);
|
||||
}),
|
||||
// Release: restore every file even if applying overrides or publishing fails.
|
||||
(resource) =>
|
||||
// Release: restore
|
||||
(resource: { readonly iconBackups: ReadonlyArray<PublishIconBackup> }) =>
|
||||
Effect.gen(function* () {
|
||||
yield* fs.writeFile(packageJsonPath, resource.originalPackageJson);
|
||||
for (const icon of resource.icons) {
|
||||
yield* fs.writeFile(icon.targetPath, icon.original);
|
||||
}
|
||||
if (config.verbose) yield* Effect.log("[cli] Restored original publish assets");
|
||||
yield* restorePublishIconOverrides(resource.iconBackups).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logError(`[cli] Failed to restore publish icon overrides: ${String(error)}`),
|
||||
),
|
||||
);
|
||||
yield* fs.rename(backupPath, packageJsonPath);
|
||||
if (config.verbose) yield* Effect.log("[cli] Restored original package.json");
|
||||
}),
|
||||
);
|
||||
}),
|
||||
|
||||
@@ -11,7 +11,6 @@ import * as PlatformError from "effect/PlatformError";
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
|
||||
import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
|
||||
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
|
||||
import { ASSET_ROUTE_PREFIX, issueAssetUrl, resolveAsset } from "./AssetAccess.ts";
|
||||
|
||||
@@ -21,10 +20,7 @@ const configLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
|
||||
const testLayer = Layer.mergeAll(
|
||||
configLayer,
|
||||
WorkspacePaths.layer,
|
||||
ProjectFaviconResolver.layer.pipe(
|
||||
Layer.provide(WorkspacePaths.layer),
|
||||
Layer.provide(T3ProjectFileLoader.layer),
|
||||
),
|
||||
ProjectFaviconResolver.layer.pipe(Layer.provide(WorkspacePaths.layer)),
|
||||
ServerSecretStore.layer.pipe(Layer.provide(configLayer)),
|
||||
).pipe(Layer.provideMerge(NodeServices.layer));
|
||||
|
||||
|
||||
@@ -202,18 +202,6 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
|
||||
}).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer))),
|
||||
);
|
||||
|
||||
it.effect("exposes service lifecycle commands without T3 Connect configuration", () =>
|
||||
Effect.gen(function* () {
|
||||
const { output } = yield* captureStdout(runCli(["service", "--help"], noConnectCli));
|
||||
|
||||
assert.include(output, "Manage the T3 Code background service.");
|
||||
assert.include(output, "install");
|
||||
assert.include(output, "uninstall");
|
||||
assert.include(output, "update");
|
||||
assert.include(output, "status");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports fresh headless connect state without requiring local configuration", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = NodeFS.mkdtempSync(
|
||||
@@ -317,10 +305,7 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
|
||||
runConnectCli(["connect", "logout", "--base-dir", baseDir]),
|
||||
);
|
||||
|
||||
assert.equal(
|
||||
output,
|
||||
"Signed out of T3 Connect locally.\nThe background service is managed separately with `t3 service`.",
|
||||
);
|
||||
assert.equal(output, "Signed out of T3 Connect locally.");
|
||||
assert.isFalse(NodeFS.existsSync(tokenPath));
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -13,7 +13,6 @@ import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
|
||||
import { sharedServerCommandFlags } from "./cli/config.ts";
|
||||
import { projectCommand } from "./cli/project.ts";
|
||||
import { runServerCommand, serveCommand, startCommand } from "./cli/server.ts";
|
||||
import { serviceCommand } from "./cli/service.ts";
|
||||
|
||||
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
||||
|
||||
@@ -48,7 +47,6 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
|
||||
serveCommand,
|
||||
authCommand,
|
||||
projectCommand,
|
||||
serviceCommand,
|
||||
cloudEnabled ? connectCommand : connectUnavailableCommand,
|
||||
]),
|
||||
);
|
||||
|
||||
@@ -16,9 +16,9 @@ import {
|
||||
formatRelayClientReady,
|
||||
headlessSessionConfig,
|
||||
isPublishAgentActivityEnabledValue,
|
||||
recoverBootServiceOffer,
|
||||
reportCloudDisconnectResults,
|
||||
} from "./connect.ts";
|
||||
import { recoverServiceOnboardingOffer } from "./service.ts";
|
||||
|
||||
it("explains how to complete headless authorization", () => {
|
||||
assert.equal(
|
||||
@@ -58,7 +58,7 @@ it.effect("detects headless operation from individual SSH config values", () =>
|
||||
|
||||
it.effect("treats cancelling optional background setup as a successful skip", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* recoverServiceOnboardingOffer(Effect.fail(new Terminal.QuitError({})));
|
||||
const result = yield* recoverBootServiceOffer(Effect.fail(new Terminal.QuitError({})));
|
||||
assert.isFalse(result);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import { RelayOkResponse } from "@t3tools/contracts/relay";
|
||||
import * as RelayClient from "@t3tools/shared/relayClient";
|
||||
import * as Terminal from "effect/Terminal";
|
||||
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Config from "effect/Config";
|
||||
@@ -19,7 +20,6 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as References from "effect/References";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Terminal from "effect/Terminal";
|
||||
import { Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli";
|
||||
import {
|
||||
FetchHttpClient,
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
} from "effect/unstable/http";
|
||||
import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient";
|
||||
|
||||
import packageJson from "../../package.json" with { type: "json" };
|
||||
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import * as BootService from "../cloud/bootService.ts";
|
||||
@@ -44,13 +45,9 @@ import { headlessRelayClientTracingLayer } from "../cloud/relayTracing.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
|
||||
import * as ExternalLauncher from "../process/externalLauncher.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
|
||||
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
|
||||
import {
|
||||
bootServiceLayer,
|
||||
offerServiceDuringOnboarding,
|
||||
recoverServiceOnboardingOffer,
|
||||
} from "./service.ts";
|
||||
|
||||
const jsonFlag = Flag.boolean("json").pipe(
|
||||
Flag.withDescription("Emit JSON instead of human-readable output."),
|
||||
@@ -399,6 +396,21 @@ const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
|
||||
if (options.clearAuthorization) {
|
||||
const tokens = yield* CliTokenManager.CloudCliTokenManager;
|
||||
yield* tokens.clear;
|
||||
|
||||
// uninstall itself no-ops when nothing is installed (and on non-Linux),
|
||||
// so no status pre-check that could mask a real removal failure.
|
||||
const bootService = yield* BootService.BootService;
|
||||
yield* bootService.uninstall.pipe(
|
||||
Effect.tap((removed) =>
|
||||
removed ? Console.log("Removed the T3 Code background service.") : Effect.void,
|
||||
),
|
||||
Effect.catchTag("BootServiceUnsupportedError", () => Effect.succeed(false)),
|
||||
Effect.catch((error) =>
|
||||
Console.warn(`Could not remove the background service: ${error.message}`).pipe(
|
||||
Effect.as(false),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
yield* reportCloudDisconnectResults({
|
||||
@@ -408,9 +420,7 @@ const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
|
||||
});
|
||||
|
||||
if (options.clearAuthorization) {
|
||||
yield* Console.log(
|
||||
"Signed out of T3 Connect locally.\nThe background service is managed separately with `t3 service`.",
|
||||
);
|
||||
yield* Console.log("Signed out of T3 Connect locally.");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -447,7 +457,11 @@ const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function* <A, E
|
||||
RelayClient.layerCloudflared({ baseDir: config.baseDir }),
|
||||
EnvironmentAuth.runtimeLayer,
|
||||
ServerEnvironment.layer,
|
||||
bootServiceLayer(config),
|
||||
BootService.layer({
|
||||
baseDir: config.baseDir,
|
||||
logsDir: config.logsDir,
|
||||
cliVersion: packageJson.version,
|
||||
}).pipe(Layer.provide(ProcessRunner.layer)),
|
||||
headlessRelayClientTracingLayer,
|
||||
).pipe(
|
||||
Layer.provideMerge(FetchHttpClient.layer),
|
||||
@@ -669,6 +683,50 @@ const connectLogoutCommand = Command.make("logout", {
|
||||
),
|
||||
);
|
||||
|
||||
const offerBootService = Effect.gen(function* () {
|
||||
const bootService = yield* BootService.BootService;
|
||||
const { supported, installed, current } = yield* bootService.status;
|
||||
if (!supported) {
|
||||
// Don't prompt for something that can only fail; background setup is
|
||||
// Linux/systemd-only for now.
|
||||
return false;
|
||||
}
|
||||
if (installed && current) {
|
||||
yield* Console.log("T3 Code is already set up to run in the background on this machine.");
|
||||
return true;
|
||||
}
|
||||
const wanted = yield* Prompt.run(
|
||||
Prompt.confirm({
|
||||
message: installed
|
||||
? "The installed T3 Code background service is from an older setup. Update it now?"
|
||||
: "Run T3 Code in the background whenever this machine boots? " +
|
||||
"It stays reachable through T3 Connect even after you log out.",
|
||||
initial: true,
|
||||
}),
|
||||
);
|
||||
if (!wanted) {
|
||||
return false;
|
||||
}
|
||||
const plan = yield* bootService.install;
|
||||
yield* Console.log(`Background service installed. Logs: ${plan.logPath}`);
|
||||
return true;
|
||||
});
|
||||
|
||||
export const recoverBootServiceOffer = <R>(
|
||||
offer: Effect.Effect<boolean, BootService.BootServiceError | Terminal.QuitError, R>,
|
||||
) =>
|
||||
offer.pipe(
|
||||
Effect.catchTags({
|
||||
QuitError: () => Effect.succeed(false),
|
||||
BootServiceUnsupportedError: (error) =>
|
||||
Console.log(`Skipping background setup: ${error.message}`).pipe(Effect.as(false)),
|
||||
BootServiceCommandError: (error) =>
|
||||
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)),
|
||||
}),
|
||||
);
|
||||
|
||||
export const connectCommand = Command.make("connect", {
|
||||
...projectLocationFlags,
|
||||
headless: headlessFlag,
|
||||
@@ -690,7 +748,7 @@ export const connectCommand = Command.make("connect", {
|
||||
|
||||
// Connect itself already succeeded; a boot-service failure must not
|
||||
// fail the command, just tell the user what happened and move on.
|
||||
const background = yield* recoverServiceOnboardingOffer(offerServiceDuringOnboarding);
|
||||
const background = yield* recoverBootServiceOffer(offerBootService);
|
||||
yield* Console.log(
|
||||
background
|
||||
? "\n✓ Background service ready\n\nT3 Code will stay reachable after you log out."
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import { formatServiceStatus } from "./service.ts";
|
||||
|
||||
const status = {
|
||||
supported: true,
|
||||
installed: true,
|
||||
current: true,
|
||||
unitPath: "/home/me/.config/systemd/user/t3code.service",
|
||||
logPath: "/home/me/.t3/userdata/logs/boot-service.log",
|
||||
} as const;
|
||||
|
||||
it("reports the installed service version and host paths", () => {
|
||||
assert.equal(
|
||||
formatServiceStatus(status, "0.0.29"),
|
||||
[
|
||||
"T3 Code service",
|
||||
" Status: installed · [email protected]",
|
||||
" Unit: /home/me/.config/systemd/user/t3code.service",
|
||||
" Logs: /home/me/.t3/userdata/logs/boot-service.log",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("gives a direct repair command for a stale service", () => {
|
||||
assert.include(
|
||||
formatServiceStatus({ ...status, current: false }, "0.0.29"),
|
||||
"Next: Run `npx t3@latest service update`.",
|
||||
);
|
||||
});
|
||||
|
||||
it("explains service availability without systemd", () => {
|
||||
assert.include(
|
||||
formatServiceStatus({ ...status, supported: false, installed: false }, "0.0.29"),
|
||||
"Supported on: Linux with systemd",
|
||||
);
|
||||
});
|
||||
@@ -1,199 +0,0 @@
|
||||
import * as Console from "effect/Console";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Terminal from "effect/Terminal";
|
||||
import { Command, GlobalFlag, Prompt } from "effect/unstable/cli";
|
||||
|
||||
import packageJson from "../../package.json" with { type: "json" };
|
||||
import * as BootService from "../cloud/bootService.ts";
|
||||
import type * as ServerConfig from "../config.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
|
||||
|
||||
export const bootServiceLayer = (config: ServerConfig.ServerConfig["Service"]) =>
|
||||
BootService.layer({
|
||||
baseDir: config.baseDir,
|
||||
logsDir: config.logsDir,
|
||||
cliVersion: packageJson.version,
|
||||
}).pipe(Layer.provide(ProcessRunner.layer));
|
||||
|
||||
export type ServiceReconcileResult =
|
||||
| {
|
||||
readonly changed: false;
|
||||
readonly status: BootService.BootServiceStatus;
|
||||
}
|
||||
| {
|
||||
readonly changed: true;
|
||||
readonly previouslyInstalled: boolean;
|
||||
readonly plan: BootService.BootServicePlan;
|
||||
};
|
||||
|
||||
/** Install, update, or repair the service using the CLI version running this command. */
|
||||
export const reconcileService = Effect.fn("cli.service.reconcile")(function* () {
|
||||
const service = yield* BootService.BootService;
|
||||
const status = yield* service.status;
|
||||
if (status.installed && status.current) {
|
||||
return { changed: false, status } satisfies ServiceReconcileResult;
|
||||
}
|
||||
const plan = yield* service.install;
|
||||
return {
|
||||
changed: true,
|
||||
previouslyInstalled: status.installed,
|
||||
plan,
|
||||
} satisfies ServiceReconcileResult;
|
||||
});
|
||||
|
||||
export function formatServiceStatus(
|
||||
status: BootService.BootServiceStatus,
|
||||
cliVersion: string,
|
||||
): string {
|
||||
if (!status.supported) {
|
||||
return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd";
|
||||
}
|
||||
if (!status.installed) {
|
||||
return "T3 Code service\n Status: not installed\n Next: Run `t3 service install`.";
|
||||
}
|
||||
return [
|
||||
"T3 Code service",
|
||||
` Status: ${status.current ? `installed · t3@${cliVersion}` : "needs an update or repair"}`,
|
||||
` Unit: ${status.unitPath}`,
|
||||
` Logs: ${status.logPath}`,
|
||||
...(status.current ? [] : [" Next: Run `npx t3@latest service update`."]),
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
const runServiceCommand = Effect.fn("cli.service.run")(function* <A, E>(
|
||||
flags: { readonly baseDir: Parameters<typeof resolveCliAuthConfig>[0]["baseDir"] },
|
||||
run: Effect.Effect<A, E, BootService.BootService>,
|
||||
) {
|
||||
const logLevel = yield* GlobalFlag.LogLevel;
|
||||
const config = yield* resolveCliAuthConfig(flags, logLevel);
|
||||
return yield* run.pipe(Effect.provide(bootServiceLayer(config)));
|
||||
});
|
||||
|
||||
const serviceInstallCommand = Command.make("install", projectLocationFlags).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();
|
||||
if (!result.changed) {
|
||||
yield* Console.log(
|
||||
`T3 Code service is already installed with t3@${packageJson.version}.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
yield* Console.log(
|
||||
`${result.previouslyInstalled ? "Updated" : "Installed"} T3 Code service with t3@${packageJson.version}.\nLogs: ${result.plan.logPath}`,
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const serviceUpdateCommand = Command.make("update", projectLocationFlags).pipe(
|
||||
Command.withDescription(
|
||||
"Update or repair the background service using this CLI version. Use `npx t3@latest service update` for the latest release.",
|
||||
),
|
||||
Command.withHandler((flags) =>
|
||||
runServiceCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const result = yield* reconcileService();
|
||||
if (!result.changed) {
|
||||
yield* Console.log(`T3 Code service is already using t3@${packageJson.version}.`);
|
||||
return;
|
||||
}
|
||||
yield* Console.log(
|
||||
`${result.previouslyInstalled ? "Updated" : "Installed"} T3 Code service with t3@${packageJson.version}.\nLogs: ${result.plan.logPath}`,
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const serviceUninstallCommand = Command.make("uninstall", projectLocationFlags).pipe(
|
||||
Command.withDescription("Stop and remove the T3 Code background service."),
|
||||
Command.withHandler((flags) =>
|
||||
runServiceCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const service = yield* BootService.BootService;
|
||||
const removed = yield* service.uninstall;
|
||||
yield* Console.log(
|
||||
removed ? "Removed the T3 Code service." : "T3 Code service is not installed.",
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const serviceStatusCommand = Command.make("status", projectLocationFlags).pipe(
|
||||
Command.withDescription("Show whether the T3 Code background service is installed."),
|
||||
Command.withHandler((flags) =>
|
||||
runServiceCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const service = yield* BootService.BootService;
|
||||
yield* Console.log(formatServiceStatus(yield* service.status, packageJson.version));
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
export const offerServiceDuringOnboarding = Effect.gen(function* () {
|
||||
const service = yield* BootService.BootService;
|
||||
const { supported, installed, current } = yield* service.status;
|
||||
if (!supported) {
|
||||
return false;
|
||||
}
|
||||
if (installed && current) {
|
||||
yield* Console.log("T3 Code is already set up to run in the background on this machine.");
|
||||
return true;
|
||||
}
|
||||
const wanted = yield* Prompt.run(
|
||||
Prompt.confirm({
|
||||
message: installed
|
||||
? "The installed T3 Code service needs an update or repair. Update it now?"
|
||||
: "Run T3 Code in the background whenever this machine boots? " +
|
||||
"It stays reachable through T3 Connect even after you log out.",
|
||||
initial: true,
|
||||
}),
|
||||
);
|
||||
if (!wanted) {
|
||||
return false;
|
||||
}
|
||||
const result = yield* reconcileService();
|
||||
if (result.changed) {
|
||||
yield* Console.log(
|
||||
`Background service ${result.previouslyInstalled ? "updated" : "installed"}. Logs: ${result.plan.logPath}`,
|
||||
);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
export const recoverServiceOnboardingOffer = <R>(
|
||||
offer: Effect.Effect<boolean, BootService.BootServiceError | Terminal.QuitError, R>,
|
||||
) =>
|
||||
offer.pipe(
|
||||
Effect.catchTags({
|
||||
QuitError: () => Effect.succeed(false),
|
||||
BootServiceUnsupportedError: (error) =>
|
||||
Console.log(`Skipping background setup: ${error.message}`).pipe(Effect.as(false)),
|
||||
BootServiceCommandError: (error) =>
|
||||
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)),
|
||||
}),
|
||||
);
|
||||
|
||||
export const serviceCommand = Command.make("service").pipe(
|
||||
Command.withDescription("Manage the T3 Code background service."),
|
||||
Command.withSubcommands([
|
||||
serviceInstallCommand,
|
||||
serviceUninstallCommand,
|
||||
serviceUpdateCommand,
|
||||
serviceStatusCommand,
|
||||
]),
|
||||
);
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
HostProcessPlatform,
|
||||
} from "@t3tools/shared/hostProcess";
|
||||
|
||||
import { reconcileService } from "../cli/service.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import * as BootService from "./bootService.ts";
|
||||
|
||||
@@ -101,7 +100,7 @@ it("renders a systemd unit with absolute paths and append-mode logging", () => {
|
||||
unit,
|
||||
[
|
||||
"[Unit]",
|
||||
"Description=T3 Code server",
|
||||
"Description=T3 Code server (T3 Connect)",
|
||||
"StartLimitIntervalSec=300",
|
||||
"StartLimitBurst=5",
|
||||
"",
|
||||
@@ -109,7 +108,6 @@ it("renders a systemd unit with absolute paths and append-mode logging", () => {
|
||||
"Type=simple",
|
||||
"WorkingDirectory=%h",
|
||||
"Environment=T3CODE_HOME=/home/theo/.t3",
|
||||
"Environment=T3_BOOT_SERVICE_UNIT=t3code.service",
|
||||
"ExecStart=/usr/local/bin/node /home/theo/.t3/runtime/versions/0.0.27/node_modules/t3/dist/bin.mjs serve",
|
||||
"Restart=always",
|
||||
"RestartSec=5",
|
||||
@@ -172,33 +170,6 @@ it("flags package-manager cache entry points as ephemeral", () => {
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("BootService", (it) => {
|
||||
it.effect("reconciles the standalone service once and is then idempotent", () =>
|
||||
Effect.gen(function* () {
|
||||
const { dirs } = yield* makeTestContext();
|
||||
const commands: Array<RecordedCommand> = [];
|
||||
const service = yield* BootService.make({
|
||||
baseDir: dirs.baseDir,
|
||||
logsDir: dirs.logsDir,
|
||||
cliVersion: "0.0.27",
|
||||
host: makeHost(dirs.stableEntry),
|
||||
}).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
|
||||
|
||||
const first = yield* reconcileService().pipe(
|
||||
Effect.provideService(BootService.BootService, service),
|
||||
);
|
||||
assert.isTrue(first.changed);
|
||||
if (!first.changed) return;
|
||||
assert.isFalse(first.previouslyInstalled);
|
||||
|
||||
const commandCount = commands.length;
|
||||
const second = yield* reconcileService().pipe(
|
||||
Effect.provideService(BootService.BootService, service),
|
||||
);
|
||||
assert.isFalse(second.changed);
|
||||
assert.lengthOf(commands, commandCount);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("installs the unit, enables the service, and enables linger", () =>
|
||||
Effect.gen(function* () {
|
||||
const { dirs, fs, path } = yield* makeTestContext();
|
||||
@@ -340,7 +311,7 @@ it.layer(NodeServices.layer)("BootService", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports an installed-but-stale unit so the lifecycle can offer a repair", () =>
|
||||
it.effect("reports an installed-but-stale unit so connect can offer a repair", () =>
|
||||
Effect.gen(function* () {
|
||||
const { dirs, fs, path } = yield* makeTestContext();
|
||||
const commands: Array<RecordedCommand> = [];
|
||||
@@ -431,8 +402,8 @@ it.layer(NodeServices.layer)("BootService", (it) => {
|
||||
|
||||
const error = yield* service.install.pipe(Effect.flip);
|
||||
assert.isTrue(isCommandError(error));
|
||||
// A leftover unit would make status report "installed" even though
|
||||
// linger never happened.
|
||||
// A leftover unit would make the next connect report "already set up"
|
||||
// even though linger never happened.
|
||||
assert.isFalse(
|
||||
yield* fs.exists(path.join(dirs.home, ".config", "systemd", "user", "t3code.service")),
|
||||
);
|
||||
|
||||
@@ -16,19 +16,21 @@ import {
|
||||
} from "@t3tools/shared/hostProcess";
|
||||
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import { ensurePinnedRuntimeInstalled, pinnedRuntimePaths } from "./pinnedRuntime.ts";
|
||||
|
||||
/**
|
||||
* Installs T3 Code as a per-user boot service. Linux-only for now: systemd
|
||||
* user unit + loginctl enable-linger. The service runs a stable or pinned
|
||||
* runtime — never an ephemeral `npx t3` cache whose eviction could break
|
||||
* startup.
|
||||
* Installs T3 Code as a per-user boot service so a connected machine stays
|
||||
* reachable through T3 Connect after the SSH session ends. Linux-only for
|
||||
* now: systemd user unit + loginctl enable-linger. The service runs a pinned
|
||||
* runtime installed under <baseDir>/runtime — never `npx t3`, whose cache is
|
||||
* ephemeral and whose registry fetch at boot would make startup depend on
|
||||
* the network.
|
||||
*/
|
||||
|
||||
const BOOT_SERVICE_NAME = "t3code";
|
||||
const BOOT_RUNTIME_DIR = "runtime";
|
||||
|
||||
export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
|
||||
export const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
|
||||
const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
|
||||
const PINNED_RUNTIME_INSTALL_TIMEOUT = Duration.minutes(10);
|
||||
|
||||
const EPHEMERAL_CACHE_SEGMENTS = [
|
||||
"/_npx/", // npx
|
||||
@@ -90,7 +92,7 @@ export function renderBootServiceUnit(plan: BootServicePlan): string {
|
||||
// relay connection, and Restart=always covers early-boot failures.
|
||||
return [
|
||||
"[Unit]",
|
||||
"Description=T3 Code server",
|
||||
"Description=T3 Code server (T3 Connect)",
|
||||
// Give up after 5 crashes in 5 minutes so a persistently broken install
|
||||
// (deleted runtime, broken workspace) stops instead of restarting every
|
||||
// 5s forever and growing the unrotated append log without bound.
|
||||
@@ -101,7 +103,6 @@ export function renderBootServiceUnit(plan: BootServicePlan): string {
|
||||
"Type=simple",
|
||||
"WorkingDirectory=%h",
|
||||
`Environment=T3CODE_HOME=${quoteSystemdValue(plan.baseDir)}`,
|
||||
`Environment=${BOOT_SERVICE_UNIT_ENV}=${BOOT_SERVICE_UNIT_FILE}`,
|
||||
`ExecStart=${quoteSystemdValue(plan.nodePath)} ${quoteSystemdValue(plan.t3EntryPath)} serve`,
|
||||
"Restart=always",
|
||||
"RestartSec=5",
|
||||
@@ -205,7 +206,14 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
|
||||
const unitDir = path.join(homeDir, ".config", "systemd", "user");
|
||||
const unitPath = path.join(unitDir, BOOT_SERVICE_UNIT_FILE);
|
||||
const logPath = path.join(input.logsDir, "boot-service.log");
|
||||
const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion);
|
||||
const runtimeVersionDir = path.join(
|
||||
input.baseDir,
|
||||
BOOT_RUNTIME_DIR,
|
||||
"versions",
|
||||
input.cliVersion,
|
||||
);
|
||||
const runtimeEntryPath = path.join(runtimeVersionDir, "node_modules", "t3", "dist", "bin.mjs");
|
||||
const runtimeSentinelPath = path.join(runtimeVersionDir, ".install-complete");
|
||||
|
||||
const requireSystemdLinux = Effect.gen(function* () {
|
||||
if (platform !== "linux" || homeDir === "") {
|
||||
@@ -255,41 +263,52 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
|
||||
if (!isEphemeralCacheEntry(host.cliEntryPath)) {
|
||||
return;
|
||||
}
|
||||
yield* ensurePinnedRuntimeInstalled({
|
||||
baseDir: input.baseDir,
|
||||
version: input.cliVersion,
|
||||
fs,
|
||||
path,
|
||||
runner,
|
||||
}).pipe(
|
||||
Effect.mapError((error) =>
|
||||
error.step.startsWith("installing")
|
||||
? new BootServiceCommandError({
|
||||
step: error.step,
|
||||
exitCode: error.exitCode,
|
||||
stdoutLength: error.stdoutLength,
|
||||
stderrLength: error.stderrLength,
|
||||
cause: error.cause,
|
||||
})
|
||||
: new BootServiceInstallError({ cause: error }),
|
||||
),
|
||||
Effect.tapError((error) =>
|
||||
DateTime.now.pipe(
|
||||
Effect.flatMap((now) =>
|
||||
fs.writeFileString(logPath, `${DateTime.formatIso(now)} ${error.message}\n`, {
|
||||
flag: "a",
|
||||
}),
|
||||
),
|
||||
Effect.ignore,
|
||||
),
|
||||
// The sentinel is written only after npm exits 0. Checking the entry
|
||||
// file alone is not enough: npm extracts files before running native
|
||||
// builds (node-pty), so a killed install leaves a plausible-looking but
|
||||
// broken tree behind.
|
||||
const alreadyPinned = yield* Effect.all([
|
||||
fs.exists(runtimeSentinelPath),
|
||||
fs.exists(runtimeEntryPath),
|
||||
]).pipe(
|
||||
Effect.map(([sentinelExists, entryExists]) => sentinelExists && entryExists),
|
||||
Effect.mapError((cause) => new BootServiceInstallError({ cause })),
|
||||
);
|
||||
if (alreadyPinned) {
|
||||
return;
|
||||
}
|
||||
yield* fs.remove(runtimeVersionDir, { recursive: true, force: true }).pipe(
|
||||
Effect.andThen(fs.makeDirectory(runtimeVersionDir, { recursive: true })),
|
||||
Effect.mapError((cause) => new BootServiceInstallError({ cause })),
|
||||
);
|
||||
yield* runStep(
|
||||
"installing the pinned t3 runtime (this can take a few minutes)",
|
||||
"npm",
|
||||
[
|
||||
"install",
|
||||
"--prefix",
|
||||
runtimeVersionDir,
|
||||
"--no-fund",
|
||||
"--no-audit",
|
||||
`t3@${input.cliVersion}`,
|
||||
],
|
||||
// Native deps (node-pty) can compile from source on slow boxes; the
|
||||
// ProcessRunner default of 60s would kill a healthy install.
|
||||
{ timeout: PINNED_RUNTIME_INSTALL_TIMEOUT },
|
||||
).pipe(
|
||||
Effect.tapError(() =>
|
||||
fs.remove(runtimeVersionDir, { recursive: true, force: true }).pipe(Effect.ignore),
|
||||
),
|
||||
);
|
||||
yield* fs
|
||||
.writeFileString(runtimeSentinelPath, `${input.cliVersion}\n`)
|
||||
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
|
||||
});
|
||||
|
||||
// Where the unit will point: derivable without touching the network, so
|
||||
// status can compare units purely; install materializes it first.
|
||||
const plannedEntryPath = isEphemeralCacheEntry(host.cliEntryPath)
|
||||
? runtimePaths.entryPath
|
||||
? runtimeEntryPath
|
||||
: host.cliEntryPath;
|
||||
const plan: BootServicePlan = {
|
||||
nodePath: host.execPath,
|
||||
@@ -322,8 +341,8 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
|
||||
);
|
||||
|
||||
// If any activation step fails, remove the unit again: a leftover file
|
||||
// would make service status report it as installed even though it was
|
||||
// never enabled or lingered.
|
||||
// would make the next `t3 connect` report the service as already set up
|
||||
// even though it was never enabled or lingered.
|
||||
yield* Effect.gen(function* () {
|
||||
yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]);
|
||||
yield* runStep("enabling the service", "systemctl", [
|
||||
@@ -353,7 +372,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
|
||||
// fails), leave nothing behind: disable removes the enable symlink, remove
|
||||
// deletes the file, daemon-reload clears the stale definition — otherwise a
|
||||
// dangling wants/ symlink logs "Failed to load unit" at every boot and the
|
||||
// next lifecycle command misreports the state.
|
||||
// next connect misreports the state.
|
||||
const rollbackFailedInstall = Effect.fn("cloud.boot_service.rollback_failed_install")(function* (
|
||||
previousUnit: Option.Option<string>,
|
||||
) {
|
||||
|
||||
@@ -1,129 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import {
|
||||
ensurePinnedRuntimeInstalled,
|
||||
pinnedRuntimePaths,
|
||||
removePinnedRuntimeInstallation,
|
||||
} from "./pinnedRuntime.ts";
|
||||
|
||||
it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => {
|
||||
it.effect("serializes concurrent installs of the same runtime", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-test-" });
|
||||
const installStarted = yield* Deferred.make<void>();
|
||||
const allowInstallToFinish = yield* Deferred.make<void>();
|
||||
const paths = pinnedRuntimePaths(path, baseDir, "0.0.29");
|
||||
let npmRuns = 0;
|
||||
|
||||
const runner = ProcessRunner.ProcessRunner.of({
|
||||
run: (_input) =>
|
||||
Effect.gen(function* () {
|
||||
npmRuns += 1;
|
||||
yield* Deferred.succeed(installStarted, undefined);
|
||||
yield* Deferred.await(allowInstallToFinish);
|
||||
yield* fs
|
||||
.makeDirectory(path.dirname(paths.entryPath), { recursive: true })
|
||||
.pipe(Effect.orDie);
|
||||
yield* fs.writeFileString(paths.entryPath, "export {};\n").pipe(Effect.orDie);
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: ChildProcessSpawner.ExitCode(0),
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
};
|
||||
}),
|
||||
});
|
||||
const install = ensurePinnedRuntimeInstalled({
|
||||
baseDir,
|
||||
version: "0.0.29",
|
||||
fs,
|
||||
path,
|
||||
runner,
|
||||
});
|
||||
|
||||
const first = yield* Effect.forkChild(install, { startImmediately: true });
|
||||
yield* Deferred.await(installStarted);
|
||||
const second = yield* Effect.forkChild(install, { startImmediately: true });
|
||||
yield* Effect.yieldNow;
|
||||
assert.equal(npmRuns, 1);
|
||||
|
||||
yield* Deferred.succeed(allowInstallToFinish, undefined);
|
||||
yield* Fiber.join(first);
|
||||
yield* Fiber.join(second);
|
||||
|
||||
assert.equal(npmRuns, 1);
|
||||
assert.isTrue(yield* fs.exists(paths.sentinelPath));
|
||||
assert.isTrue(yield* fs.exists(paths.entryPath));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("waits for an active install before removing its runtime", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-test-" });
|
||||
const installStarted = yield* Deferred.make<void>();
|
||||
const allowInstallToFinish = yield* Deferred.make<void>();
|
||||
const paths = pinnedRuntimePaths(path, baseDir, "0.0.30");
|
||||
const runner = ProcessRunner.ProcessRunner.of({
|
||||
run: (_input) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Deferred.succeed(installStarted, undefined);
|
||||
yield* Deferred.await(allowInstallToFinish);
|
||||
yield* fs
|
||||
.makeDirectory(path.dirname(paths.entryPath), { recursive: true })
|
||||
.pipe(Effect.orDie);
|
||||
yield* fs.writeFileString(paths.entryPath, "export {};\n").pipe(Effect.orDie);
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: ChildProcessSpawner.ExitCode(0),
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
const installFiber = yield* Effect.forkChild(
|
||||
ensurePinnedRuntimeInstalled({
|
||||
baseDir,
|
||||
version: "0.0.30",
|
||||
fs,
|
||||
path,
|
||||
runner,
|
||||
}),
|
||||
{ startImmediately: true },
|
||||
);
|
||||
yield* Deferred.await(installStarted);
|
||||
const removeFiber = yield* Effect.forkChild(
|
||||
removePinnedRuntimeInstallation({
|
||||
baseDir,
|
||||
version: "0.0.30",
|
||||
fs,
|
||||
path,
|
||||
}),
|
||||
{ startImmediately: true },
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
assert.isTrue(yield* fs.exists(paths.versionDir));
|
||||
|
||||
yield* Deferred.succeed(allowInstallToFinish, undefined);
|
||||
yield* Fiber.join(installFiber);
|
||||
yield* Fiber.join(removeFiber);
|
||||
assert.isFalse(yield* fs.exists(paths.versionDir));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,176 +0,0 @@
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
|
||||
/**
|
||||
* A pinned runtime is an exact `t3@<version>` npm-installed into
|
||||
* <baseDir>/runtime/versions/<version>. The boot service points its systemd
|
||||
* unit here, and server self-update installs the target version here before
|
||||
* switching over — never `npx t3`, whose cache is ephemeral and whose
|
||||
* registry fetch at boot would make startup depend on the network.
|
||||
*/
|
||||
|
||||
const PINNED_RUNTIME_DIR = "runtime";
|
||||
const PINNED_RUNTIME_INSTALL_TIMEOUT = Duration.minutes(10);
|
||||
// Boot-service setup and remote self-update share this module but can be
|
||||
// constructed in separate layers. Serialize the complete check/install/
|
||||
// sentinel transaction across all callers in this process.
|
||||
const pinnedRuntimeInstallLock = Semaphore.makeUnsafe(1);
|
||||
|
||||
export interface PinnedRuntimePaths {
|
||||
readonly versionDir: string;
|
||||
readonly entryPath: string;
|
||||
readonly sentinelPath: string;
|
||||
}
|
||||
|
||||
export function pinnedRuntimePaths(
|
||||
path: Path.Path,
|
||||
baseDir: string,
|
||||
version: string,
|
||||
): PinnedRuntimePaths {
|
||||
const versionDir = path.join(baseDir, PINNED_RUNTIME_DIR, "versions", version);
|
||||
return {
|
||||
versionDir,
|
||||
entryPath: path.join(versionDir, "node_modules", "t3", "dist", "bin.mjs"),
|
||||
sentinelPath: path.join(versionDir, ".install-complete"),
|
||||
};
|
||||
}
|
||||
|
||||
export class PinnedRuntimeInstallError extends Schema.TaggedErrorClass<PinnedRuntimeInstallError>()(
|
||||
"PinnedRuntimeInstallError",
|
||||
{
|
||||
step: Schema.String,
|
||||
exitCode: Schema.optional(Schema.Number),
|
||||
stdoutLength: Schema.optional(Schema.Number),
|
||||
stderrLength: Schema.optional(Schema.Number),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return this.exitCode === undefined
|
||||
? `Pinned runtime install failed while ${this.step}.`
|
||||
: `Pinned runtime install failed while ${this.step} (exit code ${this.exitCode}).`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Installs `t3@<version>` into the pinned runtime directory unless a complete
|
||||
* install is already there, and returns its paths. The sentinel is written
|
||||
* only after npm exits 0; checking the entry file alone is not enough — npm
|
||||
* extracts files before running native builds (node-pty), so a killed
|
||||
* install leaves a plausible-looking but broken tree behind.
|
||||
*/
|
||||
export const ensurePinnedRuntimeInstalled = Effect.fn("cloud.pinned_runtime.ensure_installed")(
|
||||
function* (input: {
|
||||
readonly baseDir: string;
|
||||
readonly version: string;
|
||||
readonly fs: FileSystem.FileSystem;
|
||||
readonly path: Path.Path;
|
||||
readonly runner: ProcessRunner.ProcessRunner["Service"];
|
||||
}) {
|
||||
const { fs, runner } = input;
|
||||
const paths = pinnedRuntimePaths(input.path, input.baseDir, input.version);
|
||||
|
||||
return yield* pinnedRuntimeInstallLock.withPermit(
|
||||
Effect.gen(function* () {
|
||||
const alreadyPinned = yield* Effect.all([
|
||||
fs.exists(paths.sentinelPath),
|
||||
fs.exists(paths.entryPath),
|
||||
]).pipe(
|
||||
Effect.map(([sentinelExists, entryExists]) => sentinelExists && entryExists),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new PinnedRuntimeInstallError({ step: "checking the pinned runtime", cause }),
|
||||
),
|
||||
);
|
||||
if (alreadyPinned) {
|
||||
return paths;
|
||||
}
|
||||
|
||||
yield* fs.remove(paths.versionDir, { recursive: true, force: true }).pipe(
|
||||
Effect.andThen(fs.makeDirectory(paths.versionDir, { recursive: true })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new PinnedRuntimeInstallError({
|
||||
step: "preparing the pinned runtime directory",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const installStep = "installing the pinned t3 runtime (this can take a few minutes)";
|
||||
yield* runner
|
||||
.run({
|
||||
command: "npm",
|
||||
args: [
|
||||
"install",
|
||||
"--prefix",
|
||||
paths.versionDir,
|
||||
"--no-fund",
|
||||
"--no-audit",
|
||||
`t3@${input.version}`,
|
||||
],
|
||||
// Native deps (node-pty) can compile from source on slow boxes; the
|
||||
// ProcessRunner default of 60s would kill a healthy install.
|
||||
timeout: PINNED_RUNTIME_INSTALL_TIMEOUT,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) => new PinnedRuntimeInstallError({ step: installStep, cause })),
|
||||
Effect.filterOrFail(
|
||||
(result) => result.code === 0,
|
||||
(result) =>
|
||||
new PinnedRuntimeInstallError({
|
||||
step: installStep,
|
||||
exitCode: Number(result.code),
|
||||
stdoutLength: result.stdout.length,
|
||||
stderrLength: result.stderr.length,
|
||||
}),
|
||||
),
|
||||
Effect.tapError(() =>
|
||||
fs.remove(paths.versionDir, { recursive: true, force: true }).pipe(Effect.ignore),
|
||||
),
|
||||
);
|
||||
|
||||
yield* fs
|
||||
.writeFileString(paths.sentinelPath, `${input.version}\n`)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new PinnedRuntimeInstallError({ step: "recording the completed install", cause }),
|
||||
),
|
||||
);
|
||||
|
||||
return paths;
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
/** Removes one pinned runtime while holding the same process-wide lock used
|
||||
* by install/check/sentinel work, so cleanup cannot race another caller that
|
||||
* is materializing or reusing the runtime tree. */
|
||||
export const removePinnedRuntimeInstallation = Effect.fn("cloud.pinned_runtime.remove")(
|
||||
function* (input: {
|
||||
readonly baseDir: string;
|
||||
readonly version: string;
|
||||
readonly fs: FileSystem.FileSystem;
|
||||
readonly path: Path.Path;
|
||||
}) {
|
||||
const paths = pinnedRuntimePaths(input.path, input.baseDir, input.version);
|
||||
yield* pinnedRuntimeInstallLock.withPermit(
|
||||
input.fs
|
||||
.remove(paths.versionDir, { recursive: true, force: true })
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new PinnedRuntimeInstallError({ step: "removing the pinned runtime", cause }),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -1,589 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import {
|
||||
HostProcessArguments,
|
||||
HostProcessEnvironment,
|
||||
HostProcessExecutablePath,
|
||||
HostProcessPlatform,
|
||||
} from "@t3tools/shared/hostProcess";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import {
|
||||
BOOT_SERVICE_UNIT_ENV,
|
||||
BOOT_SERVICE_UNIT_FILE,
|
||||
renderBootServiceUnit,
|
||||
} from "./bootService.ts";
|
||||
import * as SelfUpdate from "./selfUpdate.ts";
|
||||
|
||||
const NODE_PATH = "/usr/local/bin/node";
|
||||
|
||||
interface RecordedCommand {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
const makeRecordingRunnerLayer = (
|
||||
commands: Array<RecordedCommand>,
|
||||
options?: {
|
||||
readonly failWhen?: ((command: string, args: ReadonlyArray<string>) => boolean) | undefined;
|
||||
readonly stdoutFor?:
|
||||
| ((command: string, args: ReadonlyArray<string>) => string | undefined)
|
||||
| undefined;
|
||||
},
|
||||
) =>
|
||||
Layer.succeed(
|
||||
ProcessRunner.ProcessRunner,
|
||||
ProcessRunner.ProcessRunner.of({
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
commands.push({ command: input.command, args: input.args });
|
||||
const failed = options?.failWhen?.(input.command, input.args) === true;
|
||||
const versionFromPath =
|
||||
input.command === NODE_PATH && input.args[1] === "--version"
|
||||
? /[/\\]runtime[/\\]versions[/\\]([^/\\]+)/.exec(input.args[0] ?? "")?.[1]
|
||||
: undefined;
|
||||
return {
|
||||
stdout:
|
||||
options?.stdoutFor?.(input.command, input.args) ??
|
||||
(versionFromPath === undefined ? "" : `t3 v${versionFromPath}\n`),
|
||||
stderr: failed ? `${input.command} exploded` : "",
|
||||
code: ChildProcessSpawner.ExitCode(failed ? 1 : 0),
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
};
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
const provideHostRefs = (input: {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly entryPath: string;
|
||||
}) =>
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(HostProcessPlatform, input.platform),
|
||||
Layer.succeed(HostProcessEnvironment, input.env),
|
||||
Layer.succeed(HostProcessExecutablePath, NODE_PATH),
|
||||
Layer.succeed(HostProcessArguments, [NODE_PATH, input.entryPath, "serve"]),
|
||||
),
|
||||
);
|
||||
|
||||
it("recognizes published npm artifacts as swappable entry points", () => {
|
||||
assert.isTrue(SelfUpdate.isPublishedCliEntry("/usr/local/lib/node_modules/t3/dist/bin.mjs"));
|
||||
assert.isTrue(
|
||||
SelfUpdate.isPublishedCliEntry("/home/theo/.npm/_npx/abc123/node_modules/t3/dist/bin.mjs"),
|
||||
);
|
||||
assert.isTrue(
|
||||
SelfUpdate.isPublishedCliEntry(
|
||||
"C:\\Users\\theo\\AppData\\Roaming\\npm\\node_modules\\t3\\dist\\bin.mjs",
|
||||
),
|
||||
);
|
||||
// Dev checkouts and the desktop bundle run apps/server/dist directly.
|
||||
assert.isFalse(SelfUpdate.isPublishedCliEntry("/home/theo/dev/t3/apps/server/dist/bin.mjs"));
|
||||
assert.isFalse(SelfUpdate.isPublishedCliEntry(""));
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("resolveServerSelfUpdateCapability", (it) => {
|
||||
const makeHome = Effect.fn("test.makeHome")(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-self-update-test-" });
|
||||
return { fs, path, home };
|
||||
});
|
||||
|
||||
const writeUnitReferencing = Effect.fn("test.writeUnitReferencing")(function* (
|
||||
home: string,
|
||||
entryPath: string,
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const unitDir = path.join(home, ".config", "systemd", "user");
|
||||
yield* fs.makeDirectory(unitDir, { recursive: true });
|
||||
yield* fs.writeFileString(
|
||||
path.join(unitDir, "t3code.service"),
|
||||
renderBootServiceUnit({
|
||||
nodePath: NODE_PATH,
|
||||
t3EntryPath: entryPath,
|
||||
baseDir: path.join(home, ".t3"),
|
||||
logPath: path.join(home, ".t3", "userdata", "logs", "boot-service.log"),
|
||||
unitPath: path.join(unitDir, "t3code.service"),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("reports boot-service for the systemd-spawned unit process", () =>
|
||||
Effect.gen(function* () {
|
||||
const { home, path } = yield* makeHome();
|
||||
const entryPath = path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
|
||||
yield* writeUnitReferencing(home, entryPath);
|
||||
const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
|
||||
desktopManaged: false,
|
||||
}).pipe(
|
||||
provideHostRefs({
|
||||
platform: "linux",
|
||||
env: {
|
||||
HOME: home,
|
||||
INVOCATION_ID: "abc123",
|
||||
[BOOT_SERVICE_UNIT_ENV]: BOOT_SERVICE_UNIT_FILE,
|
||||
},
|
||||
entryPath,
|
||||
}),
|
||||
);
|
||||
assert.equal(method, "boot-service");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not claim a systemd process owned by another unit", () =>
|
||||
Effect.gen(function* () {
|
||||
const { home, path } = yield* makeHome();
|
||||
const entryPath = path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
|
||||
yield* writeUnitReferencing(home, entryPath);
|
||||
const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
|
||||
desktopManaged: false,
|
||||
}).pipe(
|
||||
provideHostRefs({
|
||||
platform: "linux",
|
||||
env: { HOME: home, INVOCATION_ID: "abc123" },
|
||||
entryPath,
|
||||
}),
|
||||
);
|
||||
assert.isNull(method);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports respawn for a manual run of the pinned artifact", () =>
|
||||
Effect.gen(function* () {
|
||||
const { home, path } = yield* makeHome();
|
||||
const entryPath = path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
|
||||
yield* writeUnitReferencing(home, entryPath);
|
||||
// Same unit on disk, but no INVOCATION_ID: restarting the unit would
|
||||
// not replace this process, so it must respawn itself instead.
|
||||
const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
|
||||
desktopManaged: false,
|
||||
}).pipe(provideHostRefs({ platform: "linux", env: { HOME: home }, entryPath }));
|
||||
assert.equal(method, "respawn");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports respawn for a foreground npx artifact on darwin", () =>
|
||||
Effect.gen(function* () {
|
||||
const { home } = yield* makeHome();
|
||||
const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
|
||||
desktopManaged: false,
|
||||
}).pipe(
|
||||
provideHostRefs({
|
||||
platform: "darwin",
|
||||
env: { HOME: home },
|
||||
entryPath: `${home}/.npm/_npx/abc123/node_modules/t3/dist/bin.mjs`,
|
||||
}),
|
||||
);
|
||||
assert.equal(method, "respawn");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports desktop-managed for desktop-supervised backends", () =>
|
||||
Effect.gen(function* () {
|
||||
const { home, path } = yield* makeHome();
|
||||
// Desktop ownership wins over every process-shape heuristic: even a
|
||||
// systemd-looking pinned artifact belongs to the app that spawned it.
|
||||
const entryPath = path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
|
||||
yield* writeUnitReferencing(home, entryPath);
|
||||
const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
|
||||
desktopManaged: true,
|
||||
}).pipe(
|
||||
provideHostRefs({
|
||||
platform: "linux",
|
||||
env: {
|
||||
HOME: home,
|
||||
INVOCATION_ID: "abc123",
|
||||
[BOOT_SERVICE_UNIT_ENV]: BOOT_SERVICE_UNIT_FILE,
|
||||
},
|
||||
entryPath,
|
||||
}),
|
||||
);
|
||||
assert.equal(method, "desktop-managed");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports no method for dev checkouts and Windows", () =>
|
||||
Effect.gen(function* () {
|
||||
const { home } = yield* makeHome();
|
||||
const devMethod = yield* SelfUpdate.resolveServerSelfUpdateCapability({
|
||||
desktopManaged: false,
|
||||
}).pipe(
|
||||
provideHostRefs({
|
||||
platform: "darwin",
|
||||
env: { HOME: home },
|
||||
entryPath: `${home}/dev/t3/apps/server/dist/bin.mjs`,
|
||||
}),
|
||||
);
|
||||
assert.isNull(devMethod);
|
||||
const windowsMethod = yield* SelfUpdate.resolveServerSelfUpdateCapability({
|
||||
desktopManaged: false,
|
||||
}).pipe(
|
||||
provideHostRefs({
|
||||
platform: "win32",
|
||||
env: { HOME: home },
|
||||
entryPath: "C:\\Users\\theo\\AppData\\Roaming\\npm\\node_modules\\t3\\dist\\bin.mjs",
|
||||
}),
|
||||
);
|
||||
assert.isNull(windowsMethod);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
|
||||
interface RecordedSpawn {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
const makeContext = Effect.fn("test.makeContext")(function* (options?: {
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly bootService?: boolean;
|
||||
readonly desktopManaged?: boolean;
|
||||
readonly entryPath?: string;
|
||||
readonly failWhen?: (command: string, args: ReadonlyArray<string>) => boolean;
|
||||
readonly stdoutFor?: (command: string, args: ReadonlyArray<string>) => string | undefined;
|
||||
readonly failSpawn?: boolean;
|
||||
}) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-self-update-test-" });
|
||||
const baseDir = path.join(home, ".t3");
|
||||
const entryPath =
|
||||
options?.entryPath ??
|
||||
path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
|
||||
const env: NodeJS.ProcessEnv =
|
||||
options?.bootService === true
|
||||
? {
|
||||
HOME: home,
|
||||
INVOCATION_ID: "abc123",
|
||||
[BOOT_SERVICE_UNIT_ENV]: BOOT_SERVICE_UNIT_FILE,
|
||||
}
|
||||
: { HOME: home };
|
||||
if (options?.bootService === true) {
|
||||
const unitDir = path.join(home, ".config", "systemd", "user");
|
||||
yield* fs.makeDirectory(unitDir, { recursive: true });
|
||||
yield* fs.writeFileString(
|
||||
path.join(unitDir, "t3code.service"),
|
||||
renderBootServiceUnit({
|
||||
nodePath: NODE_PATH,
|
||||
t3EntryPath: entryPath,
|
||||
baseDir,
|
||||
logPath: path.join(baseDir, "userdata", "logs", "boot-service.log"),
|
||||
unitPath: path.join(unitDir, "t3code.service"),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const commands: Array<RecordedCommand> = [];
|
||||
const spawns: Array<RecordedSpawn> = [];
|
||||
let exited = 0;
|
||||
// layerTest always reports mode "web"; desktop-managed contexts overlay
|
||||
// the mode the desktop app's bootstrap envelope would set.
|
||||
const configLayer =
|
||||
options?.desktopManaged === true
|
||||
? Layer.effect(
|
||||
ServerConfig.ServerConfig,
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
return { ...config, mode: "desktop" as const };
|
||||
}),
|
||||
).pipe(Layer.provide(ServerConfig.layerTest(home, baseDir)))
|
||||
: ServerConfig.layerTest(home, baseDir);
|
||||
const service = yield* SelfUpdate.make({
|
||||
host: {
|
||||
spawnDetached: (command, args) =>
|
||||
Effect.sync(() => spawns.push({ command, args })).pipe(
|
||||
Effect.andThen(
|
||||
options?.failSpawn === true
|
||||
? Effect.fail(
|
||||
new ProcessRunner.ProcessSpawnError({
|
||||
command,
|
||||
argumentCount: args.length,
|
||||
cause: new Error("detached spawn failed"),
|
||||
}),
|
||||
)
|
||||
: Effect.void,
|
||||
),
|
||||
),
|
||||
exitProcess: () => {
|
||||
exited += 1;
|
||||
},
|
||||
},
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
makeRecordingRunnerLayer(commands, {
|
||||
failWhen: options?.failWhen,
|
||||
stdoutFor: options?.stdoutFor,
|
||||
}),
|
||||
configLayer,
|
||||
),
|
||||
),
|
||||
provideHostRefs({ platform: options?.platform ?? "linux", env, entryPath }),
|
||||
);
|
||||
return {
|
||||
fs,
|
||||
path,
|
||||
home,
|
||||
baseDir,
|
||||
entryPath,
|
||||
commands,
|
||||
spawns,
|
||||
exitCount: () => exited,
|
||||
service,
|
||||
};
|
||||
});
|
||||
|
||||
it.effect("rejects dist-tags and other non-exact versions", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext();
|
||||
const error = yield* context.service.update({ targetVersion: "latest" }).pipe(Effect.flip);
|
||||
assert.include(error.reason, "not an exact t3 version");
|
||||
assert.lengthOf(context.commands, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refuses to update a desktop-managed backend and points at the app", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext({ desktopManaged: true, bootService: true });
|
||||
const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
|
||||
assert.include(error.reason, "desktop app");
|
||||
assert.lengthOf(context.commands, 0);
|
||||
assert.lengthOf(context.spawns, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails without touching anything when no update method applies", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext({
|
||||
entryPath: "/home/theo/dev/t3/apps/server/dist/bin.mjs",
|
||||
});
|
||||
const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
|
||||
assert.include(error.reason, "cannot update itself");
|
||||
assert.lengthOf(context.commands, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("surfaces a failed npm install and never schedules a restart", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext({ failWhen: (command) => command === "npm" });
|
||||
const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
|
||||
assert.equal(error.reason, "Could not install the requested t3 version.");
|
||||
yield* TestClock.adjust(Duration.seconds(10));
|
||||
assert.lengthOf(context.spawns, 0);
|
||||
assert.equal(context.exitCount(), 0);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("reinstalls the same version after a failed preflight", () =>
|
||||
Effect.gen(function* () {
|
||||
let preflightAttempts = 0;
|
||||
const context = yield* makeContext({
|
||||
failWhen: (command) => {
|
||||
if (command !== NODE_PATH) return false;
|
||||
preflightAttempts += 1;
|
||||
return preflightAttempts === 1;
|
||||
},
|
||||
});
|
||||
const versionDir = context.path.join(context.baseDir, "runtime", "versions", "0.0.29");
|
||||
const entryPath = context.path.join(versionDir, "node_modules", "t3", "dist", "bin.mjs");
|
||||
yield* context.fs.makeDirectory(context.path.dirname(entryPath), { recursive: true });
|
||||
yield* context.fs.writeFileString(entryPath, "export {};\n");
|
||||
yield* context.fs.writeFileString(
|
||||
context.path.join(versionDir, ".install-complete"),
|
||||
"0.0.29\n",
|
||||
);
|
||||
|
||||
const firstError = yield* context.service
|
||||
.update({ targetVersion: "0.0.29" })
|
||||
.pipe(Effect.flip);
|
||||
assert.include(firstError.reason, "failed its version check");
|
||||
assert.isFalse(yield* context.fs.exists(versionDir));
|
||||
|
||||
const result = yield* context.service.update({ targetVersion: "0.0.29" });
|
||||
assert.deepEqual(result, { targetVersion: "0.0.29", method: "respawn" });
|
||||
assert.deepEqual(
|
||||
context.commands.map((entry) => entry.command),
|
||||
[NODE_PATH, "npm", NODE_PATH],
|
||||
);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("rejects and removes an installed runtime that reports the wrong version", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext({
|
||||
stdoutFor: (command, args) =>
|
||||
command === NODE_PATH && args[1] === "--version" ? "t3 v0.0.28\n" : undefined,
|
||||
});
|
||||
const versionDir = context.path.join(context.baseDir, "runtime", "versions", "0.0.29");
|
||||
|
||||
const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
|
||||
|
||||
assert.include(error.reason, "did not report the requested");
|
||||
assert.isFalse(yield* context.fs.exists(versionDir));
|
||||
assert.lengthOf(context.spawns, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports a detached replacement spawn failure and leaves updates retryable", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext({ failSpawn: true });
|
||||
|
||||
const first = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
|
||||
assert.include(first.reason, "Could not start the replacement");
|
||||
|
||||
const second = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
|
||||
assert.include(second.reason, "Could not start the replacement");
|
||||
assert.notInclude(second.reason, "already in progress");
|
||||
assert.lengthOf(context.spawns, 2);
|
||||
assert.equal(context.exitCount(), 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("installs, preflights, and respawns a foreground server", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext();
|
||||
const result = yield* context.service.update({ targetVersion: "0.0.29" });
|
||||
assert.deepEqual(result, { targetVersion: "0.0.29", method: "respawn" });
|
||||
assert.lengthOf(context.spawns, 1);
|
||||
|
||||
const concurrentError = yield* context.service
|
||||
.update({ targetVersion: "0.0.30" })
|
||||
.pipe(Effect.flip);
|
||||
assert.include(concurrentError.reason, "already in progress");
|
||||
|
||||
const pinnedEntry = context.path.join(
|
||||
context.baseDir,
|
||||
"runtime/versions/0.0.29/node_modules/t3/dist/bin.mjs",
|
||||
);
|
||||
assert.deepEqual(
|
||||
context.commands.map((entry) => [entry.command, ...entry.args].join(" ")),
|
||||
[
|
||||
`npm install --prefix ${context.path.join(context.baseDir, "runtime/versions/0.0.29")} --no-fund --no-audit [email protected]`,
|
||||
`${NODE_PATH} ${pinnedEntry} --version`,
|
||||
],
|
||||
);
|
||||
|
||||
// The restart is deferred so the RPC acknowledgement flushes first.
|
||||
yield* TestClock.adjust(Duration.seconds(10));
|
||||
assert.lengthOf(context.spawns, 1);
|
||||
const spawn = context.spawns[0];
|
||||
assert.equal(spawn?.command, "/bin/sh");
|
||||
assert.include(spawn?.args ?? [], pinnedEntry);
|
||||
// The replacement replays the original CLI arguments.
|
||||
assert.include(spawn?.args ?? [], "serve");
|
||||
assert.equal(context.exitCount(), 1);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("rewrites the systemd unit and restarts the boot service", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext({ bootService: true });
|
||||
const result = yield* context.service.update({ targetVersion: "0.0.29" });
|
||||
assert.deepEqual(result, { targetVersion: "0.0.29", method: "boot-service" });
|
||||
|
||||
const pinnedEntry = context.path.join(
|
||||
context.baseDir,
|
||||
"runtime/versions/0.0.29/node_modules/t3/dist/bin.mjs",
|
||||
);
|
||||
const unit = yield* context.fs.readFileString(
|
||||
context.path.join(context.home, ".config", "systemd", "user", "t3code.service"),
|
||||
);
|
||||
assert.include(unit, `ExecStart=${NODE_PATH} ${pinnedEntry} serve`);
|
||||
assert.deepEqual(
|
||||
context.commands.map((entry) => entry.command),
|
||||
["npm", NODE_PATH, "systemctl", "systemctl"],
|
||||
);
|
||||
assert.deepEqual(context.commands[2]?.args, ["--user", "daemon-reload"]);
|
||||
|
||||
assert.deepEqual(context.commands[3], {
|
||||
command: "systemctl",
|
||||
args: ["--user", "restart", "t3code.service"],
|
||||
});
|
||||
assert.lengthOf(context.spawns, 0);
|
||||
// systemd replaces the process; the server must not exit itself.
|
||||
assert.equal(context.exitCount(), 0);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("restores the previous unit and permits a retry when systemd restart fails", () =>
|
||||
Effect.gen(function* () {
|
||||
let failRestart = true;
|
||||
const context = yield* makeContext({
|
||||
bootService: true,
|
||||
failWhen: (command, args) => {
|
||||
if (command !== "systemctl" || args[1] !== "restart" || !failRestart) {
|
||||
return false;
|
||||
}
|
||||
failRestart = false;
|
||||
return true;
|
||||
},
|
||||
});
|
||||
const unitPath = context.path.join(
|
||||
context.home,
|
||||
".config",
|
||||
"systemd",
|
||||
"user",
|
||||
BOOT_SERVICE_UNIT_FILE,
|
||||
);
|
||||
const previousUnit = yield* context.fs.readFileString(unitPath);
|
||||
|
||||
const first = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
|
||||
assert.include(first.reason, "Restarting the systemd boot service failed");
|
||||
assert.equal(yield* context.fs.readFileString(unitPath), previousUnit);
|
||||
assert.deepEqual(
|
||||
context.commands.slice(-2).map((entry) => entry.args),
|
||||
[
|
||||
["--user", "restart", BOOT_SERVICE_UNIT_FILE],
|
||||
["--user", "daemon-reload"],
|
||||
],
|
||||
);
|
||||
|
||||
const retry = yield* context.service.update({ targetVersion: "0.0.30" });
|
||||
assert.deepEqual(retry, { targetVersion: "0.0.30", method: "boot-service" });
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("restores the previous systemd unit when daemon-reload fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext({
|
||||
bootService: true,
|
||||
failWhen: (command) => command === "systemctl",
|
||||
});
|
||||
const unitPath = context.path.join(
|
||||
context.home,
|
||||
".config",
|
||||
"systemd",
|
||||
"user",
|
||||
BOOT_SERVICE_UNIT_FILE,
|
||||
);
|
||||
const previousUnit = yield* context.fs.readFileString(unitPath);
|
||||
|
||||
const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
|
||||
assert.include(error.reason, "Reloading systemd units failed");
|
||||
assert.equal(yield* context.fs.readFileString(unitPath), previousUnit);
|
||||
assert.deepEqual(
|
||||
context.commands.map((entry) => entry.command),
|
||||
["npm", NODE_PATH, "systemctl", "systemctl"],
|
||||
);
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(10));
|
||||
assert.lengthOf(context.spawns, 0);
|
||||
assert.equal(context.exitCount(), 0);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
});
|
||||
@@ -1,430 +0,0 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
// node:child_process directly: the foreground-server replacement must be a
|
||||
// detached fire-and-forget child that outlives this process, while Effect's
|
||||
// ChildProcessSpawner ties every child to a scope that kills it.
|
||||
import {
|
||||
ServerSelfUpdateError,
|
||||
type ServerSelfUpdateCapability,
|
||||
type ServerSelfUpdateInput,
|
||||
type ServerSelfUpdateResult,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
HostProcessArguments,
|
||||
HostProcessEnvironment,
|
||||
HostProcessExecutablePath,
|
||||
HostProcessPlatform,
|
||||
} from "@t3tools/shared/hostProcess";
|
||||
import * as NodeChildProcess from "node:child_process";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import { writeFileStringAtomically } from "../atomicWrite.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import {
|
||||
BOOT_SERVICE_UNIT_ENV,
|
||||
BOOT_SERVICE_UNIT_FILE,
|
||||
quoteSystemdValue,
|
||||
renderBootServiceUnit,
|
||||
} from "./bootService.ts";
|
||||
import { ensurePinnedRuntimeInstalled, removePinnedRuntimeInstallation } from "./pinnedRuntime.ts";
|
||||
|
||||
/**
|
||||
* Lets a connected client replace this server with another published `t3`
|
||||
* version over RPC — the only update path that works when the user is not at
|
||||
* the machine (phone against a home server, relay-managed box). The target
|
||||
* version is npm-installed into the pinned runtime and verified before
|
||||
* anything restarts, so a failed install leaves the running server untouched.
|
||||
*/
|
||||
|
||||
const PREFLIGHT_TIMEOUT = Duration.seconds(30);
|
||||
/** Grace between acknowledging the RPC and killing the process, so the
|
||||
response (and its relay hop) flushes before the socket drops. */
|
||||
const RESTART_DELAY = Duration.seconds(2);
|
||||
|
||||
/** Exact npm versions only — never dist-tags — so the acknowledgement names
|
||||
the version that was actually installed. Also keeps the value safe to
|
||||
pass to npm and embed in filesystem paths. */
|
||||
const EXACT_VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
|
||||
|
||||
export interface ServerSelfUpdateHost {
|
||||
readonly execPath: string;
|
||||
readonly cliEntryPath: string;
|
||||
/** Original CLI arguments after the entry path, replayed on respawn. */
|
||||
readonly cliArgs: ReadonlyArray<string>;
|
||||
/** Resolves once the foreground replacement process has actually spawned. */
|
||||
readonly spawnDetached: (
|
||||
command: string,
|
||||
args: ReadonlyArray<string>,
|
||||
) => Effect.Effect<void, ProcessRunner.ProcessSpawnError>;
|
||||
readonly exitProcess: () => void;
|
||||
}
|
||||
|
||||
function normalizeEntryPath(entryPath: string): string {
|
||||
return entryPath.replaceAll("\\", "/");
|
||||
}
|
||||
|
||||
/**
|
||||
* Only a published npm artifact can be swapped for another version: dev
|
||||
* checkouts (apps/server/dist) and the desktop app's bundled backend have no
|
||||
* npm identity, and the desktop manages its own updates.
|
||||
*/
|
||||
export function isPublishedCliEntry(entryPath: string): boolean {
|
||||
return normalizeEntryPath(entryPath).includes("/node_modules/t3/dist/");
|
||||
}
|
||||
|
||||
/**
|
||||
* The update path this process can offer, or null when only a manual
|
||||
* relaunch works. "desktop-managed" — the T3 Code desktop app spawned this
|
||||
* backend and owns its version; only updating the app updates it.
|
||||
* "boot-service" — this is the systemd-supervised process from
|
||||
* bootService.ts: rewrite the unit and let systemd swap it. "respawn" — a
|
||||
* foreground POSIX process running a published artifact: replace it with a
|
||||
* detached child. Windows foreground runs are unsupported for now (no
|
||||
* equivalent of the detach-and-exec handoff below).
|
||||
*/
|
||||
export const resolveServerSelfUpdateCapability = Effect.fn(
|
||||
"cloud.server_self_update.resolve_capability",
|
||||
)(function* (input: {
|
||||
/** True when the desktop app supervises this backend (mode "desktop"). */
|
||||
readonly desktopManaged: boolean;
|
||||
}) {
|
||||
if (input.desktopManaged) {
|
||||
return "desktop-managed" as const;
|
||||
}
|
||||
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const env = yield* HostProcessEnvironment;
|
||||
const hostArguments = yield* HostProcessArguments;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const entryPath = hostArguments[1] ?? "";
|
||||
if (entryPath === "") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const homeDir = env.HOME ?? "";
|
||||
if (platform === "linux" && homeDir !== "") {
|
||||
const unitPath = path.join(homeDir, ".config", "systemd", "user", BOOT_SERVICE_UNIT_FILE);
|
||||
const unitReferencesEntry = yield* fs.readFileString(unitPath).pipe(
|
||||
Effect.map((unit) => unit.includes(quoteSystemdValue(entryPath))),
|
||||
Effect.orElseSucceed(() => false),
|
||||
);
|
||||
// INVOCATION_ID only proves that some systemd unit launched us. The
|
||||
// explicit marker written into t3code.service identifies this unit as the
|
||||
// supervisor that will replace the current process when restarted.
|
||||
if (
|
||||
unitReferencesEntry &&
|
||||
(env.INVOCATION_ID ?? "") !== "" &&
|
||||
env[BOOT_SERVICE_UNIT_ENV] === BOOT_SERVICE_UNIT_FILE
|
||||
) {
|
||||
return "boot-service" as const;
|
||||
}
|
||||
|
||||
// A process owned by another (or a legacy unmarked) systemd unit must not
|
||||
// use the foreground respawn path: Restart=always could otherwise launch
|
||||
// the old unit beside the detached replacement.
|
||||
if ((env.INVOCATION_ID ?? "") !== "") {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if ((platform === "linux" || platform === "darwin") && isPublishedCliEntry(entryPath)) {
|
||||
return "respawn" as const;
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
export class ServerSelfUpdate extends Context.Service<
|
||||
ServerSelfUpdate,
|
||||
{
|
||||
readonly update: (
|
||||
input: ServerSelfUpdateInput,
|
||||
) => Effect.Effect<ServerSelfUpdateResult, ServerSelfUpdateError>;
|
||||
}
|
||||
>()("t3/cloud/selfUpdate/ServerSelfUpdate") {}
|
||||
|
||||
export const make = Effect.fn("cloud.server_self_update.make")(function* (options?: {
|
||||
readonly host?: Partial<ServerSelfUpdateHost>;
|
||||
}) {
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const runner = yield* ProcessRunner.ProcessRunner;
|
||||
const env = yield* HostProcessEnvironment;
|
||||
const hostExecPath = yield* HostProcessExecutablePath;
|
||||
const hostArguments = yield* HostProcessArguments;
|
||||
const capability: ServerSelfUpdateCapability | null = yield* resolveServerSelfUpdateCapability({
|
||||
desktopManaged: serverConfig.mode === "desktop",
|
||||
});
|
||||
|
||||
const host: ServerSelfUpdateHost = {
|
||||
execPath: options?.host?.execPath ?? hostExecPath,
|
||||
cliEntryPath: options?.host?.cliEntryPath ?? hostArguments[1] ?? "",
|
||||
cliArgs: options?.host?.cliArgs ?? hostArguments.slice(2),
|
||||
spawnDetached:
|
||||
options?.host?.spawnDetached ??
|
||||
((command, args) =>
|
||||
Effect.callback<void, ProcessRunner.ProcessSpawnError>((resume) => {
|
||||
const spawnError = (cause: unknown) =>
|
||||
new ProcessRunner.ProcessSpawnError({
|
||||
command,
|
||||
argumentCount: args.length,
|
||||
cause,
|
||||
});
|
||||
let child: NodeChildProcess.ChildProcess;
|
||||
try {
|
||||
child = NodeChildProcess.spawn(command, [...args], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
});
|
||||
} catch (cause) {
|
||||
resume(Effect.fail(spawnError(cause)));
|
||||
return;
|
||||
}
|
||||
|
||||
const onSpawnError = (cause: Error) => resume(Effect.fail(spawnError(cause)));
|
||||
child.once("error", onSpawnError);
|
||||
child.once("spawn", () => {
|
||||
child.removeListener("error", onSpawnError);
|
||||
// Keep asynchronous child errors from becoming uncaught after the
|
||||
// successful spawn handoff has already been acknowledged.
|
||||
child.on("error", () => undefined);
|
||||
child.unref();
|
||||
resume(Effect.void);
|
||||
});
|
||||
})),
|
||||
exitProcess: options?.host?.exitProcess ?? (() => process.exit(0)),
|
||||
};
|
||||
|
||||
const inFlight = yield* Ref.make(false);
|
||||
|
||||
const failWith = (reason: string, cause?: unknown) =>
|
||||
cause === undefined
|
||||
? new ServerSelfUpdateError({ reason })
|
||||
: new ServerSelfUpdateError({ reason, cause });
|
||||
|
||||
/** Deferred so the RPC acknowledgement flushes before the process dies.
|
||||
Detached from the request scope: the triggering connection is exactly
|
||||
what the restart tears down. */
|
||||
const scheduleRestart = (restart: Effect.Effect<void>) =>
|
||||
Effect.sleep(RESTART_DELAY).pipe(
|
||||
Effect.andThen(restart),
|
||||
Effect.forkDetach({ startImmediately: true }),
|
||||
);
|
||||
const writeUnitAtomically = (filePath: string, contents: string) =>
|
||||
writeFileStringAtomically({ filePath, contents }).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fs),
|
||||
Effect.provideService(Path.Path, path),
|
||||
);
|
||||
|
||||
const update: ServerSelfUpdate["Service"]["update"] = Effect.fn(
|
||||
"cloud.server_self_update.update",
|
||||
)(function* (input) {
|
||||
if (capability === "desktop-managed") {
|
||||
return yield* failWith(
|
||||
"This server is managed by the T3 Code desktop app on its machine; update the desktop app to update it.",
|
||||
);
|
||||
}
|
||||
if (capability === null) {
|
||||
return yield* failWith(
|
||||
"This server cannot update itself; relaunch it manually with the new version.",
|
||||
);
|
||||
}
|
||||
const activeMethod = capability;
|
||||
const targetVersion = input.targetVersion.trim();
|
||||
if (!EXACT_VERSION_PATTERN.test(targetVersion)) {
|
||||
return yield* failWith(`'${targetVersion}' is not an exact t3 version.`);
|
||||
}
|
||||
|
||||
const alreadyRunning = yield* Ref.getAndSet(inFlight, true);
|
||||
if (alreadyRunning) {
|
||||
return yield* failWith("A server update is already in progress.");
|
||||
}
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const runtimePaths = yield* ensurePinnedRuntimeInstalled({
|
||||
baseDir: serverConfig.baseDir,
|
||||
version: targetVersion,
|
||||
fs,
|
||||
path,
|
||||
runner,
|
||||
}).pipe(
|
||||
Effect.mapError((error) => failWith("Could not install the requested t3 version.", error)),
|
||||
);
|
||||
|
||||
// A broken artifact (failed native build, incompatible node) must be
|
||||
// caught while the current server is still alive to report it.
|
||||
const preflight = yield* runner
|
||||
.run({
|
||||
command: host.execPath,
|
||||
args: [runtimePaths.entryPath, "--version"],
|
||||
timeout: PREFLIGHT_TIMEOUT,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
failWith(`Could not verify the installed t3@${targetVersion}.`, cause),
|
||||
),
|
||||
);
|
||||
// Effect CLI's unstable formatVersion currently emits `${name} v${version}`.
|
||||
// Extract the version token so surrounding presentation changes do not break updates.
|
||||
const reportedVersion = /\bv(\S+)\s*$/.exec(preflight.stdout)?.[1];
|
||||
if (preflight.code !== 0 || reportedVersion !== targetVersion) {
|
||||
// A completed npm install can still be unusable under this Node or on
|
||||
// this machine. Remove its sentinel and tree so a retry of the same
|
||||
// version performs a clean install instead of reusing a known-bad one.
|
||||
yield* removePinnedRuntimeInstallation({
|
||||
baseDir: serverConfig.baseDir,
|
||||
version: targetVersion,
|
||||
fs,
|
||||
path,
|
||||
}).pipe(
|
||||
Effect.mapError((error) =>
|
||||
failWith(`Could not remove the failed t3@${targetVersion} installation.`, error),
|
||||
),
|
||||
);
|
||||
return yield* failWith(
|
||||
preflight.code !== 0
|
||||
? `The installed t3@${targetVersion} failed its version check (exit code ${String(preflight.code)}).`
|
||||
: `The installed runtime did not report the requested t3@${targetVersion} version.`,
|
||||
);
|
||||
}
|
||||
|
||||
if (activeMethod === "boot-service") {
|
||||
const homeDir = env.HOME ?? "";
|
||||
const unitPath = path.join(homeDir, ".config", "systemd", "user", BOOT_SERVICE_UNIT_FILE);
|
||||
const previousUnit = yield* fs
|
||||
.readFileString(unitPath)
|
||||
.pipe(
|
||||
Effect.mapError((cause) => failWith("Could not read the current systemd unit.", cause)),
|
||||
);
|
||||
// Same shape bootService.install writes, so host lifecycle commands
|
||||
// still recognize the unit as current.
|
||||
const unit = renderBootServiceUnit({
|
||||
nodePath: host.execPath,
|
||||
t3EntryPath: runtimePaths.entryPath,
|
||||
baseDir: serverConfig.baseDir,
|
||||
logPath: path.join(serverConfig.logsDir, "boot-service.log"),
|
||||
unitPath,
|
||||
});
|
||||
yield* writeUnitAtomically(unitPath, unit).pipe(
|
||||
Effect.mapError((cause) => failWith("Could not update the systemd unit.", cause)),
|
||||
);
|
||||
|
||||
const reloadSystemd = Effect.fn("cloud.server_self_update.reload_systemd")(function* () {
|
||||
const reload = yield* runner
|
||||
.run({ command: "systemctl", args: ["--user", "daemon-reload"] })
|
||||
.pipe(Effect.mapError((cause) => failWith("Could not reload systemd units.", cause)));
|
||||
if (reload.code !== 0) {
|
||||
return yield* failWith(
|
||||
`Reloading systemd units failed (exit code ${String(reload.code)}).`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
yield* reloadSystemd().pipe(
|
||||
Effect.catch((reloadError) =>
|
||||
writeUnitAtomically(unitPath, previousUnit).pipe(
|
||||
Effect.mapError((rollbackCause) =>
|
||||
failWith("Could not restore the previous systemd unit.", {
|
||||
reloadError,
|
||||
rollbackCause,
|
||||
}),
|
||||
),
|
||||
// Systemd should still have the old unit in memory after the
|
||||
// failed reload, but retry after restoring in case it applied a
|
||||
// partial update before returning an error.
|
||||
Effect.andThen(reloadSystemd().pipe(Effect.ignore)),
|
||||
Effect.andThen(Effect.fail(reloadError)),
|
||||
),
|
||||
),
|
||||
);
|
||||
yield* Effect.logInfo("Server self-update installed; restarting boot service.", {
|
||||
targetVersion,
|
||||
});
|
||||
// A successful systemd restart stops this process, so the RPC is
|
||||
// interrupted and the reconnecting client observes the new version.
|
||||
// A rejected restart returns while the old process is still alive;
|
||||
// restore the previous unit and report that failure through the RPC.
|
||||
yield* Effect.gen(function* () {
|
||||
const restart = yield* runner
|
||||
.run({
|
||||
command: "systemctl",
|
||||
args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
failWith("Could not restart the systemd boot service.", cause),
|
||||
),
|
||||
);
|
||||
if (restart.code !== 0) {
|
||||
return yield* failWith(
|
||||
`Restarting the systemd boot service failed (exit code ${String(restart.code)}).`,
|
||||
);
|
||||
}
|
||||
}).pipe(
|
||||
Effect.catch((restartError) =>
|
||||
writeUnitAtomically(unitPath, previousUnit).pipe(
|
||||
Effect.andThen(reloadSystemd()),
|
||||
Effect.mapError((rollbackError) =>
|
||||
failWith("Could not restore the previous systemd unit.", {
|
||||
restartError,
|
||||
rollbackError,
|
||||
}),
|
||||
),
|
||||
Effect.andThen(Effect.fail(restartError)),
|
||||
),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
// Spawn the shim before acknowledging the RPC so ENOENT/EACCES and
|
||||
// other launch failures leave this server alive and return a useful
|
||||
// error. The shim itself waits until after the acknowledgement and
|
||||
// deferred exit before binding the replacement server.
|
||||
yield* host
|
||||
.spawnDetached("/bin/sh", [
|
||||
"-c",
|
||||
'sleep 3; exec "$@"',
|
||||
"t3-self-update",
|
||||
host.execPath,
|
||||
runtimePaths.entryPath,
|
||||
...host.cliArgs,
|
||||
])
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
failWith("Could not start the replacement t3 process.", cause),
|
||||
),
|
||||
);
|
||||
yield* Effect.logInfo("Server self-update installed; respawning.", { targetVersion });
|
||||
yield* scheduleRestart(
|
||||
Effect.try({
|
||||
try: () => host.exitProcess(),
|
||||
catch: (cause) => failWith("Could not exit the replaced t3 process.", cause),
|
||||
}).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logError("Server self-update could not exit the replaced process.").pipe(
|
||||
Effect.annotateLogs({ targetVersion, error: error.reason }),
|
||||
Effect.ensuring(Ref.set(inFlight, false)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return { targetVersion, method: activeMethod };
|
||||
}).pipe(Effect.onError(() => Ref.set(inFlight, false)));
|
||||
});
|
||||
|
||||
return ServerSelfUpdate.of({ update });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ServerSelfUpdate, make()).pipe(
|
||||
Layer.provide(ProcessRunner.layer),
|
||||
);
|
||||
@@ -9,7 +9,6 @@ import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import packageJson from "../../package.json" with { type: "json" };
|
||||
import { resolveServerSelfUpdateCapability } from "../cloud/selfUpdate.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
|
||||
@@ -125,9 +124,6 @@ export const make = Effect.gen(function* () {
|
||||
const environmentId = EnvironmentId.make(environmentIdRaw);
|
||||
const cwdBaseName = path.basename(serverConfig.cwd).trim();
|
||||
const label = yield* resolveServerEnvironmentLabel({ cwdBaseName });
|
||||
const serverSelfUpdate = yield* resolveServerSelfUpdateCapability({
|
||||
desktopManaged: serverConfig.mode === "desktop",
|
||||
});
|
||||
|
||||
const descriptor: ExecutionEnvironmentDescriptor = {
|
||||
environmentId,
|
||||
@@ -141,7 +137,6 @@ export const make = Effect.gen(function* () {
|
||||
repositoryIdentity: true,
|
||||
connectionProbe: true,
|
||||
threadSettlement: true,
|
||||
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -8,7 +8,6 @@ import { it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Scope from "effect/Scope";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
@@ -2414,123 +2413,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
12_000,
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"does not reuse a cross-repo PR when GitHub omits head identity metadata",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "statemachine"]);
|
||||
const forkDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]);
|
||||
yield* runGit(repoDir, [
|
||||
"config",
|
||||
"remote.fork-seed.url",
|
||||
"[email protected]:octocat/codething-mvp.git",
|
||||
]);
|
||||
|
||||
const { manager, ghCalls } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequenceByHeadSelector: {
|
||||
"octocat:statemachine": [
|
||||
`[{"number":41,"title":"Ambiguous fork PR","url":"https://github.com/pingdotgg/codething-mvp/pull/41","baseRefName":"main","headRefName":"statemachine","state":"OPEN"}]`,
|
||||
`[{"number":142,"title":"Add stacked git actions","url":"https://github.com/pingdotgg/codething-mvp/pull/142","baseRefName":"main","headRefName":"statemachine","state":"OPEN","isCrossRepository":true,"headRepository":{"nameWithOwner":"octocat/codething-mvp"},"headRepositoryOwner":{"login":"octocat"}}]`,
|
||||
],
|
||||
"fork-seed:statemachine": ["[]"],
|
||||
statemachine: ["[]"],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit_push_pr",
|
||||
});
|
||||
|
||||
expect(result.pr.status).toBe("created");
|
||||
expect(result.pr.number).toBe(142);
|
||||
expect(ghCalls.some((call) => call.startsWith("pr create "))).toBe(true);
|
||||
}),
|
||||
20_000,
|
||||
);
|
||||
|
||||
it.effect("rejects same-repo PR metadata when matching a cross-repo head context", () =>
|
||||
Effect.sync(() => {
|
||||
const headContext = {
|
||||
headBranch: "statemachine",
|
||||
headRepositoryNameWithOwner: "pingdotgg/codething-mvp",
|
||||
headRepositoryOwnerLogin: "pingdotgg",
|
||||
isCrossRepository: true,
|
||||
};
|
||||
|
||||
expect(
|
||||
GitManager.matchesBranchHeadContext(
|
||||
{
|
||||
number: 41,
|
||||
title: "Same-repo PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/41",
|
||||
baseRefName: "main",
|
||||
headRefName: "statemachine",
|
||||
state: "open",
|
||||
updatedAt: Option.none(),
|
||||
isCrossRepository: false,
|
||||
headRepositoryNameWithOwner: "pingdotgg/codething-mvp",
|
||||
headRepositoryOwnerLogin: "pingdotgg",
|
||||
},
|
||||
headContext,
|
||||
),
|
||||
).toBe(false);
|
||||
|
||||
expect(
|
||||
GitManager.matchesBranchHeadContext(
|
||||
{
|
||||
number: 142,
|
||||
title: "Fork PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/142",
|
||||
baseRefName: "main",
|
||||
headRefName: "statemachine",
|
||||
state: "open",
|
||||
updatedAt: Option.none(),
|
||||
isCrossRepository: true,
|
||||
headRepositoryNameWithOwner: "pingdotgg/codething-mvp",
|
||||
headRepositoryOwnerLogin: "pingdotgg",
|
||||
},
|
||||
headContext,
|
||||
),
|
||||
).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("accepts fork PR metadata when origin is the fork checkout remote", () =>
|
||||
Effect.sync(() => {
|
||||
const headContext = {
|
||||
headBranch: "t3code/git-audit-stability",
|
||||
headRepositoryNameWithOwner: "justsomelegs/t3code",
|
||||
headRepositoryOwnerLogin: "justsomelegs",
|
||||
isCrossRepository: false,
|
||||
};
|
||||
|
||||
expect(
|
||||
GitManager.matchesBranchHeadContext(
|
||||
{
|
||||
number: 2284,
|
||||
title: "Improve branch mismatch warnings",
|
||||
url: "https://github.com/pingdotgg/t3code/pull/2284",
|
||||
baseRefName: "main",
|
||||
headRefName: "t3code/git-audit-stability",
|
||||
state: "open",
|
||||
updatedAt: Option.none(),
|
||||
isCrossRepository: true,
|
||||
headRepositoryNameWithOwner: "justsomelegs/t3code",
|
||||
headRepositoryOwnerLogin: "justsomelegs",
|
||||
},
|
||||
headContext,
|
||||
),
|
||||
).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates PR when one does not already exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
|
||||
@@ -252,38 +252,7 @@ function resolvePullRequestHeadRepositoryNameWithOwner(
|
||||
return `${ownerLogin}/${repositoryName}`;
|
||||
}
|
||||
|
||||
interface PullRequestHeadIdentity {
|
||||
readonly repositoryNameWithOwner: string | null;
|
||||
readonly ownerLogin: string | null;
|
||||
}
|
||||
|
||||
function resolveExpectedHeadIdentity(
|
||||
headContext: Pick<BranchHeadContext, "headRepositoryNameWithOwner" | "headRepositoryOwnerLogin">,
|
||||
): PullRequestHeadIdentity {
|
||||
const repositoryNameWithOwner = normalizeOptionalRepositoryNameWithOwner(
|
||||
headContext.headRepositoryNameWithOwner,
|
||||
);
|
||||
return {
|
||||
repositoryNameWithOwner,
|
||||
ownerLogin:
|
||||
normalizeOptionalOwnerLogin(headContext.headRepositoryOwnerLogin) ??
|
||||
parseRepositoryOwnerLogin(repositoryNameWithOwner),
|
||||
};
|
||||
}
|
||||
|
||||
function resolvePullRequestHeadIdentity(pr: PullRequestInfo): PullRequestHeadIdentity {
|
||||
const repositoryNameWithOwner = normalizeOptionalRepositoryNameWithOwner(
|
||||
resolvePullRequestHeadRepositoryNameWithOwner(pr),
|
||||
);
|
||||
return {
|
||||
repositoryNameWithOwner,
|
||||
ownerLogin:
|
||||
normalizeOptionalOwnerLogin(pr.headRepositoryOwnerLogin) ??
|
||||
parseRepositoryOwnerLogin(repositoryNameWithOwner),
|
||||
};
|
||||
}
|
||||
|
||||
export function matchesBranchHeadContext(
|
||||
function matchesBranchHeadContext(
|
||||
pr: PullRequestInfo,
|
||||
headContext: Pick<
|
||||
BranchHeadContext,
|
||||
@@ -294,51 +263,44 @@ export function matchesBranchHeadContext(
|
||||
return false;
|
||||
}
|
||||
|
||||
const expectedHead = resolveExpectedHeadIdentity(headContext);
|
||||
const pullRequestHead = resolvePullRequestHeadIdentity(pr);
|
||||
|
||||
if (expectedHead.repositoryNameWithOwner) {
|
||||
if (pullRequestHead.repositoryNameWithOwner) {
|
||||
if (expectedHead.repositoryNameWithOwner !== pullRequestHead.repositoryNameWithOwner) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (expectedHead.ownerLogin && pullRequestHead.ownerLogin) {
|
||||
if (expectedHead.ownerLogin !== pullRequestHead.ownerLogin) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (expectedHead.ownerLogin && pullRequestHead.ownerLogin) {
|
||||
if (expectedHead.ownerLogin !== pullRequestHead.ownerLogin) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const expectedHeadRepository = normalizeOptionalRepositoryNameWithOwner(
|
||||
headContext.headRepositoryNameWithOwner,
|
||||
);
|
||||
const expectedHeadOwner =
|
||||
normalizeOptionalOwnerLogin(headContext.headRepositoryOwnerLogin) ??
|
||||
parseRepositoryOwnerLogin(expectedHeadRepository);
|
||||
const prHeadRepository = normalizeOptionalRepositoryNameWithOwner(
|
||||
resolvePullRequestHeadRepositoryNameWithOwner(pr),
|
||||
);
|
||||
const prHeadOwner =
|
||||
normalizeOptionalOwnerLogin(pr.headRepositoryOwnerLogin) ??
|
||||
parseRepositoryOwnerLogin(prHeadRepository);
|
||||
|
||||
if (headContext.isCrossRepository) {
|
||||
if (pr.isCrossRepository === false) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
(expectedHead.repositoryNameWithOwner || expectedHead.ownerLogin) &&
|
||||
!pullRequestHead.repositoryNameWithOwner &&
|
||||
!pullRequestHead.ownerLogin
|
||||
) {
|
||||
if ((expectedHeadRepository || expectedHeadOwner) && !prHeadRepository && !prHeadOwner) {
|
||||
return false;
|
||||
}
|
||||
if (expectedHeadRepository && prHeadRepository && expectedHeadRepository !== prHeadRepository) {
|
||||
return false;
|
||||
}
|
||||
if (expectedHeadOwner && prHeadOwner && expectedHeadOwner !== prHeadOwner) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (pr.isCrossRepository === true) {
|
||||
if (
|
||||
(!expectedHead.repositoryNameWithOwner && !expectedHead.ownerLogin) ||
|
||||
(!pullRequestHead.repositoryNameWithOwner && !pullRequestHead.ownerLogin)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (expectedHeadRepository && prHeadRepository && expectedHeadRepository !== prHeadRepository) {
|
||||
return false;
|
||||
}
|
||||
if (expectedHeadOwner && prHeadOwner && expectedHeadOwner !== prHeadOwner) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ import type {
|
||||
PreviewAutomationRecordingArtifact,
|
||||
PreviewAutomationRecordingStatus,
|
||||
PreviewAutomationResizeResult,
|
||||
PreviewAutomationSetColorSchemeResult,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
PreviewTabId,
|
||||
@@ -59,8 +58,6 @@ const handlers = {
|
||||
invokeTargeted<PreviewAutomationStatus>("navigate", input, input.timeoutMs),
|
||||
preview_resize: (input) =>
|
||||
invokeTargeted<PreviewAutomationResizeResult>("resize", input, input.timeoutMs),
|
||||
preview_set_appearance: (input) =>
|
||||
invokeTargeted<PreviewAutomationSetColorSchemeResult>("setColorScheme", input),
|
||||
preview_snapshot: (input) => invokeTargeted<PreviewAutomationSnapshot>("snapshot", input ?? {}),
|
||||
preview_click: (input) =>
|
||||
invokeTargeted<void>("click", input, input.timeoutMs).pipe(Effect.as(null)),
|
||||
|
||||
@@ -10,8 +10,6 @@ import {
|
||||
PreviewAutomationResizeInput,
|
||||
PreviewAutomationResizeResult,
|
||||
PreviewAutomationScrollInput,
|
||||
PreviewAutomationSetColorSchemeInput,
|
||||
PreviewAutomationSetColorSchemeResult,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
PreviewAutomationTabTargetInput,
|
||||
@@ -88,19 +86,6 @@ export const PreviewResizeTool = safeBrowserTool(
|
||||
.annotate(Tool.Idempotent, true),
|
||||
);
|
||||
|
||||
export const PreviewSetAppearanceTool = safeBrowserTool(
|
||||
Tool.make("preview_set_appearance", {
|
||||
description:
|
||||
"Emulate prefers-color-scheme in a collaborative browser tab, optionally selected by tabId. Use {colorScheme:'dark'} or {colorScheme:'light'} to preview the page in that appearance, and {colorScheme:'system'} to clear the override and follow the OS appearance.",
|
||||
parameters: PreviewAutomationSetColorSchemeInput,
|
||||
success: PreviewAutomationSetColorSchemeResult,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
})
|
||||
.annotate(Tool.Title, "Set preview appearance")
|
||||
.annotate(Tool.Idempotent, true),
|
||||
);
|
||||
|
||||
export const PreviewSnapshotTool = readonlyBrowserTool(
|
||||
Tool.make("preview_snapshot", {
|
||||
description:
|
||||
@@ -204,7 +189,6 @@ export const PreviewToolkit = Toolkit.make(
|
||||
PreviewOpenTool,
|
||||
PreviewNavigateTool,
|
||||
PreviewResizeTool,
|
||||
PreviewSetAppearanceTool,
|
||||
PreviewSnapshotTool,
|
||||
PreviewClickTool,
|
||||
PreviewTypeTool,
|
||||
@@ -221,7 +205,6 @@ export const PreviewStandardToolkit = Toolkit.make(
|
||||
PreviewOpenTool,
|
||||
PreviewNavigateTool,
|
||||
PreviewResizeTool,
|
||||
PreviewSetAppearanceTool,
|
||||
PreviewClickTool,
|
||||
PreviewTypeTool,
|
||||
PreviewPressTool,
|
||||
|
||||
@@ -8,15 +8,9 @@ import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
|
||||
import * as ProjectFaviconResolver from "./ProjectFaviconResolver.ts";
|
||||
import * as T3ProjectFileLoader from "./T3ProjectFileLoader.ts";
|
||||
|
||||
const TestLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(
|
||||
ProjectFaviconResolver.layer.pipe(
|
||||
Layer.provide(WorkspacePaths.layer),
|
||||
Layer.provide(T3ProjectFileLoader.layer),
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(ProjectFaviconResolver.layer.pipe(Layer.provide(WorkspacePaths.layer))),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
@@ -43,7 +37,7 @@ const writeTextFile = Effect.fn("writeTextFile")(function* (
|
||||
|
||||
const makeResolverWithFileSystem = (fileSystem: FileSystem.FileSystem) =>
|
||||
ProjectFaviconResolver.make.pipe(
|
||||
Effect.provide([WorkspacePaths.layer, T3ProjectFileLoader.layer]),
|
||||
Effect.provide(WorkspacePaths.layer),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
);
|
||||
|
||||
@@ -62,63 +56,6 @@ it.layer(TestLayer)("ProjectFaviconResolverLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prefers a t3.json iconPath over well-known files", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
|
||||
const cwd = yield* makeTempDir;
|
||||
yield* writeTextFile(cwd, "t3.json", '{ "iconPath": "brand/mark.svg" }');
|
||||
yield* writeTextFile(cwd, "brand/mark.svg", "<svg>mark</svg>");
|
||||
yield* writeTextFile(cwd, "favicon.svg", "<svg>favicon</svg>");
|
||||
|
||||
const resolved = yield* resolver.resolvePath(cwd);
|
||||
|
||||
expect(resolved).not.toBeNull();
|
||||
expect(resolved).toContain("brand/mark.svg");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to well-known files when the t3.json iconPath does not exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
|
||||
const cwd = yield* makeTempDir;
|
||||
yield* writeTextFile(cwd, "t3.json", '{ "iconPath": "brand/missing.svg" }');
|
||||
yield* writeTextFile(cwd, "favicon.svg", "<svg>favicon</svg>");
|
||||
|
||||
const resolved = yield* resolver.resolvePath(cwd);
|
||||
|
||||
expect(resolved).not.toBeNull();
|
||||
expect(resolved).toContain("favicon.svg");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("ignores invalid t3.json files", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
|
||||
const cwd = yield* makeTempDir;
|
||||
yield* writeTextFile(cwd, "t3.json", "{ not json");
|
||||
yield* writeTextFile(cwd, "favicon.svg", "<svg>favicon</svg>");
|
||||
|
||||
const resolved = yield* resolver.resolvePath(cwd);
|
||||
|
||||
expect(resolved).not.toBeNull();
|
||||
expect(resolved).toContain("favicon.svg");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not resolve a t3.json iconPath outside the workspace root", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
|
||||
const parent = yield* makeTempDir;
|
||||
const cwd = `${parent}/app`;
|
||||
yield* writeTextFile(parent, "secret.svg", "<svg>secret</svg>");
|
||||
yield* writeTextFile(cwd, "t3.json", '{ "iconPath": "../secret.svg" }');
|
||||
|
||||
const resolved = yield* resolver.resolvePath(cwd);
|
||||
|
||||
expect(resolved).toBeNull();
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resolves icon hrefs from project source files", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
|
||||
|
||||
@@ -16,7 +16,6 @@ import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
|
||||
import * as T3ProjectFileLoader from "./T3ProjectFileLoader.ts";
|
||||
|
||||
// Well-known favicon paths checked in order.
|
||||
const FAVICON_CANDIDATES = [
|
||||
@@ -118,7 +117,6 @@ export const make = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
|
||||
const projectFileLoader = yield* T3ProjectFileLoader.T3ProjectFileLoader;
|
||||
|
||||
const resolveIconHref = (href: string): ReadonlyArray<string> => {
|
||||
const clean = href.replace(/^\//, "");
|
||||
@@ -179,15 +177,6 @@ export const make = Effect.gen(function* () {
|
||||
}),
|
||||
),
|
||||
);
|
||||
// A t3.json iconPath takes precedence over the well-known locations.
|
||||
const projectFile = yield* projectFileLoader.load(projectCwd);
|
||||
if (Option.isSome(projectFile) && projectFile.value.iconPath !== undefined) {
|
||||
const existing = yield* findExistingFile(projectCwd, [projectFile.value.iconPath]);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
|
||||
for (const candidate of FAVICON_CANDIDATES) {
|
||||
const existing = yield* findExistingFile(projectCwd, [candidate]);
|
||||
if (existing) {
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it, describe, expect } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
|
||||
import * as T3ProjectFileLoader from "./T3ProjectFileLoader.ts";
|
||||
|
||||
const TestLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(T3ProjectFileLoader.layer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const makeTempDir = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
return yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3code-project-file-",
|
||||
});
|
||||
});
|
||||
|
||||
const writeProjectFile = Effect.fn("writeProjectFile")(function* (cwd: string, contents: string) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
yield* fileSystem.writeFileString(path.join(cwd, "t3.json"), contents).pipe(Effect.orDie);
|
||||
});
|
||||
|
||||
it.layer(TestLayer)("T3ProjectFileLoader", (it) => {
|
||||
describe("load", () => {
|
||||
it.effect("loads and decodes a valid t3.json", () =>
|
||||
Effect.gen(function* () {
|
||||
const loader = yield* T3ProjectFileLoader.T3ProjectFileLoader;
|
||||
const cwd = yield* makeTempDir;
|
||||
yield* writeProjectFile(
|
||||
cwd,
|
||||
`{
|
||||
// JSONC is tolerated
|
||||
"iconPath": "assets/logo.svg",
|
||||
"scripts": [{ "name": "Dev", "command": "pnpm dev" }],
|
||||
}`,
|
||||
);
|
||||
|
||||
const loaded = yield* loader.load(cwd);
|
||||
|
||||
expect(Option.isSome(loaded)).toBe(true);
|
||||
if (Option.isSome(loaded)) {
|
||||
expect(loaded.value.iconPath).toBe("assets/logo.svg");
|
||||
expect(loaded.value.scripts).toEqual([{ name: "Dev", command: "pnpm dev" }]);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns none when t3.json is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const loader = yield* T3ProjectFileLoader.T3ProjectFileLoader;
|
||||
const cwd = yield* makeTempDir;
|
||||
|
||||
const loaded = yield* loader.load(cwd);
|
||||
|
||||
expect(Option.isNone(loaded)).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns none for malformed JSON without failing", () =>
|
||||
Effect.gen(function* () {
|
||||
const loader = yield* T3ProjectFileLoader.T3ProjectFileLoader;
|
||||
const cwd = yield* makeTempDir;
|
||||
yield* writeProjectFile(cwd, "{ not json");
|
||||
|
||||
const loaded = yield* loader.load(cwd);
|
||||
|
||||
expect(Option.isNone(loaded)).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns none for schema-invalid files without failing", () =>
|
||||
Effect.gen(function* () {
|
||||
const loader = yield* T3ProjectFileLoader.T3ProjectFileLoader;
|
||||
const cwd = yield* makeTempDir;
|
||||
yield* writeProjectFile(cwd, '{ "scripts": [{ "name": "Dev" }] }');
|
||||
|
||||
const loaded = yield* loader.load(cwd);
|
||||
|
||||
expect(Option.isNone(loaded)).toBe(true);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,108 +0,0 @@
|
||||
/**
|
||||
* T3ProjectFileLoader - Effect service that loads the checked-in `t3.json`
|
||||
* project file from a workspace root.
|
||||
*
|
||||
* Loading is best-effort: a missing file resolves to `Option.none`, and
|
||||
* unreadable or invalid files are logged and treated as absent so callers
|
||||
* can fall back to their defaults.
|
||||
*
|
||||
* @module T3ProjectFileLoader
|
||||
*/
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { T3_PROJECT_FILE_NAME, type T3ProjectFile } from "@t3tools/contracts";
|
||||
import { T3ProjectFileFromJson } from "@t3tools/shared/t3ProjectFile";
|
||||
|
||||
const decodeT3ProjectFileJson = Schema.decodeEffect(T3ProjectFileFromJson);
|
||||
|
||||
export class T3ProjectFileLoadError extends Schema.TaggedErrorClass<T3ProjectFileLoadError>()(
|
||||
"T3ProjectFileLoadError",
|
||||
{
|
||||
operation: Schema.Literals(["read", "decode"]),
|
||||
workspaceRoot: Schema.String,
|
||||
filePath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to ${this.operation} ${T3_PROJECT_FILE_NAME} at ${this.filePath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
/** Service tag for t3.json project file loading. */
|
||||
export class T3ProjectFileLoader extends Context.Service<
|
||||
T3ProjectFileLoader,
|
||||
{
|
||||
/**
|
||||
* Load and decode `t3.json` at the workspace root.
|
||||
*
|
||||
* Never fails: missing, unreadable, or invalid files resolve to
|
||||
* `Option.none` (invalid files are logged as warnings).
|
||||
*/
|
||||
readonly load: (workspaceRoot: string) => Effect.Effect<Option.Option<T3ProjectFile>>;
|
||||
}
|
||||
>()("t3/project/T3ProjectFileLoader") {}
|
||||
|
||||
const logT3ProjectFileLoadError = (error: T3ProjectFileLoadError) =>
|
||||
Effect.logWarning(error).pipe(
|
||||
Effect.annotateLogs({
|
||||
operation: error.operation,
|
||||
workspaceRoot: error.workspaceRoot,
|
||||
filePath: error.filePath,
|
||||
errorTag: error._tag,
|
||||
}),
|
||||
);
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const load: T3ProjectFileLoader["Service"]["load"] = Effect.fn("T3ProjectFileLoader.load")(
|
||||
function* (workspaceRoot) {
|
||||
const filePath = path.join(workspaceRoot, T3_PROJECT_FILE_NAME);
|
||||
const raw = yield* fileSystem.readFileString(filePath).pipe(
|
||||
Effect.map(Option.some),
|
||||
Effect.catchTags({
|
||||
PlatformError: (error) =>
|
||||
error.reason._tag === "NotFound"
|
||||
? Effect.succeed(Option.none<string>())
|
||||
: logT3ProjectFileLoadError(
|
||||
new T3ProjectFileLoadError({
|
||||
operation: "read",
|
||||
workspaceRoot,
|
||||
filePath,
|
||||
cause: error,
|
||||
}),
|
||||
).pipe(Effect.as(Option.none<string>())),
|
||||
}),
|
||||
);
|
||||
if (Option.isNone(raw)) {
|
||||
return Option.none<T3ProjectFile>();
|
||||
}
|
||||
return yield* decodeT3ProjectFileJson(raw.value).pipe(
|
||||
Effect.map(Option.some),
|
||||
Effect.catchTags({
|
||||
SchemaError: (error) =>
|
||||
logT3ProjectFileLoadError(
|
||||
new T3ProjectFileLoadError({
|
||||
operation: "decode",
|
||||
workspaceRoot,
|
||||
filePath,
|
||||
cause: error,
|
||||
}),
|
||||
).pipe(Effect.as(Option.none<T3ProjectFile>())),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
return T3ProjectFileLoader.of({ load });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(T3ProjectFileLoader, make);
|
||||
@@ -118,7 +118,6 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const { cwd } = yield* ServerConfig;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
@@ -166,11 +165,9 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
effectiveConfig,
|
||||
() => Cache.get(capabilitiesProbeCache, capabilitiesCacheKey),
|
||||
processEnv,
|
||||
cwd,
|
||||
).pipe(
|
||||
Effect.map(stampIdentity),
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,205 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
|
||||
import { discoverClaudeSkills } from "./ClaudeSkills.ts";
|
||||
|
||||
const writeSkill = Effect.fn(function* (
|
||||
skillsDir: string,
|
||||
directoryName: string,
|
||||
contents: string,
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const skillDir = path.join(skillsDir, directoryName);
|
||||
yield* fs.makeDirectory(skillDir, { recursive: true });
|
||||
yield* fs.writeFileString(path.join(skillDir, "SKILL.md"), contents);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("discoverClaudeSkills", (it) => {
|
||||
it.effect("discovers user and project skills with frontmatter metadata", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
|
||||
const configDir = path.join(tempDir, "claude-home");
|
||||
const workspace = path.join(tempDir, "workspace");
|
||||
|
||||
yield* writeSkill(
|
||||
path.join(configDir, "skills"),
|
||||
"codex-review",
|
||||
[
|
||||
"---",
|
||||
"name: codex-review",
|
||||
"description: Ask Codex for a review.",
|
||||
"---",
|
||||
"",
|
||||
"# Body",
|
||||
].join("\n"),
|
||||
);
|
||||
yield* writeSkill(
|
||||
path.join(workspace, ".claude", "skills"),
|
||||
"deploy",
|
||||
["---", "name: deploy", "description: Deploy the app.", "---", "", "# Deploy"].join("\n"),
|
||||
);
|
||||
|
||||
const skills = yield* discoverClaudeSkills({ homePath: configDir }, workspace);
|
||||
|
||||
assert.deepEqual(skills, [
|
||||
{
|
||||
name: "codex-review",
|
||||
path: path.join(configDir, "skills", "codex-review", "SKILL.md"),
|
||||
enabled: true,
|
||||
scope: "user",
|
||||
description: "Ask Codex for a review.",
|
||||
},
|
||||
{
|
||||
name: "deploy",
|
||||
path: path.join(workspace, ".claude", "skills", "deploy", "SKILL.md"),
|
||||
enabled: true,
|
||||
scope: "project",
|
||||
description: "Deploy the app.",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prefers project skills over user skills on name collisions", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
|
||||
const configDir = path.join(tempDir, "claude-home");
|
||||
const workspace = path.join(tempDir, "workspace");
|
||||
|
||||
yield* writeSkill(
|
||||
path.join(configDir, "skills"),
|
||||
"deploy",
|
||||
["---", "name: deploy", "description: User deploy.", "---"].join("\n"),
|
||||
);
|
||||
yield* writeSkill(
|
||||
path.join(workspace, ".claude", "skills"),
|
||||
"deploy",
|
||||
["---", "name: deploy", "description: Project deploy.", "---"].join("\n"),
|
||||
);
|
||||
|
||||
const skills = yield* discoverClaudeSkills({ homePath: configDir }, workspace);
|
||||
|
||||
assert.equal(skills.length, 1);
|
||||
assert.equal(skills[0]?.scope, "project");
|
||||
assert.equal(skills[0]?.description, "Project deploy.");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to the directory name and skips malformed frontmatter", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
|
||||
const configDir = path.join(tempDir, "claude-home");
|
||||
const skillsDir = path.join(configDir, "skills");
|
||||
|
||||
yield* writeSkill(skillsDir, "no-frontmatter", "# Just a heading\n");
|
||||
yield* writeSkill(skillsDir, "broken-yaml", "---\nname: [unclosed\n---\n");
|
||||
// A stray file (not a directory with SKILL.md) must be skipped.
|
||||
yield* fs.makeDirectory(skillsDir, { recursive: true });
|
||||
yield* fs.writeFileString(path.join(skillsDir, "README.md"), "not a skill");
|
||||
|
||||
const skills = yield* discoverClaudeSkills({ homePath: configDir }, undefined);
|
||||
|
||||
// A skill with no frontmatter falls back to its directory name; a skill
|
||||
// whose frontmatter fails to parse is skipped entirely (Claude Code
|
||||
// won't load it either).
|
||||
assert.deepEqual(
|
||||
skills.map((skill) => skill.name),
|
||||
["no-frontmatter"],
|
||||
);
|
||||
assert.equal(skills[0]?.description, undefined);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("honors CLAUDE_CONFIG_DIR from the environment when homePath is unset", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
|
||||
const environmentConfigDir = path.join(tempDir, "env-config");
|
||||
|
||||
yield* writeSkill(
|
||||
path.join(environmentConfigDir, "skills"),
|
||||
"env-skill",
|
||||
["---", "name: env-skill", "description: From env config dir.", "---"].join("\n"),
|
||||
);
|
||||
|
||||
const skills = yield* discoverClaudeSkills({ homePath: "" }, undefined, {
|
||||
CLAUDE_CONFIG_DIR: environmentConfigDir,
|
||||
});
|
||||
|
||||
assert.deepEqual(
|
||||
skills.map((skill) => skill.name),
|
||||
["env-skill"],
|
||||
);
|
||||
|
||||
// An explicit homePath wins over the environment variable, matching
|
||||
// makeClaudeEnvironment which overwrites CLAUDE_CONFIG_DIR for the CLI.
|
||||
const explicitHome = path.join(tempDir, "explicit-home");
|
||||
yield* writeSkill(
|
||||
path.join(explicitHome, "skills"),
|
||||
"explicit-skill",
|
||||
["---", "name: explicit-skill", "---"].join("\n"),
|
||||
);
|
||||
const explicitSkills = yield* discoverClaudeSkills({ homePath: explicitHome }, undefined, {
|
||||
CLAUDE_CONFIG_DIR: environmentConfigDir,
|
||||
});
|
||||
assert.deepEqual(
|
||||
explicitSkills.map((skill) => skill.name),
|
||||
["explicit-skill"],
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resolves a relative CLAUDE_CONFIG_DIR against the workspace cwd", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
|
||||
const workspace = path.join(tempDir, "workspace");
|
||||
yield* fs.makeDirectory(workspace, { recursive: true });
|
||||
|
||||
// The spawned CLI resolves a relative CLAUDE_CONFIG_DIR against its own
|
||||
// cwd (the workspace), so discovery must do the same.
|
||||
yield* writeSkill(
|
||||
path.join(workspace, "relative-config", "skills"),
|
||||
"relative-skill",
|
||||
["---", "name: relative-skill", "---"].join("\n"),
|
||||
);
|
||||
|
||||
const skills = yield* discoverClaudeSkills({ homePath: "" }, workspace, {
|
||||
CLAUDE_CONFIG_DIR: "relative-config",
|
||||
});
|
||||
|
||||
assert.deepEqual(
|
||||
skills.map((skill) => skill.name),
|
||||
["relative-skill"],
|
||||
);
|
||||
assert.equal(skills[0]?.scope, "user");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns an empty list when no skill roots exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
|
||||
|
||||
const skills = yield* discoverClaudeSkills(
|
||||
{ homePath: path.join(tempDir, "missing-home") },
|
||||
path.join(tempDir, "missing-workspace"),
|
||||
);
|
||||
|
||||
assert.deepEqual(skills, []);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,148 +0,0 @@
|
||||
/**
|
||||
* ClaudeSkills — filesystem discovery of Claude Code skills for the `$` picker.
|
||||
*
|
||||
* Claude Code loads skills from `<config dir>/skills` (user scope) and
|
||||
* `<cwd>/.claude/skills` (project scope), one directory per skill with a
|
||||
* `SKILL.md` carrying YAML frontmatter. The Agent SDK init handshake surfaces
|
||||
* skills only as slash commands without their filesystem paths, so the
|
||||
* provider snapshot scans the same locations directly, mirroring how the
|
||||
* Codex app-server reports its skills.
|
||||
*
|
||||
* @module provider/Drivers/ClaudeSkills
|
||||
*/
|
||||
import * as NodeOS from "node:os";
|
||||
|
||||
import type { ClaudeSettings, ServerProviderSkill } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import { parse as parseYamlDocument } from "yaml";
|
||||
|
||||
import { expandHomePath } from "../../pathExpansion.ts";
|
||||
|
||||
type ClaudeSkillScope = "user" | "project";
|
||||
|
||||
const FRONTMATTER_PATTERN = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;
|
||||
|
||||
type SkillFrontmatter =
|
||||
| { readonly kind: "missing" }
|
||||
| { readonly kind: "malformed" }
|
||||
| { readonly kind: "parsed"; readonly name?: string; readonly description?: string };
|
||||
|
||||
function parseSkillFrontmatter(contents: string): SkillFrontmatter {
|
||||
const match = FRONTMATTER_PATTERN.exec(contents);
|
||||
if (!match) {
|
||||
return { kind: "missing" };
|
||||
}
|
||||
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = parseYamlDocument(match[1] ?? "");
|
||||
} catch {
|
||||
return { kind: "malformed" };
|
||||
}
|
||||
if (typeof parsed !== "object" || parsed === null) {
|
||||
return { kind: "malformed" };
|
||||
}
|
||||
|
||||
const record = parsed as Record<string, unknown>;
|
||||
const name = typeof record.name === "string" ? record.name.trim() : "";
|
||||
const description = typeof record.description === "string" ? record.description.trim() : "";
|
||||
return {
|
||||
kind: "parsed",
|
||||
...(name ? { name } : {}),
|
||||
...(description ? { description } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the Claude config directory the CLI would use, matching the
|
||||
* precedence the spawned CLI sees: the instance's `homePath` (exported as
|
||||
* `CLAUDE_CONFIG_DIR` by `makeClaudeEnvironment`), then a `CLAUDE_CONFIG_DIR`
|
||||
* already present in the process environment, then `~/.claude`.
|
||||
*/
|
||||
const resolveClaudeConfigDirPath = Effect.fn("resolveClaudeConfigDirPath")(function* (
|
||||
config: Pick<ClaudeSettings, "homePath">,
|
||||
environment: NodeJS.ProcessEnv,
|
||||
cwd?: string,
|
||||
): Effect.fn.Return<string, never, Path.Path> {
|
||||
const path = yield* Path.Path;
|
||||
const homePath = config.homePath.trim();
|
||||
if (homePath.length > 0) {
|
||||
return path.resolve(expandHomePath(homePath));
|
||||
}
|
||||
// No tilde expansion here: the spawned CLI receives this env var verbatim
|
||||
// (env vars are never shell-expanded), so a literal `~` must stay literal
|
||||
// for discovery to scan the same directory the runtime would. A relative
|
||||
// value is resolved against the workspace cwd — the subprocess's own cwd —
|
||||
// for the same reason.
|
||||
const environmentConfigDir = environment.CLAUDE_CONFIG_DIR?.trim() ?? "";
|
||||
if (environmentConfigDir.length > 0) {
|
||||
return cwd ? path.resolve(cwd, environmentConfigDir) : path.resolve(environmentConfigDir);
|
||||
}
|
||||
return path.join(NodeOS.homedir(), ".claude");
|
||||
});
|
||||
|
||||
/**
|
||||
* Enumerate Claude Code skills from the user config dir and the workspace.
|
||||
* Discovery is best-effort: unreadable roots and malformed skill entries are
|
||||
* skipped so a broken skill never degrades the provider snapshot. On name
|
||||
* collisions the project-scoped skill wins, matching Claude Code's
|
||||
* most-specific-wins resolution.
|
||||
*/
|
||||
export const discoverClaudeSkills = Effect.fn("discoverClaudeSkills")(function* (
|
||||
config: Pick<ClaudeSettings, "homePath">,
|
||||
cwd?: string,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
): Effect.fn.Return<ReadonlyArray<ServerProviderSkill>, never, FileSystem.FileSystem | Path.Path> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const configDirPath = yield* resolveClaudeConfigDirPath(config, environment ?? process.env, cwd);
|
||||
|
||||
const roots: ReadonlyArray<{ directory: string; scope: ClaudeSkillScope }> = [
|
||||
{ directory: path.join(configDirPath, "skills"), scope: "user" },
|
||||
...(cwd ? [{ directory: path.join(cwd, ".claude", "skills"), scope: "project" as const }] : []),
|
||||
];
|
||||
|
||||
const skillsByName = new Map<string, ServerProviderSkill>();
|
||||
for (const root of roots) {
|
||||
const entries = yield* fileSystem
|
||||
.readDirectory(root.directory)
|
||||
.pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
|
||||
|
||||
for (const entry of [...entries].sort()) {
|
||||
const skillPath = path.join(root.directory, entry, "SKILL.md");
|
||||
const contents = yield* fileSystem
|
||||
.readFileString(skillPath)
|
||||
.pipe(Effect.orElseSucceed(() => undefined));
|
||||
if (contents === undefined) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const frontmatter = parseSkillFrontmatter(contents);
|
||||
// Malformed frontmatter means the skill won't load in Claude Code
|
||||
// either — skip it rather than surfacing a broken entry under its
|
||||
// directory name.
|
||||
if (frontmatter.kind === "malformed") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const name = (frontmatter.kind === "parsed" ? frontmatter.name : undefined) ?? entry.trim();
|
||||
if (!name) {
|
||||
continue;
|
||||
}
|
||||
|
||||
skillsByName.set(name, {
|
||||
name,
|
||||
path: skillPath,
|
||||
enabled: true,
|
||||
scope: root.scope,
|
||||
...(frontmatter.kind === "parsed" && frontmatter.description
|
||||
? { description: frontmatter.description }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name));
|
||||
});
|
||||
@@ -356,25 +356,6 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("derives auto permission mode from auto runtime policy without skip flag", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
runtimeMode: "auto",
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.permissionMode, "auto");
|
||||
assert.equal(createInput?.options.allowDangerouslySkipPermissions, undefined);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("loads Claude filesystem settings sources for SDK sessions", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
|
||||
@@ -3509,7 +3509,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
const effectiveEffort = getEffectiveClaudeAgentEffort(effort, modelSelection?.model);
|
||||
const runtimeModeToPermission: Record<string, PermissionMode> = {
|
||||
"auto-accept-edits": "acceptEdits",
|
||||
auto: "auto",
|
||||
"full-access": "bypassPermissions",
|
||||
};
|
||||
const permissionMode = runtimeModeToPermission[input.runtimeMode];
|
||||
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Result from "effect/Result";
|
||||
@@ -41,7 +40,6 @@ import {
|
||||
} from "../providerSnapshot.ts";
|
||||
import { resolveClaudeSdkExecutablePath } from "../Drivers/ClaudeExecutable.ts";
|
||||
import { makeClaudeEnvironment } from "../Drivers/ClaudeHome.ts";
|
||||
import { discoverClaudeSkills } from "../Drivers/ClaudeSkills.ts";
|
||||
|
||||
const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({
|
||||
optionDescriptors: [],
|
||||
@@ -734,11 +732,10 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
claudeSettings: ClaudeSettings,
|
||||
) => Effect.Effect<ClaudeCapabilitiesProbe | undefined>,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
cwd?: string,
|
||||
): Effect.fn.Return<
|
||||
ServerProviderDraft,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
|
||||
ChildProcessSpawner.ChildProcessSpawner | Path.Path
|
||||
> {
|
||||
const resolvedEnvironment = environment ?? process.env;
|
||||
const checkedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
@@ -848,7 +845,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
const capabilities = resolveCapabilities
|
||||
? yield* resolveCapabilities(claudeSettings).pipe(Effect.orElseSucceed(() => undefined))
|
||||
: undefined;
|
||||
const skills = yield* discoverClaudeSkills(claudeSettings, cwd, resolvedEnvironment);
|
||||
const slashCommands = capabilities?.slashCommands ?? [];
|
||||
const dedupedSlashCommands = dedupeSlashCommands(slashCommands);
|
||||
|
||||
@@ -859,7 +855,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
checkedAt,
|
||||
models,
|
||||
slashCommands: dedupedSlashCommands,
|
||||
skills,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
@@ -881,7 +876,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
checkedAt,
|
||||
models,
|
||||
slashCommands: dedupedSlashCommands,
|
||||
skills,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
|
||||
@@ -104,7 +104,6 @@ describe("buildTurnStartParams", () => {
|
||||
NodeAssert.deepStrictEqual(params, {
|
||||
threadId: "provider-thread-1",
|
||||
approvalPolicy: "never",
|
||||
approvalsReviewer: "user",
|
||||
sandboxPolicy: {
|
||||
type: "dangerFullAccess",
|
||||
},
|
||||
@@ -150,7 +149,6 @@ describe("buildTurnStartParams", () => {
|
||||
NodeAssert.deepStrictEqual(params, {
|
||||
threadId: "provider-thread-1",
|
||||
approvalPolicy: "on-request",
|
||||
approvalsReviewer: "user",
|
||||
sandboxPolicy: {
|
||||
type: "workspaceWrite",
|
||||
},
|
||||
@@ -195,31 +193,6 @@ describe("buildTurnStartParams", () => {
|
||||
NodeAssert.ok(settings?.developer_instructions?.includes(`as ${DEFAULT_MODEL} with medium`));
|
||||
});
|
||||
|
||||
it.effect("routes approvals to the auto reviewer in auto mode", () =>
|
||||
Effect.gen(function* () {
|
||||
const params = yield* buildTurnStartParams({
|
||||
threadId: "provider-thread-1",
|
||||
runtimeMode: "auto",
|
||||
prompt: "Ship it",
|
||||
});
|
||||
|
||||
NodeAssert.deepStrictEqual(params, {
|
||||
threadId: "provider-thread-1",
|
||||
approvalPolicy: "on-request",
|
||||
approvalsReviewer: "auto_review",
|
||||
sandboxPolicy: {
|
||||
type: "workspaceWrite",
|
||||
},
|
||||
input: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Ship it",
|
||||
},
|
||||
],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it("omits collaboration mode when interaction mode is absent", () => {
|
||||
const params = Effect.runSync(
|
||||
buildTurnStartParams({
|
||||
@@ -232,7 +205,6 @@ describe("buildTurnStartParams", () => {
|
||||
NodeAssert.deepStrictEqual(params, {
|
||||
threadId: "provider-thread-1",
|
||||
approvalPolicy: "untrusted",
|
||||
approvalsReviewer: "user",
|
||||
sandboxPolicy: {
|
||||
type: "readOnly",
|
||||
},
|
||||
|
||||
@@ -264,35 +264,23 @@ function readResumeCursorThreadId(
|
||||
function runtimeModeToThreadConfig(input: RuntimeMode): {
|
||||
readonly approvalPolicy: EffectCodexSchema.V2ThreadStartParams__AskForApproval;
|
||||
readonly sandbox: EffectCodexSchema.V2ThreadStartParams__SandboxMode;
|
||||
// Always explicit: omitting the field on resume keeps the thread's previous
|
||||
// reviewer, which would leave auto_review sticky after switching modes.
|
||||
readonly approvalsReviewer: EffectCodexSchema.V2ThreadStartParams__ApprovalsReviewer;
|
||||
} {
|
||||
switch (input) {
|
||||
case "approval-required":
|
||||
return {
|
||||
approvalPolicy: "untrusted",
|
||||
sandbox: "read-only",
|
||||
approvalsReviewer: "user",
|
||||
};
|
||||
case "auto-accept-edits":
|
||||
return {
|
||||
approvalPolicy: "on-request",
|
||||
sandbox: "workspace-write",
|
||||
approvalsReviewer: "user",
|
||||
};
|
||||
case "auto":
|
||||
return {
|
||||
approvalPolicy: "on-request",
|
||||
sandbox: "workspace-write",
|
||||
approvalsReviewer: "auto_review",
|
||||
};
|
||||
case "full-access":
|
||||
default:
|
||||
return {
|
||||
approvalPolicy: "never",
|
||||
sandbox: "danger-full-access",
|
||||
approvalsReviewer: "user",
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -308,7 +296,6 @@ function buildThreadStartParams(input: {
|
||||
cwd: input.cwd,
|
||||
approvalPolicy: config.approvalPolicy,
|
||||
sandbox: config.sandbox,
|
||||
approvalsReviewer: config.approvalsReviewer,
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
...(input.serviceTier ? { serviceTier: input.serviceTier } : {}),
|
||||
};
|
||||
@@ -323,7 +310,6 @@ function runtimeModeToTurnSandboxPolicy(
|
||||
type: "readOnly",
|
||||
};
|
||||
case "auto-accept-edits":
|
||||
case "auto":
|
||||
return {
|
||||
type: "workspaceWrite",
|
||||
};
|
||||
@@ -396,7 +382,6 @@ export function buildTurnStartParams(input: {
|
||||
threadId: input.threadId,
|
||||
input: turnInput,
|
||||
approvalPolicy: config.approvalPolicy,
|
||||
approvalsReviewer: config.approvalsReviewer,
|
||||
sandboxPolicy: runtimeModeToTurnSandboxPolicy(input.runtimeMode),
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
...(input.serviceTier ? { serviceTier: input.serviceTier } : {}),
|
||||
|
||||
@@ -92,7 +92,6 @@ import * as PreviewManager from "./preview/Manager.ts";
|
||||
import * as PortScanner from "./preview/PortScanner.ts";
|
||||
import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
|
||||
import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts";
|
||||
import * as T3ProjectFileLoader from "./project/T3ProjectFileLoader.ts";
|
||||
import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts";
|
||||
import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts";
|
||||
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
|
||||
@@ -502,10 +501,7 @@ const buildAppUnderTest = (options?: {
|
||||
Layer.provide(WorkspacePaths.layer),
|
||||
Layer.provide(workspaceEntriesLayer),
|
||||
),
|
||||
ProjectFaviconResolver.layer.pipe(
|
||||
Layer.provide(WorkspacePaths.layer),
|
||||
Layer.provide(T3ProjectFileLoader.layer),
|
||||
),
|
||||
ProjectFaviconResolver.layer.pipe(Layer.provide(WorkspacePaths.layer)),
|
||||
);
|
||||
const gitWorkflowLayer = GitWorkflowService.layer.pipe(
|
||||
Layer.provideMerge(vcsDriverRegistryLayer),
|
||||
|
||||
@@ -54,7 +54,6 @@ import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
|
||||
import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry.ts";
|
||||
import * as ServerSettings from "./serverSettings.ts";
|
||||
import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts";
|
||||
import * as T3ProjectFileLoader from "./project/T3ProjectFileLoader.ts";
|
||||
import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts";
|
||||
import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts";
|
||||
import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";
|
||||
@@ -80,7 +79,6 @@ 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 ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
|
||||
import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
|
||||
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
|
||||
@@ -266,7 +264,6 @@ const WorkspaceLayerLive = Layer.mergeAll(
|
||||
|
||||
const ProjectFaviconResolverLayerLive = ProjectFaviconResolver.layer.pipe(
|
||||
Layer.provide(WorkspacePaths.layer),
|
||||
Layer.provide(T3ProjectFileLoader.layer),
|
||||
);
|
||||
|
||||
const AuthLayerLive = EnvironmentAuth.layer.pipe(
|
||||
@@ -364,11 +361,7 @@ export const makeRoutesLayer = Layer.mergeAll(
|
||||
websocketRpcRouteLayer,
|
||||
),
|
||||
McpHttpServer.layer.pipe(Layer.provide(McpSessionRegistry.layer)),
|
||||
).pipe(
|
||||
Layer.provide(PreviewAutomationBroker.layer),
|
||||
Layer.provide(ServerSelfUpdate.layer),
|
||||
Layer.provide(browserApiCorsLayer),
|
||||
);
|
||||
).pipe(Layer.provide(PreviewAutomationBroker.layer), Layer.provide(browserApiCorsLayer));
|
||||
|
||||
export const makeServerLayer = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -713,20 +713,6 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
|
||||
});
|
||||
assert.equal(reusedForSshScheme, "origin");
|
||||
|
||||
const reusedForBareSshScheme = yield* driver.ensureRemote({
|
||||
cwd,
|
||||
preferredName: "pingdotgg",
|
||||
url: "ssh://github.com/pingdotgg/t3code",
|
||||
});
|
||||
assert.equal(reusedForBareSshScheme, "origin");
|
||||
|
||||
const reusedForSshPort = yield* driver.ensureRemote({
|
||||
cwd,
|
||||
preferredName: "pingdotgg",
|
||||
url: "ssh://[email protected]:22/pingdotgg/t3code",
|
||||
});
|
||||
assert.equal(reusedForSshPort, "origin");
|
||||
|
||||
const reusedForSshWithPort = yield* driver.ensureRemote({
|
||||
cwd,
|
||||
preferredName: "pingdotgg",
|
||||
|
||||
@@ -78,7 +78,6 @@ import {
|
||||
} from "./observability/RpcInstrumentation.ts";
|
||||
import * as ProviderRegistry from "./provider/Services/ProviderRegistry.ts";
|
||||
import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner.ts";
|
||||
import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";
|
||||
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
|
||||
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
|
||||
import * as ServerSettings from "./serverSettings.ts";
|
||||
@@ -297,7 +296,6 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
|
||||
[WS_METHODS.serverGetConfig, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.serverRefreshProviders, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.serverUpdateProvider, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.serverUpdateServer, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.serverUpsertKeybinding, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.serverRemoveKeybinding, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.serverGetSettings, AuthOrchestrationReadScope],
|
||||
@@ -420,7 +418,6 @@ const makeWsRpcLayer = (
|
||||
const portDiscovery = yield* PortScanner.PortDiscovery;
|
||||
const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
|
||||
const providerMaintenanceRunner = yield* ProviderMaintenanceRunner.ProviderMaintenanceRunner;
|
||||
const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate;
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
|
||||
const serverSettings = yield* ServerSettings.ServerSettingsService;
|
||||
@@ -1479,10 +1476,6 @@ const makeWsRpcLayer = (
|
||||
"rpc.aggregate": "server",
|
||||
},
|
||||
),
|
||||
[WS_METHODS.serverUpdateServer]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.serverUpdateServer, serverSelfUpdate.update(input), {
|
||||
"rpc.aggregate": "server",
|
||||
}),
|
||||
[WS_METHODS.serverUpsertKeybinding]: (rule) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.serverUpsertKeybinding,
|
||||
@@ -2086,7 +2079,6 @@ const makeWsRpcLayer = (
|
||||
export const websocketRpcRouteLayer = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const previewAutomationBroker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
|
||||
const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate;
|
||||
return HttpRouter.add(
|
||||
"GET",
|
||||
"/ws",
|
||||
@@ -2109,7 +2101,6 @@ export const websocketRpcRouteLayer = Layer.unwrap(
|
||||
makeWsRpcLayer(session, previewAutomationBroker).pipe(
|
||||
Layer.provideMerge(RpcSerialization.layerJson),
|
||||
Layer.provide(ProviderMaintenanceRunner.layer),
|
||||
Layer.provide(Layer.succeed(ServerSelfUpdate.ServerSelfUpdate, serverSelfUpdate)),
|
||||
Layer.provide(
|
||||
SourceControlDiscovery.layer.pipe(
|
||||
Layer.provide(
|
||||
|
||||
@@ -11,9 +11,6 @@ import {
|
||||
resolveEnvModeLabel,
|
||||
resolveBranchToolbarValue,
|
||||
resolveLockedWorkspaceLabel,
|
||||
resolveLocalCheckoutBranchMismatch,
|
||||
resolvePreviousWorktreeLabel,
|
||||
resolvePreviousWorktreeSeed,
|
||||
shouldIncludeBranchPickerItem,
|
||||
shouldShowEnvironmentIndicator,
|
||||
} from "./BranchToolbar.logic";
|
||||
@@ -21,91 +18,6 @@ import {
|
||||
const localEnvironmentId = EnvironmentId.make("environment-local");
|
||||
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
|
||||
|
||||
describe("resolvePreviousWorktreeSeed", () => {
|
||||
it("picks the most recently updated worktree thread", () => {
|
||||
expect(
|
||||
resolvePreviousWorktreeSeed({
|
||||
threads: [
|
||||
{
|
||||
branch: "t3/older",
|
||||
worktreePath: "/repo/.t3/worktrees/older",
|
||||
updatedAt: "2026-07-20T00:00:00.000Z",
|
||||
},
|
||||
{
|
||||
branch: "t3/newer",
|
||||
worktreePath: "/repo/.t3/worktrees/newer",
|
||||
updatedAt: "2026-07-22T00:00:00.000Z",
|
||||
},
|
||||
{ branch: "main", worktreePath: null, updatedAt: "2026-07-23T00:00:00.000Z" },
|
||||
],
|
||||
currentWorktreePath: null,
|
||||
}),
|
||||
).toEqual({ branch: "t3/newer", worktreePath: "/repo/.t3/worktrees/newer" });
|
||||
});
|
||||
|
||||
it("skips the worktree the composer already points at", () => {
|
||||
expect(
|
||||
resolvePreviousWorktreeSeed({
|
||||
threads: [
|
||||
{
|
||||
branch: "t3/current",
|
||||
worktreePath: "/repo/.t3/worktrees/current",
|
||||
updatedAt: "2026-07-22T00:00:00.000Z",
|
||||
},
|
||||
],
|
||||
currentWorktreePath: "/repo/.t3/worktrees/current",
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when no thread has a worktree", () => {
|
||||
expect(
|
||||
resolvePreviousWorktreeSeed({
|
||||
threads: [{ branch: "main", worktreePath: null, updatedAt: "2026-07-22T00:00:00.000Z" }],
|
||||
currentWorktreePath: null,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores archived threads and threads with unparseable timestamps", () => {
|
||||
expect(
|
||||
resolvePreviousWorktreeSeed({
|
||||
threads: [
|
||||
{
|
||||
branch: "t3/archived",
|
||||
worktreePath: "/repo/.t3/worktrees/archived",
|
||||
updatedAt: "2026-07-23T00:00:00.000Z",
|
||||
archivedAt: "2026-07-23T01:00:00.000Z",
|
||||
},
|
||||
{
|
||||
branch: "t3/garbage-timestamp",
|
||||
worktreePath: "/repo/.t3/worktrees/garbage",
|
||||
updatedAt: "not-a-date",
|
||||
},
|
||||
{
|
||||
branch: "t3/live",
|
||||
worktreePath: "/repo/.t3/worktrees/live",
|
||||
updatedAt: "2026-07-21T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
},
|
||||
],
|
||||
currentWorktreePath: null,
|
||||
}),
|
||||
).toEqual({ branch: "t3/live", worktreePath: "/repo/.t3/worktrees/live" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolvePreviousWorktreeLabel", () => {
|
||||
it("includes the branch when known", () => {
|
||||
expect(resolvePreviousWorktreeLabel({ branch: "t3/fix-thing", worktreePath: "/wt" })).toBe(
|
||||
"Previous worktree (t3/fix-thing)",
|
||||
);
|
||||
expect(resolvePreviousWorktreeLabel({ branch: null, worktreePath: "/wt" })).toBe(
|
||||
"Previous worktree",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveDraftEnvModeAfterBranchChange", () => {
|
||||
it("switches to local mode when returning from an existing worktree to the main worktree", () => {
|
||||
expect(
|
||||
@@ -173,55 +85,6 @@ describe("resolveBranchToolbarValue", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveLocalCheckoutBranchMismatch", () => {
|
||||
it("detects when a local thread is associated with a different branch than the checkout", () => {
|
||||
expect(
|
||||
resolveLocalCheckoutBranchMismatch({
|
||||
effectiveEnvMode: "local",
|
||||
activeWorktreePath: null,
|
||||
activeThreadBranch: "feature/thread",
|
||||
currentGitBranch: "feature/current",
|
||||
}),
|
||||
).toEqual({
|
||||
threadBranch: "feature/thread",
|
||||
currentBranch: "feature/current",
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores matching local checkout state", () => {
|
||||
expect(
|
||||
resolveLocalCheckoutBranchMismatch({
|
||||
effectiveEnvMode: "local",
|
||||
activeWorktreePath: null,
|
||||
activeThreadBranch: "feature/thread",
|
||||
currentGitBranch: "feature/thread",
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores dedicated worktrees because their checkout is already thread-scoped", () => {
|
||||
expect(
|
||||
resolveLocalCheckoutBranchMismatch({
|
||||
effectiveEnvMode: "worktree",
|
||||
activeWorktreePath: "/repo/.t3/worktrees/feature-thread",
|
||||
activeThreadBranch: "feature/thread",
|
||||
currentGitBranch: "feature/current",
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores new-worktree base selection before a worktree exists", () => {
|
||||
expect(
|
||||
resolveLocalCheckoutBranchMismatch({
|
||||
effectiveEnvMode: "worktree",
|
||||
activeWorktreePath: null,
|
||||
activeThreadBranch: "feature/base",
|
||||
currentGitBranch: "main",
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveEnvironmentOptionLabel", () => {
|
||||
it("prefers the primary environment's machine label", () => {
|
||||
expect(
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import type { EnvironmentId, VcsRef, ProjectId } from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { toSortableTimestamp } from "../lib/threadSort";
|
||||
export {
|
||||
dedupeRemoteBranchesWithLocalMatches,
|
||||
deriveLocalBranchNameFromRemoteRef,
|
||||
@@ -66,53 +65,6 @@ export function resolveLockedWorkspaceLabel(activeWorktreePath: string | null):
|
||||
return activeWorktreePath ? "Worktree" : "Local checkout";
|
||||
}
|
||||
|
||||
export interface PreviousWorktreeSeed {
|
||||
branch: string | null;
|
||||
worktreePath: string;
|
||||
}
|
||||
|
||||
// The most recently touched worktree in the project that the composer isn't
|
||||
// already pointing at. Backs the "Previous worktree" entry in the workspace
|
||||
// selector so a follow-up thread can hop back into the worktree you just
|
||||
// worked in without hunting for its branch. Archived threads don't compete —
|
||||
// the rest of the UI hides them, so their worktrees shouldn't resurface here.
|
||||
export function resolvePreviousWorktreeSeed(input: {
|
||||
threads: ReadonlyArray<{
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
updatedAt: string;
|
||||
archivedAt?: string | null;
|
||||
}>;
|
||||
currentWorktreePath: string | null;
|
||||
}): PreviousWorktreeSeed | null {
|
||||
let latest: { branch: string | null; worktreePath: string; updatedAt: number } | null = null;
|
||||
for (const thread of input.threads) {
|
||||
if (
|
||||
!thread.worktreePath ||
|
||||
thread.worktreePath === input.currentWorktreePath ||
|
||||
(thread.archivedAt ?? null) !== null
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const updatedAt = toSortableTimestamp(thread.updatedAt);
|
||||
if (updatedAt === null) {
|
||||
continue;
|
||||
}
|
||||
if (latest === null || updatedAt > latest.updatedAt) {
|
||||
latest = {
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
updatedAt,
|
||||
};
|
||||
}
|
||||
}
|
||||
return latest === null ? null : { branch: latest.branch, worktreePath: latest.worktreePath };
|
||||
}
|
||||
|
||||
export function resolvePreviousWorktreeLabel(seed: PreviousWorktreeSeed): string {
|
||||
return seed.branch ? `Previous worktree (${seed.branch})` : "Previous worktree";
|
||||
}
|
||||
|
||||
export function resolveEffectiveEnvMode(input: {
|
||||
activeWorktreePath: string | null;
|
||||
hasServerThread: boolean;
|
||||
@@ -156,22 +108,6 @@ export function resolveBranchToolbarValue(input: {
|
||||
return currentGitBranch ?? activeThreadBranch;
|
||||
}
|
||||
|
||||
export function resolveLocalCheckoutBranchMismatch(input: {
|
||||
effectiveEnvMode: EnvMode;
|
||||
activeWorktreePath: string | null;
|
||||
activeThreadBranch: string | null;
|
||||
currentGitBranch: string | null;
|
||||
}): { threadBranch: string; currentBranch: string } | null {
|
||||
const { effectiveEnvMode, activeWorktreePath, activeThreadBranch, currentGitBranch } = input;
|
||||
if (effectiveEnvMode !== "local" || activeWorktreePath !== null) {
|
||||
return null;
|
||||
}
|
||||
if (!activeThreadBranch || !currentGitBranch || activeThreadBranch === currentGitBranch) {
|
||||
return null;
|
||||
}
|
||||
return { threadBranch: activeThreadBranch, currentBranch: currentGitBranch };
|
||||
}
|
||||
|
||||
export function resolveBranchSelectionTarget(input: {
|
||||
activeProjectCwd: string;
|
||||
activeWorktreePath: string | null;
|
||||
|
||||
@@ -6,13 +6,12 @@ import {
|
||||
FolderGit2Icon,
|
||||
FolderGitIcon,
|
||||
FolderIcon,
|
||||
HistoryIcon,
|
||||
MonitorIcon,
|
||||
} from "lucide-react";
|
||||
import { memo, useCallback, useMemo } from "react";
|
||||
import { memo, useMemo } from "react";
|
||||
|
||||
import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
|
||||
import { useProject, useThread, useThreadShellsForProjectRefs } from "../state/entities";
|
||||
import { useProject, useThread } from "../state/entities";
|
||||
import { useIsMobile } from "../hooks/useMediaQuery";
|
||||
import {
|
||||
type EnvMode,
|
||||
@@ -21,8 +20,6 @@ import {
|
||||
resolveEnvModeLabel,
|
||||
resolveEffectiveEnvMode,
|
||||
resolveLockedWorkspaceLabel,
|
||||
resolvePreviousWorktreeLabel,
|
||||
resolvePreviousWorktreeSeed,
|
||||
shouldShowEnvironmentIndicator,
|
||||
} from "./BranchToolbar.logic";
|
||||
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
|
||||
@@ -69,8 +66,6 @@ interface MobileRunContextSelectorProps {
|
||||
effectiveEnvMode: EnvMode;
|
||||
activeWorktreePath: string | null;
|
||||
onEnvModeChange: (mode: EnvMode) => void;
|
||||
previousWorktreeLabel: string | null;
|
||||
onUsePreviousWorktree: () => void;
|
||||
}
|
||||
|
||||
const MobileRunContextSelector = memo(function MobileRunContextSelector({
|
||||
@@ -84,8 +79,6 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
|
||||
effectiveEnvMode,
|
||||
activeWorktreePath,
|
||||
onEnvModeChange,
|
||||
previousWorktreeLabel,
|
||||
onUsePreviousWorktree,
|
||||
}: MobileRunContextSelectorProps) {
|
||||
const activeEnvironment = useMemo(
|
||||
() => availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null,
|
||||
@@ -173,13 +166,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
|
||||
<MenuGroupLabel>Workspace</MenuGroupLabel>
|
||||
<MenuRadioGroup
|
||||
value={effectiveEnvMode}
|
||||
onValueChange={(value) => {
|
||||
if (value === "previous-worktree") {
|
||||
onUsePreviousWorktree();
|
||||
return;
|
||||
}
|
||||
onEnvModeChange(value as EnvMode);
|
||||
}}
|
||||
onValueChange={(value) => onEnvModeChange(value as EnvMode)}
|
||||
>
|
||||
<MenuRadioItem disabled={envModeLocked} value="local">
|
||||
<span className="flex min-w-0 items-center gap-1.5">
|
||||
@@ -199,14 +186,6 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
|
||||
<span className="min-w-0 truncate">{resolveEnvModeLabel("worktree")}</span>
|
||||
</span>
|
||||
</MenuRadioItem>
|
||||
{previousWorktreeLabel ? (
|
||||
<MenuRadioItem disabled={envModeLocked} value="previous-worktree">
|
||||
<span className="flex min-w-0 items-center gap-1.5">
|
||||
<HistoryIcon className="size-3" />
|
||||
<span className="min-w-0 truncate">{previousWorktreeLabel}</span>
|
||||
</span>
|
||||
</MenuRadioItem>
|
||||
) : null}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</MenuPopup>
|
||||
@@ -238,7 +217,6 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
const draftThread = useComposerDraftStore((store) =>
|
||||
draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef),
|
||||
);
|
||||
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
|
||||
const activeProjectRef = serverThread
|
||||
? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
|
||||
: draftThread
|
||||
@@ -256,40 +234,6 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
});
|
||||
const envModeLocked = envLocked || (serverThread !== null && activeWorktreePath !== null);
|
||||
|
||||
// "Previous worktree" hops a draft into the most recently active worktree
|
||||
// of this project — the "keep going where I just was" follow-up flow. Only
|
||||
// drafts can hop; started server threads have their workspace pinned.
|
||||
const canUsePreviousWorktree = draftThread !== null && serverThread === null && !envModeLocked;
|
||||
const projectRefsForWorktreeLookup = useMemo(
|
||||
() => (canUsePreviousWorktree && activeProjectRef ? [activeProjectRef] : []),
|
||||
[canUsePreviousWorktree, activeProjectRef],
|
||||
);
|
||||
const projectThreads = useThreadShellsForProjectRefs(projectRefsForWorktreeLookup);
|
||||
const previousWorktreeSeed = useMemo(
|
||||
() =>
|
||||
canUsePreviousWorktree
|
||||
? resolvePreviousWorktreeSeed({
|
||||
threads: projectThreads,
|
||||
currentWorktreePath: activeWorktreePath,
|
||||
})
|
||||
: null,
|
||||
[activeWorktreePath, canUsePreviousWorktree, projectThreads],
|
||||
);
|
||||
const previousWorktreeLabel = previousWorktreeSeed
|
||||
? resolvePreviousWorktreeLabel(previousWorktreeSeed)
|
||||
: null;
|
||||
const onUsePreviousWorktree = useCallback(() => {
|
||||
if (!previousWorktreeSeed || !activeProjectRef) return;
|
||||
// Same shape the branch selector writes when picking a branch that
|
||||
// already lives in a worktree: point the draft at the existing tree.
|
||||
setDraftThreadContext(draftId ?? threadRef, {
|
||||
branch: previousWorktreeSeed.branch,
|
||||
worktreePath: previousWorktreeSeed.worktreePath,
|
||||
envMode: "worktree",
|
||||
projectRef: activeProjectRef,
|
||||
});
|
||||
}, [activeProjectRef, draftId, previousWorktreeSeed, setDraftThreadContext, threadRef]);
|
||||
|
||||
const showEnvironmentPicker = Boolean(
|
||||
availableEnvironments && availableEnvironments.length > 1 && onEnvironmentChange,
|
||||
);
|
||||
@@ -304,7 +248,7 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
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 px-1 pt-5 pb-1">
|
||||
<div className="chat-composer-context-strip -mt-2 mx-auto flex w-[calc(100%-1.5rem)] max-w-[calc(48rem-1.5rem)] items-center gap-2 pt-3 pe-2 pb-1 ps-2">
|
||||
{isMobile ? (
|
||||
<MobileRunContextSelector
|
||||
envLocked={envLocked}
|
||||
@@ -317,8 +261,6 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
effectiveEnvMode={effectiveEnvMode}
|
||||
activeWorktreePath={activeWorktreePath}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
previousWorktreeLabel={previousWorktreeLabel}
|
||||
onUsePreviousWorktree={onUsePreviousWorktree}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex min-w-0 shrink-0 items-center gap-1">
|
||||
@@ -338,8 +280,6 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
effectiveEnvMode={effectiveEnvMode}
|
||||
activeWorktreePath={activeWorktreePath}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
previousWorktreeLabel={previousWorktreeLabel}
|
||||
onUsePreviousWorktree={onUsePreviousWorktree}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
isAtomCommandInterrupted,
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import type { ContextMenuItem, EnvironmentId, VcsRef, ThreadId } from "@t3tools/contracts";
|
||||
import type { EnvironmentId, VcsRef, ThreadId } from "@t3tools/contracts";
|
||||
import { LegendList, type LegendListRef } from "@legendapp/list/react";
|
||||
import { ChevronDownIcon, GitBranchIcon, RefreshCwIcon, SearchIcon } from "lucide-react";
|
||||
import {
|
||||
@@ -17,12 +17,9 @@ import {
|
||||
useRef,
|
||||
useState,
|
||||
useTransition,
|
||||
type MouseEvent as ReactMouseEvent,
|
||||
} from "react";
|
||||
|
||||
import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
|
||||
import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
|
||||
import { readLocalApi } from "../localApi";
|
||||
import { useOpenPrLink } from "../lib/openPullRequestLink";
|
||||
import { usePaginatedBranches } from "../state/queries";
|
||||
import { useProject, useThread } from "../state/entities";
|
||||
@@ -320,45 +317,6 @@ export function BranchToolbarBranchSelector({
|
||||
// ---------------------------------------------------------------------------
|
||||
// Branch actions
|
||||
// ---------------------------------------------------------------------------
|
||||
const copyBranchName = useCallback((branchName: string) => {
|
||||
void writeTextToClipboard(branchName, "branch name").then(
|
||||
(didCopy) => {
|
||||
if (!didCopy) return;
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Branch name copied",
|
||||
description: branchName,
|
||||
});
|
||||
},
|
||||
(error: unknown) => {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to copy branch name",
|
||||
description: toBranchActionErrorMessage(error),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
}, []);
|
||||
|
||||
const handleBranchContextMenu = useCallback(
|
||||
(event: ReactMouseEvent, branchName: string | null) => {
|
||||
if (!branchName) return;
|
||||
const api = readLocalApi();
|
||||
if (!api) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const items: ContextMenuItem<"copy-branch-name">[] = [
|
||||
{ id: "copy-branch-name", label: "Copy branch name", icon: "copy" },
|
||||
];
|
||||
void api.contextMenu.show(items, { x: event.clientX, y: event.clientY }).then((action) => {
|
||||
if (action === "copy-branch-name") copyBranchName(branchName);
|
||||
});
|
||||
},
|
||||
[copyBranchName],
|
||||
);
|
||||
|
||||
const runBranchAction = (action: () => Promise<void>) => {
|
||||
startBranchActionTransition(async () => {
|
||||
await action();
|
||||
@@ -473,7 +431,6 @@ export function BranchToolbarBranchSelector({
|
||||
const worktreeBaseBranchCandidate = isInitialBranchesLoadPending
|
||||
? null
|
||||
: (defaultBranchName ?? currentGitBranch);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
effectiveEnvMode !== "worktree" ||
|
||||
@@ -590,11 +547,7 @@ export function BranchToolbarBranchSelector({
|
||||
});
|
||||
|
||||
// PR pill shown next to the branch selector when the active branch has one.
|
||||
const branchPr = resolveThreadPr({
|
||||
threadBranch: resolvedActiveBranch,
|
||||
gitStatus: branchStatusQuery.data ?? null,
|
||||
hasDedicatedWorktree: activeWorktreePath !== null,
|
||||
});
|
||||
const branchPr = resolveThreadPr(resolvedActiveBranch, branchStatusQuery.data ?? null);
|
||||
const branchPrStatus = prStatusIndicator(branchPr, branchStatusQuery.data?.sourceControlProvider);
|
||||
// Action-oriented tooltip (the pill opens the PR), distinct from the sidebar's
|
||||
// state-description tooltip.
|
||||
@@ -671,7 +624,6 @@ export function BranchToolbarBranchSelector({
|
||||
value={itemValue}
|
||||
className="pe-1.5"
|
||||
onClick={() => selectBranch(refName)}
|
||||
onContextMenu={(event) => handleBranchContextMenu(event, itemValue)}
|
||||
>
|
||||
<div className="flex w-full min-w-0 items-center justify-between gap-2">
|
||||
<span className="min-w-0 flex-1 truncate">{itemValue}</span>
|
||||
@@ -722,23 +674,15 @@ export function BranchToolbarBranchSelector({
|
||||
<TooltipPopup side="top">{branchPrTooltip}</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
{/* Context menu lives on the wrapper: the disabled Button has
|
||||
pointer-events-none, so the trigger itself never sees right-clicks
|
||||
while refs are loading or a branch action is pending. */}
|
||||
<span
|
||||
className="flex min-w-0"
|
||||
onContextMenu={(event) => handleBranchContextMenu(event, resolvedActiveBranch)}
|
||||
<ComboboxTrigger
|
||||
render={<Button variant="ghost" size="xs" />}
|
||||
className="min-w-0 text-muted-foreground/70 hover:text-foreground/80"
|
||||
disabled={isInitialBranchesLoadPending || isBranchActionPending}
|
||||
>
|
||||
<ComboboxTrigger
|
||||
render={<Button variant="ghost" size="xs" />}
|
||||
className="min-w-0 max-w-full text-muted-foreground/70 hover:text-foreground/80"
|
||||
disabled={isInitialBranchesLoadPending || isBranchActionPending}
|
||||
>
|
||||
<GitBranchIcon className="size-3 shrink-0 opacity-70" />
|
||||
<span className="min-w-0 max-w-[240px] truncate">{triggerLabel}</span>
|
||||
<ChevronDownIcon className="size-3 shrink-0 opacity-50" />
|
||||
</ComboboxTrigger>
|
||||
</span>
|
||||
<GitBranchIcon className="size-3 shrink-0 opacity-70" />
|
||||
<span className="min-w-0 max-w-[240px] truncate">{triggerLabel}</span>
|
||||
<ChevronDownIcon className="size-3 shrink-0 opacity-50" />
|
||||
</ComboboxTrigger>
|
||||
</div>
|
||||
<ComboboxPopup align="end" side="top" className="flex w-80 flex-col">
|
||||
<div className="shrink-0 px-3 pt-2.5">
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { FolderGit2Icon, FolderGitIcon, FolderIcon, HistoryIcon } from "lucide-react";
|
||||
import { FolderGit2Icon, FolderGitIcon, FolderIcon } from "lucide-react";
|
||||
import { memo, useMemo } from "react";
|
||||
|
||||
import {
|
||||
@@ -17,15 +17,11 @@ import {
|
||||
SelectValue,
|
||||
} from "./ui/select";
|
||||
|
||||
export const PREVIOUS_WORKTREE_SELECT_VALUE = "previous-worktree";
|
||||
|
||||
interface BranchToolbarEnvModeSelectorProps {
|
||||
envLocked: boolean;
|
||||
effectiveEnvMode: EnvMode;
|
||||
activeWorktreePath: string | null;
|
||||
onEnvModeChange: (mode: EnvMode) => void;
|
||||
previousWorktreeLabel?: string | null;
|
||||
onUsePreviousWorktree?: () => void;
|
||||
}
|
||||
|
||||
export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSelector({
|
||||
@@ -33,19 +29,13 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
|
||||
effectiveEnvMode,
|
||||
activeWorktreePath,
|
||||
onEnvModeChange,
|
||||
previousWorktreeLabel,
|
||||
onUsePreviousWorktree,
|
||||
}: BranchToolbarEnvModeSelectorProps) {
|
||||
const showPreviousWorktree = Boolean(previousWorktreeLabel && onUsePreviousWorktree);
|
||||
const envModeItems = useMemo(
|
||||
() => [
|
||||
{ value: "local", label: resolveCurrentWorkspaceLabel(activeWorktreePath) },
|
||||
{ value: "worktree", label: resolveEnvModeLabel("worktree") },
|
||||
...(showPreviousWorktree && previousWorktreeLabel
|
||||
? [{ value: PREVIOUS_WORKTREE_SELECT_VALUE, label: previousWorktreeLabel }]
|
||||
: []),
|
||||
],
|
||||
[activeWorktreePath, previousWorktreeLabel, showPreviousWorktree],
|
||||
[activeWorktreePath],
|
||||
);
|
||||
|
||||
if (envLocked) {
|
||||
@@ -70,13 +60,7 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
|
||||
<Select
|
||||
modal={false}
|
||||
value={effectiveEnvMode}
|
||||
onValueChange={(value: string | null) => {
|
||||
if (value === PREVIOUS_WORKTREE_SELECT_VALUE) {
|
||||
onUsePreviousWorktree?.();
|
||||
return;
|
||||
}
|
||||
onEnvModeChange(value as EnvMode);
|
||||
}}
|
||||
onValueChange={(value) => onEnvModeChange(value as EnvMode)}
|
||||
items={envModeItems}
|
||||
>
|
||||
<SelectTrigger variant="ghost" size="xs" className="font-medium" aria-label="Workspace">
|
||||
@@ -108,14 +92,6 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
|
||||
{resolveEnvModeLabel("worktree")}
|
||||
</span>
|
||||
</SelectItem>
|
||||
{showPreviousWorktree && previousWorktreeLabel ? (
|
||||
<SelectItem value={PREVIOUS_WORKTREE_SELECT_VALUE}>
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<HistoryIcon className="size-3" />
|
||||
{previousWorktreeLabel}
|
||||
</span>
|
||||
</SelectItem>
|
||||
) : null}
|
||||
</SelectGroup>
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
|
||||
@@ -12,20 +12,15 @@ import type { Thread } from "../types";
|
||||
import {
|
||||
MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
|
||||
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
|
||||
branchMismatchKey,
|
||||
buildExpiredTerminalContextToastCopy,
|
||||
buildThreadTurnInterruptInput,
|
||||
createLocalDispatchSnapshot,
|
||||
deriveComposerSendState,
|
||||
dismissBranchMismatchForSession,
|
||||
getStartedThreadModelChangeBlockReason,
|
||||
hasServerAcknowledgedLocalDispatch,
|
||||
isBranchMismatchDismissedForSession,
|
||||
reconcileMountedTerminalThreadIds,
|
||||
reconcileRetainedMountedThreadIds,
|
||||
resolveThreadMetadataUpdateForNextTurn,
|
||||
resolveSendEnvMode,
|
||||
shouldShowBranchMismatchBanner,
|
||||
shouldWriteThreadErrorToCurrentServerThread,
|
||||
} from "./ChatView.logic";
|
||||
|
||||
@@ -84,34 +79,6 @@ const readySession = {
|
||||
updatedAt: "2026-03-29T00:00:10.000Z",
|
||||
};
|
||||
|
||||
describe("resolveThreadMetadataUpdateForNextTurn", () => {
|
||||
const modelSelection = {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
};
|
||||
|
||||
it("updates a stale local thread branch to the active checkout", () => {
|
||||
expect(
|
||||
resolveThreadMetadataUpdateForNextTurn({
|
||||
currentModelSelection: modelSelection,
|
||||
currentBranch: "feature/thread",
|
||||
nextBranch: "feature/checkout",
|
||||
}),
|
||||
).toEqual({ branch: "feature/checkout", worktreePath: null });
|
||||
});
|
||||
|
||||
it("does not write metadata when the model and branch are unchanged", () => {
|
||||
expect(
|
||||
resolveThreadMetadataUpdateForNextTurn({
|
||||
currentModelSelection: modelSelection,
|
||||
nextModelSelection: modelSelection,
|
||||
currentBranch: "feature/current",
|
||||
nextBranch: "feature/current",
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildThreadTurnInterruptInput", () => {
|
||||
it("targets the session's active running turn", () => {
|
||||
const activeTurnId = TurnId.make("turn-running");
|
||||
@@ -296,61 +263,6 @@ describe("resolveSendEnvMode", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("branchMismatchKey", () => {
|
||||
it("builds a key from thread id and both branches", () => {
|
||||
expect(branchMismatchKey("thread-1", { threadBranch: "feat/a", currentBranch: "feat/b" })).toBe(
|
||||
"thread-1:feat/a:feat/b",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns null without a thread or mismatch", () => {
|
||||
expect(branchMismatchKey(null, { threadBranch: "a", currentBranch: "b" })).toBeNull();
|
||||
expect(branchMismatchKey("thread-1", null)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("shouldShowBranchMismatchBanner", () => {
|
||||
const base = {
|
||||
hasMismatch: true,
|
||||
isDismissed: false,
|
||||
composerHasContent: false,
|
||||
wasShownForCurrentMismatch: false,
|
||||
};
|
||||
|
||||
it("stays hidden during passive browsing (even though the composer autofocuses)", () => {
|
||||
expect(shouldShowBranchMismatchBanner(base)).toBe(false);
|
||||
});
|
||||
|
||||
it("shows once the composer has draft content", () => {
|
||||
expect(shouldShowBranchMismatchBanner({ ...base, composerHasContent: true })).toBe(true);
|
||||
});
|
||||
|
||||
it("stays mounted after the draft clears once shown for the current mismatch", () => {
|
||||
expect(shouldShowBranchMismatchBanner({ ...base, wasShownForCurrentMismatch: true })).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("never shows when dismissed or without a mismatch", () => {
|
||||
expect(
|
||||
shouldShowBranchMismatchBanner({ ...base, composerHasContent: true, isDismissed: true }),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldShowBranchMismatchBanner({ ...base, composerHasContent: true, hasMismatch: false }),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("session branch mismatch dismissal", () => {
|
||||
it("tracks dismissed keys and treats other keys as active", () => {
|
||||
expect(isBranchMismatchDismissedForSession("t1:a:b")).toBe(false);
|
||||
dismissBranchMismatchForSession("t1:a:b");
|
||||
expect(isBranchMismatchDismissedForSession("t1:a:b")).toBe(true);
|
||||
expect(isBranchMismatchDismissedForSession("t1:a:c")).toBe(false);
|
||||
expect(isBranchMismatchDismissedForSession(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("reconcileMountedTerminalThreadIds", () => {
|
||||
it("keeps open threads and makes the active thread most recent", () => {
|
||||
expect(
|
||||
|
||||
@@ -27,33 +27,6 @@ export const MAX_HIDDEN_MOUNTED_PREVIEW_THREADS = 3;
|
||||
|
||||
export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String);
|
||||
|
||||
export function resolveThreadMetadataUpdateForNextTurn(input: {
|
||||
currentModelSelection: ModelSelection;
|
||||
nextModelSelection?: ModelSelection;
|
||||
currentBranch: string | null;
|
||||
nextBranch?: string;
|
||||
}): {
|
||||
modelSelection?: ModelSelection;
|
||||
branch?: string;
|
||||
worktreePath?: null;
|
||||
} | null {
|
||||
const nextModelSelection = input.nextModelSelection;
|
||||
const modelSelectionChanged =
|
||||
nextModelSelection !== undefined &&
|
||||
(nextModelSelection.model !== input.currentModelSelection.model ||
|
||||
nextModelSelection.instanceId !== input.currentModelSelection.instanceId ||
|
||||
JSON.stringify(nextModelSelection.options ?? null) !==
|
||||
JSON.stringify(input.currentModelSelection.options ?? null));
|
||||
const branchChanged = input.nextBranch !== undefined && input.nextBranch !== input.currentBranch;
|
||||
if (!modelSelectionChanged && !branchChanged) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
...(modelSelectionChanged ? { modelSelection: nextModelSelection } : {}),
|
||||
...(branchChanged ? { branch: input.nextBranch, worktreePath: null } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildLocalDraftThread(
|
||||
threadId: ThreadId,
|
||||
draftThread: DraftThreadState,
|
||||
@@ -289,46 +262,6 @@ export function buildExpiredTerminalContextToastCopy(
|
||||
};
|
||||
}
|
||||
|
||||
export function branchMismatchKey(
|
||||
threadId: string | null,
|
||||
mismatch: { threadBranch: string; currentBranch: string } | null,
|
||||
): string | null {
|
||||
if (!threadId || !mismatch) {
|
||||
return null;
|
||||
}
|
||||
return `${threadId}:${mismatch.threadBranch}:${mismatch.currentBranch}`;
|
||||
}
|
||||
|
||||
// The mismatch banner only matters when the user is about to send: passive
|
||||
// reading of an old thread carries no risk (the branch picker tint already
|
||||
// covers ambient awareness). Draft content is the intent signal — composer
|
||||
// focus is useless here because ChatView autofocuses the composer on every
|
||||
// thread open. `wasShownForCurrentMismatch` keeps the banner mounted once
|
||||
// revealed so it doesn't flicker away when the draft is cleared.
|
||||
export function shouldShowBranchMismatchBanner(input: {
|
||||
hasMismatch: boolean;
|
||||
isDismissed: boolean;
|
||||
composerHasContent: boolean;
|
||||
wasShownForCurrentMismatch: boolean;
|
||||
}): boolean {
|
||||
if (!input.hasMismatch || input.isDismissed) {
|
||||
return false;
|
||||
}
|
||||
return input.composerHasContent || input.wasShownForCurrentMismatch;
|
||||
}
|
||||
|
||||
// Session-scoped (module-level so it survives ChatView remounts, e.g. route
|
||||
// changes). Durable cross-device dismissal is planned as a server-side ack.
|
||||
const sessionDismissedBranchMismatchKeys = new Set<string>();
|
||||
|
||||
export function dismissBranchMismatchForSession(key: string): void {
|
||||
sessionDismissedBranchMismatchKeys.add(key);
|
||||
}
|
||||
|
||||
export function isBranchMismatchDismissedForSession(key: string | null): boolean {
|
||||
return key !== null && sessionDismissedBranchMismatchKeys.has(key);
|
||||
}
|
||||
|
||||
export function threadHasStarted(thread: Thread | null | undefined): boolean {
|
||||
return Boolean(
|
||||
thread && (thread.latestTurn !== null || thread.messages.length > 0 || thread.session !== null),
|
||||
|
||||
@@ -22,10 +22,9 @@ import {
|
||||
TerminalOpenInput,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
connectionStatusTitle,
|
||||
connectionStatusText,
|
||||
type EnvironmentConnectionPresentation,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import { effectiveSettled } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import {
|
||||
parseScopedThreadKey,
|
||||
scopedThreadKey,
|
||||
@@ -139,13 +138,7 @@ import { BranchToolbar } from "./BranchToolbar";
|
||||
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
|
||||
import PlanSidebar from "./PlanSidebar";
|
||||
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
|
||||
import {
|
||||
CheckCircle2Icon,
|
||||
ChevronDownIcon,
|
||||
GitBranchIcon,
|
||||
TriangleAlertIcon,
|
||||
WifiOffIcon,
|
||||
} from "lucide-react";
|
||||
import { ChevronDownIcon, TriangleAlertIcon, WifiOffIcon } from "lucide-react";
|
||||
import { cn, randomHex } from "~/lib/utils";
|
||||
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
|
||||
import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
@@ -160,8 +153,7 @@ import {
|
||||
import { newDraftId, newMessageId, newThreadId } from "~/lib/utils";
|
||||
import { getProviderModelCapabilities, resolveSelectableProvider } from "../providerModels";
|
||||
import { NO_PROVIDER_MODEL_SELECTION } from "../providerInstances";
|
||||
import { useClientSettings, useEnvironmentSettings } from "../hooks/useSettings";
|
||||
import { useNowMinute } from "../hooks/useNowMinute";
|
||||
import { useEnvironmentSettings } from "../hooks/useSettings";
|
||||
import { resolveAppModelSelectionForInstance } from "../modelSelection";
|
||||
import { getTerminalFocusOwner } from "../lib/terminalFocus";
|
||||
import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions";
|
||||
@@ -197,7 +189,6 @@ import { useEnvironmentQuery } from "../state/query";
|
||||
import {
|
||||
primaryServerAvailableEditorsAtom,
|
||||
primaryServerKeybindingsAtom,
|
||||
primaryServerSettingsAtom,
|
||||
serverEnvironment,
|
||||
} from "../state/server";
|
||||
import { terminalEnvironment } from "../state/terminal";
|
||||
@@ -210,7 +201,6 @@ import {
|
||||
useThread,
|
||||
useThreadProposedPlans,
|
||||
useThreadRefs,
|
||||
useThreadShell,
|
||||
} from "../state/entities";
|
||||
import { environmentShell } from "../state/shell";
|
||||
import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer";
|
||||
@@ -222,14 +212,9 @@ import { ChatHeader } from "./chat/ChatHeader";
|
||||
import { PanelLayoutControls, RightPanelMaximizeControl } from "./chat/PanelLayoutControls";
|
||||
import { type ExpandedImagePreview } from "./chat/ExpandedImagePreview";
|
||||
import { NoActiveThreadState } from "./NoActiveThreadState";
|
||||
import { resolveEffectiveEnvMode, resolveLocalCheckoutBranchMismatch } from "./BranchToolbar.logic";
|
||||
import {
|
||||
getProviderStatusBannerKey,
|
||||
ProviderStatusBanner,
|
||||
shouldShowProviderStatusBanner,
|
||||
} from "./chat/ProviderStatusBanner";
|
||||
import { resolveEffectiveEnvMode } from "./BranchToolbar.logic";
|
||||
import { ProviderStatusBanner } from "./chat/ProviderStatusBanner";
|
||||
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
|
||||
import { resolveThreadPr } from "./ThreadStatusIndicators";
|
||||
import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack";
|
||||
import {
|
||||
DRAFT_HERO_TRANSITION_ANIMATION_ID,
|
||||
@@ -241,17 +226,13 @@ import {
|
||||
} from "./chat/draftHeroTransition";
|
||||
import {
|
||||
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
|
||||
branchMismatchKey,
|
||||
buildExpiredTerminalContextToastCopy,
|
||||
buildLocalDraftThread,
|
||||
buildThreadTurnInterruptInput,
|
||||
collectUserMessageBlobPreviewUrls,
|
||||
createLocalDispatchSnapshot,
|
||||
deriveComposerSendState,
|
||||
dismissBranchMismatchForSession,
|
||||
hasServerAcknowledgedLocalDispatch,
|
||||
isBranchMismatchDismissedForSession,
|
||||
shouldShowBranchMismatchBanner,
|
||||
getStartedThreadModelChangeBlockReason,
|
||||
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
|
||||
LastInvokedScriptByProjectSchema,
|
||||
@@ -261,7 +242,6 @@ import {
|
||||
deriveLockedProvider,
|
||||
readFileAsDataUrl,
|
||||
reconcileMountedTerminalThreadIds,
|
||||
resolveThreadMetadataUpdateForNextTurn,
|
||||
resolveSendEnvMode,
|
||||
revokeBlobPreviewUrl,
|
||||
revokeUserMessagePreviewUrls,
|
||||
@@ -274,24 +254,11 @@ import { RightPanelSheet } from "./RightPanelSheet";
|
||||
import { previewEnvironment } from "../state/preview";
|
||||
import { useAtomCommand } from "../state/use-atom-command";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogClose,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogPopup,
|
||||
AlertDialogTitle,
|
||||
} from "./ui/alert-dialog";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
import { ServerUpdateAction } from "./ServerUpdateAction";
|
||||
import {
|
||||
buildVersionMismatchDismissalKey,
|
||||
dismissVersionMismatch,
|
||||
isVersionMismatchDismissed,
|
||||
resolveServerConfigVersionMismatch,
|
||||
resolveServerSelfUpdateCapability,
|
||||
serverUpdateGuidance,
|
||||
} from "../versionSkew";
|
||||
import { useAssetUrls } from "../assets/assetUrls";
|
||||
|
||||
@@ -1110,10 +1077,6 @@ type LocalThreadErrorEntry = {
|
||||
readonly at: number;
|
||||
};
|
||||
|
||||
function chatActionErrorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : "An error occurred.";
|
||||
}
|
||||
|
||||
function ChatViewContent(props: ChatViewProps) {
|
||||
const {
|
||||
environmentId,
|
||||
@@ -1141,7 +1104,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const switchGitRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
|
||||
const setThreadRuntimeMode = useAtomCommand(threadEnvironment.setRuntimeMode, {
|
||||
reportFailure: false,
|
||||
});
|
||||
@@ -1178,10 +1140,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
(store) => store.threadLastVisitedAtById[routeThreadKey],
|
||||
);
|
||||
const settings = useEnvironmentSettings(environmentId);
|
||||
// New-thread defaults live in the primary environment's settings.json (the
|
||||
// settings UI never writes to remote environments), so read them from the
|
||||
// primary server rather than the thread's environment.
|
||||
const primaryServerSettings = useAtomValue(primaryServerSettingsAtom);
|
||||
const setStickyComposerModelSelection = useComposerDraftStore(
|
||||
(store) => store.setStickyModelSelection,
|
||||
);
|
||||
@@ -1826,10 +1784,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
hasMultipleRegisteredEnvironments && activeThread
|
||||
? `${environmentById.get(activeThread.environmentId)?.label ?? serverConfig?.environment.label ?? activeThread.environmentId} server`
|
||||
: "server";
|
||||
const versionMismatchEnvironmentId =
|
||||
versionMismatch && activeThread ? activeThread.environmentId : null;
|
||||
const versionMismatchSelfUpdate = resolveServerSelfUpdateCapability(serverConfig);
|
||||
const systemComposerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {
|
||||
const composerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {
|
||||
const items: ComposerBannerStackItem[] = [];
|
||||
if (activeEnvironmentUnavailableState) {
|
||||
const connection = activeEnvironmentUnavailableState.connection;
|
||||
@@ -1839,7 +1794,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
id: `environment-unavailable:${activeEnvironmentUnavailableState.environmentId}`,
|
||||
variant: connection.phase === "error" ? "error" : "warning",
|
||||
icon: <WifiOffIcon />,
|
||||
title: `${activeEnvironmentUnavailableState.label}: ${connectionStatusTitle(connection)}`,
|
||||
title: `${activeEnvironmentUnavailableState.label}: ${connectionStatusText(connection)}`,
|
||||
description:
|
||||
connection.error ??
|
||||
"Reconnect this environment before sending messages or running actions.",
|
||||
@@ -1867,12 +1822,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
),
|
||||
});
|
||||
}
|
||||
if (
|
||||
showVersionMismatchBanner &&
|
||||
versionMismatch &&
|
||||
versionMismatchDismissKey &&
|
||||
versionMismatchEnvironmentId
|
||||
) {
|
||||
if (showVersionMismatchBanner && versionMismatch && versionMismatchDismissKey) {
|
||||
items.push({
|
||||
id: `version-mismatch:${versionMismatchDismissKey}`,
|
||||
variant: "warning",
|
||||
@@ -1881,21 +1831,9 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
description: (
|
||||
<>
|
||||
Client {versionMismatch.clientVersion} is connected to {versionMismatchServerLabel}{" "}
|
||||
{versionMismatch.serverVersion}.{" "}
|
||||
{serverUpdateGuidance(versionMismatchSelfUpdate, versionMismatchServerLabel)}
|
||||
{versionMismatch.serverVersion}. Sync them if RPC calls or reconnects fail.
|
||||
</>
|
||||
),
|
||||
// The desktop-managed guidance is already the description; the action
|
||||
// slot would only repeat it.
|
||||
actions:
|
||||
versionMismatchSelfUpdate === "desktop-managed" ? undefined : (
|
||||
<ServerUpdateAction
|
||||
environmentId={versionMismatchEnvironmentId}
|
||||
serverLabel={versionMismatchServerLabel}
|
||||
selfUpdate={versionMismatchSelfUpdate}
|
||||
targetVersion={versionMismatch.clientVersion}
|
||||
/>
|
||||
),
|
||||
dismissLabel: "Dismiss version mismatch warning",
|
||||
onDismiss: () => {
|
||||
dismissVersionMismatch(versionMismatchDismissKey);
|
||||
@@ -1908,12 +1846,9 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
activeEnvironmentUnavailableState,
|
||||
handleReconnectActiveEnvironment,
|
||||
navigate,
|
||||
setDismissedVersionMismatchKey,
|
||||
showVersionMismatchBanner,
|
||||
versionMismatch,
|
||||
versionMismatchDismissKey,
|
||||
versionMismatchEnvironmentId,
|
||||
versionMismatchSelfUpdate,
|
||||
versionMismatchServerLabel,
|
||||
]);
|
||||
const providerStatuses = serverConfig?.providers ?? EMPTY_PROVIDERS;
|
||||
@@ -2353,22 +2288,11 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
const defaultInstanceId = defaultInstanceIdForDriver(selectedProvider);
|
||||
return providerStatuses.find((status) => status.instanceId === defaultInstanceId) ?? null;
|
||||
}, [activeProviderInstanceId, providerStatuses, selectedProvider]);
|
||||
const providerStatusBannerKey = getProviderStatusBannerKey(activeProviderStatus);
|
||||
const [dismissedProviderStatusBannerKey, setDismissedProviderStatusBannerKey] = useState<
|
||||
string | null
|
||||
>(null);
|
||||
useEffect(() => {
|
||||
if (providerStatusBannerKey === null && dismissedProviderStatusBannerKey !== null) {
|
||||
setDismissedProviderStatusBannerKey(null);
|
||||
}
|
||||
}, [dismissedProviderStatusBannerKey, providerStatusBannerKey]);
|
||||
const visibleProviderStatus = shouldShowProviderStatusBanner(
|
||||
activeProviderStatus,
|
||||
dismissedProviderStatusBannerKey,
|
||||
)
|
||||
? activeProviderStatus
|
||||
: null;
|
||||
const hasTimelineTopBanner = Boolean(threadError) || visibleProviderStatus !== null;
|
||||
const hasTimelineTopBanner =
|
||||
Boolean(threadError) ||
|
||||
(activeProviderStatus !== null &&
|
||||
activeProviderStatus.status !== "ready" &&
|
||||
activeProviderStatus.status !== "disabled");
|
||||
const activeProjectCwd = activeProject?.workspaceRoot ?? null;
|
||||
const activeThreadWorktreePath = activeThread?.worktreePath ?? null;
|
||||
const activeWorkspaceRoot = activeThreadWorktreePath ?? activeProjectCwd ?? undefined;
|
||||
@@ -2376,7 +2300,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
terminalUiLaunchContext?.threadId === activeThreadId ? terminalUiLaunchContext : null;
|
||||
// Default true while loading to avoid toolbar flicker.
|
||||
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
|
||||
const showComposerContextStrip = isGitRepo && activeProject !== null;
|
||||
const initialDiffPanelGitScope =
|
||||
gitStatusQuery.data?.hasWorkingTreeChanges === true ? "unstaged" : "branch";
|
||||
const diffPanelGitStatusResolutionKey = gitStatusQuery.data ? "resolved" : "pending";
|
||||
@@ -3306,7 +3229,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
threadId: ThreadId;
|
||||
createdAt: string;
|
||||
modelSelection?: ModelSelection;
|
||||
branch?: string;
|
||||
runtimeMode: RuntimeMode;
|
||||
interactionMode: ProviderInteractionMode;
|
||||
}): Promise<AtomCommandResult<void, unknown>> => {
|
||||
@@ -3315,19 +3237,19 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}
|
||||
|
||||
let result: AtomCommandResult<void, unknown> = AsyncResult.success(undefined);
|
||||
const metadataUpdate = resolveThreadMetadataUpdateForNextTurn({
|
||||
currentModelSelection: serverThread.modelSelection,
|
||||
...(input.modelSelection ? { nextModelSelection: input.modelSelection } : {}),
|
||||
currentBranch: serverThread.branch,
|
||||
...(input.branch ? { nextBranch: input.branch } : {}),
|
||||
});
|
||||
if (metadataUpdate) {
|
||||
if (
|
||||
input.modelSelection !== undefined &&
|
||||
(input.modelSelection.model !== serverThread.modelSelection.model ||
|
||||
input.modelSelection.instanceId !== serverThread.modelSelection.instanceId ||
|
||||
JSON.stringify(input.modelSelection.options ?? null) !==
|
||||
JSON.stringify(serverThread.modelSelection.options ?? null))
|
||||
) {
|
||||
result = mapAtomCommandResult(
|
||||
await updateThreadMetadata({
|
||||
environmentId,
|
||||
input: {
|
||||
threadId: input.threadId,
|
||||
...metadataUpdate,
|
||||
modelSelection: input.modelSelection,
|
||||
},
|
||||
}),
|
||||
() => undefined,
|
||||
@@ -3815,277 +3737,12 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
? (draftThread?.startFromOrigin ?? false)
|
||||
: canOverrideServerThreadEnvMode
|
||||
? (pendingServerThreadStartFromOriginByThreadId[activeThread?.id ?? ""] ??
|
||||
primaryServerSettings.newWorktreesStartFromOrigin)
|
||||
settings.newWorktreesStartFromOrigin)
|
||||
: false;
|
||||
const sendEnvMode = resolveSendEnvMode({
|
||||
requestedEnvMode: envMode,
|
||||
isGitRepo,
|
||||
});
|
||||
const localCheckoutBranchMismatch = useMemo(
|
||||
() =>
|
||||
isServerThread
|
||||
? resolveLocalCheckoutBranchMismatch({
|
||||
effectiveEnvMode: envMode,
|
||||
activeWorktreePath,
|
||||
activeThreadBranch,
|
||||
currentGitBranch: gitStatusQuery.data?.refName ?? null,
|
||||
})
|
||||
: null,
|
||||
[activeThreadBranch, activeWorktreePath, envMode, gitStatusQuery.data?.refName, isServerThread],
|
||||
);
|
||||
// Settled state of the open thread, resolved exactly like the sidebar
|
||||
// partition (same shell, same capability gate, same PR auto-settle input)
|
||||
// so the banner and the sidebar row never disagree.
|
||||
const activeThreadShell = useThreadShell(isServerThread ? activeThreadRef : null);
|
||||
const autoSettleAfterDays = useClientSettings((settings) => settings.sidebarAutoSettleAfterDays);
|
||||
const activeThreadPr = resolveThreadPr({
|
||||
threadBranch: activeThread?.branch ?? null,
|
||||
gitStatus: gitStatusQuery.data ?? null,
|
||||
hasDedicatedWorktree: (activeThread?.worktreePath ?? null) !== null,
|
||||
});
|
||||
const supportsSettlement = serverConfig?.environment.capabilities.threadSettlement === true;
|
||||
const nowMinute = useNowMinute();
|
||||
const activeThreadSettled = useMemo(() => {
|
||||
if (activeThreadShell === null || !supportsSettlement) return false;
|
||||
return effectiveSettled(activeThreadShell, {
|
||||
now: `${nowMinute}:00.000Z`,
|
||||
autoSettleAfterDays,
|
||||
changeRequestState: activeThreadPr?.state ?? null,
|
||||
});
|
||||
}, [
|
||||
activeThreadPr?.state,
|
||||
activeThreadShell,
|
||||
autoSettleAfterDays,
|
||||
nowMinute,
|
||||
supportsSettlement,
|
||||
]);
|
||||
const unsettleThreadMutation = useAtomCommand(threadEnvironment.unsettle, {
|
||||
reportFailure: false,
|
||||
});
|
||||
// Keyed by thread, not a boolean: the pending state must follow the thread
|
||||
// it belongs to across navigation, and a request resolving for thread A
|
||||
// must never clear (or re-enable) thread B's button.
|
||||
const [unsettlingThreadKey, setUnsettlingThreadKey] = useState<string | null>(null);
|
||||
const isUnsettling = unsettlingThreadKey !== null && unsettlingThreadKey === activeThreadKey;
|
||||
const handleUnsettleActiveThread = useCallback(async () => {
|
||||
if (!activeThreadRef) return;
|
||||
const threadKey = scopedThreadKey(activeThreadRef);
|
||||
setUnsettlingThreadKey(threadKey);
|
||||
try {
|
||||
const result = await unsettleThreadMutation({
|
||||
environmentId: activeThreadRef.environmentId,
|
||||
input: { threadId: activeThreadRef.threadId, reason: "user" },
|
||||
});
|
||||
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to un-settle thread",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
setUnsettlingThreadKey((current) => (current === threadKey ? null : current));
|
||||
}
|
||||
}, [activeThreadRef, unsettleThreadMutation]);
|
||||
const [isRestoringThreadBranch, setIsRestoringThreadBranch] = useState(false);
|
||||
const [branchRestoreConfirmOpen, setBranchRestoreConfirmOpen] = useState(false);
|
||||
// Once revealed for a given mismatch, the banner stays mounted until the
|
||||
// mismatch changes or resolves, so clearing the draft doesn't flicker it.
|
||||
const [revealedBranchMismatchKey, setRevealedBranchMismatchKey] = useState<string | null>(null);
|
||||
// Dismissal lives in a module-level set (survives remounts); this tick just
|
||||
// forces a re-render so the banner leaves immediately.
|
||||
const [, setBranchMismatchDismissTick] = useState(0);
|
||||
const composerHasDraftContent = useComposerDraftStore((store) => {
|
||||
const draft = store.getComposerDraft(composerDraftTarget);
|
||||
return Boolean(
|
||||
draft &&
|
||||
(draft.prompt.trim().length > 0 ||
|
||||
draft.images.length > 0 ||
|
||||
draft.terminalContexts.length > 0 ||
|
||||
draft.elementContexts.length > 0 ||
|
||||
draft.previewAnnotations.length > 0 ||
|
||||
draft.reviewComments.length > 0),
|
||||
);
|
||||
});
|
||||
const activeBranchMismatchKey = branchMismatchKey(
|
||||
activeThread?.id ?? null,
|
||||
localCheckoutBranchMismatch,
|
||||
);
|
||||
const showBranchMismatchBanner = shouldShowBranchMismatchBanner({
|
||||
hasMismatch: localCheckoutBranchMismatch !== null,
|
||||
isDismissed: isBranchMismatchDismissedForSession(activeBranchMismatchKey),
|
||||
composerHasContent: composerHasDraftContent,
|
||||
wasShownForCurrentMismatch:
|
||||
revealedBranchMismatchKey !== null && revealedBranchMismatchKey === activeBranchMismatchKey,
|
||||
});
|
||||
useEffect(() => {
|
||||
setRevealedBranchMismatchKey((revealed) => {
|
||||
if (showBranchMismatchBanner) {
|
||||
return activeBranchMismatchKey;
|
||||
}
|
||||
// Hysteresis is scoped to an uninterrupted mismatch: reset when the
|
||||
// mismatch resolves or changes so a recurrence re-gates on intent.
|
||||
return revealed !== null && revealed !== activeBranchMismatchKey ? null : revealed;
|
||||
});
|
||||
}, [activeBranchMismatchKey, showBranchMismatchBanner]);
|
||||
const handleSwitchCheckoutToThread = useCallback(async () => {
|
||||
if (
|
||||
!activeProjectCwd ||
|
||||
!activeThread ||
|
||||
!localCheckoutBranchMismatch ||
|
||||
isRestoringThreadBranch
|
||||
) {
|
||||
return;
|
||||
}
|
||||
setIsRestoringThreadBranch(true);
|
||||
const checkoutResult = await switchGitRef({
|
||||
environmentId,
|
||||
input: {
|
||||
cwd: activeProjectCwd,
|
||||
refName: localCheckoutBranchMismatch.threadBranch,
|
||||
},
|
||||
});
|
||||
if (checkoutResult._tag === "Failure") {
|
||||
setIsRestoringThreadBranch(false);
|
||||
if (!isAtomCommandInterrupted(checkoutResult)) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to switch checkout",
|
||||
description: chatActionErrorMessage(squashAtomCommandFailure(checkoutResult)),
|
||||
}),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const nextBranch = checkoutResult.value.refName ?? localCheckoutBranchMismatch.threadBranch;
|
||||
if (nextBranch !== activeThread.branch) {
|
||||
const updateResult = await updateThreadMetadata({
|
||||
environmentId,
|
||||
input: { threadId: activeThread.id, branch: nextBranch, worktreePath: null },
|
||||
});
|
||||
if (updateResult._tag === "Failure") {
|
||||
setIsRestoringThreadBranch(false);
|
||||
if (!isAtomCommandInterrupted(updateResult)) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Checkout switched, but the thread could not be updated",
|
||||
description: chatActionErrorMessage(squashAtomCommandFailure(updateResult)),
|
||||
}),
|
||||
);
|
||||
}
|
||||
gitStatusQuery.refresh();
|
||||
return;
|
||||
}
|
||||
}
|
||||
gitStatusQuery.refresh();
|
||||
setIsRestoringThreadBranch(false);
|
||||
scheduleComposerFocus();
|
||||
}, [
|
||||
activeProjectCwd,
|
||||
activeThread,
|
||||
environmentId,
|
||||
gitStatusQuery,
|
||||
isRestoringThreadBranch,
|
||||
localCheckoutBranchMismatch,
|
||||
scheduleComposerFocus,
|
||||
switchGitRef,
|
||||
updateThreadMetadata,
|
||||
]);
|
||||
// The stack renders items[0] front-most and tucks the rest behind hover, so
|
||||
// ordering is priority: system banners, then the branch-mismatch notice,
|
||||
// and the informational settled banner last — it must never cover another.
|
||||
const settledComposerBannerItem = useMemo<ComposerBannerStackItem | null>(() => {
|
||||
if (!activeThreadSettled) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
id: `thread-settled:${activeThread?.id ?? "unknown"}`,
|
||||
variant: "info",
|
||||
icon: <CheckCircle2Icon />,
|
||||
title: "This thread is settled",
|
||||
description: "Sending a message moves it back to Active in the sidebar.",
|
||||
actions: (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={isUnsettling}
|
||||
onClick={() => void handleUnsettleActiveThread()}
|
||||
>
|
||||
{isUnsettling ? "Un-settling..." : "Un-settle"}
|
||||
</Button>
|
||||
),
|
||||
};
|
||||
}, [activeThread?.id, activeThreadSettled, handleUnsettleActiveThread, isUnsettling]);
|
||||
const handleRestoreThreadBranch = useCallback(() => {
|
||||
if (gitStatusQuery.data?.hasWorkingTreeChanges) {
|
||||
setBranchRestoreConfirmOpen(true);
|
||||
return;
|
||||
}
|
||||
void handleSwitchCheckoutToThread();
|
||||
}, [gitStatusQuery.data?.hasWorkingTreeChanges, handleSwitchCheckoutToThread]);
|
||||
const composerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {
|
||||
const settledItems = settledComposerBannerItem === null ? [] : [settledComposerBannerItem];
|
||||
if (!localCheckoutBranchMismatch || !showBranchMismatchBanner || !activeBranchMismatchKey) {
|
||||
return [...systemComposerBannerItems, ...settledItems];
|
||||
}
|
||||
return [
|
||||
...systemComposerBannerItems,
|
||||
{
|
||||
id: `branch-mismatch:${activeBranchMismatchKey}`,
|
||||
variant: "info",
|
||||
icon: <GitBranchIcon />,
|
||||
title: (
|
||||
<span className="flex min-w-0 items-baseline gap-1.5">
|
||||
<span className="shrink-0 font-normal text-muted-foreground">Branch changed — was</span>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<code className="min-w-0 truncate font-medium text-foreground">
|
||||
{localCheckoutBranchMismatch.threadBranch}
|
||||
</code>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top" className="max-w-80">
|
||||
This thread last ran on {localCheckoutBranchMismatch.threadBranch}. Sending will
|
||||
continue on {localCheckoutBranchMismatch.currentBranch}.
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</span>
|
||||
),
|
||||
className: "dark:shadow-none",
|
||||
actions: (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
disabled={isRestoringThreadBranch}
|
||||
onClick={handleRestoreThreadBranch}
|
||||
>
|
||||
{isRestoringThreadBranch ? "Restoring..." : "Restore branch"}
|
||||
</Button>
|
||||
),
|
||||
dismissLabel: "Dismiss branch change notice",
|
||||
onDismiss: () => {
|
||||
dismissBranchMismatchForSession(activeBranchMismatchKey);
|
||||
setBranchMismatchDismissTick((tick) => tick + 1);
|
||||
},
|
||||
},
|
||||
...settledItems,
|
||||
];
|
||||
}, [
|
||||
activeBranchMismatchKey,
|
||||
handleRestoreThreadBranch,
|
||||
isRestoringThreadBranch,
|
||||
localCheckoutBranchMismatch,
|
||||
settledComposerBannerItem,
|
||||
showBranchMismatchBanner,
|
||||
systemComposerBannerItems,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
setPendingServerThreadEnvMode(null);
|
||||
@@ -4635,9 +4292,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
threadId: threadIdForSend,
|
||||
createdAt: messageCreatedAt,
|
||||
...(ctxSelectedModel ? { modelSelection: ctxSelectedModelSelection } : {}),
|
||||
...(localCheckoutBranchMismatch
|
||||
? { branch: localCheckoutBranchMismatch.currentBranch }
|
||||
: {}),
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
});
|
||||
@@ -5019,9 +4673,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
threadId: threadIdForSend,
|
||||
createdAt: messageCreatedAt,
|
||||
modelSelection: ctxSelectedModelSelection,
|
||||
...(localCheckoutBranchMismatch
|
||||
? { branch: localCheckoutBranchMismatch.currentBranch }
|
||||
: {}),
|
||||
runtimeMode,
|
||||
interactionMode: nextInteractionMode,
|
||||
});
|
||||
@@ -5098,7 +4749,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
isConnecting,
|
||||
isSendBusy,
|
||||
isServerThread,
|
||||
localCheckoutBranchMismatch,
|
||||
persistThreadSettingsForNextTurn,
|
||||
resetLocalDispatch,
|
||||
runtimeMode,
|
||||
@@ -5376,7 +5026,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
envMode: mode,
|
||||
startFromOrigin: resolveNewDraftStartFromOrigin({
|
||||
envMode: mode,
|
||||
newWorktreesStartFromOrigin: primaryServerSettings.newWorktreesStartFromOrigin,
|
||||
newWorktreesStartFromOrigin: settings.newWorktreesStartFromOrigin,
|
||||
}),
|
||||
...(mode === "worktree" && draftThread?.worktreePath ? { worktreePath: null } : {}),
|
||||
});
|
||||
@@ -5388,7 +5038,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
composerDraftTarget,
|
||||
draftThread?.worktreePath,
|
||||
isLocalDraftThread,
|
||||
primaryServerSettings.newWorktreesStartFromOrigin,
|
||||
settings.newWorktreesStartFromOrigin,
|
||||
setPendingServerThreadEnvMode,
|
||||
scheduleComposerFocus,
|
||||
setDraftThreadContext,
|
||||
@@ -5600,10 +5250,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
<div className="relative flex min-h-0 min-w-0 flex-1 flex-col">
|
||||
{/* Provider status overlays the timeline without changing its content height. */}
|
||||
<div className="pointer-events-none absolute inset-x-0 top-0 z-20">
|
||||
<ProviderStatusBanner
|
||||
status={visibleProviderStatus}
|
||||
onDismiss={() => setDismissedProviderStatusBannerKey(providerStatusBannerKey)}
|
||||
/>
|
||||
<ProviderStatusBanner status={activeProviderStatus} />
|
||||
</div>
|
||||
{/* Messages Wrapper */}
|
||||
<div className="relative flex min-h-0 flex-1 flex-col">
|
||||
@@ -5678,7 +5325,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
ref={attachDraftHeroTransitionGroupRef}
|
||||
className="chat-composer-horizontal-inset w-full"
|
||||
>
|
||||
<div className="pointer-events-auto relative z-10">
|
||||
<div className="pointer-events-auto relative z-10 isolate">
|
||||
{isDraftHeroState ? (
|
||||
<div className="absolute inset-x-0 bottom-full z-0">
|
||||
<div
|
||||
@@ -5710,168 +5357,129 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"chat-composer-glass-shell relative mx-auto w-full max-w-3xl",
|
||||
showComposerContextStrip && "chat-composer-glass-shell-with-context",
|
||||
)}
|
||||
ref={attachDraftHeroComposerAnchorRef}
|
||||
className="relative z-10 isolate mx-auto w-full max-w-3xl before:pointer-events-none before:absolute before:inset-x-0 before:bottom-0 before:-z-10 before:h-2 before:rounded-b-[22px] before:bg-background"
|
||||
>
|
||||
<div className="chat-composer-glass-host relative z-10 w-full rounded-[22px]">
|
||||
<div ref={attachDraftHeroComposerAnchorRef} className="relative z-10">
|
||||
<ChatComposer
|
||||
composerRef={composerRef}
|
||||
composerDraftTarget={composerDraftTarget}
|
||||
environmentId={environmentId}
|
||||
routeKind={routeKind}
|
||||
routeThreadRef={routeThreadRef}
|
||||
draftId={draftId}
|
||||
activeThreadId={activeThreadId}
|
||||
activeThreadEnvironmentId={activeThread?.environmentId}
|
||||
activeThread={activeThread}
|
||||
isServerThread={isServerThread}
|
||||
isLocalDraftThread={isLocalDraftThread}
|
||||
forceExpandedOnMobile={forceExpandedMobileComposer && isDraftHeroState}
|
||||
projectSelectionRequired={isLocalDraftThread && activeProject === null}
|
||||
phase={phase}
|
||||
isConnecting={isConnecting}
|
||||
isSendBusy={isSendBusy}
|
||||
isPreparingWorktree={isPreparingWorktree}
|
||||
environmentUnavailable={activeEnvironmentUnavailableState}
|
||||
activePendingApproval={activePendingApproval}
|
||||
pendingApprovals={pendingApprovals}
|
||||
pendingUserInputs={pendingUserInputs}
|
||||
activePendingProgress={activePendingProgress}
|
||||
activePendingResolvedAnswers={activePendingResolvedAnswers}
|
||||
activePendingIsResponding={activePendingIsResponding}
|
||||
activePendingDraftAnswers={activePendingDraftAnswers}
|
||||
activePendingQuestionIndex={activePendingQuestionIndex}
|
||||
respondingRequestIds={respondingRequestIds}
|
||||
showPlanFollowUpPrompt={showPlanFollowUpPrompt}
|
||||
activeProposedPlan={activeProposedPlan}
|
||||
activePlan={activePlan as { turnId?: TurnId } | null}
|
||||
sidebarProposedPlan={sidebarProposedPlan as { turnId?: TurnId } | null}
|
||||
planSidebarLabel={planSidebarLabel}
|
||||
planSidebarOpen={planSidebarOpen}
|
||||
runtimeMode={runtimeMode}
|
||||
interactionMode={interactionMode}
|
||||
lockedProvider={lockedProvider}
|
||||
providerStatuses={providerStatuses as ServerProvider[]}
|
||||
activeProjectDefaultModelSelection={
|
||||
activeProject?.defaultModelSelection
|
||||
}
|
||||
activeThreadModelSelection={activeThread?.modelSelection}
|
||||
activeThreadActivities={activeThread?.activities}
|
||||
resolvedTheme={resolvedTheme}
|
||||
settings={settings}
|
||||
keybindings={keybindings}
|
||||
terminalOpen={Boolean(terminalUiState.terminalOpen)}
|
||||
gitCwd={gitCwd}
|
||||
promptRef={promptRef}
|
||||
composerImagesRef={composerImagesRef}
|
||||
composerTerminalContextsRef={composerTerminalContextsRef}
|
||||
composerElementContextsRef={composerElementContextsRef}
|
||||
onSend={onSend}
|
||||
onInterrupt={onInterrupt}
|
||||
onImplementPlanInNewThread={onImplementPlanInNewThread}
|
||||
onRespondToApproval={onRespondToApproval}
|
||||
onSelectActivePendingUserInputOption={
|
||||
onSelectActivePendingUserInputOption
|
||||
}
|
||||
onAdvanceActivePendingUserInput={onAdvanceActivePendingUserInput}
|
||||
onPreviousActivePendingUserInputQuestion={
|
||||
onPreviousActivePendingUserInputQuestion
|
||||
}
|
||||
onChangeActivePendingUserInputCustomAnswer={
|
||||
onChangeActivePendingUserInputCustomAnswer
|
||||
}
|
||||
onProviderModelSelect={onProviderModelSelect}
|
||||
getModelDisabledReason={getModelDisabledReason}
|
||||
toggleInteractionMode={toggleInteractionMode}
|
||||
handleRuntimeModeChange={handleRuntimeModeChange}
|
||||
handleInteractionModeChange={handleInteractionModeChange}
|
||||
togglePlanSidebar={togglePlanSidebar}
|
||||
focusComposer={focusComposer}
|
||||
scheduleComposerFocus={scheduleComposerFocus}
|
||||
setThreadError={setThreadError}
|
||||
onExpandImage={onExpandTimelineImage}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="min-h-0">
|
||||
<div
|
||||
data-terminal-open={terminalUiState.terminalOpen ? "true" : undefined}
|
||||
className="relative z-0"
|
||||
>
|
||||
{showComposerContextStrip && (
|
||||
<div className="pointer-events-auto">
|
||||
<BranchToolbar
|
||||
environmentId={activeThread.environmentId}
|
||||
threadId={activeThread.id}
|
||||
{...(routeKind === "draft" && draftId ? { draftId } : {})}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
startFromOrigin={startFromOrigin}
|
||||
onStartFromOriginChange={onStartFromOriginChange}
|
||||
{...(canOverrideServerThreadEnvMode
|
||||
? { effectiveEnvModeOverride: envMode }
|
||||
: {})}
|
||||
{...(canOverrideServerThreadEnvMode
|
||||
? {
|
||||
activeThreadBranchOverride: activeThreadBranch,
|
||||
onActiveThreadBranchOverrideChange:
|
||||
setPendingServerThreadBranch,
|
||||
}
|
||||
: {})}
|
||||
envLocked={envLocked}
|
||||
onComposerFocusRequest={scheduleComposerFocus}
|
||||
{...(canCheckoutPullRequestIntoThread
|
||||
? { onCheckoutPullRequestRequest: openPullRequestDialog }
|
||||
: {})}
|
||||
{...(hasMultipleEnvironments ? { onEnvironmentChange } : {})}
|
||||
availableEnvironments={logicalProjectEnvironments}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<ChatComposer
|
||||
composerRef={composerRef}
|
||||
composerDraftTarget={composerDraftTarget}
|
||||
environmentId={environmentId}
|
||||
routeKind={routeKind}
|
||||
routeThreadRef={routeThreadRef}
|
||||
draftId={draftId}
|
||||
activeThreadId={activeThreadId}
|
||||
activeThreadEnvironmentId={activeThread?.environmentId}
|
||||
activeThread={activeThread}
|
||||
isServerThread={isServerThread}
|
||||
isLocalDraftThread={isLocalDraftThread}
|
||||
forceExpandedOnMobile={forceExpandedMobileComposer && isDraftHeroState}
|
||||
projectSelectionRequired={isLocalDraftThread && activeProject === null}
|
||||
phase={phase}
|
||||
isConnecting={isConnecting}
|
||||
isSendBusy={isSendBusy}
|
||||
isPreparingWorktree={isPreparingWorktree}
|
||||
environmentUnavailable={activeEnvironmentUnavailableState}
|
||||
activePendingApproval={activePendingApproval}
|
||||
pendingApprovals={pendingApprovals}
|
||||
pendingUserInputs={pendingUserInputs}
|
||||
activePendingProgress={activePendingProgress}
|
||||
activePendingResolvedAnswers={activePendingResolvedAnswers}
|
||||
activePendingIsResponding={activePendingIsResponding}
|
||||
activePendingDraftAnswers={activePendingDraftAnswers}
|
||||
activePendingQuestionIndex={activePendingQuestionIndex}
|
||||
respondingRequestIds={respondingRequestIds}
|
||||
showPlanFollowUpPrompt={showPlanFollowUpPrompt}
|
||||
activeProposedPlan={activeProposedPlan}
|
||||
activePlan={activePlan as { turnId?: TurnId } | null}
|
||||
sidebarProposedPlan={sidebarProposedPlan as { turnId?: TurnId } | null}
|
||||
planSidebarLabel={planSidebarLabel}
|
||||
planSidebarOpen={planSidebarOpen}
|
||||
runtimeMode={runtimeMode}
|
||||
interactionMode={interactionMode}
|
||||
lockedProvider={lockedProvider}
|
||||
providerStatuses={providerStatuses as ServerProvider[]}
|
||||
activeProjectDefaultModelSelection={activeProject?.defaultModelSelection}
|
||||
activeThreadModelSelection={activeThread?.modelSelection}
|
||||
activeThreadActivities={activeThread?.activities}
|
||||
resolvedTheme={resolvedTheme}
|
||||
settings={settings}
|
||||
keybindings={keybindings}
|
||||
terminalOpen={Boolean(terminalUiState.terminalOpen)}
|
||||
gitCwd={gitCwd}
|
||||
promptRef={promptRef}
|
||||
composerImagesRef={composerImagesRef}
|
||||
composerTerminalContextsRef={composerTerminalContextsRef}
|
||||
composerElementContextsRef={composerElementContextsRef}
|
||||
onSend={onSend}
|
||||
onInterrupt={onInterrupt}
|
||||
onImplementPlanInNewThread={onImplementPlanInNewThread}
|
||||
onRespondToApproval={onRespondToApproval}
|
||||
onSelectActivePendingUserInputOption={onSelectActivePendingUserInputOption}
|
||||
onAdvanceActivePendingUserInput={onAdvanceActivePendingUserInput}
|
||||
onPreviousActivePendingUserInputQuestion={
|
||||
onPreviousActivePendingUserInputQuestion
|
||||
}
|
||||
onChangeActivePendingUserInputCustomAnswer={
|
||||
onChangeActivePendingUserInputCustomAnswer
|
||||
}
|
||||
onProviderModelSelect={onProviderModelSelect}
|
||||
getModelDisabledReason={getModelDisabledReason}
|
||||
toggleInteractionMode={toggleInteractionMode}
|
||||
handleRuntimeModeChange={handleRuntimeModeChange}
|
||||
handleInteractionModeChange={handleInteractionModeChange}
|
||||
togglePlanSidebar={togglePlanSidebar}
|
||||
focusComposer={focusComposer}
|
||||
scheduleComposerFocus={scheduleComposerFocus}
|
||||
setThreadError={setThreadError}
|
||||
onExpandImage={onExpandTimelineImage}
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
aria-hidden
|
||||
className="h-[calc(env(safe-area-inset-bottom)+1rem)] sm:h-[calc(env(safe-area-inset-bottom)+1.25rem)]"
|
||||
/>
|
||||
className={cn(
|
||||
"min-h-0",
|
||||
isDraftHeroState ? "absolute inset-x-0 top-full" : null,
|
||||
)}
|
||||
>
|
||||
<div
|
||||
data-terminal-open={terminalUiState.terminalOpen ? "true" : undefined}
|
||||
className="chat-composer-lower-chrome relative z-0 pb-[calc(env(safe-area-inset-bottom)+1rem)] sm:pb-[calc(env(safe-area-inset-bottom)+1.25rem)]"
|
||||
>
|
||||
{isGitRepo && (
|
||||
<div className="pointer-events-auto">
|
||||
<BranchToolbar
|
||||
environmentId={activeThread.environmentId}
|
||||
threadId={activeThread.id}
|
||||
{...(routeKind === "draft" && draftId ? { draftId } : {})}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
startFromOrigin={startFromOrigin}
|
||||
onStartFromOriginChange={onStartFromOriginChange}
|
||||
{...(canOverrideServerThreadEnvMode
|
||||
? { effectiveEnvModeOverride: envMode }
|
||||
: {})}
|
||||
{...(canOverrideServerThreadEnvMode
|
||||
? {
|
||||
activeThreadBranchOverride: activeThreadBranch,
|
||||
onActiveThreadBranchOverrideChange:
|
||||
setPendingServerThreadBranch,
|
||||
}
|
||||
: {})}
|
||||
envLocked={envLocked}
|
||||
onComposerFocusRequest={scheduleComposerFocus}
|
||||
{...(canCheckoutPullRequestIntoThread
|
||||
? { onCheckoutPullRequestRequest: openPullRequestDialog }
|
||||
: {})}
|
||||
{...(hasMultipleEnvironments ? { onEnvironmentChange } : {})}
|
||||
availableEnvironments={logicalProjectEnvironments}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<AlertDialog open={branchRestoreConfirmOpen} onOpenChange={setBranchRestoreConfirmOpen}>
|
||||
<AlertDialogPopup>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
Switch to{" "}
|
||||
<code className="font-medium">
|
||||
{localCheckoutBranchMismatch?.threadBranch ?? ""}
|
||||
</code>
|
||||
?
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
You have uncommitted changes. They'll carry over to the other branch, or block
|
||||
the switch if they conflict.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
|
||||
<Button
|
||||
variant="default"
|
||||
onClick={() => {
|
||||
setBranchRestoreConfirmOpen(false);
|
||||
void handleSwitchCheckoutToThread();
|
||||
}}
|
||||
>
|
||||
Switch branch
|
||||
</Button>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogPopup>
|
||||
</AlertDialog>
|
||||
|
||||
{pullRequestDialogState ? (
|
||||
<PullRequestThreadDialog
|
||||
key={pullRequestDialogState.key}
|
||||
|
||||
@@ -111,13 +111,12 @@ export function buildProjectActionItems(input: {
|
||||
valuePrefix: string;
|
||||
icon: (project: Project) => ReactNode;
|
||||
runProject: (project: Project) => Promise<void>;
|
||||
searchTerms?: (project: Project) => ReadonlyArray<string>;
|
||||
shortcutCommand?: KeybindingCommand;
|
||||
}): CommandPaletteActionItem[] {
|
||||
return input.projects.map((project) => ({
|
||||
kind: "action",
|
||||
value: `${input.valuePrefix}:${project.environmentId}:${project.id}`,
|
||||
searchTerms: [project.title, project.workspaceRoot, ...(input.searchTerms?.(project) ?? [])],
|
||||
searchTerms: [project.title, project.workspaceRoot],
|
||||
title: project.title,
|
||||
description: project.workspaceRoot,
|
||||
icon: input.icon(project),
|
||||
|
||||
@@ -56,9 +56,12 @@ import { useEnvironmentQuery } from "../state/query";
|
||||
import { sourceControlEnvironment } from "../state/sourceControl";
|
||||
import { useAtomCommand } from "../state/use-atom-command";
|
||||
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
|
||||
import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
|
||||
import { useEnvironments, usePrimaryEnvironment } from "../state/environments";
|
||||
import { useProjects, useThreadShells } from "../state/entities";
|
||||
import { resolveThreadActionProjectRef, startNewThreadFromContext } from "../lib/chatThreadActions";
|
||||
import {
|
||||
startNewThreadInProjectFromContext,
|
||||
startNewThreadFromContext,
|
||||
} from "../lib/chatThreadActions";
|
||||
import {
|
||||
appendBrowsePathSegment,
|
||||
canNavigateUp,
|
||||
@@ -76,7 +79,7 @@ import {
|
||||
} from "../lib/projectPaths";
|
||||
import { onOpenCommandPalette } from "../commandPaletteBus";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import { getLatestThreadForProject, sortThreads } from "../lib/threadSort";
|
||||
import { getLatestThreadForProject } from "../lib/threadSort";
|
||||
import { cn, isMacPlatform, isWindowsPlatform, newProjectId } from "../lib/utils";
|
||||
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
|
||||
import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";
|
||||
@@ -103,7 +106,6 @@ import {
|
||||
ITEM_ICON_CLASS,
|
||||
RECENT_THREAD_LIMIT,
|
||||
} from "./CommandPalette.logic";
|
||||
import { orderItemsByPreferredIds, sortLogicalProjectsForSidebar } from "./Sidebar.logic";
|
||||
import { resolveEnvironmentOptionLabel } from "./BranchToolbar.logic";
|
||||
import { CommandPaletteResults } from "./CommandPaletteResults";
|
||||
import { AzureDevOpsIcon, BitbucketIcon, GitHubIcon, GitLabIcon } from "./Icons";
|
||||
@@ -126,12 +128,6 @@ import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
import { ComposerHandleContext, useComposerHandleContext } from "../composerHandleContext";
|
||||
import type { ChatComposerHandle } from "./chat/ChatComposer";
|
||||
import { getProjectOrderKey, selectProjectGroupingSettings } from "../logicalProject";
|
||||
import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";
|
||||
import {
|
||||
buildSidebarProjectPickerEntries,
|
||||
buildSidebarProjectSnapshots,
|
||||
} from "../sidebarProjectGrouping";
|
||||
|
||||
const EMPTY_BROWSE_ENTRIES: FilesystemBrowseResult["entries"] = [];
|
||||
|
||||
@@ -491,11 +487,10 @@ function OpenCommandPaletteDialog(props: {
|
||||
});
|
||||
const { environments } = useEnvironments();
|
||||
const desktopLocalBootstraps = useDesktopLocalBootstraps();
|
||||
const primaryEnvironmentId = usePrimaryEnvironmentId();
|
||||
const primaryEnvironment = usePrimaryEnvironment();
|
||||
const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread } =
|
||||
useHandleNewThread();
|
||||
const projects = useProjects();
|
||||
const projectOrder = useUiStateStore((store) => store.projectOrder);
|
||||
const threads = useThreadShells();
|
||||
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
|
||||
const providers = useAtomValue(primaryServerProvidersAtom);
|
||||
@@ -509,93 +504,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
const [addProjectCloneFlow, setAddProjectCloneFlow] = useState<AddProjectCloneFlow | null>(null);
|
||||
const [isRemoteProjectLookingUp, setIsRemoteProjectLookingUp] = useState(false);
|
||||
const [isRemoteProjectCloning, setIsRemoteProjectCloning] = useState(false);
|
||||
const projectGroupingSettings = useMemo(
|
||||
() => selectProjectGroupingSettings(clientSettings),
|
||||
[clientSettings],
|
||||
);
|
||||
|
||||
const environmentLabelById = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
environments.map((environment) => [environment.environmentId, environment.label] as const),
|
||||
),
|
||||
[environments],
|
||||
);
|
||||
const orderedProjects = useMemo(
|
||||
() =>
|
||||
orderItemsByPreferredIds({
|
||||
items: projects,
|
||||
preferredIds: projectOrder,
|
||||
getId: getProjectOrderKey,
|
||||
getPreferenceIds: (project) => [
|
||||
getProjectOrderKey(project),
|
||||
legacyProjectCwdPreferenceKey(project.workspaceRoot),
|
||||
],
|
||||
}),
|
||||
[projectOrder, projects],
|
||||
);
|
||||
const unsortedProjectGroups = useMemo(
|
||||
() =>
|
||||
buildSidebarProjectSnapshots({
|
||||
projects: clientSettings.sidebarProjectSortOrder === "manual" ? orderedProjects : projects,
|
||||
settings: projectGroupingSettings,
|
||||
primaryEnvironmentId,
|
||||
resolveEnvironmentLabel: (environmentId) => environmentLabelById.get(environmentId) ?? null,
|
||||
}),
|
||||
[
|
||||
clientSettings.sidebarProjectSortOrder,
|
||||
environmentLabelById,
|
||||
orderedProjects,
|
||||
primaryEnvironmentId,
|
||||
projectGroupingSettings,
|
||||
projects,
|
||||
],
|
||||
);
|
||||
const projectGroups = useMemo(
|
||||
() =>
|
||||
sortLogicalProjectsForSidebar(
|
||||
unsortedProjectGroups,
|
||||
threads,
|
||||
clientSettings.sidebarProjectSortOrder,
|
||||
),
|
||||
[clientSettings.sidebarProjectSortOrder, threads, unsortedProjectGroups],
|
||||
);
|
||||
const contextualProjectRef = useMemo(
|
||||
() =>
|
||||
resolveThreadActionProjectRef({
|
||||
activeDraftThread,
|
||||
activeThread: activeThread ?? undefined,
|
||||
defaultProjectRef,
|
||||
handleNewThread,
|
||||
}),
|
||||
[activeDraftThread, activeThread, defaultProjectRef, handleNewThread],
|
||||
);
|
||||
const projectPickerEntries = useMemo(
|
||||
() =>
|
||||
buildSidebarProjectPickerEntries({
|
||||
groups: projectGroups,
|
||||
preferredProjectRef: contextualProjectRef,
|
||||
}),
|
||||
[contextualProjectRef, projectGroups],
|
||||
);
|
||||
const pickerProjects = useMemo(
|
||||
() =>
|
||||
projectPickerEntries.map(({ group, targetProject }) => ({
|
||||
...targetProject,
|
||||
title: group.displayName,
|
||||
})),
|
||||
[projectPickerEntries],
|
||||
);
|
||||
const projectGroupByTargetKey = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
projectPickerEntries.map(({ group, targetProject }) => [
|
||||
`${targetProject.environmentId}:${targetProject.id}`,
|
||||
group,
|
||||
]),
|
||||
),
|
||||
[projectPickerEntries],
|
||||
);
|
||||
const primaryEnvironmentId = primaryEnvironment?.environmentId ?? null;
|
||||
|
||||
const addProjectEnvironmentOptions = useMemo(() => {
|
||||
const options = environments.map((environment): AddProjectEnvironmentOption => {
|
||||
@@ -739,28 +648,11 @@ function OpenCommandPaletteDialog(props: {
|
||||
|
||||
const openProjectFromSearch = useMemo(
|
||||
() => async (project: (typeof projects)[number]) => {
|
||||
const group = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`);
|
||||
const groupedProjectKeys = group
|
||||
? new Set(
|
||||
group.memberProjectRefs.map(
|
||||
(projectRef) => `${projectRef.environmentId}:${projectRef.projectId}`,
|
||||
),
|
||||
)
|
||||
: null;
|
||||
const latestThread = groupedProjectKeys
|
||||
? (sortThreads(
|
||||
threads.filter(
|
||||
(thread) =>
|
||||
thread.archivedAt === null &&
|
||||
groupedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`),
|
||||
),
|
||||
clientSettings.sidebarThreadSortOrder,
|
||||
)[0] ?? null)
|
||||
: getLatestThreadForProject(
|
||||
threads.filter((thread) => thread.environmentId === project.environmentId),
|
||||
project.id,
|
||||
clientSettings.sidebarThreadSortOrder,
|
||||
);
|
||||
const latestThread = getLatestThreadForProject(
|
||||
threads.filter((thread) => thread.environmentId === project.environmentId),
|
||||
project.id,
|
||||
clientSettings.sidebarThreadSortOrder,
|
||||
);
|
||||
if (latestThread) {
|
||||
await navigate({
|
||||
to: "/$environmentId/$threadId",
|
||||
@@ -773,26 +665,14 @@ function OpenCommandPaletteDialog(props: {
|
||||
|
||||
await handleNewThread(scopeProjectRef(project.environmentId, project.id));
|
||||
},
|
||||
[
|
||||
clientSettings.sidebarThreadSortOrder,
|
||||
handleNewThread,
|
||||
navigate,
|
||||
projectGroupByTargetKey,
|
||||
threads,
|
||||
],
|
||||
[handleNewThread, navigate, clientSettings.sidebarThreadSortOrder, threads],
|
||||
);
|
||||
|
||||
const projectSearchItems = useMemo(
|
||||
() =>
|
||||
buildProjectActionItems({
|
||||
projects: pickerProjects,
|
||||
projects,
|
||||
valuePrefix: "project",
|
||||
searchTerms: (project) => {
|
||||
const group = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`);
|
||||
return (
|
||||
group?.memberProjects.flatMap((member) => [member.title, member.workspaceRoot]) ?? []
|
||||
);
|
||||
},
|
||||
icon: (project) => (
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
@@ -802,21 +682,15 @@ function OpenCommandPaletteDialog(props: {
|
||||
),
|
||||
runProject: openProjectFromSearch,
|
||||
}),
|
||||
[openProjectFromSearch, pickerProjects, projectGroupByTargetKey],
|
||||
[openProjectFromSearch, projects],
|
||||
);
|
||||
|
||||
const projectThreadItems = useMemo(
|
||||
() =>
|
||||
enumerateCommandPaletteItems(
|
||||
buildProjectActionItems({
|
||||
projects: pickerProjects,
|
||||
projects,
|
||||
valuePrefix: "new-thread-in",
|
||||
searchTerms: (project) => {
|
||||
const group = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`);
|
||||
return (
|
||||
group?.memberProjects.flatMap((member) => [member.title, member.workspaceRoot]) ?? []
|
||||
);
|
||||
},
|
||||
icon: (project) => (
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
@@ -825,23 +699,19 @@ function OpenCommandPaletteDialog(props: {
|
||||
/>
|
||||
),
|
||||
runProject: async (project) => {
|
||||
const group = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`);
|
||||
const contextualRefBelongsToGroup =
|
||||
contextualProjectRef !== null &&
|
||||
group?.memberProjectRefs.some(
|
||||
(projectRef) =>
|
||||
projectRef.environmentId === contextualProjectRef.environmentId &&
|
||||
projectRef.projectId === contextualProjectRef.projectId,
|
||||
);
|
||||
await handleNewThread(
|
||||
contextualRefBelongsToGroup
|
||||
? contextualProjectRef
|
||||
: scopeProjectRef(project.environmentId, project.id),
|
||||
await startNewThreadInProjectFromContext(
|
||||
{
|
||||
activeDraftThread,
|
||||
activeThread: activeThread ?? undefined,
|
||||
defaultProjectRef,
|
||||
handleNewThread,
|
||||
},
|
||||
scopeProjectRef(project.environmentId, project.id),
|
||||
);
|
||||
},
|
||||
}),
|
||||
),
|
||||
[contextualProjectRef, handleNewThread, pickerProjects, projectGroupByTargetKey],
|
||||
[activeDraftThread, activeThread, defaultProjectRef, handleNewThread, projects],
|
||||
);
|
||||
|
||||
const allThreadItems = useMemo(
|
||||
@@ -1148,9 +1018,9 @@ function OpenCommandPaletteDialog(props: {
|
||||
const actionItems: Array<CommandPaletteActionItem | CommandPaletteSubmenuItem> = [];
|
||||
|
||||
if (projects.length > 0) {
|
||||
const activeProjectTitle =
|
||||
projectPickerEntries.find((entry) => entry.isPreferred)?.group.displayName ??
|
||||
(currentProjectId ? (projectTitleById.get(currentProjectId) ?? null) : null);
|
||||
const activeProjectTitle = currentProjectId
|
||||
? (projectTitleById.get(currentProjectId) ?? null)
|
||||
: null;
|
||||
|
||||
if (activeProjectTitle) {
|
||||
actionItems.push({
|
||||
|
||||
@@ -544,9 +544,9 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
|
||||
|
||||
return (
|
||||
<Dialog open={props.open} onOpenChange={handleOpenChange}>
|
||||
<DialogPopup className="max-w-xl overflow-hidden">
|
||||
<DialogPopup className="workflow-dialog-surface max-w-xl overflow-hidden before:hidden">
|
||||
<div className="flex min-h-0 flex-col overflow-hidden border-foreground/10 bg-transparent">
|
||||
<DialogHeader className="border-b border-border/70 bg-foreground/[0.025] dark:border-transparent dark:bg-transparent">
|
||||
<DialogHeader className="border-b border-border/70 bg-foreground/[0.025]">
|
||||
<DialogTitle>Publish repository</DialogTitle>
|
||||
<DialogDescription>
|
||||
Pick where to host it, then point us at a repo to push to.
|
||||
@@ -567,10 +567,10 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
|
||||
className={cn(
|
||||
"grid min-w-0 grid-cols-[1rem_minmax(0,1fr)] gap-x-2 rounded-lg border px-3 py-2 text-left",
|
||||
index === publishWizardStep
|
||||
? "border-primary bg-primary/10 ring-1 ring-primary/25 dark:border-transparent"
|
||||
? "border-primary bg-primary/10 ring-1 ring-primary/25"
|
||||
: isComplete
|
||||
? "border-border bg-background dark:border-transparent dark:bg-white/[0.05]"
|
||||
: "border-border bg-muted/40 dark:border-transparent dark:bg-white/[0.025]",
|
||||
? "border-border bg-background"
|
||||
: "border-border bg-muted/40",
|
||||
!isClickable && "cursor-default",
|
||||
)}
|
||||
>
|
||||
@@ -602,7 +602,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
|
||||
</div>
|
||||
</DialogHeader>
|
||||
|
||||
<DialogPanel className="space-y-5 border-b border-border/70 bg-muted/20 px-6 py-5 dark:border-transparent dark:bg-transparent">
|
||||
<DialogPanel className="space-y-5 border-b border-border/70 bg-muted/20 px-6 py-5">
|
||||
<AnimatedHeight>
|
||||
<div className={cn("space-y-2", publishWizardStep !== 0 && "hidden")}>
|
||||
<span
|
||||
@@ -627,7 +627,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
|
||||
return (
|
||||
<div
|
||||
key={option.value}
|
||||
className="relative flex cursor-not-allowed items-center gap-3 rounded-lg border border-border bg-background px-3 py-3 text-left opacity-55 dark:border-transparent dark:bg-white/[0.035]"
|
||||
className="relative flex cursor-not-allowed items-center gap-3 rounded-lg border border-border bg-background px-3 py-3 text-left opacity-55"
|
||||
>
|
||||
<option.Icon
|
||||
className="size-5 shrink-0 text-muted-foreground"
|
||||
@@ -670,8 +670,8 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
|
||||
"relative flex cursor-pointer items-center gap-3 rounded-lg border px-3 py-3 text-left outline-none transition-[background-color,border-color,box-shadow]",
|
||||
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
|
||||
isSelected
|
||||
? "border-primary bg-background shadow-sm ring-2 ring-primary/35 dark:border-transparent dark:bg-primary/10 dark:shadow-none dark:ring-1 dark:ring-primary/30"
|
||||
: "border-border bg-background hover:border-foreground/20 hover:bg-muted/50 dark:border-transparent dark:bg-white/[0.035] dark:hover:bg-accent",
|
||||
? "border-primary bg-background shadow-sm ring-2 ring-primary/35"
|
||||
: "border-border bg-background hover:border-foreground/20 hover:bg-muted/50",
|
||||
)}
|
||||
>
|
||||
<option.Icon className="size-5 shrink-0" aria-hidden />
|
||||
@@ -756,8 +756,8 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
|
||||
"relative flex cursor-pointer items-center gap-3 rounded-lg border px-3 py-2.5 text-left outline-none transition-[background-color,border-color,box-shadow]",
|
||||
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
|
||||
isSelected
|
||||
? "border-primary bg-background shadow-sm ring-2 ring-primary/35 dark:border-transparent dark:bg-primary/10 dark:shadow-none dark:ring-1 dark:ring-primary/30"
|
||||
: "border-border bg-background hover:border-foreground/20 hover:bg-muted/50 dark:border-transparent dark:bg-white/[0.035] dark:hover:bg-accent",
|
||||
? "border-primary bg-background shadow-sm ring-2 ring-primary/35"
|
||||
: "border-border bg-background hover:border-foreground/20 hover:bg-muted/50",
|
||||
)}
|
||||
>
|
||||
<option.Icon
|
||||
@@ -831,8 +831,8 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
|
||||
"rounded-md border px-3 py-1.5 text-center text-sm font-medium outline-none transition",
|
||||
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
|
||||
isSelected
|
||||
? "border-primary bg-background ring-2 ring-primary/35 text-foreground dark:border-transparent dark:bg-primary/10 dark:ring-1 dark:ring-primary/30"
|
||||
: "border-border bg-background text-muted-foreground hover:border-foreground/20 hover:text-foreground dark:border-transparent dark:bg-white/[0.035]",
|
||||
? "border-primary bg-background ring-2 ring-primary/35 text-foreground"
|
||||
: "border-border bg-background text-muted-foreground hover:border-foreground/20 hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
{value === "ssh" ? "SSH" : "HTTPS"}
|
||||
@@ -849,7 +849,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
|
||||
<div
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
className="flex items-center gap-2 rounded-md border border-input bg-muted/40 px-3 py-2 text-xs text-muted-foreground dark:border-transparent dark:bg-white/[0.035]"
|
||||
className="flex items-center gap-2 rounded-md border border-input bg-muted/40 px-3 py-2 text-xs text-muted-foreground"
|
||||
>
|
||||
<Spinner className="size-3.5" aria-hidden />
|
||||
Publishing repository to {publishProviderLabel}...
|
||||
@@ -884,7 +884,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
|
||||
: `Remote "${publishResult.remoteName}" is set up. Make a commit and push it to share your code.`}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 rounded-lg border border-input bg-muted/40 px-3 py-2 dark:border-transparent dark:bg-white/[0.035]">
|
||||
<div className="flex items-center gap-2 rounded-lg border border-input bg-muted/40 px-3 py-2">
|
||||
<currentPublishProvider.Icon className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
<span className="min-w-0 flex-1 truncate font-mono text-xs text-foreground">
|
||||
{publishResult.repository.nameWithOwner}
|
||||
@@ -905,7 +905,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<div className="rounded-md border border-input bg-background px-3 py-2 text-xs text-muted-foreground dark:border-transparent dark:bg-white/[0.035]">
|
||||
<div className="rounded-md border border-input bg-background px-3 py-2 text-xs text-muted-foreground">
|
||||
Publish result unavailable.
|
||||
</div>
|
||||
)}
|
||||
@@ -913,7 +913,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
|
||||
</AnimatedHeight>
|
||||
</DialogPanel>
|
||||
|
||||
<DialogFooter className="dark:border-transparent dark:bg-transparent">
|
||||
<DialogFooter className="dark:border-white/5 dark:bg-white/[0.025]">
|
||||
{publishWizardStep === 2 ? (
|
||||
<Button size="sm" onClick={() => handleOpenChange(false)}>
|
||||
Done
|
||||
@@ -1117,12 +1117,12 @@ export default function GitActionsControl({
|
||||
activeDraftThread.worktreePath === null;
|
||||
|
||||
useEffect(() => {
|
||||
if (isGitActionRunning || isSelectingWorktreeBase || activeServerThread) {
|
||||
if (isGitActionRunning || isSelectingWorktreeBase) {
|
||||
return;
|
||||
}
|
||||
|
||||
const branchUpdate = resolveLiveThreadBranchUpdate({
|
||||
threadBranch: activeDraftThread?.branch ?? null,
|
||||
threadBranch: activeServerThread?.branch ?? activeDraftThread?.branch ?? null,
|
||||
gitStatus: gitStatusForActions,
|
||||
});
|
||||
if (!branchUpdate) {
|
||||
@@ -1131,7 +1131,7 @@ export default function GitActionsControl({
|
||||
|
||||
persistThreadBranchSync(branchUpdate.branch);
|
||||
}, [
|
||||
activeServerThread,
|
||||
activeServerThread?.branch,
|
||||
activeDraftThread?.branch,
|
||||
gitStatusForActions,
|
||||
isGitActionRunning,
|
||||
@@ -1736,7 +1736,7 @@ export default function GitActionsControl({
|
||||
>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-4" />
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="end" className="w-full">
|
||||
<MenuPopup align="end" className="command-menu-surface w-full">
|
||||
{gitActionMenuItems.map((item) => {
|
||||
const disabledReason = getMenuActionDisabledReason({
|
||||
item,
|
||||
@@ -1825,13 +1825,13 @@ export default function GitActionsControl({
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogPopup>
|
||||
<DialogPopup className="workflow-dialog-surface before:hidden">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{COMMIT_DIALOG_TITLE}</DialogTitle>
|
||||
<DialogDescription>{COMMIT_DIALOG_DESCRIPTION}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogPanel className="space-y-4">
|
||||
<div className="space-y-3 rounded-xl bg-zinc-25 p-3 text-sm ring-1 ring-black/5 dark:bg-white/[0.035] dark:ring-white/5">
|
||||
<div className="space-y-3 rounded-lg border border-input bg-muted/40 p-3 text-xs">
|
||||
<div className="grid grid-cols-[auto_1fr] items-center gap-x-2 gap-y-1">
|
||||
<span className="text-muted-foreground">Branch</span>
|
||||
<span className="flex items-center justify-between gap-2">
|
||||
@@ -1839,7 +1839,9 @@ export default function GitActionsControl({
|
||||
{gitStatusForActions?.refName ?? "(detached HEAD)"}
|
||||
</span>
|
||||
{isDefaultRef && (
|
||||
<span className="text-right text-warning">Warning: default refName</span>
|
||||
<span className="text-right text-warning text-xs">
|
||||
Warning: default refName
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
@@ -1878,14 +1880,14 @@ export default function GitActionsControl({
|
||||
<p className="font-medium">none</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<ScrollArea className="h-44 rounded-lg bg-card ring-1 ring-black/5 dark:bg-white/[0.025] dark:ring-white/5">
|
||||
<ScrollArea className="h-44 rounded-md border border-input bg-background">
|
||||
<div className="space-y-1 p-1">
|
||||
{allFiles.map((file) => {
|
||||
const isExcluded = excludedFiles.has(file.path);
|
||||
return (
|
||||
<div
|
||||
key={file.path}
|
||||
className="flex w-full items-center gap-2 rounded-md px-2 py-1 font-mono hover:bg-accent/50"
|
||||
className="flex w-full items-center gap-2 rounded-md px-2 py-1 font-mono text-xs transition-colors hover:bg-accent/50"
|
||||
>
|
||||
{isEditingFiles && (
|
||||
<Checkbox
|
||||
@@ -1944,7 +1946,7 @@ export default function GitActionsControl({
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium">Commit message (optional)</p>
|
||||
<p className="text-xs font-medium">Commit message (optional)</p>
|
||||
<Textarea
|
||||
value={dialogCommitMessage}
|
||||
onChange={(event) => setDialogCommitMessage(event.target.value)}
|
||||
@@ -1953,7 +1955,7 @@ export default function GitActionsControl({
|
||||
/>
|
||||
</div>
|
||||
</DialogPanel>
|
||||
<DialogFooter variant="bare">
|
||||
<DialogFooter className="dark:border-white/5 dark:bg-white/[0.025]">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
@@ -1996,14 +1998,14 @@ export default function GitActionsControl({
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogPopup className="max-w-xl">
|
||||
<DialogPopup className="workflow-dialog-surface max-w-xl before:hidden">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{pendingDefaultBranchActionCopy?.title ?? "Run action on default refName?"}
|
||||
</DialogTitle>
|
||||
<DialogDescription>{pendingDefaultBranchActionCopy?.description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter className="dark:border-transparent dark:bg-transparent sm:flex-wrap sm:items-center">
|
||||
<DialogFooter className="dark:border-white/5 dark:bg-white/[0.025] sm:flex-wrap sm:items-center">
|
||||
<Button
|
||||
className="w-full sm:mr-auto sm:w-auto"
|
||||
variant="outline"
|
||||
|
||||
@@ -2,7 +2,6 @@ import type {
|
||||
ProjectScript,
|
||||
ProjectScriptIcon,
|
||||
ResolvedKeybindingsConfig,
|
||||
T3ProjectFileScript,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
@@ -12,7 +11,6 @@ import {
|
||||
import {
|
||||
BugIcon,
|
||||
ChevronDownIcon,
|
||||
DownloadIcon,
|
||||
FlaskConicalIcon,
|
||||
HammerIcon,
|
||||
ListChecksIcon,
|
||||
@@ -56,16 +54,7 @@ import {
|
||||
import { Group, GroupSeparator } from "./ui/group";
|
||||
import { Input } from "./ui/input";
|
||||
import { Label } from "./ui/label";
|
||||
import {
|
||||
Menu,
|
||||
MenuGroup,
|
||||
MenuGroupLabel,
|
||||
MenuItem,
|
||||
MenuPopup,
|
||||
MenuSeparator,
|
||||
MenuShortcut,
|
||||
MenuTrigger,
|
||||
} from "./ui/menu";
|
||||
import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "./ui/menu";
|
||||
import { Popover, PopoverPopup, PopoverTrigger } from "./ui/popover";
|
||||
import { Switch } from "./ui/switch";
|
||||
import { Textarea } from "./ui/textarea";
|
||||
@@ -109,12 +98,8 @@ export interface NewProjectScriptInput {
|
||||
|
||||
export type ProjectScriptActionResult = AtomCommandResult<void, unknown>;
|
||||
|
||||
const NO_FILE_SCRIPTS: ReadonlyArray<T3ProjectFileScript> = [];
|
||||
|
||||
interface ProjectScriptsControlProps {
|
||||
scripts: ReadonlyArray<ProjectScript>;
|
||||
/** Scripts declared in the project's checked-in t3.json, offered for import. */
|
||||
fileScripts?: ReadonlyArray<T3ProjectFileScript>;
|
||||
keybindings: ResolvedKeybindingsConfig;
|
||||
preferredScriptId?: string | null;
|
||||
onRunScript: (script: ProjectScript) => void;
|
||||
@@ -128,7 +113,6 @@ interface ProjectScriptsControlProps {
|
||||
|
||||
export default function ProjectScriptsControl({
|
||||
scripts,
|
||||
fileScripts = NO_FILE_SCRIPTS,
|
||||
keybindings,
|
||||
preferredScriptId = null,
|
||||
onRunScript,
|
||||
@@ -157,18 +141,6 @@ export default function ProjectScriptsControl({
|
||||
}
|
||||
return primaryProjectScript(scripts);
|
||||
}, [preferredScriptId, scripts]);
|
||||
const importableScripts = useMemo(
|
||||
() =>
|
||||
fileScripts.filter(
|
||||
(fileScript) =>
|
||||
!scripts.some(
|
||||
(script) =>
|
||||
script.command === fileScript.command ||
|
||||
script.name.toLowerCase() === fileScript.name.toLowerCase(),
|
||||
),
|
||||
),
|
||||
[fileScripts, scripts],
|
||||
);
|
||||
const isEditing = editingScriptId !== null;
|
||||
const dropdownItemClassName =
|
||||
"data-highlighted:bg-transparent data-highlighted:text-foreground hover:bg-accent hover:text-accent-foreground focus-visible:bg-accent focus-visible:text-accent-foreground data-highlighted:hover:bg-accent data-highlighted:hover:text-accent-foreground data-highlighted:focus-visible:bg-accent data-highlighted:focus-visible:text-accent-foreground";
|
||||
@@ -275,57 +247,6 @@ export default function ProjectScriptsControl({
|
||||
void onDeleteScript(editingScriptId);
|
||||
}, [editingScriptId, onDeleteScript]);
|
||||
|
||||
const importFileScript = async (fileScript: T3ProjectFileScript) => {
|
||||
const payload: NewProjectScriptInput = {
|
||||
name: fileScript.name,
|
||||
command: fileScript.command,
|
||||
icon: fileScript.icon ?? "play",
|
||||
runOnWorktreeCreate: fileScript.runOnWorktreeCreate ?? false,
|
||||
keybinding: null,
|
||||
previewUrl: fileScript.previewUrl ?? null,
|
||||
autoOpenPreview: fileScript.previewUrl ? (fileScript.autoOpenPreview ?? false) : false,
|
||||
};
|
||||
const result = await onAddScript(payload);
|
||||
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
|
||||
// Surface the failure through the regular add dialog, prefilled so the
|
||||
// user can adjust and retry.
|
||||
const error = squashAtomCommandFailure(result);
|
||||
setEditingScriptId(null);
|
||||
setName(payload.name);
|
||||
setCommand(payload.command);
|
||||
setIcon(payload.icon);
|
||||
setIconPickerOpen(false);
|
||||
setRunOnWorktreeCreate(payload.runOnWorktreeCreate);
|
||||
setKeybinding("");
|
||||
setPreviewUrl(payload.previewUrl ?? "");
|
||||
setAutoOpenPreview(payload.autoOpenPreview);
|
||||
setValidationError(error instanceof Error ? error.message : "Failed to import action.");
|
||||
setDialogOpen(true);
|
||||
}
|
||||
};
|
||||
|
||||
const importMenuItems = importableScripts.length > 0 && (
|
||||
<>
|
||||
{primaryScript && <MenuSeparator />}
|
||||
<MenuGroup>
|
||||
<MenuGroupLabel>From t3.json</MenuGroupLabel>
|
||||
{importableScripts.map((fileScript) => (
|
||||
<MenuItem
|
||||
key={`${fileScript.name} ${fileScript.command}`}
|
||||
className={dropdownItemClassName}
|
||||
onClick={() => void importFileScript(fileScript)}
|
||||
>
|
||||
<ScriptIcon icon={fileScript.icon ?? "play"} className="size-4" />
|
||||
<span className="truncate">{fileScript.name}</span>
|
||||
<MenuShortcut className="ms-auto">
|
||||
<DownloadIcon className="size-3.5" aria-label="Import" />
|
||||
</MenuShortcut>
|
||||
</MenuItem>
|
||||
))}
|
||||
</MenuGroup>
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{primaryScript ? (
|
||||
@@ -355,7 +276,7 @@ export default function ProjectScriptsControl({
|
||||
>
|
||||
<ChevronDownIcon className="size-4" />
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="end">
|
||||
<MenuPopup align="end" className="command-menu-surface">
|
||||
{scripts.map((script) => {
|
||||
const shortcutLabel = shortcutLabelForCommand(
|
||||
keybindings,
|
||||
@@ -399,7 +320,6 @@ export default function ProjectScriptsControl({
|
||||
</MenuItem>
|
||||
);
|
||||
})}
|
||||
{importMenuItems}
|
||||
<MenuItem className={dropdownItemClassName} onClick={openAddDialog}>
|
||||
<PlusIcon className="size-4" />
|
||||
Add action
|
||||
@@ -407,23 +327,6 @@ export default function ProjectScriptsControl({
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
</Group>
|
||||
) : importableScripts.length > 0 ? (
|
||||
<Menu highlightItemOnHover={false}>
|
||||
<MenuTrigger render={<Button size="xs" variant="outline" aria-label="Project actions" />}>
|
||||
<PlusIcon className="size-3.5" />
|
||||
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
|
||||
Add action
|
||||
</span>
|
||||
<ChevronDownIcon className="size-3.5" />
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="end">
|
||||
{importMenuItems}
|
||||
<MenuItem className={dropdownItemClassName} onClick={openAddDialog}>
|
||||
<PlusIcon className="size-4" />
|
||||
Add action
|
||||
</MenuItem>
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
) : (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
@@ -461,7 +364,7 @@ export default function ProjectScriptsControl({
|
||||
}}
|
||||
open={dialogOpen}
|
||||
>
|
||||
<DialogPopup>
|
||||
<DialogPopup className="workflow-dialog-surface before:hidden">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{isEditing ? "Edit Action" : "Add Action"}</DialogTitle>
|
||||
<DialogDescription>
|
||||
@@ -479,14 +382,14 @@ export default function ProjectScriptsControl({
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="size-9 shrink-0 hover:bg-popover active:bg-popover data-pressed:bg-popover data-pressed:shadow-xs/5 data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] dark:border-transparent dark:bg-white/[0.035] dark:data-pressed:before:shadow-none"
|
||||
className="size-9 shrink-0 hover:bg-popover active:bg-popover data-pressed:bg-popover data-pressed:shadow-xs/5 data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] dark:data-pressed:before:shadow-[0_-1px_--theme(--color-white/6%)]"
|
||||
aria-label="Choose icon"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<ScriptIcon icon={icon} className="size-4.5" />
|
||||
</PopoverTrigger>
|
||||
<PopoverPopup align="start">
|
||||
<PopoverPopup align="start" className="command-menu-surface">
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{SCRIPT_ICONS.map((entry) => {
|
||||
const isSelected = entry.id === icon;
|
||||
@@ -494,10 +397,10 @@ export default function ProjectScriptsControl({
|
||||
<button
|
||||
key={entry.id}
|
||||
type="button"
|
||||
className={`relative flex flex-col items-center gap-2 rounded-md border px-2 py-2 text-xs dark:border-transparent ${
|
||||
className={`relative flex flex-col items-center gap-2 rounded-md border px-2 py-2 text-xs ${
|
||||
isSelected
|
||||
? "border-primary/70 bg-primary/10 dark:ring-1 dark:ring-primary/30"
|
||||
: "border-border/70 hover:bg-accent/60 dark:bg-white/[0.035]"
|
||||
? "border-primary/70 bg-primary/10"
|
||||
: "border-border/70 hover:bg-accent/60"
|
||||
}`}
|
||||
onClick={() => {
|
||||
setIcon(entry.id);
|
||||
@@ -555,7 +458,7 @@ export default function ProjectScriptsControl({
|
||||
Open this URL in the in-app preview when this action runs.
|
||||
</p>
|
||||
</div>
|
||||
<label className="flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm dark:border-transparent dark:bg-white/[0.035]">
|
||||
<label className="flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm">
|
||||
<span>Run automatically on worktree creation</span>
|
||||
<Switch
|
||||
checked={runOnWorktreeCreate}
|
||||
@@ -563,7 +466,7 @@ export default function ProjectScriptsControl({
|
||||
/>
|
||||
</label>
|
||||
<label
|
||||
className={`flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm dark:border-transparent dark:bg-white/[0.035] ${
|
||||
className={`flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm ${
|
||||
previewUrl.trim().length === 0 ? "opacity-60" : ""
|
||||
}`}
|
||||
>
|
||||
@@ -577,7 +480,7 @@ export default function ProjectScriptsControl({
|
||||
{validationError && <p className="text-sm text-destructive">{validationError}</p>}
|
||||
</form>
|
||||
</DialogPanel>
|
||||
<DialogFooter className="dark:border-transparent dark:bg-transparent">
|
||||
<DialogFooter className="dark:border-white/5 dark:bg-white/[0.025]">
|
||||
{isEditing && (
|
||||
<Button
|
||||
type="button"
|
||||
|
||||
@@ -1,198 +0,0 @@
|
||||
import type { Dispatch, ReactElement, SetStateAction } from "react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import * as Cause from "effect/Cause";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
|
||||
const testState = vi.hoisted(() => ({
|
||||
updateServer: vi.fn(),
|
||||
toast: vi.fn(),
|
||||
}));
|
||||
|
||||
const hooks = vi.hoisted(() => {
|
||||
let cursor = 0;
|
||||
let slots: unknown[] = [];
|
||||
const nextIndex = () => cursor++;
|
||||
|
||||
return {
|
||||
beginRender() {
|
||||
cursor = 0;
|
||||
},
|
||||
reset() {
|
||||
cursor = 0;
|
||||
slots = [];
|
||||
},
|
||||
useEffect() {
|
||||
nextIndex();
|
||||
},
|
||||
useMemoCache(size: number): unknown[] {
|
||||
const index = nextIndex();
|
||||
if (!slots[index]) {
|
||||
slots[index] = Array.from({ length: size }, () => Symbol.for("react.memo_cache_sentinel"));
|
||||
}
|
||||
return slots[index] as unknown[];
|
||||
},
|
||||
useRef<T>(initialValue: T): { current: T } {
|
||||
const index = nextIndex();
|
||||
if (!slots[index]) {
|
||||
slots[index] = { current: initialValue };
|
||||
}
|
||||
return slots[index] as { current: T };
|
||||
},
|
||||
useState<T>(initialValue: T | (() => T)): [T, Dispatch<SetStateAction<T>>] {
|
||||
const index = nextIndex();
|
||||
if (index >= slots.length) {
|
||||
slots[index] =
|
||||
typeof initialValue === "function" ? (initialValue as () => T)() : initialValue;
|
||||
}
|
||||
const setValue: Dispatch<SetStateAction<T>> = (nextValue) => {
|
||||
const previous = slots[index] as T;
|
||||
slots[index] =
|
||||
typeof nextValue === "function" ? (nextValue as (value: T) => T)(previous) : nextValue;
|
||||
};
|
||||
return [slots[index] as T, setValue];
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("react", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("react")>();
|
||||
return {
|
||||
...actual,
|
||||
useEffect: hooks.useEffect,
|
||||
useRef: hooks.useRef,
|
||||
useState: hooks.useState,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("react/compiler-runtime", () => ({ c: hooks.useMemoCache }));
|
||||
vi.mock("~/hooks/useCopyToClipboard", () => ({
|
||||
useCopyToClipboard: () => ({ copyToClipboard: vi.fn() }),
|
||||
}));
|
||||
vi.mock("~/state/server", () => ({
|
||||
serverEnvironment: { updateServer: Symbol("updateServer") },
|
||||
}));
|
||||
vi.mock("~/state/use-atom-command", () => ({
|
||||
useAtomCommand: () => testState.updateServer,
|
||||
}));
|
||||
vi.mock("./ui/toast", () => ({
|
||||
toastManager: { add: testState.toast },
|
||||
}));
|
||||
|
||||
import { ServerUpdateAction } from "./ServerUpdateAction";
|
||||
|
||||
type ActionElement = ReactElement<{
|
||||
readonly disabled?: boolean;
|
||||
readonly onClick?: () => void;
|
||||
}>;
|
||||
|
||||
function renderAction(): ActionElement {
|
||||
hooks.beginRender();
|
||||
return ServerUpdateAction({
|
||||
environmentId: "env-test" as EnvironmentId,
|
||||
serverLabel: "Test server",
|
||||
selfUpdate: "boot-service",
|
||||
targetVersion: "0.0.29",
|
||||
}) as ActionElement;
|
||||
}
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>((complete) => {
|
||||
resolve = complete;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
async function flushPromises(): Promise<void> {
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
}
|
||||
|
||||
describe("ServerUpdateAction", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
hooks.reset();
|
||||
testState.updateServer.mockReset();
|
||||
testState.toast.mockReset();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("starts a fresh reconnect timeout after a long install succeeds", async () => {
|
||||
const update =
|
||||
deferred<
|
||||
ReturnType<typeof AsyncResult.success<{ targetVersion: string; method: "boot-service" }>>
|
||||
>();
|
||||
testState.updateServer.mockReturnValue(update.promise);
|
||||
|
||||
renderAction().props.onClick?.();
|
||||
expect(renderAction().props.disabled).toBe(true);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(11 * 60_000);
|
||||
update.resolve(
|
||||
AsyncResult.success({
|
||||
targetVersion: "0.0.29",
|
||||
method: "boot-service",
|
||||
}),
|
||||
);
|
||||
await flushPromises();
|
||||
|
||||
// The click-based deadline would have fired by now. Success gets a fresh
|
||||
// twelve-minute reconnect window, so the action remains disabled.
|
||||
await vi.advanceTimersByTimeAsync(2 * 60_000);
|
||||
expect(renderAction().props.disabled).toBe(true);
|
||||
expect(testState.toast).not.toHaveBeenCalledWith(
|
||||
expect.objectContaining({ title: "Server update timed out" }),
|
||||
);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(10 * 60_000);
|
||||
expect(renderAction().props.disabled).not.toBe(true);
|
||||
expect(testState.toast).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ title: "Server update timed out" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("does not let an expired request clear a newer retry", async () => {
|
||||
const first = deferred<ReturnType<typeof AsyncResult.failure>>();
|
||||
const retry =
|
||||
deferred<
|
||||
ReturnType<typeof AsyncResult.success<{ targetVersion: string; method: "boot-service" }>>
|
||||
>();
|
||||
testState.updateServer.mockReturnValueOnce(first.promise).mockReturnValueOnce(retry.promise);
|
||||
|
||||
renderAction().props.onClick?.();
|
||||
await vi.advanceTimersByTimeAsync(12 * 60_000);
|
||||
expect(renderAction().props.disabled).not.toBe(true);
|
||||
|
||||
renderAction().props.onClick?.();
|
||||
expect(renderAction().props.disabled).toBe(true);
|
||||
|
||||
first.resolve(AsyncResult.failure(Cause.fail(new Error("first request failed late"))));
|
||||
await flushPromises();
|
||||
|
||||
expect(renderAction().props.disabled).toBe(true);
|
||||
expect(testState.updateServer).toHaveBeenCalledTimes(2);
|
||||
|
||||
retry.resolve(AsyncResult.success({ targetVersion: "0.0.29", method: "boot-service" }));
|
||||
await flushPromises();
|
||||
expect(renderAction().props.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it("quietly releases the action when a restart RPC is interrupted", async () => {
|
||||
testState.updateServer.mockResolvedValue(AsyncResult.failure(Cause.interrupt()));
|
||||
|
||||
renderAction().props.onClick?.();
|
||||
await flushPromises();
|
||||
|
||||
expect(renderAction().props.disabled).not.toBe(true);
|
||||
expect(testState.toast).not.toHaveBeenCalledWith(
|
||||
expect.objectContaining({ title: "Server update failed" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,201 +0,0 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { EnvironmentId, ServerSelfUpdateCapability } from "@t3tools/contracts";
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
|
||||
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
import { serverEnvironment } from "~/state/server";
|
||||
import { useAtomCommand } from "~/state/use-atom-command";
|
||||
import { manualServerUpdateCommand } from "~/versionSkew";
|
||||
import { Button } from "./ui/button";
|
||||
import { Spinner } from "./ui/spinner";
|
||||
import { toastManager } from "./ui/toast";
|
||||
|
||||
/**
|
||||
* The npm install on the server side is capped at 10 minutes; expire the
|
||||
* spinner a bit beyond that so a dead transport never strands a disabled
|
||||
* button, while a legitimately slow install is never cut off.
|
||||
*/
|
||||
const UPDATE_PENDING_EXPIRY_MS = 12 * 60_000;
|
||||
|
||||
function updateFailureMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : "Server update failed.";
|
||||
}
|
||||
|
||||
/**
|
||||
* The call-to-action for a version-skewed server, matched to the update path
|
||||
* it advertises: a one-click install-and-restart for servers that can update
|
||||
* themselves, an update-the-desktop-app hint for desktop-managed backends
|
||||
* (running `npx t3` there would start a second server, not update this one),
|
||||
* and copying the manual relaunch command for everything else — so the skew
|
||||
* warning always offers a way out.
|
||||
*/
|
||||
export function ServerUpdateAction({
|
||||
environmentId,
|
||||
serverLabel,
|
||||
selfUpdate,
|
||||
targetVersion,
|
||||
}: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly serverLabel: string;
|
||||
readonly selfUpdate: ServerSelfUpdateCapability | null;
|
||||
readonly targetVersion: string;
|
||||
}) {
|
||||
const updateServer = useAtomCommand(serverEnvironment.updateServer, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const [pending, setPending] = useState(false);
|
||||
const inFlightRef = useRef(false);
|
||||
const attemptRef = useRef(0);
|
||||
const expiryRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const { copyToClipboard } = useCopyToClipboard<{ command: string }>({
|
||||
target: "update command",
|
||||
onCopy: ({ command }) => {
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Update command copied",
|
||||
description: `Run \`${command}\` on ${serverLabel} to update it.`,
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not copy update command",
|
||||
description: error.message,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (expiryRef.current !== null) {
|
||||
clearTimeout(expiryRef.current);
|
||||
expiryRef.current = null;
|
||||
}
|
||||
attemptRef.current += 1;
|
||||
inFlightRef.current = false;
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handleUpdate = () => {
|
||||
// Synchronous re-entry guard: setPending is async, so a rapid
|
||||
// double-click would otherwise dispatch two updates.
|
||||
if (inFlightRef.current) {
|
||||
return;
|
||||
}
|
||||
inFlightRef.current = true;
|
||||
const attempt = attemptRef.current + 1;
|
||||
attemptRef.current = attempt;
|
||||
const ownsAttempt = () => attemptRef.current === attempt;
|
||||
setPending(true);
|
||||
const armExpiry = () => {
|
||||
const expiry = setTimeout(() => {
|
||||
if (!ownsAttempt()) return;
|
||||
expiryRef.current = null;
|
||||
attemptRef.current += 1;
|
||||
inFlightRef.current = false;
|
||||
setPending(false);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Server update timed out",
|
||||
description: "The update may still be running on the server — check again in a minute.",
|
||||
});
|
||||
}, UPDATE_PENDING_EXPIRY_MS);
|
||||
expiryRef.current = expiry;
|
||||
return expiry;
|
||||
};
|
||||
let expiry = armExpiry();
|
||||
let restartAccepted = false;
|
||||
const keepPendingForRestart = () => {
|
||||
restartAccepted = true;
|
||||
if (expiryRef.current === expiry) {
|
||||
clearTimeout(expiry);
|
||||
expiry = armExpiry();
|
||||
}
|
||||
};
|
||||
void Promise.resolve()
|
||||
.then(() =>
|
||||
updateServer({
|
||||
environmentId,
|
||||
input: { targetVersion },
|
||||
}),
|
||||
)
|
||||
.then((result) => {
|
||||
if (!ownsAttempt()) return;
|
||||
if (result._tag === "Failure") {
|
||||
// An interrupt may be the expected boot-service disconnect, but it
|
||||
// can also be client-side cancellation before restart was accepted.
|
||||
// Release the action quietly; version sync will remove it when a
|
||||
// successful replacement reconnects.
|
||||
if (isAtomCommandInterrupted(result)) {
|
||||
return;
|
||||
}
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Server update failed",
|
||||
description: updateFailureMessage(squashAtomCommandFailure(result)),
|
||||
});
|
||||
return;
|
||||
}
|
||||
keepPendingForRestart();
|
||||
// Installation can legitimately consume most of the request window.
|
||||
// Give restart/reconnect a fresh full window after the server accepts
|
||||
// the handoff instead of expiring based on the original click time.
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: `Updating ${serverLabel}`,
|
||||
description: `t3@${result.value.targetVersion} is installed — the server is restarting and will reconnect shortly.`,
|
||||
});
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (!ownsAttempt()) return;
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Server update failed",
|
||||
description: updateFailureMessage(error),
|
||||
});
|
||||
})
|
||||
.finally(() => {
|
||||
// A successful RPC only acknowledges that restart is scheduled. Keep
|
||||
// the action disabled until version sync unmounts it, or until the
|
||||
// safety expiry reports that reconnection never arrived.
|
||||
if (restartAccepted || !ownsAttempt() || expiryRef.current !== expiry) return;
|
||||
expiryRef.current = null;
|
||||
clearTimeout(expiry);
|
||||
attemptRef.current += 1;
|
||||
inFlightRef.current = false;
|
||||
setPending(false);
|
||||
});
|
||||
};
|
||||
|
||||
if (selfUpdate === "desktop-managed") {
|
||||
return (
|
||||
<span className="text-muted-foreground text-xs">
|
||||
Update the desktop app on that machine to update this server.
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
if (selfUpdate === null) {
|
||||
const command = manualServerUpdateCommand(targetVersion);
|
||||
return (
|
||||
<Button size="xs" variant="outline" onClick={() => copyToClipboard(command, { command })}>
|
||||
Copy update command
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
return pending ? (
|
||||
<Button size="xs" disabled>
|
||||
<Spinner className="size-3.5" />
|
||||
Updating...
|
||||
</Button>
|
||||
) : (
|
||||
<Button size="xs" onClick={() => void handleUpdate()}>
|
||||
Update server
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -14,16 +14,13 @@ import {
|
||||
isTrailingDoubleClick,
|
||||
orderItemsByPreferredIds,
|
||||
resolveProjectStatusIndicator,
|
||||
resolveSidebarNewThreadSeedContext,
|
||||
resolveSidebarNewThreadEnvMode,
|
||||
resolveSidebarStageBadgeLabel,
|
||||
resolveThreadRowClassName,
|
||||
resolveSidebarV2Status,
|
||||
resolveThreadStatusPill,
|
||||
resolveWorkingStartedAt,
|
||||
formatWorkingDurationLabel,
|
||||
shouldNavigateAfterProjectRemoval,
|
||||
shouldClearThreadSelectionOnMouseDown,
|
||||
sortLogicalProjectsForSidebar,
|
||||
sortSettledThreadsForSidebarV2,
|
||||
sortThreadsForSidebarV2,
|
||||
sortProjectsForSidebar,
|
||||
sortScopedProjectsForSidebar,
|
||||
@@ -36,7 +33,6 @@ import {
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
DEFAULT_INTERACTION_MODE,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
@@ -46,56 +42,6 @@ import {
|
||||
|
||||
const localEnvironmentId = EnvironmentId.make("environment-local");
|
||||
|
||||
describe("shouldNavigateAfterProjectRemoval", () => {
|
||||
const projectThreads = [{ environmentId: "environment-local", id: "thread-1" }];
|
||||
|
||||
it("navigates away from a draft route owned by the removed project", () => {
|
||||
expect(
|
||||
shouldNavigateAfterProjectRemoval({
|
||||
routeTarget: { kind: "draft", draftId: "draft-1" as never },
|
||||
projectThreads,
|
||||
projectDraftId: "draft-1",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("does not navigate away from a different draft route", () => {
|
||||
expect(
|
||||
shouldNavigateAfterProjectRemoval({
|
||||
routeTarget: { kind: "draft", draftId: "draft-2" as never },
|
||||
projectThreads,
|
||||
projectDraftId: "draft-1",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("navigates away from a server thread owned by the removed project", () => {
|
||||
expect(
|
||||
shouldNavigateAfterProjectRemoval({
|
||||
routeTarget: {
|
||||
kind: "server",
|
||||
threadRef: {
|
||||
environmentId: EnvironmentId.make("environment-local"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
},
|
||||
projectThreads,
|
||||
projectDraftId: null,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("does not navigate from an unrelated route", () => {
|
||||
expect(
|
||||
shouldNavigateAfterProjectRemoval({
|
||||
routeTarget: null,
|
||||
projectThreads,
|
||||
projectDraftId: null,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("archiveSelectedThreadEntries", () => {
|
||||
const entries = [{ threadKey: "one" }, { threadKey: "two" }, { threadKey: "three" }] as const;
|
||||
const success = { _tag: "Success" } as const;
|
||||
@@ -210,10 +156,8 @@ function makeLatestTurn(overrides?: {
|
||||
state: "completed",
|
||||
assistantMessageId: null,
|
||||
requestedAt: "2026-03-09T10:00:00.000Z",
|
||||
startedAt:
|
||||
overrides?.startedAt !== undefined ? overrides.startedAt : "2026-03-09T10:00:00.000Z",
|
||||
completedAt:
|
||||
overrides?.completedAt !== undefined ? overrides.completedAt : "2026-03-09T10:05:00.000Z",
|
||||
startedAt: overrides?.startedAt ?? "2026-03-09T10:00:00.000Z",
|
||||
completedAt: overrides?.completedAt ?? "2026-03-09T10:05:00.000Z",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -369,6 +313,112 @@ describe("isTrailingDoubleClick", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveSidebarNewThreadEnvMode", () => {
|
||||
it("uses the app default when the caller does not request a specific mode", () => {
|
||||
expect(
|
||||
resolveSidebarNewThreadEnvMode({
|
||||
defaultEnvMode: "worktree",
|
||||
}),
|
||||
).toBe("worktree");
|
||||
});
|
||||
|
||||
it("preserves an explicit requested mode over the app default", () => {
|
||||
expect(
|
||||
resolveSidebarNewThreadEnvMode({
|
||||
requestedEnvMode: "local",
|
||||
defaultEnvMode: "worktree",
|
||||
}),
|
||||
).toBe("local");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveSidebarNewThreadSeedContext", () => {
|
||||
it("prefers the default worktree mode over active thread context", () => {
|
||||
expect(
|
||||
resolveSidebarNewThreadSeedContext({
|
||||
projectId: "project-1",
|
||||
defaultEnvMode: "worktree",
|
||||
activeThread: {
|
||||
projectId: "project-1",
|
||||
branch: "feature/existing",
|
||||
worktreePath: "/repo/.t3/worktrees/existing",
|
||||
},
|
||||
activeDraftThread: {
|
||||
projectId: "project-1",
|
||||
branch: "feature/draft",
|
||||
worktreePath: "/repo/.t3/worktrees/draft",
|
||||
envMode: "worktree",
|
||||
startFromOrigin: true,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
envMode: "worktree",
|
||||
});
|
||||
});
|
||||
|
||||
it("inherits the active server thread context when creating a new thread in the same project", () => {
|
||||
expect(
|
||||
resolveSidebarNewThreadSeedContext({
|
||||
projectId: "project-1",
|
||||
defaultEnvMode: "local",
|
||||
activeThread: {
|
||||
projectId: "project-1",
|
||||
branch: "effect-atom",
|
||||
worktreePath: null,
|
||||
},
|
||||
activeDraftThread: null,
|
||||
}),
|
||||
).toEqual({
|
||||
branch: "effect-atom",
|
||||
worktreePath: null,
|
||||
envMode: "local",
|
||||
});
|
||||
});
|
||||
|
||||
it("prefers the active draft thread context when it matches the target project", () => {
|
||||
expect(
|
||||
resolveSidebarNewThreadSeedContext({
|
||||
projectId: "project-1",
|
||||
defaultEnvMode: "local",
|
||||
activeThread: {
|
||||
projectId: "project-1",
|
||||
branch: "effect-atom",
|
||||
worktreePath: null,
|
||||
},
|
||||
activeDraftThread: {
|
||||
projectId: "project-1",
|
||||
branch: "feature/new-draft",
|
||||
worktreePath: "/repo/worktree",
|
||||
envMode: "worktree",
|
||||
startFromOrigin: true,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
branch: "feature/new-draft",
|
||||
worktreePath: "/repo/worktree",
|
||||
envMode: "worktree",
|
||||
startFromOrigin: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to the default env mode when there is no matching active thread context", () => {
|
||||
expect(
|
||||
resolveSidebarNewThreadSeedContext({
|
||||
projectId: "project-2",
|
||||
defaultEnvMode: "worktree",
|
||||
activeThread: {
|
||||
projectId: "project-1",
|
||||
branch: "effect-atom",
|
||||
worktreePath: null,
|
||||
},
|
||||
activeDraftThread: null,
|
||||
}),
|
||||
).toEqual({
|
||||
envMode: "worktree",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("orderItemsByPreferredIds", () => {
|
||||
it("keeps preferred ids first, skips stale ids, and preserves the relative order of remaining items", () => {
|
||||
const ordered = orderItemsByPreferredIds({
|
||||
@@ -680,141 +730,6 @@ describe("sortThreadsForSidebarV2", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("sortSettledThreadsForSidebarV2", () => {
|
||||
const settled = (input: {
|
||||
id: string;
|
||||
settledAt?: string | null;
|
||||
latestUserMessageAt?: string | null;
|
||||
latestTurn?: OrchestrationLatestTurn | null;
|
||||
updatedAt?: string;
|
||||
}) => ({
|
||||
id: input.id,
|
||||
settledAt: input.settledAt ?? null,
|
||||
latestUserMessageAt: input.latestUserMessageAt ?? null,
|
||||
latestTurn: input.latestTurn ?? null,
|
||||
updatedAt: input.updatedAt ?? "2026-03-09T09:00:00.000Z",
|
||||
});
|
||||
|
||||
it("orders by settle time, most recently settled first", () => {
|
||||
const sorted = sortSettledThreadsForSidebarV2([
|
||||
settled({
|
||||
id: "settled-first",
|
||||
settledAt: "2026-03-09T10:00:00.000Z",
|
||||
// Created/active later than the other thread: settle time must win.
|
||||
latestUserMessageAt: "2026-03-09T09:59:00.000Z",
|
||||
}),
|
||||
settled({
|
||||
id: "settled-last",
|
||||
settledAt: "2026-03-09T12:00:00.000Z",
|
||||
latestUserMessageAt: "2026-03-09T08:00:00.000Z",
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual(["settled-last", "settled-first"]);
|
||||
});
|
||||
|
||||
it("falls back to last activity for auto-settled threads without a settledAt stamp", () => {
|
||||
const sorted = sortSettledThreadsForSidebarV2([
|
||||
settled({ id: "auto-old", latestUserMessageAt: "2026-03-09T08:00:00.000Z" }),
|
||||
settled({ id: "explicit", settledAt: "2026-03-09T10:00:00.000Z" }),
|
||||
settled({ id: "auto-recent", latestUserMessageAt: "2026-03-09T11:00:00.000Z" }),
|
||||
]);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual(["auto-recent", "explicit", "auto-old"]);
|
||||
});
|
||||
|
||||
it("counts a turn completion as activity for auto-settled threads", () => {
|
||||
// The message came in before the other thread's, but its turn finished
|
||||
// after: completion time is the real "work ended" moment.
|
||||
const sorted = sortSettledThreadsForSidebarV2([
|
||||
settled({ id: "message-only", latestUserMessageAt: "2026-03-09T10:04:00.000Z" }),
|
||||
settled({
|
||||
id: "completed-later",
|
||||
latestUserMessageAt: "2026-03-09T10:00:00.000Z",
|
||||
latestTurn: makeLatestTurn({ completedAt: "2026-03-09T10:30:00.000Z" }),
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual(["completed-later", "message-only"]);
|
||||
});
|
||||
|
||||
it("breaks timestamp ties by id so the order is stable", () => {
|
||||
const sorted = sortSettledThreadsForSidebarV2([
|
||||
settled({ id: "b", settledAt: "2026-03-09T10:00:00.000Z" }),
|
||||
settled({ id: "a", settledAt: "2026-03-09T10:00:00.000Z" }),
|
||||
]);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual(["a", "b"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveWorkingStartedAt", () => {
|
||||
const session = {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "running" as const,
|
||||
providerName: "Codex",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
activeTurnId: "turn-1" as never,
|
||||
lastError: null,
|
||||
updatedAt: "2026-03-09T10:02:00.000Z",
|
||||
};
|
||||
|
||||
it("uses the running turn's start time", () => {
|
||||
expect(
|
||||
resolveWorkingStartedAt({
|
||||
latestTurn: makeLatestTurn({ completedAt: null }),
|
||||
session,
|
||||
}),
|
||||
).toBe("2026-03-09T10:00:00.000Z");
|
||||
});
|
||||
|
||||
it("uses the request time while a turn awaits adoption", () => {
|
||||
expect(
|
||||
resolveWorkingStartedAt({
|
||||
latestTurn: makeLatestTurn({ startedAt: null, completedAt: null }),
|
||||
session,
|
||||
}),
|
||||
).toBe("2026-03-09T10:00:00.000Z");
|
||||
});
|
||||
|
||||
it("falls back to the session transition when the latest turn already completed", () => {
|
||||
expect(
|
||||
resolveWorkingStartedAt({
|
||||
latestTurn: makeLatestTurn(),
|
||||
session,
|
||||
}),
|
||||
).toBe("2026-03-09T10:02:00.000Z");
|
||||
});
|
||||
|
||||
it("skips a malformed startedAt instead of returning it", () => {
|
||||
expect(
|
||||
resolveWorkingStartedAt({
|
||||
latestTurn: makeLatestTurn({ startedAt: "not-a-date", completedAt: null }),
|
||||
session,
|
||||
}),
|
||||
).toBe("2026-03-09T10:00:00.000Z");
|
||||
});
|
||||
|
||||
it("returns null with neither a running turn nor a session", () => {
|
||||
expect(resolveWorkingStartedAt({ latestTurn: null, session: null })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatWorkingDurationLabel", () => {
|
||||
it("formats seconds, minutes, and hours", () => {
|
||||
expect(formatWorkingDurationLabel(0)).toBe("0s");
|
||||
expect(formatWorkingDurationLabel(42_000)).toBe("42s");
|
||||
expect(formatWorkingDurationLabel(5 * 60_000)).toBe("5m");
|
||||
expect(formatWorkingDurationLabel(90 * 60_000)).toBe("1h 30m");
|
||||
});
|
||||
|
||||
it("clamps negative and non-finite elapsed values to zero", () => {
|
||||
expect(formatWorkingDurationLabel(-5_000)).toBe("0s");
|
||||
expect(formatWorkingDurationLabel(Number.NaN)).toBe("0s");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveThreadStatusPill", () => {
|
||||
const baseThread = {
|
||||
hasActionableProposedPlan: false,
|
||||
@@ -1387,40 +1302,3 @@ describe("sortScopedProjectsForSidebar", () => {
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sortLogicalProjectsForSidebar", () => {
|
||||
it("uses saved order only in manual mode and activity order otherwise", () => {
|
||||
const olderProjectId = ProjectId.make("project-older");
|
||||
const newerProjectId = ProjectId.make("project-newer");
|
||||
const projects = [
|
||||
{
|
||||
...makeProject({ id: olderProjectId, title: "Older project" }),
|
||||
projectKey: "logical-older",
|
||||
memberProjectRefs: [{ environmentId: localEnvironmentId, projectId: olderProjectId }],
|
||||
},
|
||||
{
|
||||
...makeProject({ id: newerProjectId, title: "Newer project" }),
|
||||
projectKey: "logical-newer",
|
||||
memberProjectRefs: [{ environmentId: localEnvironmentId, projectId: newerProjectId }],
|
||||
},
|
||||
];
|
||||
const threads = [
|
||||
makeThread({
|
||||
projectId: olderProjectId,
|
||||
updatedAt: "2026-03-09T10:01:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-newer"),
|
||||
projectId: newerProjectId,
|
||||
updatedAt: "2026-03-09T10:05:00.000Z",
|
||||
}),
|
||||
];
|
||||
|
||||
expect(sortLogicalProjectsForSidebar(projects, threads, "manual")).toEqual(projects);
|
||||
expect(
|
||||
sortLogicalProjectsForSidebar(projects, threads, "updated_at").map(
|
||||
(project) => project.projectKey,
|
||||
),
|
||||
).toEqual(["logical-newer", "logical-older"]);
|
||||
});
|
||||
});
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
type ThreadSortInput,
|
||||
} from "../lib/threadSort";
|
||||
import type { SidebarThreadSummary, Thread } from "../types";
|
||||
import type { ThreadRouteTarget } from "../threadRoutes";
|
||||
import { cn } from "../lib/utils";
|
||||
import { isLatestTurnSettled } from "../session-logic";
|
||||
import { resolveServerBackedAppStageLabel } from "../branding.logic";
|
||||
@@ -18,6 +17,7 @@ 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;
|
||||
export type SidebarNewThreadEnvMode = "local" | "worktree";
|
||||
type SidebarProject = {
|
||||
id: string;
|
||||
title: string;
|
||||
@@ -35,14 +35,6 @@ type ScopedSidebarThread = ThreadSortInput & {
|
||||
archivedAt: string | null;
|
||||
};
|
||||
|
||||
type LogicalSidebarProject = SidebarProject & {
|
||||
projectKey: string;
|
||||
memberProjectRefs: readonly {
|
||||
environmentId: string;
|
||||
projectId: string;
|
||||
}[];
|
||||
};
|
||||
|
||||
export type ThreadTraversalDirection = "previous" | "next";
|
||||
|
||||
export async function archiveSelectedThreadEntries<
|
||||
@@ -245,6 +237,62 @@ export function isTrailingDoubleClick(detail: number): boolean {
|
||||
return detail > 1;
|
||||
}
|
||||
|
||||
export function resolveSidebarNewThreadEnvMode(input: {
|
||||
requestedEnvMode?: SidebarNewThreadEnvMode;
|
||||
defaultEnvMode: SidebarNewThreadEnvMode;
|
||||
}): SidebarNewThreadEnvMode {
|
||||
return input.requestedEnvMode ?? input.defaultEnvMode;
|
||||
}
|
||||
|
||||
export function resolveSidebarNewThreadSeedContext(input: {
|
||||
projectId: string;
|
||||
defaultEnvMode: SidebarNewThreadEnvMode;
|
||||
activeThread?: {
|
||||
projectId: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
} | null;
|
||||
activeDraftThread?: {
|
||||
projectId: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
envMode: SidebarNewThreadEnvMode;
|
||||
startFromOrigin: boolean;
|
||||
} | null;
|
||||
}): {
|
||||
branch?: string | null;
|
||||
worktreePath?: string | null;
|
||||
envMode: SidebarNewThreadEnvMode;
|
||||
startFromOrigin?: boolean;
|
||||
} {
|
||||
if (input.defaultEnvMode === "worktree") {
|
||||
return {
|
||||
envMode: "worktree",
|
||||
};
|
||||
}
|
||||
|
||||
if (input.activeDraftThread?.projectId === input.projectId) {
|
||||
return {
|
||||
branch: input.activeDraftThread.branch,
|
||||
worktreePath: input.activeDraftThread.worktreePath,
|
||||
envMode: input.activeDraftThread.envMode,
|
||||
startFromOrigin: input.activeDraftThread.startFromOrigin,
|
||||
};
|
||||
}
|
||||
|
||||
if (input.activeThread?.projectId === input.projectId) {
|
||||
return {
|
||||
branch: input.activeThread.branch,
|
||||
worktreePath: input.activeThread.worktreePath,
|
||||
envMode: input.activeThread.worktreePath ? "worktree" : "local",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
envMode: input.defaultEnvMode,
|
||||
};
|
||||
}
|
||||
|
||||
export function orderItemsByPreferredIds<TItem, TId>(input: {
|
||||
items: readonly TItem[];
|
||||
preferredIds: readonly TId[];
|
||||
@@ -329,28 +377,6 @@ export function resolveAdjacentThreadId<T>(input: {
|
||||
return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null;
|
||||
}
|
||||
|
||||
export function shouldNavigateAfterProjectRemoval(input: {
|
||||
routeTarget: ThreadRouteTarget | null;
|
||||
projectThreads: readonly {
|
||||
environmentId: string;
|
||||
id: string;
|
||||
}[];
|
||||
projectDraftId: string | null;
|
||||
}): boolean {
|
||||
const { projectDraftId, projectThreads, routeTarget } = input;
|
||||
if (routeTarget?.kind === "draft") {
|
||||
return projectDraftId === routeTarget.draftId;
|
||||
}
|
||||
if (routeTarget?.kind !== "server") {
|
||||
return false;
|
||||
}
|
||||
return projectThreads.some(
|
||||
(thread) =>
|
||||
thread.environmentId === routeTarget.threadRef.environmentId &&
|
||||
thread.id === routeTarget.threadRef.threadId,
|
||||
);
|
||||
}
|
||||
|
||||
export function isContextMenuPointerDown(input: {
|
||||
button: number;
|
||||
ctrlKey: boolean;
|
||||
@@ -445,18 +471,6 @@ export function firstValidTimestampMs(
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** String twin of firstValidTimestampMs for callers that need the ISO string
|
||||
(display labels, tick anchors) rather than epoch ms. */
|
||||
export function firstValidTimestamp(
|
||||
...candidates: ReadonlyArray<string | null | undefined>
|
||||
): string | null {
|
||||
for (const candidate of candidates) {
|
||||
if (candidate == null) continue;
|
||||
if (!Number.isNaN(Date.parse(candidate))) return candidate;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// v2 sort: static creation order, newest thread on top. Activity NEVER
|
||||
// reorders the list — a row holds its position from open until settled, so
|
||||
// the screen only moves at lifecycle transitions. Status (including pending
|
||||
@@ -471,73 +485,6 @@ export function sortThreadsForSidebarV2<
|
||||
);
|
||||
}
|
||||
|
||||
type SettledTimestampInput = Pick<
|
||||
SidebarThreadSummary,
|
||||
"settledAt" | "latestUserMessageAt" | "latestTurn" | "updatedAt"
|
||||
>;
|
||||
|
||||
/** The timestamp a settled row sorts and labels by: settledAt when stamped
|
||||
(explicit settles), otherwise last activity — the same candidates
|
||||
threadLastActivityAt feeds the auto-settle window (user message plus all
|
||||
latestTurn stamps), so a thread whose last activity was a turn completion
|
||||
doesn't sort by an older message time. updatedAt is the final net. */
|
||||
export function resolveSettledTimestamp(thread: SettledTimestampInput): string | null {
|
||||
const settledAt = firstValidTimestamp(thread.settledAt);
|
||||
if (settledAt !== null) return settledAt;
|
||||
let latest: string | null = null;
|
||||
let latestMs = Number.NEGATIVE_INFINITY;
|
||||
for (const candidate of [
|
||||
thread.latestUserMessageAt,
|
||||
thread.latestTurn?.requestedAt,
|
||||
thread.latestTurn?.startedAt,
|
||||
thread.latestTurn?.completedAt,
|
||||
]) {
|
||||
if (candidate == null) continue;
|
||||
const parsed = Date.parse(candidate);
|
||||
if (!Number.isNaN(parsed) && parsed > latestMs) {
|
||||
latest = candidate;
|
||||
latestMs = parsed;
|
||||
}
|
||||
}
|
||||
return latest ?? firstValidTimestamp(thread.updatedAt);
|
||||
}
|
||||
|
||||
// Settled rows are history, so they order by when the work ENDED, not when
|
||||
// the thread was created or last touched.
|
||||
export function sortSettledThreadsForSidebarV2<
|
||||
T extends SettledTimestampInput & { readonly id: string },
|
||||
>(threads: readonly T[]): T[] {
|
||||
const timestampMs = (thread: T) => {
|
||||
const timestamp = resolveSettledTimestamp(thread);
|
||||
return timestamp === null ? 0 : Date.parse(timestamp);
|
||||
};
|
||||
return [...threads].toSorted(
|
||||
(left, right) => timestampMs(right) - timestampMs(left) || left.id.localeCompare(right.id),
|
||||
);
|
||||
}
|
||||
|
||||
/** The timestamp a working thread's elapsed label counts from: the running
|
||||
turn's start (request time until adoption), falling back to the session's
|
||||
last transition when the turn projection lags behind. Malformed
|
||||
timestamps fall through to the next candidate, not just missing ones. */
|
||||
export function resolveWorkingStartedAt(
|
||||
thread: Pick<SidebarThreadSummary, "latestTurn" | "session">,
|
||||
): string | null {
|
||||
const turn = thread.latestTurn;
|
||||
if (turn && turn.completedAt === null) {
|
||||
return firstValidTimestamp(turn.startedAt, turn.requestedAt, thread.session?.updatedAt);
|
||||
}
|
||||
return firstValidTimestamp(thread.session?.updatedAt);
|
||||
}
|
||||
|
||||
export function formatWorkingDurationLabel(elapsedMs: number): string {
|
||||
const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
|
||||
if (seconds < 60) return `${seconds}s`;
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
if (minutes < 60) return `${minutes}m`;
|
||||
return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
|
||||
}
|
||||
|
||||
export function resolveThreadStatusPill(input: {
|
||||
thread: ThreadStatusInput;
|
||||
}): ThreadStatusPill | null {
|
||||
@@ -757,44 +704,6 @@ export function sortProjectsForSidebar<
|
||||
);
|
||||
}
|
||||
|
||||
export function sortLogicalProjectsForSidebar<
|
||||
TProject extends LogicalSidebarProject,
|
||||
TThread extends ScopedSidebarThread,
|
||||
>(
|
||||
projects: readonly TProject[],
|
||||
threads: readonly TThread[],
|
||||
sortOrder: SidebarProjectSortOrder,
|
||||
): TProject[] {
|
||||
const groupKeyByProjectRef = new Map(
|
||||
projects.flatMap((project) =>
|
||||
project.memberProjectRefs.map(
|
||||
(projectRef) =>
|
||||
[`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
|
||||
),
|
||||
),
|
||||
);
|
||||
const threadsByProjectKey = new Map<string, TThread[]>();
|
||||
for (const thread of threads) {
|
||||
if (thread.archivedAt !== null) continue;
|
||||
const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
|
||||
if (!projectKey) continue;
|
||||
const existing = threadsByProjectKey.get(projectKey);
|
||||
if (existing) {
|
||||
existing.push(thread);
|
||||
} else {
|
||||
threadsByProjectKey.set(projectKey, [thread]);
|
||||
}
|
||||
}
|
||||
|
||||
return sortProjectsByActivity(
|
||||
projects,
|
||||
sortOrder,
|
||||
(project) => threadsByProjectKey.get(project.projectKey) ?? [],
|
||||
(left, right) =>
|
||||
left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorts the cross-environment project collection used by landing surfaces.
|
||||
* Project ids are only unique within an environment, and archived threads
|
||||
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
import {
|
||||
ChangeRequestStatusIcon,
|
||||
prStatusIndicator,
|
||||
PrStatusTooltipContent,
|
||||
resolveThreadPr,
|
||||
terminalStatusFromRunningIds,
|
||||
ThreadStatusLabel,
|
||||
@@ -43,6 +42,7 @@ import { restrictToFirstScrollableAncestor, restrictToVerticalAxis } from "@dnd-
|
||||
import { CSS } from "@dnd-kit/utilities";
|
||||
import {
|
||||
type ContextMenuItem,
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
ProjectId,
|
||||
type ScopedThreadRef,
|
||||
type ResolvedKeybindingsConfig,
|
||||
@@ -80,6 +80,7 @@ import {
|
||||
readThreadShell,
|
||||
useProject,
|
||||
useProjects,
|
||||
useServerConfigs,
|
||||
useThreadShells,
|
||||
useThreadShellsForProjectRefs,
|
||||
} from "../state/entities";
|
||||
@@ -145,7 +146,15 @@ import {
|
||||
DialogTitle,
|
||||
} from "./ui/dialog";
|
||||
import { Input } from "./ui/input";
|
||||
import { Menu, MenuGroup, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "./ui/menu";
|
||||
import {
|
||||
Menu,
|
||||
MenuGroup,
|
||||
MenuPopup,
|
||||
MenuRadioGroup,
|
||||
MenuRadioItem,
|
||||
MenuSeparator,
|
||||
MenuTrigger,
|
||||
} from "./ui/menu";
|
||||
import {
|
||||
NumberField,
|
||||
NumberFieldDecrement,
|
||||
@@ -177,6 +186,8 @@ import {
|
||||
isContextMenuPointerDown,
|
||||
isTrailingDoubleClick,
|
||||
resolveProjectStatusIndicator,
|
||||
resolveSidebarNewThreadSeedContext,
|
||||
resolveSidebarNewThreadEnvMode,
|
||||
resolveThreadRowClassName,
|
||||
resolveThreadStatusPill,
|
||||
orderItemsByPreferredIds,
|
||||
@@ -449,11 +460,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
|
||||
lastVisitedAt,
|
||||
},
|
||||
});
|
||||
const pr = resolveThreadPr({
|
||||
threadBranch: thread.branch,
|
||||
gitStatus: gitStatus.data,
|
||||
hasDedicatedWorktree: thread.worktreePath !== null,
|
||||
});
|
||||
const pr = resolveThreadPr(thread.branch, gitStatus.data);
|
||||
const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider);
|
||||
const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
|
||||
const isConfirmingArchive = confirmingArchiveThreadKey === threadKey && !isThreadRunning;
|
||||
@@ -693,9 +700,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">
|
||||
<PrStatusTooltipContent status={prStatus} />
|
||||
</TooltipPopup>
|
||||
<TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
{threadStatus && <ThreadStatusLabel status={threadStatus} />}
|
||||
@@ -1101,6 +1106,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
(settings) => settings.confirmThreadArchive,
|
||||
);
|
||||
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
|
||||
const serverConfigs = useServerConfigs();
|
||||
const deleteProject = useAtomCommand(projectEnvironment.delete, {
|
||||
reportFailure: false,
|
||||
});
|
||||
@@ -1872,14 +1878,61 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
|
||||
const createThreadForProjectMember = useCallback(
|
||||
(member: SidebarProjectGroupMember) => {
|
||||
const currentRouteParams =
|
||||
router.state.matches[router.state.matches.length - 1]?.params ?? {};
|
||||
const currentRouteTarget = resolveThreadRouteTarget(currentRouteParams);
|
||||
const currentActiveThread =
|
||||
currentRouteTarget?.kind === "server"
|
||||
? readThreadShell(currentRouteTarget.threadRef)
|
||||
: null;
|
||||
const draftStore = useComposerDraftStore.getState();
|
||||
const currentActiveDraftThread =
|
||||
currentRouteTarget?.kind === "server"
|
||||
? (draftStore.getDraftThread(currentRouteTarget.threadRef) ?? null)
|
||||
: currentRouteTarget?.kind === "draft"
|
||||
? (draftStore.getDraftSession(currentRouteTarget.draftId) ?? null)
|
||||
: null;
|
||||
const seedContext = resolveSidebarNewThreadSeedContext({
|
||||
projectId: member.id,
|
||||
defaultEnvMode: resolveSidebarNewThreadEnvMode({
|
||||
defaultEnvMode:
|
||||
serverConfigs.get(member.environmentId)?.settings.defaultThreadEnvMode ??
|
||||
DEFAULT_SERVER_SETTINGS.defaultThreadEnvMode,
|
||||
}),
|
||||
activeThread:
|
||||
currentActiveThread && currentActiveThread.projectId === member.id
|
||||
? {
|
||||
projectId: currentActiveThread.projectId,
|
||||
branch: currentActiveThread.branch,
|
||||
worktreePath: currentActiveThread.worktreePath,
|
||||
}
|
||||
: null,
|
||||
activeDraftThread:
|
||||
currentActiveDraftThread && currentActiveDraftThread.projectId === member.id
|
||||
? {
|
||||
projectId: currentActiveDraftThread.projectId,
|
||||
branch: currentActiveDraftThread.branch,
|
||||
worktreePath: currentActiveDraftThread.worktreePath,
|
||||
envMode: currentActiveDraftThread.envMode,
|
||||
startFromOrigin: currentActiveDraftThread.startFromOrigin,
|
||||
}
|
||||
: null,
|
||||
});
|
||||
if (isMobile) {
|
||||
setOpenMobile(false);
|
||||
}
|
||||
void (async () => {
|
||||
// No options: branch, worktree, and env mode come from the user's
|
||||
// configured defaults, never from the currently viewed thread.
|
||||
const result = await settlePromise(() =>
|
||||
handleNewThread(scopeProjectRef(member.environmentId, member.id)),
|
||||
handleNewThread(scopeProjectRef(member.environmentId, member.id), {
|
||||
...(seedContext.branch !== undefined ? { branch: seedContext.branch } : {}),
|
||||
...(seedContext.worktreePath !== undefined
|
||||
? { worktreePath: seedContext.worktreePath }
|
||||
: {}),
|
||||
envMode: seedContext.envMode,
|
||||
...(seedContext.startFromOrigin !== undefined
|
||||
? { startFromOrigin: seedContext.startFromOrigin }
|
||||
: {}),
|
||||
}),
|
||||
);
|
||||
if (result._tag === "Failure") {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
@@ -1893,7 +1946,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
}
|
||||
})();
|
||||
},
|
||||
[handleNewThread, isMobile, setOpenMobile],
|
||||
[handleNewThread, isMobile, router, serverConfigs, setOpenMobile],
|
||||
);
|
||||
|
||||
const handleCreateThreadClick = useCallback(
|
||||
@@ -2114,9 +2167,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
thread.worktreePath ?? threadProject?.workspaceRoot ?? project.workspaceRoot ?? null;
|
||||
const clicked = await api.contextMenu.show(
|
||||
[
|
||||
...(thread.branch
|
||||
? [{ id: "new-thread-on-branch", label: `New thread on ${thread.branch}` }]
|
||||
: []),
|
||||
{ id: "rename", label: "Rename thread" },
|
||||
{ id: "mark-unread", label: "Mark unread" },
|
||||
{ id: "copy-path", label: "Copy Path" },
|
||||
@@ -2126,30 +2176,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
position,
|
||||
);
|
||||
|
||||
if (clicked === "new-thread-on-branch") {
|
||||
// Explicit branch carry-over: reuse the thread's worktree when it
|
||||
// has one, otherwise its branch on the local checkout.
|
||||
const result = await settlePromise(() =>
|
||||
handleNewThread(scopeProjectRef(thread.environmentId, thread.projectId), {
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
envMode: thread.worktreePath ? "worktree" : "local",
|
||||
startFromOrigin: false,
|
||||
}),
|
||||
);
|
||||
if (result._tag === "Failure") {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Could not create thread",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (clicked === "rename") {
|
||||
startThreadRename(threadKey, thread.title);
|
||||
return;
|
||||
@@ -2206,7 +2232,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
copyPathToClipboard,
|
||||
copyThreadIdToClipboard,
|
||||
deleteThread,
|
||||
handleNewThread,
|
||||
markThreadUnread,
|
||||
memberProjectByScopedKey,
|
||||
project.workspaceRoot,
|
||||
@@ -2571,16 +2596,20 @@ type SortableProjectHandleProps = Pick<
|
||||
function ProjectSortMenu({
|
||||
projectSortOrder,
|
||||
threadSortOrder,
|
||||
projectGroupingMode,
|
||||
threadPreviewCount,
|
||||
onProjectSortOrderChange,
|
||||
onThreadSortOrderChange,
|
||||
onProjectGroupingModeChange,
|
||||
onThreadPreviewCountChange,
|
||||
}: {
|
||||
projectSortOrder: SidebarProjectSortOrder;
|
||||
threadSortOrder: SidebarThreadSortOrder;
|
||||
projectGroupingMode: SidebarProjectGroupingMode;
|
||||
threadPreviewCount: SidebarThreadPreviewCount;
|
||||
onProjectSortOrderChange: (sortOrder: SidebarProjectSortOrder) => void;
|
||||
onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
|
||||
onProjectGroupingModeChange: (mode: SidebarProjectGroupingMode) => void;
|
||||
onThreadPreviewCountChange: (count: SidebarThreadPreviewCount) => void;
|
||||
}) {
|
||||
const handleThreadPreviewCountChange = useCallback(
|
||||
@@ -2684,6 +2713,30 @@ function ProjectSortMenu({
|
||||
</NumberField>
|
||||
</div>
|
||||
</MenuGroup>
|
||||
<MenuSeparator />
|
||||
<MenuGroup>
|
||||
<div className="px-2 pt-2 pb-1 font-medium text-muted-foreground sm:text-xs">
|
||||
Group projects
|
||||
</div>
|
||||
<MenuRadioGroup
|
||||
value={projectGroupingMode}
|
||||
onValueChange={(value) => {
|
||||
if (value === "repository" || value === "repository_path" || value === "separate") {
|
||||
onProjectGroupingModeChange(value);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{(
|
||||
Object.entries(PROJECT_GROUPING_MODE_LABELS) as Array<
|
||||
[SidebarProjectGroupingMode, string]
|
||||
>
|
||||
).map(([value, label]) => (
|
||||
<MenuRadioItem key={value} value={value} className="min-h-7 py-1 sm:text-xs">
|
||||
{label}
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
);
|
||||
@@ -2734,6 +2787,7 @@ interface SidebarProjectsContentProps {
|
||||
handleDesktopUpdateButtonClick: () => void;
|
||||
projectSortOrder: SidebarProjectSortOrder;
|
||||
threadSortOrder: SidebarThreadSortOrder;
|
||||
projectGroupingMode: SidebarProjectGroupingMode;
|
||||
threadPreviewCount: SidebarThreadPreviewCount;
|
||||
updateSettings: ReturnType<typeof useUpdateClientSettings>;
|
||||
openAddProject: () => void;
|
||||
@@ -2774,6 +2828,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
|
||||
handleDesktopUpdateButtonClick,
|
||||
projectSortOrder,
|
||||
threadSortOrder,
|
||||
projectGroupingMode,
|
||||
threadPreviewCount,
|
||||
updateSettings,
|
||||
openAddProject,
|
||||
@@ -2815,6 +2870,12 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
|
||||
},
|
||||
[updateSettings],
|
||||
);
|
||||
const handleProjectGroupingModeChange = useCallback(
|
||||
(groupingMode: SidebarProjectGroupingMode) => {
|
||||
updateSettings({ sidebarProjectGroupingMode: groupingMode });
|
||||
},
|
||||
[updateSettings],
|
||||
);
|
||||
const handleThreadPreviewCountChange = useCallback(
|
||||
(count: SidebarThreadPreviewCount) => {
|
||||
updateSettings({ sidebarThreadPreviewCount: count });
|
||||
@@ -2878,9 +2939,11 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
|
||||
<ProjectSortMenu
|
||||
projectSortOrder={projectSortOrder}
|
||||
threadSortOrder={threadSortOrder}
|
||||
projectGroupingMode={projectGroupingMode}
|
||||
threadPreviewCount={threadPreviewCount}
|
||||
onProjectSortOrderChange={handleProjectSortOrderChange}
|
||||
onThreadSortOrderChange={handleThreadSortOrderChange}
|
||||
onProjectGroupingModeChange={handleProjectGroupingModeChange}
|
||||
onThreadPreviewCountChange={handleThreadPreviewCountChange}
|
||||
/>
|
||||
<Tooltip>
|
||||
@@ -2996,6 +3059,7 @@ export default function Sidebar() {
|
||||
const isOnSettings = pathname.startsWith("/settings");
|
||||
const sidebarThreadSortOrder = useClientSettings((s) => s.sidebarThreadSortOrder);
|
||||
const sidebarProjectSortOrder = useClientSettings((s) => s.sidebarProjectSortOrder);
|
||||
const sidebarProjectGroupingMode = useClientSettings((s) => s.sidebarProjectGroupingMode);
|
||||
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
|
||||
const sidebarThreadPreviewCount = useClientSettings((s) => s.sidebarThreadPreviewCount);
|
||||
const updateSettings = useUpdateClientSettings();
|
||||
@@ -3539,7 +3603,7 @@ export default function Sidebar() {
|
||||
|
||||
if (desktopUpdateButtonAction === "install") {
|
||||
const confirmed = window.confirm(
|
||||
getDesktopUpdateInstallConfirmationMessage(desktopUpdateState, navigator.platform),
|
||||
getDesktopUpdateInstallConfirmationMessage(desktopUpdateState),
|
||||
);
|
||||
if (!confirmed) return;
|
||||
void bridge
|
||||
@@ -3605,6 +3669,7 @@ export default function Sidebar() {
|
||||
handleDesktopUpdateButtonClick={handleDesktopUpdateButtonClick}
|
||||
projectSortOrder={sidebarProjectSortOrder}
|
||||
threadSortOrder={sidebarThreadSortOrder}
|
||||
projectGroupingMode={sidebarProjectGroupingMode}
|
||||
threadPreviewCount={sidebarThreadPreviewCount}
|
||||
updateSettings={updateSettings}
|
||||
openAddProject={openAddProjectCommandPalette}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,73 +0,0 @@
|
||||
import type { VcsStatusResult } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { prStatusIndicator, resolveThreadPr } from "./ThreadStatusIndicators";
|
||||
|
||||
function status(overrides: Partial<VcsStatusResult> = {}): VcsStatusResult {
|
||||
return {
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/current",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: {
|
||||
number: 42,
|
||||
title: "PR branch",
|
||||
url: "https://github.com/pingdotgg/t3code/pull/42",
|
||||
baseRef: "main",
|
||||
headRef: "feature/current",
|
||||
state: "open",
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("resolveThreadPr", () => {
|
||||
it("keeps local-checkout PR indicators scoped to the stored thread branch", () => {
|
||||
expect(
|
||||
resolveThreadPr({
|
||||
threadBranch: "feature/other",
|
||||
gitStatus: status(),
|
||||
hasDedicatedWorktree: false,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("shows PR indicators for dedicated worktree threads even when branch metadata is stale", () => {
|
||||
const gitStatus = status();
|
||||
|
||||
expect(
|
||||
resolveThreadPr({
|
||||
threadBranch: "feature/old-name",
|
||||
gitStatus,
|
||||
hasDedicatedWorktree: true,
|
||||
}),
|
||||
).toBe(gitStatus.pr);
|
||||
});
|
||||
|
||||
it("shows PR indicators for dedicated worktree threads even when branch metadata is missing", () => {
|
||||
const gitStatus = status();
|
||||
|
||||
expect(
|
||||
resolveThreadPr({
|
||||
threadBranch: null,
|
||||
gitStatus,
|
||||
hasDedicatedWorktree: true,
|
||||
}),
|
||||
).toBe(gitStatus.pr);
|
||||
});
|
||||
});
|
||||
|
||||
describe("prStatusIndicator", () => {
|
||||
it("formats PR tooltips with number, uppercase status, and title", () => {
|
||||
expect(prStatusIndicator(status().pr, undefined)).toMatchObject({
|
||||
tooltip: "PR #42 - Open: PR branch",
|
||||
tooltipLead: "PR #42 - Open",
|
||||
tooltipTitle: "PR branch",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -22,8 +22,6 @@ export interface PrStatusIndicator {
|
||||
label: string;
|
||||
colorClass: string;
|
||||
tooltip: string;
|
||||
tooltipLead: string;
|
||||
tooltipTitle: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
@@ -39,26 +37,14 @@ export function prStatusIndicator(
|
||||
pr: ThreadPr,
|
||||
provider: VcsStatusResult["sourceControlProvider"] | null | undefined,
|
||||
): PrStatusIndicator | null {
|
||||
function formatPrState(state: NonNullable<ThreadPr>["state"]): string {
|
||||
return state.charAt(0).toUpperCase() + state.slice(1);
|
||||
}
|
||||
|
||||
function formatPrStatusLead(pr: NonNullable<ThreadPr>, changeRequestShortName: string): string {
|
||||
return `${changeRequestShortName} #${pr.number} - ${formatPrState(pr.state)}`;
|
||||
}
|
||||
if (!pr) return null;
|
||||
const presentation = resolveChangeRequestPresentation(provider);
|
||||
|
||||
const tooltipLead = formatPrStatusLead(pr, presentation.shortName);
|
||||
const tooltip = `${tooltipLead}: ${pr.title}`;
|
||||
|
||||
if (pr.state === "open") {
|
||||
return {
|
||||
label: `${presentation.shortName} open`,
|
||||
colorClass: "text-emerald-600 dark:text-emerald-300/90",
|
||||
tooltip,
|
||||
tooltipLead,
|
||||
tooltipTitle: pr.title,
|
||||
tooltip: `#${pr.number} ${presentation.shortName} open: ${pr.title}`,
|
||||
url: pr.url,
|
||||
};
|
||||
}
|
||||
@@ -66,9 +52,7 @@ export function prStatusIndicator(
|
||||
return {
|
||||
label: `${presentation.shortName} closed`,
|
||||
colorClass: "text-zinc-500 dark:text-zinc-400/80",
|
||||
tooltip,
|
||||
tooltipLead,
|
||||
tooltipTitle: pr.title,
|
||||
tooltip: `#${pr.number} ${presentation.shortName} closed: ${pr.title}`,
|
||||
url: pr.url,
|
||||
};
|
||||
}
|
||||
@@ -76,9 +60,7 @@ export function prStatusIndicator(
|
||||
return {
|
||||
label: `${presentation.shortName} merged`,
|
||||
colorClass: "text-violet-600 dark:text-violet-300/90",
|
||||
tooltip,
|
||||
tooltipLead,
|
||||
tooltipTitle: pr.title,
|
||||
tooltip: `#${pr.number} ${presentation.shortName} merged: ${pr.title}`,
|
||||
url: pr.url,
|
||||
};
|
||||
}
|
||||
@@ -89,31 +71,11 @@ export function ChangeRequestStatusIcon({ className }: { className?: string }) {
|
||||
return <GitPullRequestIcon className={className} />;
|
||||
}
|
||||
|
||||
export function PrStatusTooltipContent({ status }: { status: PrStatusIndicator }) {
|
||||
return (
|
||||
<span className="flex max-w-[min(34rem,calc(100vw-2rem))] items-stretch overflow-hidden whitespace-nowrap">
|
||||
<span className="shrink-0 pr-2 font-medium">{status.tooltipLead}</span>
|
||||
<span className="min-h-4 shrink-0 border-border/70 border-l" aria-hidden="true" />
|
||||
<span className="min-w-0 truncate pl-2">{status.tooltipTitle}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveThreadPr(input: {
|
||||
threadBranch: string | null;
|
||||
gitStatus: VcsStatusResult | null;
|
||||
hasDedicatedWorktree: boolean;
|
||||
}): ThreadPr | null {
|
||||
const { threadBranch, gitStatus, hasDedicatedWorktree } = input;
|
||||
if (gitStatus === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (hasDedicatedWorktree) {
|
||||
return gitStatus.pr ?? null;
|
||||
}
|
||||
|
||||
if (threadBranch === null || gitStatus.refName !== threadBranch) {
|
||||
export function resolveThreadPr(
|
||||
threadBranch: string | null,
|
||||
gitStatus: VcsStatusResult | null,
|
||||
): ThreadPr | null {
|
||||
if (threadBranch === null || gitStatus === null || gitStatus.refName !== threadBranch) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -237,18 +199,14 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar
|
||||
const threadProjectCwd = threadProject?.workspaceRoot ?? null;
|
||||
const gitCwd = thread.worktreePath ?? threadProjectCwd;
|
||||
const gitStatus = useEnvironmentQuery(
|
||||
(thread.branch != null || thread.worktreePath !== null) && gitCwd !== null
|
||||
thread.branch != null && gitCwd !== null
|
||||
? vcsEnvironment.status({
|
||||
environmentId: thread.environmentId,
|
||||
input: { cwd: gitCwd },
|
||||
})
|
||||
: null,
|
||||
);
|
||||
const pr = resolveThreadPr({
|
||||
threadBranch: thread.branch,
|
||||
gitStatus: gitStatus.data,
|
||||
hasDedicatedWorktree: thread.worktreePath !== null,
|
||||
});
|
||||
const pr = resolveThreadPr(thread.branch, gitStatus.data);
|
||||
const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider);
|
||||
const threadStatus = resolveThreadStatusPill({
|
||||
thread: {
|
||||
@@ -275,9 +233,7 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar
|
||||
>
|
||||
<ChangeRequestStatusIcon className="size-3" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
<PrStatusTooltipContent status={prStatus} />
|
||||
</TooltipPopup>
|
||||
<TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
{threadStatus ? <ThreadStatusLabel status={threadStatus} /> : null}
|
||||
|
||||
@@ -10,86 +10,23 @@ describe("ChangedFilesCard", () => {
|
||||
<ChangedFilesCard
|
||||
turnId={TurnId.make("turn-1")}
|
||||
files={[{ path: "README.md", kind: "modified", additions: 2, deletions: 1 }]}
|
||||
expanded
|
||||
showCompactPreview={false}
|
||||
allDirectoriesExpanded
|
||||
resolvedTheme="light"
|
||||
onExpandedChange={() => {}}
|
||||
onToggleAllDirectories={() => {}}
|
||||
onOpenTurnDiff={() => {}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain('data-changed-files-state="expanded"');
|
||||
expect(markup).toContain('aria-expanded="true"');
|
||||
expect(markup).toContain('class="sticky top-0 z-10');
|
||||
expect(markup).not.toContain("self-start");
|
||||
expect(markup).toContain("whitespace-nowrap");
|
||||
expect(markup).toContain("!size-[22px]");
|
||||
expect(markup).toContain("size-3");
|
||||
expect(markup).toContain('aria-label="Collapse all folders"');
|
||||
expect(markup).toContain('aria-label="Open diff"');
|
||||
expect(markup).toContain('role="group" aria-label="2 additions, 1 deletions"');
|
||||
expect(markup).toContain('aria-label="Collapse all"');
|
||||
expect(markup).toContain('aria-label="View diff"');
|
||||
expect(markup).toContain("1 changed file");
|
||||
expect(markup).not.toContain("1 changed files");
|
||||
});
|
||||
|
||||
it("renders a scope and representative-file preview for a large latest change", () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<ChangedFilesCard
|
||||
turnId={TurnId.make("turn-1")}
|
||||
files={[
|
||||
{ path: "apps/web/src/App.tsx", kind: "modified", additions: 120, deletions: 20 },
|
||||
{ path: "apps/web/src/App.test.tsx", kind: "modified", additions: 30, deletions: 2 },
|
||||
{
|
||||
path: "packages/shared/src/git.ts",
|
||||
kind: "modified",
|
||||
additions: 15,
|
||||
deletions: 4,
|
||||
},
|
||||
{ path: "README.md", kind: "modified", additions: 3, deletions: 0 },
|
||||
]}
|
||||
expanded={false}
|
||||
showCompactPreview
|
||||
allDirectoriesExpanded={false}
|
||||
resolvedTheme="light"
|
||||
onExpandedChange={() => {}}
|
||||
onToggleAllDirectories={() => {}}
|
||||
onOpenTurnDiff={() => {}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain('data-changed-files-state="preview"');
|
||||
expect(markup).toContain('aria-expanded="false"');
|
||||
expect(markup).toContain("apps");
|
||||
expect(markup).toContain("2 files");
|
||||
expect(markup).toContain("packages");
|
||||
expect(markup).toContain("root");
|
||||
expect(markup).toContain("App.tsx");
|
||||
expect(markup).toContain("git.ts");
|
||||
expect(markup).toContain("README.md");
|
||||
expect(markup).toContain("Show all 4 files");
|
||||
expect(markup).not.toContain("App.test.tsx");
|
||||
});
|
||||
|
||||
it("keeps older collapsed changes to a one-line receipt", () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<ChangedFilesCard
|
||||
turnId={TurnId.make("turn-1")}
|
||||
files={[{ path: "apps/web/src/App.tsx", kind: "modified", additions: 120, deletions: 20 }]}
|
||||
expanded={false}
|
||||
showCompactPreview={false}
|
||||
allDirectoriesExpanded={false}
|
||||
resolvedTheme="light"
|
||||
onExpandedChange={() => {}}
|
||||
onToggleAllDirectories={() => {}}
|
||||
onOpenTurnDiff={() => {}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain('data-changed-files-state="collapsed"');
|
||||
expect(markup).toContain("1 changed file");
|
||||
expect(markup).not.toContain("Show all");
|
||||
expect(markup).not.toContain("App.tsx");
|
||||
});
|
||||
});
|
||||
|
||||
describe("ChangedFilesTree", () => {
|
||||
|
||||
@@ -19,184 +19,95 @@ import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
|
||||
import { PierreEntryIcon } from "./PierreEntryIcon";
|
||||
import { Button } from "../ui/button";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import {
|
||||
changedFileName,
|
||||
selectChangedFilePreview,
|
||||
summarizeChangedFileScopes,
|
||||
} from "./changedFilesPresentation";
|
||||
|
||||
const EMPTY_DIRECTORY_OVERRIDES: Record<string, boolean> = {};
|
||||
|
||||
export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
|
||||
turnId: TurnId;
|
||||
files: ReadonlyArray<TurnDiffFileChange>;
|
||||
expanded: boolean;
|
||||
showCompactPreview: boolean;
|
||||
allDirectoriesExpanded: boolean;
|
||||
resolvedTheme: "light" | "dark";
|
||||
onExpandedChange: (expanded: boolean) => void;
|
||||
onToggleAllDirectories: () => void;
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
}) {
|
||||
const {
|
||||
turnId,
|
||||
files,
|
||||
expanded,
|
||||
showCompactPreview,
|
||||
allDirectoriesExpanded,
|
||||
resolvedTheme,
|
||||
onExpandedChange,
|
||||
onToggleAllDirectories,
|
||||
onOpenTurnDiff,
|
||||
} = props;
|
||||
const summaryStat = useMemo(() => summarizeTurnDiffStats(files), [files]);
|
||||
const scopeSummary = useMemo(() => summarizeChangedFileScopes(files), [files]);
|
||||
const previewFiles = useMemo(() => selectChangedFilePreview(files), [files]);
|
||||
const compactPreviewVisible = showCompactPreview && !expanded;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="mt-4 rounded-2xl border border-border/70 bg-secondary p-2 dark:border-transparent dark:bg-input/32"
|
||||
data-changed-files-state={
|
||||
expanded ? "expanded" : compactPreviewVisible ? "preview" : "collapsed"
|
||||
}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-between gap-2 rounded-xl px-1",
|
||||
expanded &&
|
||||
"sticky top-2 z-10 mb-2 bg-secondary dark:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))]",
|
||||
)}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={expanded}
|
||||
data-scroll-anchor-ignore
|
||||
className="group flex min-w-0 flex-1 items-center gap-1.5 rounded-lg px-1 py-1.5 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
onClick={() => onExpandedChange(!expanded)}
|
||||
>
|
||||
<ChevronRightIcon
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"size-3.5 shrink-0 text-muted-foreground transition-transform",
|
||||
expanded && "rotate-90",
|
||||
)}
|
||||
/>
|
||||
<span className="flex min-w-0 items-center gap-1 whitespace-nowrap font-medium text-foreground text-xs leading-4">
|
||||
<span>
|
||||
{files.length} changed file{files.length === 1 ? "" : "s"}
|
||||
</span>
|
||||
{hasNonZeroStat(summaryStat) && (
|
||||
<DiffStatLabel
|
||||
additions={summaryStat.additions}
|
||||
className="text-xs leading-4"
|
||||
deletions={summaryStat.deletions}
|
||||
layout="inline"
|
||||
/>
|
||||
)}
|
||||
<div className="mt-4 rounded-2xl bg-background p-2 pt-4 shadow-xs/5 not-dark:bg-clip-padding dark:bg-input/32">
|
||||
<div className="sticky top-0 z-10 mb-3 flex items-center justify-between gap-2 bg-background px-2 before:absolute before:inset-x-0 before:-top-4 before:h-4 before:bg-background before:content-[''] dark:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))] dark:before:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))]">
|
||||
<p className="flex items-center gap-1 whitespace-nowrap font-medium text-foreground text-xs leading-4">
|
||||
<span>
|
||||
{files.length} changed file{files.length === 1 ? "" : "s"}
|
||||
</span>
|
||||
<span className="ml-1 hidden truncate text-[11px] text-muted-foreground group-hover:text-foreground/80 sm:inline">
|
||||
{expanded ? "Hide files" : "Show files"}
|
||||
</span>
|
||||
</button>
|
||||
{hasNonZeroStat(summaryStat) && (
|
||||
<DiffStatLabel
|
||||
additions={summaryStat.additions}
|
||||
className="text-xs leading-4"
|
||||
deletions={summaryStat.deletions}
|
||||
layout="inline"
|
||||
/>
|
||||
)}
|
||||
</p>
|
||||
<div className="flex items-center gap-1.5">
|
||||
{expanded ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="outline"
|
||||
className="!size-[22px]"
|
||||
aria-label={
|
||||
allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"
|
||||
}
|
||||
data-scroll-anchor-ignore
|
||||
onClick={onToggleAllDirectories}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{allDirectoriesExpanded ? (
|
||||
<ChevronsDownUpIcon className="size-3" />
|
||||
) : (
|
||||
<ChevronsUpDownIcon className="size-3" />
|
||||
)}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
{allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
size="icon-xs"
|
||||
variant="outline"
|
||||
aria-label="Open diff"
|
||||
className="!size-[22px]"
|
||||
aria-label={allDirectoriesExpanded ? "Collapse all" : "Expand all"}
|
||||
data-scroll-anchor-ignore
|
||||
onClick={onToggleAllDirectories}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{allDirectoriesExpanded ? (
|
||||
<ChevronsDownUpIcon className="size-3" />
|
||||
) : (
|
||||
<ChevronsUpDownIcon className="size-3" />
|
||||
)}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="outline"
|
||||
className="!size-[22px]"
|
||||
aria-label="View diff"
|
||||
onClick={() => onOpenTurnDiff(turnId, files[0]?.path)}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<FileDiffIcon className="size-3" />
|
||||
<span className="hidden sm:inline">Open diff</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">Open the full diff</TooltipPopup>
|
||||
<TooltipPopup side="top">View diff</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
{expanded ? (
|
||||
<ChangedFilesTree
|
||||
key={`changed-files-tree:${turnId}`}
|
||||
turnId={turnId}
|
||||
files={files}
|
||||
allDirectoriesExpanded={allDirectoriesExpanded}
|
||||
resolvedTheme={resolvedTheme}
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
/>
|
||||
) : compactPreviewVisible ? (
|
||||
<div className="px-2 pb-1.5 pt-1">
|
||||
<p className="flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-[11px] text-muted-foreground">
|
||||
{scopeSummary.map((scope, index) => (
|
||||
<span key={scope.label} className="inline-flex items-center gap-1">
|
||||
{index > 0 ? <span aria-hidden="true">·</span> : null}
|
||||
<span className="font-mono text-foreground/75">{scope.label}</span>
|
||||
<span>
|
||||
{scope.fileCount} file{scope.fileCount === 1 ? "" : "s"}
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
</p>
|
||||
<div className="mt-2 flex flex-wrap items-center gap-1.5">
|
||||
{previewFiles.map((file) => (
|
||||
<button
|
||||
key={file.path}
|
||||
type="button"
|
||||
title={file.path}
|
||||
className="inline-flex max-w-48 items-center gap-1 rounded-md border border-border/70 bg-background/45 px-1.5 py-1 font-mono text-[10px] text-muted-foreground transition-colors hover:bg-accent/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
onClick={() => onOpenTurnDiff(turnId, file.path)}
|
||||
>
|
||||
<PierreEntryIcon
|
||||
pathValue={file.path}
|
||||
kind="file"
|
||||
theme={resolvedTheme}
|
||||
className="size-3 shrink-0 text-muted-foreground/70"
|
||||
/>
|
||||
<span className="truncate">{changedFileName(file.path)}</span>
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md px-1.5 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-accent/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
onClick={() => onExpandedChange(true)}
|
||||
>
|
||||
Show all {files.length} files
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
<ChangedFilesTree
|
||||
key={`changed-files-tree:${turnId}`}
|
||||
turnId={turnId}
|
||||
files={files}
|
||||
allDirectoriesExpanded={allDirectoriesExpanded}
|
||||
resolvedTheme={resolvedTheme}
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
@@ -18,12 +18,14 @@ import {
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
} from "@t3tools/contracts";
|
||||
import type { EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection";
|
||||
import {
|
||||
connectionStatusText,
|
||||
type EnvironmentConnectionPresentation,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";
|
||||
import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import {
|
||||
memo,
|
||||
type ReactNode,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useImperativeHandle,
|
||||
@@ -32,7 +34,6 @@ import {
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import {
|
||||
clampCollapsedComposerCursor,
|
||||
type ComposerTrigger,
|
||||
@@ -92,64 +93,6 @@ import { buildExpandedImagePreview, type ExpandedImagePreview } from "./Expanded
|
||||
import { basenameOfPath } from "../../pierre-icons";
|
||||
import { cn, randomUUID } from "~/lib/utils";
|
||||
import { Separator } from "../ui/separator";
|
||||
|
||||
function ComposerCommandMenuLayer(props: { anchor: HTMLElement | null; children: ReactNode }) {
|
||||
const [position, setPosition] = useState<{
|
||||
bottom: number;
|
||||
left: number;
|
||||
maxHeight: number;
|
||||
width: number;
|
||||
} | null>(null);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const anchor = props.anchor;
|
||||
if (!anchor) {
|
||||
setPosition(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const updatePosition = () => {
|
||||
const rect = anchor.getBoundingClientRect();
|
||||
setPosition({
|
||||
bottom: window.innerHeight - rect.top + 8,
|
||||
left: rect.left,
|
||||
maxHeight: Math.max(96, rect.top - 24),
|
||||
width: rect.width,
|
||||
});
|
||||
};
|
||||
|
||||
updatePosition();
|
||||
window.addEventListener("resize", updatePosition);
|
||||
window.addEventListener("scroll", updatePosition, true);
|
||||
|
||||
const observer =
|
||||
typeof ResizeObserver === "undefined" ? null : new ResizeObserver(updatePosition);
|
||||
observer?.observe(anchor);
|
||||
|
||||
return () => {
|
||||
observer?.disconnect();
|
||||
window.removeEventListener("resize", updatePosition);
|
||||
window.removeEventListener("scroll", updatePosition, true);
|
||||
};
|
||||
}, [props.anchor]);
|
||||
|
||||
if (!position) return null;
|
||||
|
||||
return createPortal(
|
||||
<div
|
||||
className="pointer-events-auto fixed z-[70]"
|
||||
style={{
|
||||
bottom: position.bottom,
|
||||
left: position.left,
|
||||
maxHeight: position.maxHeight,
|
||||
width: position.width,
|
||||
}}
|
||||
>
|
||||
{props.children}
|
||||
</div>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
import { Button } from "../ui/button";
|
||||
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
@@ -163,7 +106,6 @@ import {
|
||||
LockIcon,
|
||||
LockOpenIcon,
|
||||
PenLineIcon,
|
||||
SparklesIcon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import { proposedPlanTitle } from "../../proposedPlan";
|
||||
@@ -207,11 +149,6 @@ const runtimeModeConfig: Record<
|
||||
description: "Auto-approve edits, ask before other actions.",
|
||||
icon: PenLineIcon,
|
||||
},
|
||||
auto: {
|
||||
label: "Auto",
|
||||
description: "An AI reviewer approves routine actions; risky ones still ask.",
|
||||
icon: SparklesIcon,
|
||||
},
|
||||
"full-access": {
|
||||
label: "Full access",
|
||||
description: "Allow commands and edits without prompts.",
|
||||
@@ -960,7 +897,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
const [isComposerPrimaryActionsCompact, setIsComposerPrimaryActionsCompact] = useState(false);
|
||||
const [isComposerModelPickerOpen, setIsComposerModelPickerOpen] = useState(false);
|
||||
const [isComposerFocused, setIsComposerFocused] = useState(false);
|
||||
const [composerMenuAnchor, setComposerMenuAnchor] = useState<HTMLDivElement | null>(null);
|
||||
const isMobileViewport = useMediaQuery("max-sm");
|
||||
const isComposerCollapsedMobile =
|
||||
isMobileViewport && !forceExpandedOnMobile && !isComposerFocused;
|
||||
@@ -2218,7 +2154,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
ref={composerSurfaceRef}
|
||||
data-chat-composer-mobile-collapsed={isComposerCollapsedMobile ? "true" : "false"}
|
||||
className={cn(
|
||||
"rounded-[20px] transition-[background-color] duration-200",
|
||||
"chat-composer-glass rounded-[20px] transition-[background-color] duration-200",
|
||||
isDragOverComposer ? "bg-accent/45 ring-1 ring-primary/70" : null,
|
||||
projectSelectionRequired ? "opacity-75" : null,
|
||||
composerProviderState.composerSurfaceClassName,
|
||||
@@ -2395,7 +2331,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
) : null}
|
||||
|
||||
<div
|
||||
ref={setComposerMenuAnchor}
|
||||
className={cn(
|
||||
"relative px-3 pb-2 sm:px-4",
|
||||
hasComposerHeader ? "pt-2.5 sm:pt-3" : "pt-3.5 sm:pt-4",
|
||||
@@ -2403,7 +2338,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
)}
|
||||
>
|
||||
{composerMenuOpen && !isComposerApprovalState && (
|
||||
<ComposerCommandMenuLayer anchor={composerMenuAnchor}>
|
||||
<div className="absolute inset-x-0 bottom-full z-20 mb-2">
|
||||
<ComposerCommandMenu
|
||||
items={composerMenuItems}
|
||||
resolvedTheme={resolvedTheme}
|
||||
@@ -2418,7 +2353,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
onHighlightedItemChange={onComposerMenuItemHighlighted}
|
||||
onSelect={onSelectComposerItem}
|
||||
/>
|
||||
</ComposerCommandMenuLayer>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isComposerCollapsedMobile &&
|
||||
@@ -2574,11 +2509,15 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
? "Add feedback to refine the plan, or leave this blank to implement it"
|
||||
: projectSelectionRequired
|
||||
? "Choose a project above to start a thread"
|
||||
: noProviderAvailable
|
||||
? "Enable a provider in Settings to send a message"
|
||||
: phase === "disconnected"
|
||||
? "Ask for follow-up changes or attach images"
|
||||
: "Ask anything, @tag files/folders, $use skills, or / for commands"
|
||||
: environmentUnavailable
|
||||
? `${environmentUnavailable.label}: ${connectionStatusText(
|
||||
environmentUnavailable.connection,
|
||||
)}`
|
||||
: noProviderAvailable
|
||||
? "Enable a provider in Settings to send a message"
|
||||
: phase === "disconnected"
|
||||
? "Ask for follow-up changes or attach images"
|
||||
: "Ask anything, @tag files/folders, $use skills, or / for commands"
|
||||
}
|
||||
disabled={isConnecting || isComposerApprovalState || projectSelectionRequired}
|
||||
/>
|
||||
|
||||
@@ -16,7 +16,6 @@ import ProjectScriptsControl, {
|
||||
} from "../ProjectScriptsControl";
|
||||
import { OpenInPicker } from "./OpenInPicker";
|
||||
import { usePrimaryEnvironmentId } from "../../state/environments";
|
||||
import { useT3ProjectFileScripts } from "~/hooks/useT3ProjectFileScripts";
|
||||
import { ProjectFavicon } from "../ProjectFavicon";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
@@ -75,10 +74,6 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
onDeleteProjectScript,
|
||||
}: ChatHeaderProps) {
|
||||
const primaryEnvironmentId = usePrimaryEnvironmentId();
|
||||
const fileScripts = useT3ProjectFileScripts(
|
||||
activeThreadEnvironmentId,
|
||||
activeProjectScripts ? activeProjectCwd : null,
|
||||
);
|
||||
const showOpenInPicker = shouldShowOpenInPicker({
|
||||
activeProjectName,
|
||||
activeThreadEnvironmentId,
|
||||
@@ -131,7 +126,6 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
{activeProjectScripts && (
|
||||
<ProjectScriptsControl
|
||||
scripts={activeProjectScripts}
|
||||
fileScripts={fileScripts}
|
||||
keybindings={keybindings}
|
||||
preferredScriptId={preferredScriptId}
|
||||
onRunScript={onRunProjectScript}
|
||||
|
||||
@@ -71,7 +71,6 @@ export const CompactComposerControlsMenu = memo(function CompactComposerControls
|
||||
>
|
||||
<MenuRadioItem value="approval-required">Supervised</MenuRadioItem>
|
||||
<MenuRadioItem value="auto-accept-edits">Auto-accept edits</MenuRadioItem>
|
||||
<MenuRadioItem value="auto">Auto</MenuRadioItem>
|
||||
<MenuRadioItem value="full-access">Full access</MenuRadioItem>
|
||||
</MenuRadioGroup>
|
||||
{props.activePlan ? (
|
||||
|
||||
Loaded 100 of 189 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user