Compare commits

...
Author SHA1 Message Date
Theo BrowneandClaude Opus 5 83faf56b65 fix: make restart-aware reconnect work from every entry point
The restart overlay only worked in ChatView, but ServerUpdateAction also
renders in Settings → Connections. An update triggered there armed the
window and then nothing consumed it: no calm status, no fast reconnect,
and the window was never cleared — exactly the behavior this PR set out
to fix, still reachable from the other entry point.

The window lifecycle (reconnect pokes, and ending the window once its
restart has been seen through) moves out of ChatView into an app-level
hook mounted in AppRoot, since a restart outlives whatever view started
it. ChatView now only presents. The saved-backend rows in Settings get
the same calm treatment: status dot, tooltip, and a "restarting to
finish the server update" line instead of a connection error.

The retry cadence was also a hardcoded 2s with no cap, which is ~45
teardown/rebuild cycles across a 90s window for a server that never
returns. It now starts at 2s (the point is beating the supervisor's
1s→16s escalation), eases to 8s, and stops after 12 pokes, leaving
normal supervisor backoff in charge — the right end state for a server
that is not coming back.

Pacing and poke-eligibility are pure exported functions with tests;
verified by removing the cap, which fails the budget test.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-26 15:37:16 -07:00
Theo BrowneandClaude Opus 5 85b8a38455 fix: end the restart window when its restart has been seen through
Two more review findings, plus a self-correction.

Stale wentAwayRef (Macroscope): the ref persists for the component's
lifetime, so an outage from before the click satisfied the resolve
predicate on the next render and re-enabled the button mid-update,
allowing a second dispatch. Reset both refs when an attempt is armed so
only outages during that attempt count.

Unrelated outage shown as a restart (Bugbot): making the window
write-once-and-expire last round traded one bug for another — any
disconnect within 90s was dressed up as an intentional restart. The
window now ends once the environment has gone away and come back, i.e.
the restart it was armed for has been seen through. That is the narrow
version of what an earlier revision got wrong by ending it on any healthy
connection; the difference is requiring the disconnect first.

The observation is used only for the banner. The update action's release
path stays independent of it — coupling those is what produced the
earlier family of bugs where each consumer invalidated the other's
evidence.

Also removed a test committed in the previous change that passed with and
without its fix, so it verified nothing.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-24 17:23:35 -07:00
Theo BrowneandClaude Opus 5 3c9f1db60f fix: decouple update-action release from the restart window
Cursor found three defects (one High) that shared a root cause: the
restart window had been given a second job — releasing the update
action — while the window itself deleted the evidence that job depended
on. Patching each symptom would have kept the coupling, so sawDisconnect
is gone.

The window is now write-once-and-expire. It is armed while the old
server is still connected, so nothing observed on the connection can
reliably end it early; presentation gates on the environment actually
being unavailable, which makes a window outliving its restart inert.
That removes both "a brief blip during install poisons the flag" and
"reconnecting clears the flag before the action can read it".

Releasing the action is now its own signal, independent of the window,
with the two shapes a rejected restart can take:
  - the environment went away and came back, so something restarted but
    did not deliver the new version; or
  - the window lapsed with the connection never dropping, so no restart
    ever happened (systemd refused it and rolled back).
The second is the High-severity case: previously nothing set the flag,
so the action stayed disabled for the full 12-minute window.

The decision is a pure exported predicate because the component harness
stubs useEffect. Verified by removing the lapsed-window branch, which
fails exactly the test covering that case.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-24 17:13:30 -07:00
Theo BrowneandClaude Opus 5 02abc2cb3d fix: make the restart window survive until the restart is observed
An independent gpt-5.6-sol review found that the restart overlay never
actually engaged in the normal flow — the feature was inert.

ChatView cleared the expectation on any render where the connection was
"connected". But the window is armed while the old server is still
connected (that is the point: the acknowledgement races its own
disconnect), so the store update triggered a render that destroyed the
window within milliseconds, long before the server went away. Both
re-arm points had the same problem. The user therefore still got the
outage banner and escalating backoff.

The window now tracks whether the restart's disconnect was actually
observed. A connected environment only ends the window once that has
happened; before it, "connected" just means the restart has not started
yet. Re-arming preserves an already-observed disconnect.

Also fixes the follow-on the same review found: because a rejected
restart can no longer be reported through the acknowledged RPC, the
update action could stay disabled for the full 12-minute safety window
with the mismatch unresolved. A settled restart window (disconnect seen,
window closed) now releases it so the user can retry immediately.

The restarting/settled decisions are pure exported predicates, since the
component test harness stubs useEffect and cannot exercise
effect-driven behavior. Both are tested, and both tests were confirmed
to fail against the old logic.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-24 16:59:17 -07:00
Theo BrowneandClaude Opus 5 7aecc5d47a fix: address review findings on the reconnect flow
Three defects found by Macroscope and Cursor Bugbot:

- The restart window was armed only at click time, but an npm install can
  consume most of the 10-minute request window, so a slow-but-successful
  update restarted after the window had lapsed and was presented as an
  outage. Re-arm from the acknowledgement and from the interrupt path,
  matching what keepPendingForRestart already does for the button expiry.

- Effect.catch on the detached restart fiber only sees typed failures, so
  an unexpected defect skipped the inFlight reset and left a live process
  refusing every further update until restarted by other means. Release
  the guard from Effect.onExit, outside the typed handler. Success still
  deliberately keeps it set: systemd is about to stop the process and a
  second update would race the handoff.

- "A server update is already in progress" is a typed failure, so it
  cleared a restart overlay that the earlier still-pending update needed,
  restoring the harsh reconnect UI mid-restart. That reason now lives in
  contracts as SERVER_SELF_UPDATE_ALREADY_RUNNING_REASON with an
  isAlreadyRunning helper, so the client can distinguish it structurally
  instead of matching prose.

Each fix has a regression test; the defect-path test was confirmed to
fail without the onExit change.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-24 16:47:51 -07:00
Theo BrowneandClaude Opus 5 b462ae5f2f fix: clean up the remote server update reconnect flow
Clicking "Update server" on a relay-connected server showed a spinner,
then a disconnected banner with a raw transport error, then hung until
the page was refreshed. Three separate causes:

1. The boot-service (systemd) update path ran `systemctl --user restart`
   synchronously inside the RPC handler, so the process died before the
   acknowledgement flushed. Every successful update reached the client as
   an interrupt, which ServerUpdateAction released quietly — no success
   toast, and nothing told the connection layer a restart was coming.
   The restart is now deferred like the respawn path. Rollback and the
   in-flight reset move onto the detached fiber and log instead of
   failing the (already-acknowledged) RPC.

2. Reconnect backoff escalates to 16s, so the client was frequently
   asleep exactly when the server came back; refreshing reset the
   failure count, which is why refreshing "fixed" it. A restart-expected
   overlay is now armed before dispatch and retries on a flat 2s cadence
   while it is active, and only while the supervisor is sleeping in
   backoff so a live attempt is never interrupted. It expires on its own
   after 90s and is withdrawn on an explicit RPC failure, which proves
   the server stayed up.

3. Two consecutive websocket-ticket failures evicted the cached DPoP
   token, forcing a full relay bootstrap and token exchange during
   reconnect. Eviction is now limited to failures suggesting a stale
   endpoint; plain unreachability (network/timeout) — the shape of a
   restart — keeps the token.

Also stops piping raw transport messages (which embed internal endpoint
URLs) into the composer banner: presentation maps each failure reason to
a stable summary and carries the reason for callers, while the raw
message remains on the supervisor state for diagnostics.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-24 16:35:49 -07:00
202e5609ff feat(sidebar-v2): thread snoozing (#4311)
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: maria <[email protected]>
2026-07-23 22:09:32 -07:00
Theo BrowneandClaude Fable 5 bb38c3320d fix(web): keep settled threads reachable when opened directly (#4413)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-23 19:18:32 -07:00
Theo BrowneandClaude Fable 5 6b9a5987f6 fix: Claude Code skills discoverable for the composer $ picker (#4414)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-23 18:39:42 -07:00
Theo BrowneandClaude Fable 5 fc3f78f5d9 fix: tone down branch-mismatch banner (#4416)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-23 18:38:05 -07:00
Theo BrowneandClaude Fable 5 2f41c073a2 Stop new threads inheriting checkout/branch from viewed thread (#4411)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-23 18:06:21 -07:00
Theo Browne 51672b6ecb feat(web): collapse large git diffs by default to make chat more readable (#4409) 2026-07-23 18:06:04 -07:00
Julius Marmingeandcodex 67a7b1a1d3 Improve composer glass fallbacks (#4406)
Co-authored-by: codex <[email protected]>
2026-07-23 22:41:10 +00:00
Julius Marminge ce467da9cf Polish iOS git progress overlay with glass effects (#4387) 2026-07-24 00:39:09 +02:00
Julius Marminge 6ef7aa8399 Fix composer context strip alignment and glass shell (#4404) 2026-07-23 18:32:14 -04:00
Theo BrowneandClaude Fable 5 193e3c62e6 fix(client-runtime): keep a warm thread un-settled despite a merged/closed PR (#4309)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-23 15:20:44 -07:00
Theo Browne 91dfe60a99 Fix thread loading flash (#4396) 2026-07-23 15:19:06 -07:00
maria edb12401e5 fix(cli): publish nightly branded favicons (#4372) 2026-07-23 23:36:02 +02:00
79fe11bc1c Add preview color scheme controls and simplify project grouping (#4385)
Co-authored-by: codex <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-23 23:35:40 +02:00
Julius Marmingeandcodex b3e51317e4 Fix logical project grouping labels on mobile (#4391)
Co-authored-by: codex <[email protected]>
2026-07-23 22:57:42 +02:00
Theo BrowneandClaude Fable 5 ddd5a46f39 fix(web): sidebar v2 polish — jump hints, working duration, in-flight fade, settled sort (#4274)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-23 22:50:19 +02:00
Theo Browne 88c69ffff6 fix(server): parse CLI version in update preflight (#4389) 2026-07-23 12:58:33 -07:00
maria 979854895c Fix thread tooltip folder icon color (#4383) 2026-07-23 18:10:51 +00:00
maria 9cbe50d10d fix(web): restore dark composer toolbar styling 2026-07-23 12:52:15 -04:00
Julius Marmingeandcodex 9d9208cec5 [codex] Group projects in new-thread pickers (#4312)
Co-authored-by: codex <[email protected]>
2026-07-23 16:11:48 +00:00
Julius Marmingeandcodex 57100fba85 [codex] restore Sidebar V2 project actions (#4373)
Co-authored-by: codex <[email protected]>
2026-07-23 16:11:27 +00:00
3afb4a9ef9 Restore grouped project filtering in Sidebar V2 (#4282)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-07-23 18:06:56 +02:00
Julius Marmingeandcodex 315b27385d [codex] Deduplicate connection failure messaging (#4367)
Co-authored-by: codex <[email protected]>
2026-07-23 18:06:49 +02:00
Julius Marmingeandcodex 719c905eac [codex] Move mobile project grouping to General settings (#4315)
Co-authored-by: codex <[email protected]>
2026-07-23 18:06:44 +02:00
Julius Marmingeandcodex 0542abc75e [codex] Group project scopes in mobile thread lists (#4314)
Co-authored-by: codex <[email protected]>
2026-07-23 18:06:38 +02:00
Julius Marmingeandcodex 7609495bf7 [codex] Move project grouping to General settings (#4313)
Co-authored-by: codex <[email protected]>
2026-07-23 18:06:33 +02:00
Yukun Shan b41e89eba9 fix(web): warn before silent Windows updates (#4350) 2026-07-23 14:36:56 +02:00
Julius Marmingeandcodex 4d83436415 Unify dialog glass and fix composer overlays (#4365)
Co-authored-by: codex <[email protected]>
2026-07-23 14:15:29 +02:00
Julius Marminge e51538b812 Restore light-mode surfaces and refine dialog styling
- Restore light-mode glass, dialog, dropdown, and composer colors
- Refine provider wizard, changed-file cards, sidebar controls, and buttons
- Update wizard step tests for the new list structure
2026-07-23 13:09:55 +02:00
149 changed files with 8535 additions and 1884 deletions

No files matched your search

+1
View File
@@ -50,6 +50,7 @@ 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";
+11
View File
@@ -13,6 +13,7 @@ import {
DesktopPreviewRecordingSaveInputSchema,
DesktopPreviewRegisterWebviewInputSchema,
DesktopPreviewScreenshotArtifactSchema,
DesktopPreviewSetColorSchemeInputSchema,
DesktopPreviewTabInputSchema,
DesktopPreviewWebviewConfigSchema,
PreviewAnnotationPayloadSchema,
@@ -138,6 +139,15 @@ 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",
@@ -346,6 +356,7 @@ export const methods = [
zoomOut,
resetZoom,
hardReload,
setColorScheme,
openDevTools,
clearCookies,
clearCache,
+2
View File
@@ -160,6 +160,8 @@ 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),
+73
View File
@@ -365,6 +365,79 @@ 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* () {
+72 -2
View File
@@ -7,6 +7,7 @@
*/
import type {
DesktopPreviewAnnotationTheme,
DesktopPreviewColorScheme,
DesktopPreviewPointerEvent,
PreviewAnnotationPayload,
PreviewAnnotationRect,
@@ -84,6 +85,7 @@ export interface PreviewTabState {
canGoBack: boolean;
canGoForward: boolean;
zoomFactor: number;
colorScheme: DesktopPreviewColorScheme;
controller: "human" | "agent" | "none";
updatedAt: string;
}
@@ -1288,6 +1290,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
canGoBack: false,
canGoForward: false,
zoomFactor: DEFAULT_ZOOM_FACTOR,
colorScheme: "system",
controller: "none",
updatedAt,
};
@@ -1320,6 +1323,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
canGoBack: false,
canGoForward: false,
zoomFactor: DEFAULT_ZOOM_FACTOR,
colorScheme: "system",
controller: "none",
updatedAt,
};
@@ -1386,7 +1390,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
wc.getZoomFactor(),
);
yield* attachListeners(tabId, wc);
runFork(ensureControlSession(wc).pipe(Effect.ignore));
runFork(restoreControlSession(tabId, wc));
const registeredAt = yield* currentIso;
const registration = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
const current = tabs.get(tabId);
@@ -1457,6 +1461,7 @@ 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,
};
@@ -1525,7 +1530,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(ensureControlSession(wc).pipe(Effect.ignore));
if (!wc.isDestroyed()) runFork(restoreControlSession(tabId, wc));
});
wc.openDevTools({ mode: "detach" });
});
@@ -1684,6 +1689,65 @@ 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,
) {
@@ -2526,6 +2590,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
revealArtifact,
saveRecording,
setAnnotationTheme,
setColorScheme,
setMainWindow,
startRecording,
stopRecording,
@@ -2830,6 +2895,10 @@ 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>;
@@ -2921,6 +2990,7 @@ 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 -5
View File
@@ -13,7 +13,10 @@ 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 } from "./features/settings/appearance/AppearancePreferencesProvider";
import {
AppearancePreferencesProvider,
useAppearancePreferences,
} from "./features/settings/appearance/AppearancePreferencesProvider";
import { RootStack } from "./Stack";
import { appAtomRegistry } from "./state/atom-registry";
import { OverlayPortalHost } from "./components/OverlayPortal";
@@ -26,6 +29,10 @@ 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
@@ -40,18 +47,25 @@ 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>
+1 -43
View File
@@ -1,8 +1,4 @@
import type {
EnvironmentId,
SidebarProjectGroupingMode,
SidebarThreadSortOrder,
} from "@t3tools/contracts";
import type { EnvironmentId, SidebarThreadSortOrder } from "@t3tools/contracts";
import type { MenuAction } from "@react-native-menu/menu";
import { useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
@@ -28,7 +24,6 @@ import {
} from "./home-list-filter-menu";
import {
hasCustomHomeListOptions,
PROJECT_GROUPING_OPTIONS,
PROJECT_SORT_OPTIONS,
THREAD_SORT_OPTIONS,
} from "./home-list-options";
@@ -43,13 +38,11 @@ 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;
}) {
@@ -143,20 +136,10 @@ 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,
@@ -210,13 +193,6 @@ 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],
);
@@ -409,10 +385,6 @@ 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
@@ -480,20 +452,6 @@ 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,7 +4,6 @@ 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";
@@ -16,6 +15,7 @@ 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,7 +54,6 @@ export function HomeRouteScreen() {
const {
options: listOptions,
setSelectedEnvironmentId,
setProjectGroupingMode,
setProjectSortOrder,
setThreadSortOrder,
} = useHomeListOptions(availableEnvironmentIds);
@@ -62,16 +61,15 @@ export function HomeRouteScreen() {
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
const projectFilterOptions = useMemo(
() =>
projects
.filter(
(project) =>
selectedEnvironmentId === null || project.environmentId === selectedEnvironmentId,
)
.map((project) => ({
key: scopedProjectKey(project.environmentId, project.id),
label: project.title,
})),
[projects, selectedEnvironmentId],
buildHomeProjectScopes({
projects,
environmentId: selectedEnvironmentId,
projectGroupingMode: listOptions.projectGroupingMode,
}).map((scope) => ({
key: scope.key,
label: scope.title,
})),
[listOptions.projectGroupingMode, projects, selectedEnvironmentId],
);
useEffect(() => {
if (
@@ -119,11 +117,9 @@ 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" })}
@@ -146,7 +142,6 @@ export function HomeRouteScreen() {
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
}
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
onProjectGroupingModeChange={setProjectGroupingMode}
onProjectSortOrderChange={setProjectSortOrder}
onSearchQueryChange={setSearchQuery}
onSelectThread={(thread) => {
+172 -52
View File
@@ -15,17 +15,15 @@ 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, ScrollView, View } from "react-native";
import { ActivityIndicator, FlatList, Platform, Pressable, View } from "react-native";
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { 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";
@@ -54,7 +52,12 @@ import {
type HomeGroupDisplayState,
type HomeListItem,
} from "./homeListItems";
import { buildHomeThreadGroups, type HomeProjectSortOrder } from "./homeThreadList";
import {
buildHomeProjectScopes,
buildHomeThreadGroups,
sortHomeProjectScopes,
type HomeProjectSortOrder,
} from "./homeThreadList";
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "./thread-swipe-actions";
import { WorkspaceConnectionStatus } from "./WorkspaceConnectionStatus";
import { shouldShowWorkspaceConnectionStatus } from "./workspace-connection-status";
@@ -79,7 +82,6 @@ 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;
@@ -243,43 +245,69 @@ export function HomeScreen(props: HomeScreenProps) {
onScrollBeginDrag: handleScrollBeginDrag,
});
const scopedProject = useMemo(
const projectScopes = useMemo(
() =>
buildHomeProjectScopes({
projects: props.projects,
environmentId: props.selectedEnvironmentId,
projectGroupingMode: props.projectGroupingMode,
}),
[props.projectGroupingMode, props.projects, props.selectedEnvironmentId],
);
const selectedProjectScope = useMemo(
() =>
props.selectedProjectKey === null
? null
: (props.projects.find(
(project) =>
scopedProjectKey(project.environmentId, project.id) === props.selectedProjectKey &&
(props.selectedEnvironmentId === null ||
project.environmentId === props.selectedEnvironmentId),
: (projectScopes.find(
(scope) =>
scope.key === props.selectedProjectKey ||
scope.projectRefs.some(
(projectRef) =>
scopedProjectKey(projectRef.environmentId, projectRef.projectId) ===
props.selectedProjectKey,
),
) ?? null),
[props.projects, props.selectedEnvironmentId, props.selectedProjectKey],
[projectScopes, props.selectedProjectKey],
);
const selectedProjectRefKeys = useMemo(
() =>
selectedProjectScope === null
? null
: new Set(
selectedProjectScope.projectRefs.map((projectRef) =>
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
),
),
[selectedProjectScope],
);
const scopedProjects = useMemo(
() => (scopedProject === null ? props.projects : [scopedProject]),
[props.projects, scopedProject],
() =>
selectedProjectRefKeys === null
? props.projects
: props.projects.filter((project) =>
selectedProjectRefKeys.has(scopedProjectKey(project.environmentId, project.id)),
),
[props.projects, selectedProjectRefKeys],
);
const scopedThreads = useMemo(
() =>
scopedProject === null
selectedProjectRefKeys === null
? props.threads
: props.threads.filter(
(thread) =>
thread.environmentId === scopedProject.environmentId &&
thread.projectId === scopedProject.id,
: props.threads.filter((thread) =>
selectedProjectRefKeys.has(scopedProjectKey(thread.environmentId, thread.projectId)),
),
[props.threads, scopedProject],
[props.threads, selectedProjectRefKeys],
);
const scopedPendingTasks = useMemo(
() =>
scopedProject === null
selectedProjectRefKeys === null
? props.pendingTasks
: props.pendingTasks.filter(
(pendingTask) =>
pendingTask.message.environmentId === scopedProject.environmentId &&
pendingTask.creation.projectId === scopedProject.id,
: props.pendingTasks.filter((pendingTask) =>
selectedProjectRefKeys.has(
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
),
),
[props.pendingTasks, scopedProject],
[props.pendingTasks, selectedProjectRefKeys],
);
const projectGroups = useMemo(
@@ -334,23 +362,64 @@ export function HomeScreen(props: HomeScreenProps) {
}, [props.projects]);
const v2ProjectScopeKey = props.selectedProjectKey;
const setV2ProjectScopeKey = props.onProjectChange;
const v2ScopeProjects = useMemo(
() =>
props.selectedEnvironmentId === null
? props.projects
: props.projects.filter((project) => project.environmentId === props.selectedEnvironmentId),
[props.projects, props.selectedEnvironmentId],
sortHomeProjectScopes({
scopes: projectScopes,
threads: props.threads,
pendingTasks: props.pendingTasks,
projectSortOrder: props.projectSortOrder,
}),
[
props.pendingTasks,
props.projects,
props.projectSortOrder,
props.selectedEnvironmentId,
props.threads,
projectScopes,
],
);
const v2ScopedProject = useMemo(
const v2ScopedProjectGroup = useMemo(
() =>
v2ProjectScopeKey === null
? null
: (v2ScopeProjects.find(
(project) => scopedProjectKey(project.environmentId, project.id) === v2ProjectScopeKey,
(scope) =>
scope.key === v2ProjectScopeKey ||
scope.projectRefs.some(
(projectRef) =>
scopedProjectKey(projectRef.environmentId, projectRef.projectId) ===
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
@@ -403,6 +472,10 @@ export function HomeScreen(props: HomeScreenProps) {
// boundary is actually crossed while the app stays open (mirrors web);
// without a clock dependency the partition memoizes a frozen "now".
const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
// Snooze wake times are second-precise; a counter bumped exactly at the
// next wake boundary re-runs the partition with a fresh clock so a woken
// thread reappears immediately instead of on the next minute tick.
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
useEffect(() => {
if (!threadListV2Enabled) return;
// Refresh immediately on enable: the mount-time value can be hours old
@@ -424,37 +497,59 @@ export function HomeScreen(props: HomeScreenProps) {
}
return supported;
}, [serverConfigs]);
const snoozeEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>();
for (const [environmentId, config] of serverConfigs) {
if (config.environment.capabilities.threadSnooze === true) {
supported.add(environmentId);
}
}
return supported;
}, [serverConfigs]);
const threadListV2Layout = useMemo(() => {
if (!threadListV2Enabled) return { items: [], hiddenSettledCount: 0 };
if (!threadListV2Enabled)
return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
// Settled threads are live shells; archived threads keep their original
// "hidden from lists" meaning.
return buildThreadListV2Items({
threads: props.threads.filter((thread) => thread.archivedAt === null),
environmentId: props.selectedEnvironmentId,
projectRef:
v2ScopedProject === null
? null
: {
environmentId: v2ScopedProject.environmentId,
projectId: v2ScopedProject.id,
},
projectRefs: v2ScopedProjectGroup === null ? null : v2ScopedProjectGroup.projectRefs,
searchQuery: props.searchQuery,
changeRequestStateByKey,
settlementEnvironmentIds,
snoozeEnvironmentIds,
settledLimit: settledVisibleCount,
now: `${nowMinute}:00.000Z`,
snoozeNow: new Date().toISOString(),
});
}, [
changeRequestStateByKey,
nowMinute,
snoozeWakeTick,
settledVisibleCount,
settlementEnvironmentIds,
snoozeEnvironmentIds,
props.searchQuery,
props.selectedEnvironmentId,
props.threads,
threadListV2Enabled,
v2ScopedProject,
v2ScopedProjectGroup,
]);
// Re-partition the moment the earliest snooze expires (clamped to the
// signed-32-bit setTimeout range; far-future wakes re-arm at the clamp).
const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
useEffect(() => {
if (nextSnoozeWakeAt === null) return;
const wakeAtMs = Date.parse(nextSnoozeWakeAt);
if (Number.isNaN(wakeAtMs)) return;
const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
const id = setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs);
return () => clearTimeout(id);
// snoozeWakeTick must re-arm the timer even when nextSnoozeWakeAt is
// unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
// range) the boundary string is identical and the chain would die.
}, [nextSnoozeWakeAt, snoozeWakeTick]);
const threadListV2Items = threadListV2Layout.items;
const renderV2Item = useCallback(
@@ -467,6 +562,9 @@ 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)
@@ -510,6 +608,7 @@ export function HomeScreen(props: HomeScreenProps) {
props.savedConnectionsById,
serverConfigs,
settlementEnvironmentIds,
v2ProjectTitleByProjectKey,
],
);
const v2KeyExtractor = useCallback(
@@ -699,9 +798,10 @@ export function HomeScreen(props: HomeScreenProps) {
(pendingTask) =>
(props.selectedEnvironmentId === null ||
pendingTask.message.environmentId === props.selectedEnvironmentId) &&
(v2ScopedProject === null ||
(pendingTask.message.environmentId === v2ScopedProject.environmentId &&
pendingTask.creation.projectId === v2ScopedProject.id)) &&
(v2ScopedProjectKeys === null ||
v2ScopedProjectKeys.has(
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
)) &&
(v2SearchQuery.length === 0 || pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
);
// Project scoping lives in the header filter menu (no inline chip row on
@@ -728,9 +828,9 @@ export function HomeScreen(props: HomeScreenProps) {
const listEmpty = !hasResults ? (
hasSearchQuery ? (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
) : scopedProject !== null ? (
) : selectedProjectScope !== null ? (
<EmptyState
title={`No threads in ${scopedProject.title}`}
title={`No threads in ${selectedProjectScope.title}`}
detail="Choose another project or create a new task."
/>
) : selectedEnvironmentLabel ? (
@@ -745,14 +845,34 @@ export function HomeScreen(props: HomeScreenProps) {
// Self-contained: v1's listEmpty keys off projectGroups, which ignores the
// v2 project scope, so it can be null (results elsewhere) while this list
// is empty. Search outranks the scope — "No results" names the actionable
// fact when a query is active. Pending tasks render in the header, so the
// list showing them isn't empty in the user's eyes.
// fact when a query is active. Snoozed threads outrank the rest: "No
// threads yet" over an inbox that is merely all-snoozed reads as data
// loss. Pending tasks render in the header, so the list showing them
// isn't empty in the user's eyes.
const v2SnoozedCount = threadListV2Layout.snoozedCount;
const v2ListEmpty =
v2PendingTasks.length > 0 ? null : hasSearchQuery ? (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
) : v2ScopedProject !== null ? (
v2SnoozedCount > 0 ? (
// The snoozed threads already passed this search filter: "No
// results" would claim nothing matched when matches are merely
// parked.
<EmptyState
title={
v2SnoozedCount === 1 ? "1 matching thread snoozed" : `All matching threads snoozed`
}
detail={`Threads matching "${props.searchQuery}" are snoozed and return when their wake time passes.`}
/>
) : (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
)
) : v2SnoozedCount > 0 ? (
<EmptyState
title={`No threads in ${v2ScopedProject.title}`}
title={v2SnoozedCount === 1 ? "1 thread snoozed" : `${v2SnoozedCount} threads snoozed`}
detail="Snoozed threads return when their wake time passes."
/>
) : v2ScopedProjectGroup !== null ? (
<EmptyState
title={`No threads in ${v2ScopedProjectGroup.title}`}
detail="Choose another project or create a new task."
/>
) : (
@@ -15,17 +15,16 @@ 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,15 +1,7 @@
import type {
EnvironmentId,
SidebarProjectGroupingMode,
SidebarThreadSortOrder,
} from "@t3tools/contracts";
import type { EnvironmentId, SidebarThreadSortOrder } from "@t3tools/contracts";
import type { HomeProjectSortOrder } from "./homeThreadList";
import {
PROJECT_GROUPING_OPTIONS,
PROJECT_SORT_OPTIONS,
THREAD_SORT_OPTIONS,
} from "./home-list-options";
import { PROJECT_SORT_OPTIONS, THREAD_SORT_OPTIONS } from "./home-list-options";
export interface HomeListFilterMenuEnvironment {
readonly environmentId: EnvironmentId;
@@ -47,13 +39,10 @@ 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. */
@@ -61,14 +50,6 @@ 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",
@@ -136,17 +117,6 @@ 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,5 +1,4 @@
import {
DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
} from "@t3tools/contracts";
@@ -14,7 +13,6 @@ 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", () => {
@@ -22,11 +20,10 @@ describe("home list options", () => {
expect(hasCustomHomeListOptions(defaults)).toBe(false);
});
it("marks environment filters and grouping changes as customized", () => {
it("marks environment filters 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,7 +4,6 @@ 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";
@@ -26,9 +25,18 @@ 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;
@@ -45,28 +53,6 @@ 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,
@@ -75,26 +61,34 @@ 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 }: PropsWithChildren) {
export function HomeListOptionsProvider({
children,
projectGroupingMode,
}: PropsWithChildren<{ readonly projectGroupingMode: SidebarProjectGroupingMode }>) {
const [options, setOptions] = useState<HomeListOptions>(defaultHomeListOptions);
const value = useMemo(() => ({ options, setOptions }), [options]);
const value = useMemo(
() => ({ options, setOptions, projectGroupingMode }),
[options, projectGroupingMode],
);
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"
@@ -104,8 +98,7 @@ export function hasCustomHomeListOptions(
options.selectedEnvironmentId !== null ||
(options.selectedProjectKey !== null && options.selectedProjectKey !== undefined) ||
options.projectSortOrder !== defaultProjectSortOrder ||
options.threadSortOrder !== DEFAULT_SIDEBAR_THREAD_SORT_ORDER ||
options.projectGroupingMode !== DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE
options.threadSortOrder !== DEFAULT_SIDEBAR_THREAD_SORT_ORDER
);
}
@@ -119,10 +112,14 @@ export function useHomeListOptions(availableEnvironmentIds: ReadonlySet<Environm
availableEnvironmentIds.has(options.selectedEnvironmentId)
? options.selectedEnvironmentId
: null;
const resolvedOptions =
const availableOptions =
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 }));
@@ -133,15 +130,10 @@ 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,7 +5,11 @@ import type {
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { buildHomeThreadGroups } from "./homeThreadList";
import {
buildHomeProjectScopes,
buildHomeThreadGroups,
sortHomeProjectScopes,
} from "./homeThreadList";
function makeProject(
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
@@ -67,6 +71,346 @@ 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({
+185 -29
View File
@@ -1,14 +1,20 @@
import {
deriveLogicalProjectKey,
derivePhysicalProjectKey,
deriveProjectGroupLabel,
} from "@t3tools/client-runtime/state/project-grouping";
import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { getThreadSortTimestamp, sortThreads } from "@t3tools/client-runtime/state/thread-sort";
import {
getThreadSortTimestamp,
sortThreads,
toSortableTimestamp,
} from "@t3tools/client-runtime/state/thread-sort";
import type {
EnvironmentId,
ScopedProjectRef,
SidebarProjectGroupingMode,
SidebarProjectSortOrder,
SidebarThreadSortOrder,
@@ -22,6 +28,161 @@ 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.
@@ -103,22 +264,18 @@ export function buildHomeThreadGroups(input: {
const groups = new Map<string, MutableHomeThreadGroup>();
const groupKeyByProjectKey = new Map<string, string>();
for (const project of input.projects) {
if (input.environmentId !== null && project.environmentId !== input.environmentId) {
continue;
}
const groupKey = deriveLogicalProjectKey(project, {
groupingMode: input.projectGroupingMode,
for (const scope of buildHomeProjectScopes(input)) {
groups.set(scope.key, {
key: scope.key,
projects: [...scope.projects],
pendingTasks: [],
threads: [],
});
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: [] });
for (const projectRef of scope.projectRefs) {
groupKeyByProjectKey.set(
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
scope.key,
);
}
}
@@ -186,10 +343,7 @@ export function buildHomeThreadGroups(input: {
continue;
}
const title =
group.projects.length > 1
? deriveProjectGroupLabel({ representative, members: group.projects })
: representative.title;
const title = deriveProjectGroupLabel({ representative, members: group.projects });
const groupMatches =
query.length === 0 ||
title.toLocaleLowerCase().includes(query) ||
@@ -215,19 +369,21 @@ export function buildHomeThreadGroups(input: {
? selectRecentThreads(sortedThreads, input.threadSortOrder, now)
: sortedThreads;
// 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,
),
).pipe(
// 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,
),
),
Option.flatMap((threadProject) =>
Arr.findFirst(
group.projects,
(project) =>
project.environmentId === thread.environmentId && project.id === thread.projectId,
derivePhysicalProjectKey(project) === derivePhysicalProjectKey(threadProject),
),
),
Option.getOrNull,
@@ -2,7 +2,8 @@ import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { EnvironmentId, ThreadId, type SidebarProjectGroupingMode } from "@t3tools/contracts";
import { useAtomValue } from "@effect/atom-react";
import { useFocusEffect } from "@react-navigation/native";
import {
NavigationContext,
@@ -22,6 +23,7 @@ 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,
@@ -34,11 +36,12 @@ 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 } from "../home/home-list-options";
import { HomeListOptionsProvider, resolveProjectGroupingMode } from "../home/home-list-options";
import { ThreadNavigationSidebar } from "../threads/ThreadNavigationSidebar";
import { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation";
import { WorkspaceInspectorPane } from "./workspace-inspector-pane";
@@ -184,6 +187,31 @@ 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();
@@ -474,7 +502,7 @@ export function AdaptiveWorkspaceLayout(props: {
);
return (
<HomeListOptionsProvider>
<HomeListOptionsProvider projectGroupingMode={projectGroupingMode}>
<AdaptiveWorkspaceContext.Provider value={contextValue}>
<View testID="adaptive-workspace-layout" className="flex-1 flex-row">
{shouldRenderPrimarySidebar && layout.listPaneWidth !== null ? (
@@ -771,7 +771,9 @@ export function ReviewSheet(props: ReviewSheetProps) {
environment.presentation?.connection ?? {
phase: "available",
error: null,
reason: null,
traceId: null,
retryAt: null,
}
}
resourceName="review"
@@ -119,6 +119,8 @@ function LocalSettingsRouteScreen() {
/>
</SettingsSection>
<GeneralSettingsSection />
<SettingsSection title="Appearance">
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
</SettingsSection>
@@ -504,6 +506,8 @@ function ConfiguredSettingsRouteScreen() {
/>
</SettingsSection>
<GeneralSettingsSection />
<SettingsSection title="Appearance">
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
</SettingsSection>
@@ -518,6 +522,25 @@ 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.
@@ -1209,7 +1209,9 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
environment.presentation?.connection ?? {
phase: "available",
error: null,
reason: null,
traceId: null,
retryAt: null,
}
}
resourceName="terminal"
@@ -1,8 +1,9 @@
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, View } from "react-native";
import Animated, { FadeIn, FadeOut } from "react-native-reanimated";
import { ActivityIndicator, Pressable, StyleSheet, useColorScheme, View } from "react-native";
import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText";
@@ -10,6 +11,9 @@ 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;
@@ -45,7 +49,7 @@ export function GitActionProgressOverlay(props: {
return (
<Animated.View
entering={FadeIn.duration(200)}
entering={isLiquidGlassSupported ? undefined : FadeIn.duration(200)}
exiting={FadeOut.duration(150)}
className="absolute inset-x-3 z-[100]"
style={{ top: insets.top + 48 }}
@@ -61,16 +65,11 @@ export function GitActionProgressOverlay(props: {
function OverlayContent(props: { readonly progress: GitActionProgress }) {
const { progress } = props;
const iconColor = useThemeColor("--color-icon");
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}`}
>
const glassBorder = useThemeColor("--color-header-border");
const glassTint = useThemeColor("--color-glass-tint");
const isDarkMode = useColorScheme() === "dark";
const content = (
<>
<OverlayIcon phase={progress.phase} iconColor={iconColor} />
<View className="flex-1 gap-0.5">
@@ -89,7 +88,56 @@ function OverlayContent(props: { readonly progress: GitActionProgress }) {
{progress.prUrl ? (
<SymbolView name="arrow.up.right" size={13} tintColor={iconColor} type="monochrome" />
) : null}
</View>
</>
);
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>
);
}
@@ -33,7 +33,6 @@ 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,
@@ -48,7 +47,7 @@ import {
type HomeGroupDisplayState,
type HomeListItem,
} from "../home/homeListItems";
import { buildHomeThreadGroups } from "../home/homeThreadList";
import { buildHomeProjectScopes, buildHomeThreadGroups } from "../home/homeThreadList";
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "../home/thread-swipe-actions";
import { usePendingTaskListActions } from "../home/usePendingTaskListActions";
import { useThreadListActions } from "../home/useThreadListActions";
@@ -217,36 +216,47 @@ function ThreadNavigationSidebarPane(
() => new Set(environments.map((environment) => environment.environmentId)),
[environments],
);
const {
options,
setSelectedEnvironmentId,
setProjectGroupingMode,
setProjectSortOrder,
setThreadSortOrder,
} = useHomeListOptions(availableEnvironmentIds);
const { options, setSelectedEnvironmentId, 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(
() =>
projects
.filter(
(project) =>
options.selectedEnvironmentId === null ||
project.environmentId === options.selectedEnvironmentId,
)
.map((project) => ({
key: scopedProjectKey(project.environmentId, project.id),
label: project.title,
})),
[options.selectedEnvironmentId, projects],
projectScopes.map((scope) => ({
key: scope.key,
label: scope.title,
})),
[projectScopes],
);
const selectedProject = useMemo(
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(
() =>
selectedProjectKey === null
? null
: (projects.find(
(project) => scopedProjectKey(project.environmentId, project.id) === selectedProjectKey,
) ?? null),
[projects, selectedProjectKey],
: (projectScopes.find((scope) => scope.key === selectedProjectKey) ?? null),
[projectScopes, selectedProjectKey],
);
useEffect(() => {
if (
@@ -256,31 +266,45 @@ 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(
() => (selectedProject === null ? projects : [selectedProject]),
[projects, selectedProject],
() =>
selectedProjectRefs === null
? projects
: projects.filter((project) =>
selectedProjectRefs.has(scopedProjectKey(project.environmentId, project.id)),
),
[projects, selectedProjectRefs],
);
const scopedThreads = useMemo(
() =>
selectedProject === null
selectedProjectRefs === null
? threads
: threads.filter(
(thread) =>
thread.environmentId === selectedProject.environmentId &&
thread.projectId === selectedProject.id,
: threads.filter((thread) =>
selectedProjectRefs.has(scopedProjectKey(thread.environmentId, thread.projectId)),
),
[selectedProject, threads],
[selectedProjectRefs, threads],
);
const scopedPendingTasks = useMemo(
() =>
selectedProject === null
selectedProjectRefs === null
? pendingTasks
: pendingTasks.filter(
(pendingTask) =>
pendingTask.message.environmentId === selectedProject.environmentId &&
pendingTask.creation.projectId === selectedProject.id,
: pendingTasks.filter((pendingTask) =>
selectedProjectRefs.has(
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
),
),
[pendingTasks, selectedProject],
[pendingTasks, selectedProjectRefs],
);
const groups = useMemo(
() =>
@@ -375,6 +399,10 @@ function ThreadNavigationSidebarPane(
// crossed while the pane stays open; without a clock dependency the
// partition memoizes a frozen "now".
const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
// Snooze wake times are second-precise; a counter bumped exactly at the
// next wake boundary re-runs the partition with a fresh clock so a woken
// thread reappears immediately instead of on the next minute tick.
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
useEffect(() => {
if (!threadListV2Enabled) return;
// Refresh immediately on enable: the mount-time value can be hours old
@@ -396,35 +424,57 @@ function ThreadNavigationSidebarPane(
}
return supported;
}, [serverConfigs]);
const snoozeEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>();
for (const [environmentId, config] of serverConfigs) {
if (config.environment.capabilities.threadSnooze === true) {
supported.add(environmentId);
}
}
return supported;
}, [serverConfigs]);
const threadListV2Layout = useMemo(() => {
if (!threadListV2Enabled) return { items: [], hiddenSettledCount: 0 };
if (!threadListV2Enabled)
return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
return buildThreadListV2Items({
threads: threads.filter((thread) => thread.archivedAt === null),
environmentId: options.selectedEnvironmentId,
projectRef:
selectedProject === null
? null
: {
environmentId: selectedProject.environmentId,
projectId: selectedProject.id,
},
projectRefs: selectedProjectScope === null ? null : selectedProjectScope.projectRefs,
searchQuery: props.searchQuery,
changeRequestStateByKey,
settlementEnvironmentIds,
snoozeEnvironmentIds,
settledLimit: settledVisibleCount,
now: `${nowMinute}:00.000Z`,
snoozeNow: new Date().toISOString(),
});
}, [
changeRequestStateByKey,
nowMinute,
snoozeWakeTick,
options.selectedEnvironmentId,
props.searchQuery,
settledVisibleCount,
settlementEnvironmentIds,
snoozeEnvironmentIds,
threadListV2Enabled,
threads,
selectedProject,
selectedProjectScope,
]);
// Re-partition the moment the earliest snooze expires (clamped to the
// signed-32-bit setTimeout range; far-future wakes re-arm at the clamp).
const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
useEffect(() => {
if (nextSnoozeWakeAt === null) return;
const wakeAtMs = Date.parse(nextSnoozeWakeAt);
if (Number.isNaN(wakeAtMs)) return;
const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
const id = setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs);
return () => clearTimeout(id);
// snoozeWakeTick must re-arm the timer even when nextSnoozeWakeAt is
// unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
// range) the boundary string is identical and the chain would die.
}, [nextSnoozeWakeAt, snoozeWakeTick]);
const listItems = useMemo<readonly SidebarListItem[]>(() => {
if (!threadListV2Enabled) return listLayout.items;
// Queued offline tasks render above the thread rows (mirrors the
@@ -437,9 +487,10 @@ function ThreadNavigationSidebarPane(
(pendingTask) =>
(options.selectedEnvironmentId === null ||
pendingTask.message.environmentId === options.selectedEnvironmentId) &&
(selectedProject === null ||
(pendingTask.message.environmentId === selectedProject.environmentId &&
pendingTask.creation.projectId === selectedProject.id)) &&
(selectedProjectRefs === null ||
selectedProjectRefs.has(
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
)) &&
(v2SearchQuery.length === 0 ||
pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
);
@@ -469,7 +520,7 @@ function ThreadNavigationSidebarPane(
options.selectedEnvironmentId,
pendingTasks,
props.searchQuery,
selectedProject,
selectedProjectRefs,
threadListV2Enabled,
threadListV2Layout,
]);
@@ -541,16 +592,6 @@ 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],
@@ -594,15 +635,10 @@ 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,
@@ -739,6 +775,7 @@ function ThreadNavigationSidebarPane(
variant={item.item.variant}
showSettledDivider={item.item.showSettledDivider}
project={projectByKey.get(scopeKey) ?? null}
projectTitle={projectTitleByProjectKey.get(scopeKey)}
providerDriver={
serverConfigs
.get(thread.environmentId)
@@ -868,6 +905,7 @@ function ThreadNavigationSidebarPane(
openPendingTask,
projectByKey,
projectCwdByKey,
projectTitleByProjectKey,
props.onNewThreadInProject,
props.selectedThreadKey,
props.width,
@@ -898,12 +936,10 @@ function ThreadNavigationSidebarPane(
selectedProjectKey,
projectSortOrder: options.projectSortOrder,
threadSortOrder: options.threadSortOrder,
projectGroupingMode: options.projectGroupingMode,
onEnvironmentChange: setSelectedEnvironmentId,
onProjectChange: setSelectedProjectKey,
onProjectSortOrderChange: setProjectSortOrder,
onThreadSortOrderChange: setThreadSortOrder,
onProjectGroupingModeChange: setProjectGroupingMode,
listOrganization: !threadListV2Enabled,
}),
[
@@ -911,7 +947,6 @@ function ThreadNavigationSidebarPane(
options,
projectFilterOptions,
selectedProjectKey,
setProjectGroupingMode,
setProjectSortOrder,
setSelectedEnvironmentId,
setThreadSortOrder,
@@ -927,15 +962,28 @@ function ThreadNavigationSidebarPane(
}),
[filterIcon, filterMenu, props.onOpenSettings],
);
// "No threads yet" over an inbox that is merely all-snoozed reads as
// data loss; name the snoozed threads instead.
const snoozedCount = threadListV2Layout.snoozedCount;
const listEmpty = (
<Text className="px-2 py-4 text-sm text-foreground-muted">
{catalogState.isLoadingConnections
? "Loading threads…"
: props.searchQuery.trim().length > 0
? "No matching threads"
: selectedProject !== null
? `No threads in ${selectedProject.title}`
: "No threads yet"}
? snoozedCount > 0
? // Snoozed matches passed this same search filter — "No
// matching threads" would misreport them as nonexistent.
snoozedCount === 1
? "1 matching thread snoozed"
: "All matching threads snoozed"
: "No matching threads"
: snoozedCount > 0
? snoozedCount === 1
? "1 thread snoozed"
: `${snoozedCount} threads snoozed`
: selectedProjectScope !== null
? `No threads in ${selectedProjectScope.title}`
: "No threads yet"}
</Text>
);
@@ -90,6 +90,7 @@ 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
@@ -219,7 +220,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
<ProjectFavicon
environmentId={thread.environmentId}
size={15}
projectTitle={props.project.title}
projectTitle={props.projectTitle ?? props.project.title}
workspaceRoot={props.project.workspaceRoot}
/>
) : null}
@@ -230,7 +231,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
)}
numberOfLines={1}
>
{props.project?.title ?? ""}
{props.projectTitle ?? props.project?.title ?? ""}
</Text>
<Text
className={cn(
@@ -393,7 +394,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
<ProjectFavicon
environmentId={thread.environmentId}
size={15}
projectTitle={props.project.title}
projectTitle={props.projectTitle ?? props.project.title}
workspaceRoot={props.project.workspaceRoot}
/>
</View>
@@ -77,6 +77,85 @@ describe("sortThreadsForListV2", () => {
});
describe("buildThreadListV2Items", () => {
it("hides snoozed threads and counts them — visibility parity with web", () => {
const layout = buildThreadListV2Items({
threads: [
makeThread({ id: ThreadId.make("active"), title: "Active" }),
makeThread({
id: ThreadId.make("snoozed"),
title: "Snoozed",
snoozedUntil: "2026-06-03T09:00:00.000Z",
snoozedAt: "2026-06-01T12:00:00.000Z",
}),
makeThread({
id: ThreadId.make("woken"),
title: "Woken",
// Wake time already passed: back in the active list.
snoozedUntil: "2026-06-01T18:00:00.000Z",
snoozedAt: "2026-06-01T12:00:00.000Z",
}),
],
environmentId: null,
searchQuery: "",
now: NOW,
});
// Same createdAt → static sort tiebreaks by id; the point is the woken
// thread is BACK in the card block and the snoozed one is gone.
expect(layout.items.map((item) => item.thread.id)).toEqual(["active", "woken"]);
expect(layout.snoozedCount).toBe(1);
});
it("classifies snooze with the second-precise clock and reports the next wake", () => {
const layout = buildThreadListV2Items({
threads: [
makeThread({
id: ThreadId.make("just-woke"),
title: "Just woke",
// Woke 30s ago: hidden under the minute-floored clock, visible
// under the precise one.
snoozedUntil: "2026-06-02T00:00:30.000Z",
snoozedAt: "2026-06-01T12:00:00.000Z",
}),
makeThread({
id: ThreadId.make("still-snoozed"),
title: "Still snoozed",
snoozedUntil: "2026-06-02T09:00:00.000Z",
snoozedAt: "2026-06-01T12:00:00.000Z",
}),
],
environmentId: null,
searchQuery: "",
// Minute-floored partition clock vs precise snooze clock.
now: "2026-06-02T00:01:00.000Z",
snoozeNow: "2026-06-02T00:01:07.500Z",
});
expect(layout.items.map((item) => item.thread.id)).toEqual(["just-woke"]);
expect(layout.snoozedCount).toBe(1);
expect(layout.nextSnoozeWakeAt).toBe("2026-06-02T09:00:00.000Z");
});
it("keeps snoozed threads visible on environments without the snooze capability", () => {
const layout = buildThreadListV2Items({
threads: [
makeThread({
id: ThreadId.make("snoozed"),
title: "Snoozed",
snoozedUntil: "2026-06-03T09:00:00.000Z",
snoozedAt: "2026-06-01T12:00:00.000Z",
}),
],
environmentId: null,
searchQuery: "",
snoozeEnvironmentIds: new Set(),
now: NOW,
});
expect(layout.items.map((item) => item.thread.id)).toEqual(["snoozed"]);
expect(layout.snoozedCount).toBe(0);
});
it("partitions settled threads into a slim tail with one divider", () => {
const { items } = buildThreadListV2Items({
threads: [
@@ -166,13 +245,36 @@ describe("buildThreadListV2Items", () => {
}),
],
environmentId: null,
projectRef: { environmentId, projectId: ProjectId.make("project-1") },
projectRefs: [{ 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", () => {
@@ -1,4 +1,4 @@
import { effectiveSettled } from "@t3tools/client-runtime/state/thread-settled";
import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
@@ -84,6 +84,13 @@ export interface ThreadListV2Layout {
readonly items: ThreadListV2Item[];
/** Settled threads beyond the render limit (behind "Show more"). */
readonly hiddenSettledCount: number;
/** Snoozed threads hidden from the list (visibility parity with web's
collapsed Snoozed shelf; mobile has no shelf UI yet). */
readonly snoozedCount: number;
/** Soonest wake time among hidden snoozed threads, or null. Callers arm
a timeout at this boundary so the list re-partitions the moment a
snooze expires instead of on the next minute tick. */
readonly nextSnoozeWakeAt: string | null;
}
/**
@@ -95,10 +102,10 @@ export interface ThreadListV2Layout {
export function buildThreadListV2Items(input: {
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
readonly environmentId: EnvironmentId | null;
readonly projectRef?: {
readonly projectRefs?: ReadonlyArray<{
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">;
@@ -106,33 +113,58 @@ export function buildThreadListV2Items(input: {
other environments never classify as settled — the user could neither
un-settle nor pin them. Absent = no gating (tests). */
readonly settlementEnvironmentIds?: ReadonlySet<EnvironmentId>;
/** Environments whose server supports thread.snooze/unsnooze. Same
contract as settlementEnvironmentIds. */
readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
readonly autoSettleAfterDays?: number;
/** Max settled rows to render; the rest are counted, not built. */
readonly settledLimit?: number;
/** Injectable for tests; defaults to now. */
readonly now?: string;
/** Second-precise clock for snooze classification. Callers pass a
minute-quantized `now` for memoization; snooze wake times are
second-precise, so classifying with the floored minute would hold a
woken thread hidden for up to a minute. Defaults to `now`. */
readonly snoozeNow?: string;
}): ThreadListV2Layout {
const now = input.now ?? new Date().toISOString();
const snoozeNow = input.snoozeNow ?? now;
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[] = [];
let snoozedCount = 0;
let nextSnoozeWakeAt: string | null = null;
for (const thread of input.threads) {
// 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 (
input.projectRef != null &&
(thread.environmentId !== input.projectRef.environmentId ||
thread.projectId !== input.projectRef.projectId)
) {
if (projectKeys !== null && !projectKeys.has(`${thread.environmentId}:${thread.projectId}`)) {
continue;
}
if (query.length > 0 && !thread.title.toLocaleLowerCase().includes(query)) continue;
const supportsSettlement = input.settlementEnvironmentIds?.has(thread.environmentId) ?? true;
const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true;
const changeRequestState =
input.changeRequestStateByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null;
// Visibility parity with web: a snoozed thread leaves the list until it
// wakes (or raises its hand — effectiveSnoozed refuses blocked/failed
// work). Snooze outranks settled classification, same as web.
if (supportsSnooze && effectiveSnoozed(thread, { now: snoozeNow })) {
snoozedCount += 1;
if (
thread.snoozedUntil != null &&
(nextSnoozeWakeAt === null ||
parseTimestampMs(thread.snoozedUntil) < parseTimestampMs(nextSnoozeWakeAt))
) {
nextSnoozeWakeAt = thread.snoozedUntil;
}
continue;
}
if (
supportsSettlement &&
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
@@ -169,5 +201,10 @@ export function buildThreadListV2Items(input: {
if (last) {
items[items.length - 1] = { ...last, isLast: true };
}
return { items, hiddenSettledCount: orderedSettled.length - visibleSettled.length };
return {
items,
hiddenSettledCount: orderedSettled.length - visibleSettled.length,
snoozedCount,
nextSnoozeWakeAt,
};
}
@@ -22,6 +22,7 @@ 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
@@ -77,6 +78,7 @@ function sanitizePreferences(parsed: Preferences): Preferences {
codeWordBreak?: boolean;
connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
collapsedProjectGroups?: readonly string[];
projectGroupingEnabled?: boolean;
threadListV2Enabled?: boolean;
} = {};
@@ -104,6 +106,9 @@ 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;
}
@@ -60,6 +60,8 @@ function threadDetailToShell(
archivedAt: thread.archivedAt,
settledOverride: thread.settledOverride,
settledAt: thread.settledAt,
snoozedUntil: thread.snoozedUntil ?? null,
snoozedAt: thread.snoozedAt ?? null,
session: thread.session,
latestUserMessageAt: latestUserMessageAt(thread),
hasPendingApprovals: false,
@@ -40,7 +40,9 @@ function environment(
connection: {
phase,
error: phase === "error" ? "Connection failed." : null,
reason: phase === "error" ? "authentication" : null,
traceId: phase === "error" ? "trace-1" : null,
retryAt: null,
},
serverConfig: null,
};
+2 -1
View File
@@ -31,7 +31,8 @@
"@opencode-ai/sdk": "^1.3.15",
"@pierre/diffs": "catalog:",
"effect": "catalog:",
"node-pty": "^1.1.0"
"node-pty": "^1.1.0",
"yaml": "catalog:"
},
"devDependencies": {
"@effect/vitest": "catalog:",
+40 -55
View File
@@ -12,7 +12,8 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
DEVELOPMENT_ICON_OVERRIDES,
PUBLISH_ICON_OVERRIDES,
resolveWebAssetBrandForPackageVersion,
resolveWebIconOverrides,
} from "../../../scripts/lib/brand-assets.ts";
import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
@@ -81,50 +82,34 @@ const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Stan
}
});
interface PublishIconBackup {
readonly targetPath: string;
readonly backupPath: string;
}
const applyPublishIconOverrides = Effect.fn("applyPublishIconOverrides")(function* (
const preparePublishIcons = Effect.fn("preparePublishIcons")(function* (
repoRoot: string,
serverDir: string,
version: string,
) {
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
const backups: PublishIconBackup[] = [];
const brand = resolveWebAssetBrandForPackageVersion(version);
const icons = resolveWebIconOverrides(brand, "dist/client").map((override) => ({
sourcePath: path.join(repoRoot, override.sourceRelativePath),
targetPath: path.join(serverDir, override.targetRelativePath),
}));
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 });
for (const icon of icons) {
if (!(yield* fs.exists(icon.sourcePath))) {
return yield* new ServerCliPublishIconSourceMissingError({ sourcePath: icon.sourcePath });
}
if (!(yield* fs.exists(targetPath))) {
return yield* new ServerCliPublishIconTargetMissingError({ targetPath });
if (!(yield* fs.exists(icon.targetPath))) {
return yield* new ServerCliPublishIconTargetMissingError({ targetPath: icon.targetPath });
}
yield* fs.copyFile(targetPath, backupPath);
yield* fs.copyFile(sourcePath, targetPath);
backups.push({ targetPath, backupPath });
}
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);
}
return yield* Effect.forEach(icons, (icon) =>
Effect.all({
original: fs.readFile(icon.targetPath),
publish: fs.readFile(icon.sourcePath),
}).pipe(Effect.map((contents) => ({ ...icon, ...contents }))),
);
});
const applyDevelopmentIconOverrides = Effect.fn("applyDevelopmentIconOverrides")(function* (
@@ -236,7 +221,6 @@ 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"]) {
@@ -247,7 +231,7 @@ const publishCmd = Command.make(
}
yield* Effect.acquireUseRelease(
// Acquire: backup package.json, resolve catalog dependencies, and strip devDependencies/scripts
// Acquire: resolve publish metadata and read every original before mutation.
Effect.gen(function* () {
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
const workspaceConfig = yield* readWorkspaceConfig();
@@ -273,19 +257,22 @@ const publishCmd = Command.make(
),
};
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 };
return {
packageJsonString: yield* encodePackageJson(pkg),
originalPackageJson: yield* fs.readFile(packageJsonPath),
icons: yield* preparePublishIcons(repoRoot, serverDir, version),
};
}),
// 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]);
@@ -299,16 +286,14 @@ const publishCmd = Command.make(
}),
);
}),
// Release: restore
(resource: { readonly iconBackups: ReadonlyArray<PublishIconBackup> }) =>
// Release: restore every file even if applying overrides or publishing fails.
(resource) =>
Effect.gen(function* () {
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");
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");
}),
);
}),
+71 -8
View File
@@ -26,6 +26,30 @@ import * as SelfUpdate from "./selfUpdate.ts";
const NODE_PATH = "/usr/local/bin/node";
/**
* The deferred restart runs on a detached fiber, so its rollback performs
* real filesystem I/O that advancing the TestClock does not await. Poll on
* real time until the expected content lands.
*/
const eventuallyFileString = Effect.fn("test.eventuallyFileString")(function* (
filePath: string,
expected: string,
) {
const fs = yield* FileSystem.FileSystem;
let last = "";
for (let iteration = 0; iteration < 1_000; iteration += 1) {
last = yield* fs.readFileString(filePath);
if (last === expected) {
return last;
}
// Yielding (rather than sleeping) keeps this on the real event loop:
// TestClock would only advance virtual time and never let the
// detached fiber's filesystem writes land.
yield* Effect.yieldNow;
}
return yield* Effect.die(new Error(`Expected file contents were not observed at ${filePath}.`));
});
interface RecordedCommand {
readonly command: string;
readonly args: ReadonlyArray<string>;
@@ -38,6 +62,8 @@ const makeRecordingRunnerLayer = (
readonly stdoutFor?:
| ((command: string, args: ReadonlyArray<string>) => string | undefined)
| undefined;
/** Raises a defect (not a typed failure) to exercise unexpected-error paths. */
readonly dieWhen?: ((command: string, args: ReadonlyArray<string>) => boolean) | undefined;
},
) =>
Layer.succeed(
@@ -46,6 +72,9 @@ const makeRecordingRunnerLayer = (
run: (input) =>
Effect.sync(() => {
commands.push({ command: input.command, args: input.args });
if (options?.dieWhen?.(input.command, input.args) === true) {
throw new Error(`${input.command} died unexpectedly`);
}
const failed = options?.failWhen?.(input.command, input.args) === true;
const versionFromPath =
input.command === NODE_PATH && input.args[1] === "--version"
@@ -54,7 +83,7 @@ const makeRecordingRunnerLayer = (
return {
stdout:
options?.stdoutFor?.(input.command, input.args) ??
(versionFromPath === undefined ? "" : `${versionFromPath}\n`),
(versionFromPath === undefined ? "" : `t3 v${versionFromPath}\n`),
stderr: failed ? `${input.command} exploded` : "",
code: ChildProcessSpawner.ExitCode(failed ? 1 : 0),
timedOut: false,
@@ -257,6 +286,7 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
readonly failWhen?: (command: string, args: ReadonlyArray<string>) => boolean;
readonly stdoutFor?: (command: string, args: ReadonlyArray<string>) => string | undefined;
readonly failSpawn?: boolean;
readonly dieWhen?: (command: string, args: ReadonlyArray<string>) => boolean;
}) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -329,6 +359,7 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
makeRecordingRunnerLayer(commands, {
failWhen: options?.failWhen,
stdoutFor: options?.stdoutFor,
dieWhen: options?.dieWhen,
}),
configLayer,
),
@@ -427,7 +458,7 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
Effect.gen(function* () {
const context = yield* makeContext({
stdoutFor: (command, args) =>
command === NODE_PATH && args[1] === "--version" ? "0.0.28\n" : undefined,
command === NODE_PATH && args[1] === "--version" ? "t3 v0.0.28\n" : undefined,
});
const versionDir = context.path.join(context.baseDir, "runtime", "versions", "0.0.29");
@@ -490,7 +521,7 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("rewrites the systemd unit and restarts the boot service", () =>
it.effect("rewrites the systemd unit and defers the boot-service restart", () =>
Effect.gen(function* () {
const context = yield* makeContext({ bootService: true });
const result = yield* context.service.update({ targetVersion: "0.0.29" });
@@ -504,12 +535,15 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
context.path.join(context.home, ".config", "systemd", "user", "t3code.service"),
);
assert.include(unit, `ExecStart=${NODE_PATH} ${pinnedEntry} serve`);
// The restart is deferred so the RPC acknowledgement flushes before
// systemd stops this process.
assert.deepEqual(
context.commands.map((entry) => entry.command),
["npm", NODE_PATH, "systemctl", "systemctl"],
["npm", NODE_PATH, "systemctl"],
);
assert.deepEqual(context.commands[2]?.args, ["--user", "daemon-reload"]);
yield* TestClock.adjust(Duration.seconds(10));
assert.deepEqual(context.commands[3], {
command: "systemctl",
args: ["--user", "restart", "t3code.service"],
@@ -520,7 +554,7 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("restores the previous unit and permits a retry when systemd restart fails", () =>
it.effect("restores the previous unit and permits a retry when the deferred restart fails", () =>
Effect.gen(function* () {
let failRestart = true;
const context = yield* makeContext({
@@ -542,9 +576,12 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
);
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);
// The RPC acknowledges before the restart runs, so a rejected
// restart can only roll back and log — never fail the request.
const first = yield* context.service.update({ targetVersion: "0.0.29" });
assert.deepEqual(first, { targetVersion: "0.0.29", method: "boot-service" });
yield* TestClock.adjust(Duration.seconds(10));
yield* eventuallyFileString(unitPath, previousUnit);
assert.deepEqual(
context.commands.slice(-2).map((entry) => entry.args),
[
@@ -558,6 +595,32 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("permits a retry when the deferred restart dies unexpectedly", () =>
Effect.gen(function* () {
let dieOnRestart = true;
const context = yield* makeContext({
bootService: true,
dieWhen: (command, args) => {
if (command !== "systemctl" || args[1] !== "restart" || !dieOnRestart) {
return false;
}
dieOnRestart = false;
return true;
},
});
const first = yield* context.service.update({ targetVersion: "0.0.29" });
assert.deepEqual(first, { targetVersion: "0.0.29", method: "boot-service" });
yield* TestClock.adjust(Duration.seconds(10));
// A defect bypasses the typed rollback handler, so the in-flight guard
// has to be released outside it — otherwise this live process would
// reject every further update until restarted by other means.
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({
+61 -33
View File
@@ -3,6 +3,7 @@
// detached fire-and-forget child that outlives this process, while Effect's
// ChildProcessSpawner ties every child to a scope that kills it.
import {
SERVER_SELF_UPDATE_ALREADY_RUNNING_REASON,
ServerSelfUpdateError,
type ServerSelfUpdateCapability,
type ServerSelfUpdateInput,
@@ -18,6 +19,7 @@ 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 Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
@@ -246,7 +248,7 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* (option
const alreadyRunning = yield* Ref.getAndSet(inFlight, true);
if (alreadyRunning) {
return yield* failWith("A server update is already in progress.");
return yield* failWith(SERVER_SELF_UPDATE_ALREADY_RUNNING_REASON);
}
return yield* Effect.gen(function* () {
@@ -273,8 +275,10 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* (option
failWith(`Could not verify the installed t3@${targetVersion}.`, cause),
),
);
const preflightVersion = preflight.stdout.trim();
if (preflight.code !== 0 || preflightVersion !== targetVersion) {
// 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.
@@ -347,37 +351,61 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* (option
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),
// Deferred like the respawn path: a synchronous systemctl restart
// stops this process mid-RPC, so every successful update used to
// surface to the client as an interrupted call indistinguishable
// from a dropped connection. Deferring lets the acknowledgement
// flush first. The trade: a rejected restart can no longer be
// reported through this RPC — it rolls back, logs, and clears the
// in-flight guard so a retry works.
yield* scheduleRestart(
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) =>
Effect.logError(
"Server self-update restart was rejected; restoring the previous systemd unit.",
).pipe(
Effect.annotateLogs({ targetVersion, error: restartError.reason }),
Effect.andThen(
writeUnitAtomically(unitPath, previousUnit).pipe(Effect.andThen(reloadSystemd())),
),
Effect.catch((rollbackError) =>
Effect.logError(
"Server self-update could not restore the previous systemd unit after a rejected restart.",
).pipe(Effect.annotateLogs({ targetVersion, error: String(rollbackError) })),
),
// The process survived a rejected restart, so it must stay
// updatable — leaving the guard set would reject every retry
// until the server was restarted by other means.
Effect.ensuring(Ref.set(inFlight, false)),
),
);
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)),
),
// The typed catch above cannot see defects or interrupts, which
// would otherwise strand the guard on a live process. A success
// deliberately leaves it set: systemd is about to stop this
// process and a second update would race the handoff.
Effect.onExit((exit) =>
Exit.isSuccess(exit)
? Effect.void
: Effect.logError("Server self-update restart fiber ended unexpectedly.").pipe(
Effect.annotateLogs({ targetVersion, exit: String(exit) }),
Effect.ensuring(Ref.set(inFlight, false)),
),
),
),
);
@@ -141,6 +141,7 @@ export const make = Effect.gen(function* () {
repositoryIdentity: true,
connectionProbe: true,
threadSettlement: true,
threadSnooze: true,
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
},
};
@@ -4,6 +4,7 @@ import type {
PreviewAutomationRecordingArtifact,
PreviewAutomationRecordingStatus,
PreviewAutomationResizeResult,
PreviewAutomationSetColorSchemeResult,
PreviewAutomationSnapshot,
PreviewAutomationStatus,
PreviewTabId,
@@ -58,6 +59,8 @@ 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,6 +10,8 @@ import {
PreviewAutomationResizeInput,
PreviewAutomationResizeResult,
PreviewAutomationScrollInput,
PreviewAutomationSetColorSchemeInput,
PreviewAutomationSetColorSchemeResult,
PreviewAutomationSnapshot,
PreviewAutomationStatus,
PreviewAutomationTabTargetInput,
@@ -86,6 +88,19 @@ 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:
@@ -189,6 +204,7 @@ export const PreviewToolkit = Toolkit.make(
PreviewOpenTool,
PreviewNavigateTool,
PreviewResizeTool,
PreviewSetAppearanceTool,
PreviewSnapshotTool,
PreviewClickTool,
PreviewTypeTool,
@@ -205,6 +221,7 @@ export const PreviewStandardToolkit = Toolkit.make(
PreviewOpenTool,
PreviewNavigateTool,
PreviewResizeTool,
PreviewSetAppearanceTool,
PreviewClickTool,
PreviewTypeTool,
PreviewPressTool,
@@ -609,6 +609,8 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
archivedAt: null,
settledOverride: null,
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
latestUserMessageAt: null,
pendingApprovalCount: 0,
pendingUserInputCount: 0,
@@ -679,6 +681,38 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
return;
}
case "thread.snoozed": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) {
return;
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
snoozedUntil: event.payload.snoozedUntil,
snoozedAt: event.payload.snoozedAt,
updatedAt: event.payload.updatedAt,
});
return;
}
case "thread.unsnoozed": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) {
return;
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
snoozedUntil: null,
snoozedAt: null,
updatedAt: event.payload.updatedAt,
});
return;
}
case "thread.meta-updated": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
@@ -310,6 +310,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
archivedAt: null,
settledOverride: null,
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
deletedAt: null,
messages: [
{
@@ -422,6 +424,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
archivedAt: null,
settledOverride: null,
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
session: {
threadId: ThreadId.make("thread-1"),
status: "running",
@@ -336,6 +336,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
@@ -366,6 +368,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
@@ -398,6 +402,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
@@ -762,6 +768,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
@@ -1196,6 +1204,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
deletedAt: row.deletedAt,
messages: messagesByThread.get(row.threadId) ?? [],
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
@@ -1396,6 +1406,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
deletedAt: row.deletedAt,
messages: [],
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
@@ -1527,6 +1539,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
hasPendingApprovals: row.pendingApprovalCount > 0,
@@ -1663,6 +1677,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
hasPendingApprovals: row.pendingApprovalCount > 0,
@@ -1905,6 +1921,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: threadRow.value.archivedAt,
settledOverride: threadRow.value.settledOverride,
settledAt: threadRow.value.settledAt,
snoozedUntil: threadRow.value.snoozedUntil,
snoozedAt: threadRow.value.snoozedAt,
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
latestUserMessageAt: threadRow.value.latestUserMessageAt,
hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,
@@ -2001,6 +2019,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: threadRow.value.archivedAt,
settledOverride: threadRow.value.settledOverride,
settledAt: threadRow.value.settledAt,
snoozedUntil: threadRow.value.snoozedUntil,
snoozedAt: threadRow.value.snoozedAt,
deletedAt: null,
messages: messageRows.map((row) => {
const message = {
+4
View File
@@ -11,6 +11,8 @@ import {
ThreadDeletedPayload as ContractsThreadDeletedPayloadSchema,
ThreadUnarchivedPayload as ContractsThreadUnarchivedPayloadSchema,
ThreadUnsettledPayload as ContractsThreadUnsettledPayloadSchema,
ThreadSnoozedPayload as ContractsThreadSnoozedPayloadSchema,
ThreadUnsnoozedPayload as ContractsThreadUnsnoozedPayloadSchema,
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
@@ -38,6 +40,8 @@ export const ThreadInteractionModeSetPayload = ContractsThreadInteractionModeSet
export const ThreadDeletedPayload = ContractsThreadDeletedPayloadSchema;
export const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema;
export const ThreadUnsettledPayload = ContractsThreadUnsettledPayloadSchema;
export const ThreadSnoozedPayload = ContractsThreadSnoozedPayloadSchema;
export const ThreadUnsnoozedPayload = ContractsThreadUnsnoozedPayloadSchema;
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;
@@ -0,0 +1,286 @@
import {
CommandId,
EventId,
MessageId,
ProjectId,
ProviderInstanceId,
ThreadId,
type OrchestrationReadModel,
type OrchestrationThread,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { decideOrchestrationCommand } from "./decider.ts";
const NOW = "2026-01-01T00:00:00.000Z";
// The decider's clock is the Effect test clock, pinned to the epoch, so
// "future" wake times are relative to 1970-01-01T00:00:00.000Z.
const FUTURE_WAKE = "1970-01-02T09:00:00.000Z";
const PAST_WAKE = "1969-12-31T09:00:00.000Z";
const SNOOZED_AT = "1969-12-30T00:00:00.000Z";
function makeReadModel(input: {
readonly snoozedUntil?: string | null;
readonly snoozedAt?: string | null;
readonly archivedAt?: string | null;
readonly activities?: OrchestrationThread["activities"];
readonly messages?: OrchestrationThread["messages"];
}): OrchestrationReadModel {
return {
snapshotSequence: 0,
projects: [],
threads: [
{
id: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-1"),
title: "Thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: NOW,
updatedAt: NOW,
archivedAt: input.archivedAt ?? null,
settledOverride: null,
settledAt: null,
snoozedUntil: input.snoozedUntil ?? null,
snoozedAt: input.snoozedAt ?? (input.snoozedUntil != null ? SNOOZED_AT : null),
deletedAt: null,
messages: input.messages ?? [],
proposedPlans: [],
activities: input.activities ?? [],
checkpoints: [],
session: null,
},
],
updatedAt: NOW,
};
}
it.layer(NodeServices.layer)("snoozed thread decider", (it) => {
it.effect("snoozes a thread to a future wake time", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.snooze",
commandId: CommandId.make("cmd-snooze"),
threadId: ThreadId.make("thread-1"),
snoozedUntil: FUTURE_WAKE,
},
readModel: makeReadModel({}),
});
const events = Array.isArray(event) ? event : [event];
expect(events).toHaveLength(1);
expect(events[0]?.type).toBe("thread.snoozed");
if (events[0]?.type === "thread.snoozed") {
expect(events[0].payload.snoozedUntil).toBe(FUTURE_WAKE);
expect(events[0].payload.snoozedAt).toBe(events[0].payload.updatedAt);
}
}),
);
it.effect("rejects a wake time that is not in the future", () =>
Effect.gen(function* () {
const error = yield* decideOrchestrationCommand({
command: {
type: "thread.snooze",
commandId: CommandId.make("cmd-snooze-past"),
threadId: ThreadId.make("thread-1"),
snoozedUntil: PAST_WAKE,
},
readModel: makeReadModel({}),
}).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationCommandInvariantError");
}),
);
it.effect("rejects an unparseable wake time", () =>
Effect.gen(function* () {
// IsoDateTime is structurally a string, so garbage can reach the
// decider; a NaN wake time must never persist as snooze state.
const error = yield* decideOrchestrationCommand({
command: {
type: "thread.snooze",
commandId: CommandId.make("cmd-snooze-garbage"),
threadId: ThreadId.make("thread-1"),
snoozedUntil: "not-a-date",
},
readModel: makeReadModel({}),
}).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationCommandInvariantError");
}),
);
it.effect("rejects snoozing blocked-on-you work", () =>
Effect.gen(function* () {
const requestActivity = {
id: EventId.make("activity-req-1"),
tone: "approval" as const,
kind: "approval.requested",
summary: "approval.requested",
payload: { requestId: "req-1" },
turnId: null,
createdAt: NOW,
} as OrchestrationThread["activities"][number];
const error = yield* decideOrchestrationCommand({
command: {
type: "thread.snooze",
commandId: CommandId.make("cmd-snooze-blocked"),
threadId: ThreadId.make("thread-1"),
snoozedUntil: FUTURE_WAKE,
},
readModel: makeReadModel({ activities: [requestActivity] }),
}).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationCommandInvariantError");
}),
);
it.effect("re-emits idempotently for a duplicate snooze to the same wake time", () =>
Effect.gen(function* () {
const reEmit = yield* decideOrchestrationCommand({
command: {
type: "thread.snooze",
commandId: CommandId.make("cmd-snooze-again"),
threadId: ThreadId.make("thread-1"),
snoozedUntil: FUTURE_WAKE,
},
readModel: makeReadModel({ snoozedUntil: FUTURE_WAKE }),
});
const events = Array.isArray(reEmit) ? reEmit : [reEmit];
expect(events).toHaveLength(1);
if (events[0]?.type === "thread.snoozed") {
// Original snoozedAt preserved; updatedAt must not churn.
expect(events[0].payload.snoozedAt).toBe(SNOOZED_AT);
expect(events[0].payload.updatedAt).toBe(NOW);
}
}),
);
it.effect("re-snoozing to a DIFFERENT wake time stamps fresh", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.snooze",
commandId: CommandId.make("cmd-snooze-extend"),
threadId: ThreadId.make("thread-1"),
snoozedUntil: "1970-01-03T09:00:00.000Z",
},
readModel: makeReadModel({ snoozedUntil: FUTURE_WAKE }),
});
const events = Array.isArray(event) ? event : [event];
if (events[0]?.type === "thread.snoozed") {
expect(events[0].payload.snoozedUntil).toBe("1970-01-03T09:00:00.000Z");
expect(events[0].payload.updatedAt).not.toBe(NOW);
}
}),
);
it.effect("unsnoozes with reason user and re-emits idempotently when awake", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.unsnooze",
commandId: CommandId.make("cmd-unsnooze"),
threadId: ThreadId.make("thread-1"),
reason: "user",
},
readModel: makeReadModel({ snoozedUntil: FUTURE_WAKE }),
});
const events = Array.isArray(event) ? event : [event];
expect(events[0]?.type).toBe("thread.unsnoozed");
if (events[0]?.type === "thread.unsnoozed") {
expect(events[0].payload.reason).toBe("user");
expect(events[0].payload.updatedAt).not.toBe(NOW);
}
const awake = yield* decideOrchestrationCommand({
command: {
type: "thread.unsnooze",
commandId: CommandId.make("cmd-unsnooze-awake"),
threadId: ThreadId.make("thread-1"),
reason: "user",
},
readModel: makeReadModel({}),
});
const awakeEvents = Array.isArray(awake) ? awake : [awake];
expect(awakeEvents[0]?.type).toBe("thread.unsnoozed");
if (awakeEvents[0]?.type === "thread.unsnoozed") {
// No state change — keep the existing updatedAt.
expect(awakeEvents[0].payload.updatedAt).toBe(NOW);
}
}),
);
it.effect("rejects snoozing a thread with a queued turn start", () =>
Effect.gen(function* () {
// The decider clock is the Effect test clock pinned to the epoch: a
// user message 30s before it with no adopting turn is queued work.
const queuedMessage = {
id: MessageId.make("message-queued"),
role: "user",
text: "Continue",
turnId: null,
streaming: false,
createdAt: "1969-12-31T23:59:30.000Z",
updatedAt: "1969-12-31T23:59:30.000Z",
} as OrchestrationThread["messages"][number];
const error = yield* decideOrchestrationCommand({
command: {
type: "thread.snooze",
commandId: CommandId.make("cmd-snooze-queued"),
threadId: ThreadId.make("thread-1"),
snoozedUntil: FUTURE_WAKE,
},
readModel: makeReadModel({ messages: [queuedMessage] }),
}).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationCommandInvariantError");
}),
);
it.effect("rejects snoozing an archived thread", () =>
Effect.gen(function* () {
const error = yield* decideOrchestrationCommand({
command: {
type: "thread.snooze",
commandId: CommandId.make("cmd-snooze-archived"),
threadId: ThreadId.make("thread-1"),
snoozedUntil: FUTURE_WAKE,
},
readModel: makeReadModel({ archivedAt: NOW }),
}).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationCommandInvariantError");
}),
);
it.effect("a user message spends the snooze return ticket (activity wake)", () =>
Effect.gen(function* () {
const result = yield* decideOrchestrationCommand({
command: {
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: MessageId.make("message-1"),
role: "user",
text: "Continue",
attachments: [],
},
runtimeMode: "full-access",
interactionMode: "default",
createdAt: NOW,
},
readModel: makeReadModel({ snoozedUntil: FUTURE_WAKE }),
});
const events = Array.isArray(result) ? result : [result];
const unsnoozed = events.find((entry) => entry.type === "thread.unsnoozed");
expect(unsnoozed).toBeDefined();
if (unsnoozed?.type === "thread.unsnoozed") {
expect(unsnoozed.payload.reason).toBe("activity");
}
}),
);
});
+203 -58
View File
@@ -53,6 +53,13 @@ function isStaleRequestFailureDetail(payload: Record<string, unknown> | null): b
);
}
// Scans the read model's activities, which the projector caps at the most
// recent 500. That bound is safe here: an OPEN approval/user-input request
// blocks its turn, so the thread cannot accumulate hundreds of later
// activities while one is outstanding — a request that has scrolled out of
// the window is one whose turn kept running, i.e. it was resolved or went
// stale. (The projection pipeline's pendingApprovalCount reads the same
// capped stream and stays consistent with this view.)
function hasOpenBlockingRequest(thread: {
readonly activities: ReadonlyArray<{ readonly kind: string; readonly payload: unknown }>;
}): boolean {
@@ -79,6 +86,62 @@ function hasOpenBlockingRequest(thread: {
return openRequestIds.size > 0;
}
/**
* A queued turn start — a user message no turn has picked up yet — is work
* in flight even though session is still null (turn.start emits
* message-sent + turn-start-requested; the session arrives later). Detection
* mirrors the client's hasQueuedTurnStart: the newest user message is
* strictly newer than every latestTurn timestamp (adoption stamps the new
* turn's requestedAt with the message time, clearing this), and only within
* the adoption grace window — historical threads whose last user message
* postdates their turn timestamps (older-server data, mid-turn messages)
* must not be blocked forever. A failed session start (status "error")
* clears the block immediately.
*
* The age check is bounded on BOTH sides: message timestamps are
* client-supplied, so a client clock ahead of the server yields a negative
* age. Without the lower bound that negative age satisfies `<= grace` for
* as long as the skew lasts, extending the block far past the intended two
* minutes.
*/
function threadHasQueuedTurnStart(
thread: {
readonly messages: ReadonlyArray<{ readonly role: string; readonly createdAt: string }>;
readonly latestTurn: {
readonly requestedAt: string;
readonly startedAt: string | null;
readonly completedAt: string | null;
} | null;
readonly session: { readonly status: string } | null;
},
occurredAt: string,
): boolean {
const latestUserMessageAtMs = thread.messages.reduce(
(latest, message) =>
message.role === "user" ? Math.max(latest, Date.parse(message.createdAt)) : latest,
Number.NEGATIVE_INFINITY,
);
const latestTurnAtMs =
thread.latestTurn === null
? Number.NEGATIVE_INFINITY
: Math.max(
...[
thread.latestTurn.requestedAt,
thread.latestTurn.startedAt,
thread.latestTurn.completedAt,
].map((candidate) =>
candidate == null ? Number.NEGATIVE_INFINITY : Date.parse(candidate),
),
);
const queuedAgeMs = Date.parse(occurredAt) - latestUserMessageAtMs;
return (
thread.session?.status !== "error" &&
Number.isFinite(latestUserMessageAtMs) &&
latestUserMessageAtMs > latestTurnAtMs &&
Math.abs(queuedAgeMs) <= QUEUED_TURN_START_GRACE_MS
);
}
function withEventBase(
input: Pick<OrchestrationCommand, "commandId"> & {
readonly aggregateKind: OrchestrationEvent["aggregateKind"];
@@ -411,46 +474,8 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
);
}
const occurredAt = yield* nowIso;
// A queued turn start — a user message no turn has picked up yet — is
// work in flight even though session is still null (turn.start emits
// message-sent + turn-start-requested; the session arrives later).
// Settling in that window would hide just-requested work. Detection
// mirrors the client's hasQueuedTurnStart: the newest user message is
// strictly newer than every latestTurn timestamp (adoption stamps the
// new turn's requestedAt with the message time, clearing this), and
// only within the adoption grace window — historical threads whose
// last user message postdates their turn timestamps (older-server
// data, mid-turn messages) must stay settleable. A failed session
// start (status "error") clears the block immediately.
const latestUserMessageAtMs = thread.messages.reduce(
(latest, message) =>
message.role === "user" ? Math.max(latest, Date.parse(message.createdAt)) : latest,
Number.NEGATIVE_INFINITY,
);
const latestTurnAtMs =
thread.latestTurn === null
? Number.NEGATIVE_INFINITY
: Math.max(
...[
thread.latestTurn.requestedAt,
thread.latestTurn.startedAt,
thread.latestTurn.completedAt,
].map((candidate) =>
candidate == null ? Number.NEGATIVE_INFINITY : Date.parse(candidate),
),
);
// The age check is bounded on BOTH sides: message timestamps are
// client-supplied, so a client clock ahead of the server yields a
// negative age. Without the lower bound that negative age satisfies
// `<= grace` for as long as the skew lasts, extending the settle
// block far past the intended two minutes.
const queuedAgeMs = Date.parse(occurredAt) - latestUserMessageAtMs;
const hasQueuedTurnStart =
thread.session?.status !== "error" &&
Number.isFinite(latestUserMessageAtMs) &&
latestUserMessageAtMs > latestTurnAtMs &&
Math.abs(queuedAgeMs) <= QUEUED_TURN_START_GRACE_MS;
if (hasQueuedTurnStart) {
// Settling inside the adoption window would hide just-requested work.
if (threadHasQueuedTurnStart(thread, occurredAt)) {
return yield* Effect.fail(
new OrchestrationCommandInvariantError({
commandType: command.type,
@@ -508,6 +533,103 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
case "thread.snooze": {
const thread = yield* requireThreadNotArchived({
readModel,
command,
threadId: command.threadId,
});
const occurredAt = yield* nowIso;
// A wake time in the past would create a thread that is snoozed and
// woken at once — the row would never leave the inbox but still carry
// snooze state. Reject instead of silently normalizing. The negated
// comparison also catches unparseable wake times (IsoDateTime is
// structurally just a string): NaN fails every comparison, and an
// unparseable snoozedUntil must never persist.
if (!(Date.parse(command.snoozedUntil) > Date.parse(occurredAt))) {
return yield* Effect.fail(
new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `thread ${command.threadId} snooze wake time ${command.snoozedUntil} is not in the future`,
}),
);
}
// Blocked-on-you work must not be snoozed away: a pending approval or
// user-input request is the agent waiting on the user, and hiding it
// defeats the request. (A running session IS snoozable — snooze only
// affects visibility, never the agent.)
if (hasOpenBlockingRequest(thread)) {
return yield* Effect.fail(
new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `thread ${command.threadId} has a pending approval or user-input request and cannot be snoozed`,
}),
);
}
// A queued turn start — a user message no turn has adopted yet — is
// invisible pending work: no session, no pending flags. Snoozing in
// that window would hide a just-requested turn exactly the way settle
// would.
if (threadHasQueuedTurnStart(thread, occurredAt)) {
return yield* Effect.fail(
new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `thread ${command.threadId} has a queued turn start and cannot be snoozed`,
}),
);
}
// Re-snoozing an already-snoozed thread to the SAME wake time is a
// duplicate (double-click, raced clients): re-emit with the original
// timestamps so the projection is a no-op. A different wake time is a
// real change and stamps fresh.
const existingSnoozedAt =
thread.snoozedUntil === command.snoozedUntil && thread.snoozedAt != null
? thread.snoozedAt
: null;
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.snoozed",
payload: {
threadId: command.threadId,
snoozedUntil: command.snoozedUntil,
snoozedAt: existingSnoozedAt ?? occurredAt,
updatedAt: existingSnoozedAt !== null ? thread.updatedAt : occurredAt,
},
};
}
case "thread.unsnooze": {
const thread = yield* requireThreadNotArchived({
readModel,
command,
threadId: command.threadId,
});
// Idempotent by re-emission (see thread.settle): waking a thread that
// is not snoozed lands on the same null state without churning
// updatedAt.
const alreadyAwake = thread.snoozedUntil == null;
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.unsnoozed",
payload: {
threadId: command.threadId,
reason: command.reason,
updatedAt: alreadyAwake ? thread.updatedAt : occurredAt,
},
};
}
case "thread.meta.update": {
const thread = yield* requireThread({
readModel,
@@ -663,24 +785,42 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
// Real activity resets ANY override: it wakes an explicitly settled
// thread, and it clears a keep-active pin back to neutral so the
// thread can auto-settle again after this burst of work goes stale.
if (targetThread.settledOverride === null) {
return [userMessageEvent, turnStartRequestedEvent];
// A snooze clears the same way — sending a message to a snoozed
// thread is the user re-engaging, so the return ticket is spent.
const lifecycleResetEvents: Array<Omit<OrchestrationEvent, "sequence">> = [];
if (targetThread.settledOverride !== null) {
lifecycleResetEvents.push({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
type: "thread.unsettled",
payload: {
threadId: command.threadId,
reason: "activity",
updatedAt: command.createdAt,
},
});
}
const unsettledEvent: Omit<OrchestrationEvent, "sequence"> = {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
type: "thread.unsettled",
payload: {
threadId: command.threadId,
reason: "activity",
updatedAt: command.createdAt,
},
};
return [unsettledEvent, userMessageEvent, turnStartRequestedEvent];
if (targetThread.snoozedUntil != null) {
lifecycleResetEvents.push({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
type: "thread.unsnoozed",
payload: {
threadId: command.threadId,
reason: "activity",
updatedAt: command.createdAt,
},
});
}
return [...lifecycleResetEvents, userMessageEvent, turnStartRequestedEvent];
}
case "thread.turn.interrupt": {
@@ -822,7 +962,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
// Only a session coming alive is activity worth waking a settled thread
// for — status writes like ready/stopped/error arrive after the fact and
// must not fight a user's explicit settle.
// must not fight a user's explicit settle. Snooze is deliberately NOT
// cleared here: snooze never pauses the agent, so its session starting
// or erroring is not the user re-engaging. Blocked/failed work still
// surfaces immediately — effectiveSnoozed refuses to classify a thread
// with a raised hand (approval / input / failure / fresh completion)
// as snoozed, without spending the return ticket.
const isSessionActivity =
command.session.status === "starting" || command.session.status === "running";
// Real activity resets ANY override (settled wakes, active unpins).
@@ -91,6 +91,8 @@ describe("orchestration projector", () => {
archivedAt: null,
settledOverride: null,
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
deletedAt: null,
messages: [],
proposedPlans: [],
@@ -23,8 +23,10 @@ import {
ThreadProposedPlanUpsertedPayload,
ThreadRuntimeModeSetPayload,
ThreadSettledPayload,
ThreadSnoozedPayload,
ThreadUnarchivedPayload,
ThreadUnsettledPayload,
ThreadUnsnoozedPayload,
ThreadRevertedPayload,
ThreadSessionSetPayload,
ThreadTurnDiffCompletedPayload,
@@ -290,6 +292,8 @@ export function projectEvent(
archivedAt: null,
settledOverride: null,
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
deletedAt: null,
messages: [],
activities: [],
@@ -365,6 +369,30 @@ export function projectEvent(
})),
);
case "thread.snoozed":
return decodeForEvent(ThreadSnoozedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
snoozedUntil: payload.snoozedUntil,
snoozedAt: payload.snoozedAt,
updatedAt: payload.updatedAt,
}),
})),
);
case "thread.unsnoozed":
return decodeForEvent(ThreadUnsnoozedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
snoozedUntil: null,
snoozedAt: null,
updatedAt: payload.updatedAt,
}),
})),
);
case "thread.meta-updated":
return decodeForEvent(ThreadMetaUpdatedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
@@ -93,6 +93,8 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
archivedAt: null,
settledOverride: null,
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
latestUserMessageAt: null,
pendingApprovalCount: 0,
pendingUserInputCount: 0,
@@ -153,6 +155,8 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
archivedAt: null,
settledOverride: "settled",
settledAt: "2026-03-25T00:00:00.000Z",
snoozedUntil: "2026-03-26T09:00:00.000Z",
snoozedAt: "2026-03-25T00:00:00.000Z",
latestUserMessageAt: null,
pendingApprovalCount: 0,
pendingUserInputCount: 0,
@@ -169,12 +173,17 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
}
assert.strictEqual(row.settledOverride, "settled");
assert.strictEqual(row.settledAt, "2026-03-25T00:00:00.000Z");
assert.strictEqual(row.snoozedUntil, "2026-03-26T09:00:00.000Z");
assert.strictEqual(row.snoozedAt, "2026-03-25T00:00:00.000Z");
// Un-settle to the keep-active pin and confirm the flip persists.
// Un-settle to the keep-active pin and wake the snooze; confirm the
// flips persist.
yield* threads.upsert({
...row,
settledOverride: "active",
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
});
const repersisted = yield* threads.getById({
threadId: ThreadId.make("thread-settled"),
@@ -182,6 +191,8 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
const updated = Option.getOrNull(repersisted);
assert.strictEqual(updated?.settledOverride, "active");
assert.strictEqual(updated?.settledAt, null);
assert.strictEqual(updated?.snoozedUntil, null);
assert.strictEqual(updated?.snoozedAt, null);
}),
);
});
@@ -45,6 +45,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
archived_at,
settled_override,
settled_at,
snoozed_until,
snoozed_at,
latest_user_message_at,
pending_approval_count,
pending_user_input_count,
@@ -66,6 +68,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
${row.archivedAt},
${row.settledOverride},
${row.settledAt},
${row.snoozedUntil},
${row.snoozedAt},
${row.latestUserMessageAt},
${row.pendingApprovalCount},
${row.pendingUserInputCount},
@@ -87,6 +91,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
archived_at = excluded.archived_at,
settled_override = excluded.settled_override,
settled_at = excluded.settled_at,
snoozed_until = excluded.snoozed_until,
snoozed_at = excluded.snoozed_at,
latest_user_message_at = excluded.latest_user_message_at,
pending_approval_count = excluded.pending_approval_count,
pending_user_input_count = excluded.pending_user_input_count,
@@ -115,6 +121,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
@@ -145,6 +153,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
@@ -46,6 +46,7 @@ import Migration0030 from "./Migrations/030_ProjectionThreadShellArchiveIndexes.
import Migration0031 from "./Migrations/031_AuthAuthorizationScopes.ts";
import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts";
import Migration0033 from "./Migrations/033_ProjectionThreadsSettled.ts";
import Migration0034 from "./Migrations/034_ProjectionThreadsSnoozed.ts";
/**
* Migration loader with all migrations defined inline.
@@ -91,6 +92,7 @@ export const migrationEntries = [
[31, "AuthAuthorizationScopes", Migration0031],
[32, "AuthPairingProofKeyThumbprint", Migration0032],
[33, "ProjectionThreadsSettled", Migration0033],
[34, "ProjectionThreadsSnoozed", Migration0034],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
@@ -0,0 +1,23 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const columns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_threads)
`;
if (!columns.some((column) => column.name === "snoozed_until")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN snoozed_until TEXT
`;
}
if (!columns.some((column) => column.name === "snoozed_at")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN snoozed_at TEXT
`;
}
});
@@ -38,6 +38,8 @@ export const ProjectionThread = Schema.Struct({
archivedAt: Schema.NullOr(IsoDateTime),
settledOverride: Schema.NullOr(Schema.Literals(["settled", "active"])),
settledAt: Schema.NullOr(IsoDateTime),
snoozedUntil: Schema.NullOr(IsoDateTime),
snoozedAt: Schema.NullOr(IsoDateTime),
latestUserMessageAt: Schema.NullOr(IsoDateTime),
pendingApprovalCount: NonNegativeInt,
pendingUserInputCount: NonNegativeInt,
@@ -118,6 +118,7 @@ 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;
@@ -165,9 +166,11 @@ 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),
);
@@ -0,0 +1,205 @@
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, []);
}),
);
});
@@ -0,0 +1,148 @@
/**
* 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));
});
@@ -7,6 +7,7 @@ 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";
@@ -40,6 +41,7 @@ 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: [],
@@ -732,10 +734,11 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
claudeSettings: ClaudeSettings,
) => Effect.Effect<ClaudeCapabilitiesProbe | undefined>,
environment?: NodeJS.ProcessEnv,
cwd?: string,
): Effect.fn.Return<
ServerProviderDraft,
never,
ChildProcessSpawner.ChildProcessSpawner | Path.Path
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
> {
const resolvedEnvironment = environment ?? process.env;
const checkedAt = DateTime.formatIso(yield* DateTime.now);
@@ -845,6 +848,7 @@ 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);
@@ -855,6 +859,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
checkedAt,
models,
slashCommands: dedupedSlashCommands,
skills,
probe: {
installed: true,
version: parsedVersion,
@@ -876,6 +881,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
checkedAt,
models,
slashCommands: dedupedSlashCommands,
skills,
probe: {
installed: true,
version: parsedVersion,
+9 -5
View File
@@ -6,7 +6,7 @@ import { ElectronBrowserHost } from "./browser/ElectronBrowserHost";
import { PreviewAutomationHosts } from "./components/preview/PreviewAutomationHosts";
import { AppAtomRegistryProvider } from "./rpc/atomRegistry";
import type { AppRouter } from "./router";
import { AppRoot } from "./AppRoot";
import { AppRoot, ServerRestartReconnectHost } from "./AppRoot";
describe("AppRoot", () => {
it("shares the application atom registry with routed UI and renderer-wide desktop hosts", () => {
@@ -16,9 +16,13 @@ describe("AppRoot", () => {
const children = Children.toArray(
(root as ReactElement<{ readonly children: ReactNode }>).props.children,
);
expect(children).toHaveLength(3);
expect(isValidElement(children[0]) && children[0].type).toBe(RouterProvider);
expect(isValidElement(children[1]) && children[1].type).toBe(PreviewAutomationHosts);
expect(isValidElement(children[2]) && children[2].type).toBe(ElectronBrowserHost);
expect(children).toHaveLength(4);
// The restart-reconnect host is inside the registry provider (it reads
// environment atoms) and outside the router, because a server restart
// outlives the route the update was triggered from.
expect(isValidElement(children[0]) && children[0].type).toBe(ServerRestartReconnectHost);
expect(isValidElement(children[1]) && children[1].type).toBe(RouterProvider);
expect(isValidElement(children[2]) && children[2].type).toBe(PreviewAutomationHosts);
expect(isValidElement(children[3]) && children[3].type).toBe(ElectronBrowserHost);
});
});
+13
View File
@@ -4,6 +4,18 @@ import { ElectronBrowserHost } from "./browser/ElectronBrowserHost";
import { PreviewAutomationHosts } from "./components/preview/PreviewAutomationHosts";
import { AppAtomRegistryProvider } from "./rpc/atomRegistry";
import type { AppRouter } from "./router";
import { useServerRestartReconnect } from "./useServerRestartReconnect";
/**
* Reconnects environments through an expected server restart. Mounted here
* because a restart outlives the view it was triggered from — the update
* action appears both in the chat composer's skew banner and in
* Settings → Connections.
*/
export function ServerRestartReconnectHost() {
useServerRestartReconnect();
return null;
}
/**
* Owns renderer-wide providers. The Electron browser host intentionally sits
@@ -13,6 +25,7 @@ import type { AppRouter } from "./router";
export function AppRoot({ router }: { readonly router: AppRouter }) {
return (
<AppAtomRegistryProvider>
<ServerRestartReconnectHost />
<RouterProvider router={router} />
<PreviewAutomationHosts />
<ElectronBrowserHost />
@@ -12,6 +12,8 @@ import {
resolveBranchToolbarValue,
resolveLockedWorkspaceLabel,
resolveLocalCheckoutBranchMismatch,
resolvePreviousWorktreeLabel,
resolvePreviousWorktreeSeed,
shouldIncludeBranchPickerItem,
shouldShowEnvironmentIndicator,
} from "./BranchToolbar.logic";
@@ -19,6 +21,91 @@ 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(
@@ -1,5 +1,6 @@
import type { EnvironmentId, VcsRef, ProjectId } from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import { toSortableTimestamp } from "../lib/threadSort";
export {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
@@ -65,6 +66,53 @@ 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;
+64 -4
View File
@@ -6,12 +6,13 @@ import {
FolderGit2Icon,
FolderGitIcon,
FolderIcon,
HistoryIcon,
MonitorIcon,
} from "lucide-react";
import { memo, useMemo } from "react";
import { memo, useCallback, useMemo } from "react";
import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
import { useProject, useThread } from "../state/entities";
import { useProject, useThread, useThreadShellsForProjectRefs } from "../state/entities";
import { useIsMobile } from "../hooks/useMediaQuery";
import {
type EnvMode,
@@ -20,6 +21,8 @@ import {
resolveEnvModeLabel,
resolveEffectiveEnvMode,
resolveLockedWorkspaceLabel,
resolvePreviousWorktreeLabel,
resolvePreviousWorktreeSeed,
shouldShowEnvironmentIndicator,
} from "./BranchToolbar.logic";
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
@@ -66,6 +69,8 @@ interface MobileRunContextSelectorProps {
effectiveEnvMode: EnvMode;
activeWorktreePath: string | null;
onEnvModeChange: (mode: EnvMode) => void;
previousWorktreeLabel: string | null;
onUsePreviousWorktree: () => void;
}
const MobileRunContextSelector = memo(function MobileRunContextSelector({
@@ -79,6 +84,8 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
effectiveEnvMode,
activeWorktreePath,
onEnvModeChange,
previousWorktreeLabel,
onUsePreviousWorktree,
}: MobileRunContextSelectorProps) {
const activeEnvironment = useMemo(
() => availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null,
@@ -166,7 +173,13 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
<MenuGroupLabel>Workspace</MenuGroupLabel>
<MenuRadioGroup
value={effectiveEnvMode}
onValueChange={(value) => onEnvModeChange(value as EnvMode)}
onValueChange={(value) => {
if (value === "previous-worktree") {
onUsePreviousWorktree();
return;
}
onEnvModeChange(value as EnvMode);
}}
>
<MenuRadioItem disabled={envModeLocked} value="local">
<span className="flex min-w-0 items-center gap-1.5">
@@ -186,6 +199,14 @@ 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>
@@ -217,6 +238,7 @@ 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
@@ -234,6 +256,40 @@ 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,
);
@@ -248,7 +304,7 @@ export const BranchToolbar = memo(function BranchToolbar({
if (!hasActiveThread || !activeProject) return null;
return (
<div className="flex w-full items-center gap-2 border-t border-border/60 px-3 py-2">
<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">
{isMobile ? (
<MobileRunContextSelector
envLocked={envLocked}
@@ -261,6 +317,8 @@ 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">
@@ -280,6 +338,8 @@ export const BranchToolbar = memo(function BranchToolbar({
effectiveEnvMode={effectiveEnvMode}
activeWorktreePath={activeWorktreePath}
onEnvModeChange={onEnvModeChange}
previousWorktreeLabel={previousWorktreeLabel}
onUsePreviousWorktree={onUsePreviousWorktree}
/>
</div>
)}
@@ -731,7 +731,7 @@ export function BranchToolbarBranchSelector({
>
<ComboboxTrigger
render={<Button variant="ghost" size="xs" />}
className="min-w-0 text-muted-foreground/70 hover:text-foreground/80"
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" />
@@ -1,4 +1,4 @@
import { FolderGit2Icon, FolderGitIcon, FolderIcon } from "lucide-react";
import { FolderGit2Icon, FolderGitIcon, FolderIcon, HistoryIcon } from "lucide-react";
import { memo, useMemo } from "react";
import {
@@ -17,11 +17,15 @@ 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({
@@ -29,13 +33,19 @@ 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],
[activeWorktreePath, previousWorktreeLabel, showPreviousWorktree],
);
if (envLocked) {
@@ -60,7 +70,13 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
<Select
modal={false}
value={effectiveEnvMode}
onValueChange={(value) => onEnvModeChange(value as EnvMode)}
onValueChange={(value: string | null) => {
if (value === PREVIOUS_WORKTREE_SELECT_VALUE) {
onUsePreviousWorktree?.();
return;
}
onEnvModeChange(value as EnvMode);
}}
items={envModeItems}
>
<SelectTrigger variant="ghost" size="xs" className="font-medium" aria-label="Workspace">
@@ -92,6 +108,14 @@ 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,16 +12,20 @@ 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";
@@ -292,6 +296,61 @@ 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(
+40
View File
@@ -289,6 +289,46 @@ 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),
+422 -170
View File
@@ -22,9 +22,11 @@ import {
TerminalOpenInput,
} from "@t3tools/contracts";
import {
connectionStatusText,
connectionStatusTitle,
type EnvironmentConnectionPresentation,
} from "@t3tools/client-runtime/connection";
import { isServerRestarting, useServerRestartExpected } from "~/serverRestartStore";
import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
import {
parseScopedThreadKey,
scopedThreadKey,
@@ -138,7 +140,14 @@ import { BranchToolbar } from "./BranchToolbar";
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
import PlanSidebar from "./PlanSidebar";
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
import { ChevronDownIcon, TriangleAlertIcon, WifiOffIcon } from "lucide-react";
import {
AlarmClockIcon,
CheckCircle2Icon,
ChevronDownIcon,
GitBranchIcon,
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";
@@ -153,7 +162,8 @@ import {
import { newDraftId, newMessageId, newThreadId } from "~/lib/utils";
import { getProviderModelCapabilities, resolveSelectableProvider } from "../providerModels";
import { NO_PROVIDER_MODEL_SELECTION } from "../providerInstances";
import { useEnvironmentSettings } from "../hooks/useSettings";
import { useClientSettings, useEnvironmentSettings } from "../hooks/useSettings";
import { useNowMinute } from "../hooks/useNowMinute";
import { resolveAppModelSelectionForInstance } from "../modelSelection";
import { getTerminalFocusOwner } from "../lib/terminalFocus";
import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions";
@@ -202,6 +212,7 @@ import {
useThread,
useThreadProposedPlans,
useThreadRefs,
useThreadShell,
} from "../state/entities";
import { environmentShell } from "../state/shell";
import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer";
@@ -220,6 +231,7 @@ import {
shouldShowProviderStatusBanner,
} 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,
@@ -231,13 +243,17 @@ 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,
@@ -260,6 +276,17 @@ import { RightPanelSheet } from "./RightPanelSheet";
import { previewEnvironment } from "../state/preview";
import { useAtomCommand } from "../state/use-atom-command";
import { Button } from "./ui/button";
import { Spinner } from "./ui/spinner";
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,
@@ -1594,6 +1621,19 @@ function ChatViewContent(props: ChatViewProps) {
connection: activeEnvironment.connection,
};
}, [activeEnvironment, activeEnvironmentUnavailable, activeEnvironmentUnavailableLabel]);
// While a server self-update restart is expected, disconnects are routine:
// present them calmly and retry fast instead of letting exponential
// backoff strand the client asleep when the server comes back.
const activeEnvironmentId = activeEnvironment?.environmentId ?? null;
const activeEnvironmentRestartExpected = useServerRestartExpected(activeEnvironmentId);
const activeEnvironmentRestarting = isServerRestarting({
restartExpected: activeEnvironmentRestartExpected,
environmentUnavailable: activeEnvironmentUnavailable,
});
// Reconnecting through the restart (and ending the window once its restart
// has been seen through) is owned by useServerRestartReconnect at the app
// level, since an update can be triggered from Settings → Connections too.
// This view only presents the result.
const handleReconnectActiveEnvironment = useCallback(
async (environmentId: EnvironmentId) => {
const result = await retryEnvironment(environmentId);
@@ -1807,7 +1847,19 @@ function ChatViewContent(props: ChatViewProps) {
const versionMismatchSelfUpdate = resolveServerSelfUpdateCapability(serverConfig);
const systemComposerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {
const items: ComposerBannerStackItem[] = [];
if (activeEnvironmentUnavailableState) {
if (activeEnvironmentUnavailableState && activeEnvironmentRestarting) {
// An expected self-update restart: the disconnect and the transient
// connection errors behind it are routine, so keep the tone neutral
// and let the fast auto-retry loop do the work instead of asking the
// user to reconnect by hand.
items.push({
id: `environment-restarting:${activeEnvironmentUnavailableState.environmentId}`,
variant: "info",
icon: <Spinner className="size-4" />,
title: `${activeEnvironmentUnavailableState.label} is restarting`,
description: "Finishing the server update — reconnecting automatically.",
});
} else if (activeEnvironmentUnavailableState) {
const connection = activeEnvironmentUnavailableState.connection;
const isReconnecting =
connection.phase === "connecting" || connection.phase === "reconnecting";
@@ -1815,7 +1867,7 @@ function ChatViewContent(props: ChatViewProps) {
id: `environment-unavailable:${activeEnvironmentUnavailableState.environmentId}`,
variant: connection.phase === "error" ? "error" : "warning",
icon: <WifiOffIcon />,
title: `${activeEnvironmentUnavailableState.label}: ${connectionStatusText(connection)}`,
title: `${activeEnvironmentUnavailableState.label}: ${connectionStatusTitle(connection)}`,
description:
connection.error ??
"Reconnect this environment before sending messages or running actions.",
@@ -1847,7 +1899,10 @@ function ChatViewContent(props: ChatViewProps) {
showVersionMismatchBanner &&
versionMismatch &&
versionMismatchDismissKey &&
versionMismatchEnvironmentId
versionMismatchEnvironmentId &&
// The mismatch data predates the disconnect; during an expected
// restart it is stale and its update action would double-trigger.
!activeEnvironmentRestarting
) {
items.push({
id: `version-mismatch:${versionMismatchDismissKey}`,
@@ -1881,6 +1936,7 @@ function ChatViewContent(props: ChatViewProps) {
}
return items;
}, [
activeEnvironmentRestarting,
activeEnvironmentUnavailableState,
handleReconnectActiveEnvironment,
navigate,
@@ -2352,6 +2408,7 @@ 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";
@@ -3808,52 +3865,159 @@ function ChatViewContent(props: ChatViewProps) {
: null,
[activeThreadBranch, activeWorktreePath, envMode, gitStatusQuery.data?.refName, isServerThread],
);
const [branchRepairAction, setBranchRepairAction] = useState<
"update-thread" | "switch-checkout" | null
>(null);
const handleUpdateThreadToCheckout = useCallback(async () => {
if (!activeThread || !localCheckoutBranchMismatch || branchRepairAction !== null) {
return;
}
setBranchRepairAction("update-thread");
const updateResult = await updateThreadMetadata({
environmentId,
input: {
threadId: activeThread.id,
branch: localCheckoutBranchMismatch.currentBranch,
worktreePath: null,
},
// 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 supportsSnooze = serverConfig?.environment.capabilities.threadSnooze === true;
const nowMinute = useNowMinute();
const activeThreadSnoozed =
activeThreadShell !== null &&
supportsSnooze &&
effectiveSnoozed(activeThreadShell, { now: new Date().toISOString() });
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
useEffect(() => {
void snoozeWakeTick;
if (!activeThreadSnoozed) return;
const wakeAtMs = Date.parse(activeThreadShell?.snoozedUntil ?? "");
if (!Number.isFinite(wakeAtMs)) return;
const id = window.setTimeout(
() => bumpSnoozeWakeTick((tick) => tick + 1),
Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647),
);
return () => window.clearTimeout(id);
}, [activeThreadShell?.snoozedUntil, activeThreadSnoozed, snoozeWakeTick]);
const activeThreadSettled = useMemo(() => {
if (activeThreadShell === null || !supportsSettlement) return false;
return effectiveSettled(activeThreadShell, {
now: `${nowMinute}:00.000Z`,
autoSettleAfterDays,
changeRequestState: activeThreadPr?.state ?? null,
});
setBranchRepairAction(null);
if (updateResult._tag === "Failure" && !isAtomCommandInterrupted(updateResult)) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to update thread branch",
description: chatActionErrorMessage(squashAtomCommandFailure(updateResult)),
}),
);
return;
}
scheduleComposerFocus();
}, [
activeThread,
branchRepairAction,
environmentId,
localCheckoutBranchMismatch,
scheduleComposerFocus,
updateThreadMetadata,
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 unsnoozeThreadMutation = useAtomCommand(threadEnvironment.unsnooze, {
reportFailure: false,
});
const [unsnoozingThreadKey, setUnsnoozingThreadKey] = useState<string | null>(null);
const isUnsnoozing = unsnoozingThreadKey !== null && unsnoozingThreadKey === activeThreadKey;
const handleUnsnoozeActiveThread = useCallback(async () => {
if (!activeThreadRef) return;
const threadKey = scopedThreadKey(activeThreadRef);
setUnsnoozingThreadKey(threadKey);
try {
const result = await unsnoozeThreadMutation({
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 wake thread",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
}
} finally {
setUnsnoozingThreadKey((current) => (current === threadKey ? null : current));
}
}, [activeThreadRef, unsnoozeThreadMutation]);
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 ||
branchRepairAction !== null
isRestoringThreadBranch
) {
return;
}
setBranchRepairAction("switch-checkout");
setIsRestoringThreadBranch(true);
const checkoutResult = await switchGitRef({
environmentId,
input: {
@@ -3862,7 +4026,7 @@ function ChatViewContent(props: ChatViewProps) {
},
});
if (checkoutResult._tag === "Failure") {
setBranchRepairAction(null);
setIsRestoringThreadBranch(false);
if (!isAtomCommandInterrupted(checkoutResult)) {
toastManager.add(
stackedThreadToast({
@@ -3882,7 +4046,7 @@ function ChatViewContent(props: ChatViewProps) {
input: { threadId: activeThread.id, branch: nextBranch, worktreePath: null },
});
if (updateResult._tag === "Failure") {
setBranchRepairAction(null);
setIsRestoringThreadBranch(false);
if (!isAtomCommandInterrupted(updateResult)) {
toastManager.add(
stackedThreadToast({
@@ -3897,76 +4061,125 @@ function ChatViewContent(props: ChatViewProps) {
}
}
gitStatusQuery.refresh();
setBranchRepairAction(null);
setIsRestoringThreadBranch(false);
scheduleComposerFocus();
}, [
activeProjectCwd,
activeThread,
branchRepairAction,
environmentId,
gitStatusQuery,
isRestoringThreadBranch,
localCheckoutBranchMismatch,
scheduleComposerFocus,
switchGitRef,
updateThreadMetadata,
]);
const composerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {
if (!localCheckoutBranchMismatch) {
return systemComposerBannerItems;
// 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 parked-thread banner last — it must never cover another.
const parkedThreadBannerItem = useMemo<ComposerBannerStackItem | null>(() => {
if (!activeThreadSnoozed && !activeThreadSettled) {
return null;
}
const isSnoozed = activeThreadSnoozed;
return {
id: `thread-${isSnoozed ? "snoozed" : "settled"}:${activeThread?.id ?? "unknown"}`,
variant: "info",
icon: isSnoozed ? <AlarmClockIcon /> : <CheckCircle2Icon />,
title: `This thread is ${isSnoozed ? "snoozed" : "settled"}`,
description: isSnoozed
? "Sending a message wakes it and moves it back to Active in the sidebar."
: "Sending a message moves it back to Active in the sidebar.",
actions: (
<Button
size="xs"
variant="outline"
disabled={isSnoozed ? isUnsnoozing : isUnsettling}
onClick={() =>
void (isSnoozed ? handleUnsnoozeActiveThread() : handleUnsettleActiveThread())
}
>
{isSnoozed
? isUnsnoozing
? "Waking..."
: "Wake now"
: isUnsettling
? "Un-settling..."
: "Un-settle"}
</Button>
),
};
}, [
activeThread?.id,
activeThreadSettled,
activeThreadSnoozed,
handleUnsnoozeActiveThread,
handleUnsettleActiveThread,
isUnsnoozing,
isUnsettling,
]);
const handleRestoreThreadBranch = useCallback(() => {
if (gitStatusQuery.data?.hasWorkingTreeChanges) {
setBranchRestoreConfirmOpen(true);
return;
}
void handleSwitchCheckoutToThread();
}, [gitStatusQuery.data?.hasWorkingTreeChanges, handleSwitchCheckoutToThread]);
const composerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {
const parkedThreadItems = parkedThreadBannerItem === null ? [] : [parkedThreadBannerItem];
if (!localCheckoutBranchMismatch || !showBranchMismatchBanner || !activeBranchMismatchKey) {
return [...systemComposerBannerItems, ...parkedThreadItems];
}
const isRepairingBranch = branchRepairAction !== null;
return [
...systemComposerBannerItems,
{
id: `branch-mismatch:${activeThread?.id ?? "unknown"}:${localCheckoutBranchMismatch.threadBranch}:${localCheckoutBranchMismatch.currentBranch}`,
variant: "warning",
icon: <TriangleAlertIcon />,
title: "You're on a different branch",
className:
"text-base sm:text-sm [&>div]:items-start max-sm:[&>div]:flex-wrap max-sm:[&>div>div:last-child]:w-full max-sm:[&>div>div:last-child]:self-start dark:shadow-none",
actionClassName:
"max-sm:w-full max-sm:border-t max-sm:border-border/60 max-sm:pt-2 max-sm:pl-6 sm:border-l sm:border-border/60 sm:pl-3",
description: (
<p className="text-pretty">
This thread is on{" "}
<code className="font-medium text-foreground">
{localCheckoutBranchMismatch.threadBranch}
</code>
, but you're currently checked out at{" "}
<code className="font-medium text-foreground">
{localCheckoutBranchMismatch.currentBranch}
</code>
. Sending a message will update the thread.
</p>
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="outline"
disabled={isRepairingBranch}
onClick={() => void handleUpdateThreadToCheckout()}
>
{branchRepairAction === "update-thread" ? "Moving..." : "Move thread here"}
</Button>
<Button
size="xs"
variant="ghost"
disabled={isRepairingBranch}
onClick={() => void handleSwitchCheckoutToThread()}
>
{branchRepairAction === "switch-checkout" ? "Switching..." : "Checkout thread branch"}
</Button>
</>
<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);
},
},
...parkedThreadItems,
];
}, [
activeThread?.id,
branchRepairAction,
handleSwitchCheckoutToThread,
handleUpdateThreadToCheckout,
activeBranchMismatchKey,
handleRestoreThreadBranch,
isRestoringThreadBranch,
localCheckoutBranchMismatch,
parkedThreadBannerItem,
showBranchMismatchBanner,
systemComposerBannerItems,
]);
@@ -5561,7 +5774,7 @@ function ChatViewContent(props: ChatViewProps) {
ref={attachDraftHeroTransitionGroupRef}
className="chat-composer-horizontal-inset w-full"
>
<div className="pointer-events-auto relative z-10 isolate">
<div className="pointer-events-auto relative z-10">
{isDraftHeroState ? (
<div className="absolute inset-x-0 bottom-full z-0">
<div
@@ -5592,90 +5805,99 @@ function ChatViewContent(props: ChatViewProps) {
: undefined
}
>
<div className="chat-composer-glass-host mx-auto w-full max-w-3xl overflow-hidden rounded-[22px]">
<div ref={attachDraftHeroComposerAnchorRef} className="relative z-10 isolate">
<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
className={cn(
"chat-composer-glass-shell relative mx-auto w-full max-w-3xl",
showComposerContextStrip && "chat-composer-glass-shell-with-context",
)}
>
<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"
>
{isGitRepo && (
{showComposerContextStrip && (
<div className="pointer-events-auto">
<BranchToolbar
environmentId={activeThread.environmentId}
@@ -5716,6 +5938,36 @@ function ChatViewContent(props: ChatViewProps) {
</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,12 +111,13 @@ 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],
searchTerms: [project.title, project.workspaceRoot, ...(input.searchTerms?.(project) ?? [])],
title: project.title,
description: project.workspaceRoot,
icon: input.icon(project),
+159 -29
View File
@@ -56,12 +56,9 @@ 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, usePrimaryEnvironment } from "../state/environments";
import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
import { useProjects, useThreadShells } from "../state/entities";
import {
startNewThreadInProjectFromContext,
startNewThreadFromContext,
} from "../lib/chatThreadActions";
import { resolveThreadActionProjectRef, startNewThreadFromContext } from "../lib/chatThreadActions";
import {
appendBrowsePathSegment,
canNavigateUp,
@@ -79,7 +76,7 @@ import {
} from "../lib/projectPaths";
import { onOpenCommandPalette } from "../commandPaletteBus";
import { isTerminalFocused } from "../lib/terminalFocus";
import { getLatestThreadForProject } from "../lib/threadSort";
import { getLatestThreadForProject, sortThreads } from "../lib/threadSort";
import { cn, isMacPlatform, isWindowsPlatform, newProjectId } from "../lib/utils";
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";
@@ -106,6 +103,7 @@ 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";
@@ -128,6 +126,12 @@ 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"] = [];
@@ -487,10 +491,11 @@ function OpenCommandPaletteDialog(props: {
});
const { environments } = useEnvironments();
const desktopLocalBootstraps = useDesktopLocalBootstraps();
const primaryEnvironment = usePrimaryEnvironment();
const primaryEnvironmentId = usePrimaryEnvironmentId();
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);
@@ -504,7 +509,93 @@ function OpenCommandPaletteDialog(props: {
const [addProjectCloneFlow, setAddProjectCloneFlow] = useState<AddProjectCloneFlow | null>(null);
const [isRemoteProjectLookingUp, setIsRemoteProjectLookingUp] = useState(false);
const [isRemoteProjectCloning, setIsRemoteProjectCloning] = useState(false);
const primaryEnvironmentId = primaryEnvironment?.environmentId ?? null;
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 addProjectEnvironmentOptions = useMemo(() => {
const options = environments.map((environment): AddProjectEnvironmentOption => {
@@ -648,11 +739,28 @@ function OpenCommandPaletteDialog(props: {
const openProjectFromSearch = useMemo(
() => async (project: (typeof projects)[number]) => {
const latestThread = getLatestThreadForProject(
threads.filter((thread) => thread.environmentId === project.environmentId),
project.id,
clientSettings.sidebarThreadSortOrder,
);
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,
);
if (latestThread) {
await navigate({
to: "/$environmentId/$threadId",
@@ -665,14 +773,26 @@ function OpenCommandPaletteDialog(props: {
await handleNewThread(scopeProjectRef(project.environmentId, project.id));
},
[handleNewThread, navigate, clientSettings.sidebarThreadSortOrder, threads],
[
clientSettings.sidebarThreadSortOrder,
handleNewThread,
navigate,
projectGroupByTargetKey,
threads,
],
);
const projectSearchItems = useMemo(
() =>
buildProjectActionItems({
projects,
projects: pickerProjects,
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}
@@ -682,15 +802,21 @@ function OpenCommandPaletteDialog(props: {
),
runProject: openProjectFromSearch,
}),
[openProjectFromSearch, projects],
[openProjectFromSearch, pickerProjects, projectGroupByTargetKey],
);
const projectThreadItems = useMemo(
() =>
enumerateCommandPaletteItems(
buildProjectActionItems({
projects,
projects: pickerProjects,
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}
@@ -699,19 +825,23 @@ function OpenCommandPaletteDialog(props: {
/>
),
runProject: async (project) => {
await startNewThreadInProjectFromContext(
{
activeDraftThread,
activeThread: activeThread ?? undefined,
defaultProjectRef,
handleNewThread,
},
scopeProjectRef(project.environmentId, project.id),
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),
);
},
}),
),
[activeDraftThread, activeThread, defaultProjectRef, handleNewThread, projects],
[contextualProjectRef, handleNewThread, pickerProjects, projectGroupByTargetKey],
);
const allThreadItems = useMemo(
@@ -1018,9 +1148,9 @@ function OpenCommandPaletteDialog(props: {
const actionItems: Array<CommandPaletteActionItem | CommandPaletteSubmenuItem> = [];
if (projects.length > 0) {
const activeProjectTitle = currentProjectId
? (projectTitleById.get(currentProjectId) ?? null)
: null;
const activeProjectTitle =
projectPickerEntries.find((entry) => entry.isPreferred)?.group.displayName ??
(currentProjectId ? (projectTitleById.get(currentProjectId) ?? null) : null);
if (activeProjectTitle) {
actionItems.push({
+9 -20
View File
@@ -544,10 +544,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
return (
<Dialog open={props.open} onOpenChange={handleOpenChange}>
<DialogPopup
backdropClassName="bg-black/40 backdrop-blur-none"
className="workflow-dialog-surface max-w-xl overflow-hidden before:hidden"
>
<DialogPopup className="max-w-xl overflow-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">
<DialogTitle>Publish repository</DialogTitle>
@@ -1828,16 +1825,13 @@ export default function GitActionsControl({
}
}}
>
<DialogPopup
backdropClassName="bg-black/40 backdrop-blur-none"
className="command-palette-dialog-surface workflow-dialog-surface before:hidden"
>
<DialogPopup>
<DialogHeader>
<DialogTitle>{COMMIT_DIALOG_TITLE}</DialogTitle>
<DialogDescription>{COMMIT_DIALOG_DESCRIPTION}</DialogDescription>
</DialogHeader>
<DialogPanel className="space-y-4">
<div className="space-y-3 rounded-lg border border-input bg-muted/40 p-3 text-xs dark:border-transparent dark:bg-white/[0.035]">
<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="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">
@@ -1845,9 +1839,7 @@ export default function GitActionsControl({
{gitStatusForActions?.refName ?? "(detached HEAD)"}
</span>
{isDefaultRef && (
<span className="text-right text-warning text-xs">
Warning: default refName
</span>
<span className="text-right text-warning">Warning: default refName</span>
)}
</span>
</div>
@@ -1886,14 +1878,14 @@ export default function GitActionsControl({
<p className="font-medium">none</p>
) : (
<div className="space-y-2">
<ScrollArea className="h-44 rounded-md border border-input bg-background dark:border-transparent dark:bg-white/[0.025]">
<ScrollArea className="h-44 rounded-lg bg-card ring-1 ring-black/5 dark:bg-white/[0.025] dark:ring-white/5">
<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 text-xs transition-colors hover:bg-accent/50"
className="flex w-full items-center gap-2 rounded-md px-2 py-1 font-mono hover:bg-accent/50"
>
{isEditingFiles && (
<Checkbox
@@ -1952,7 +1944,7 @@ export default function GitActionsControl({
</div>
</div>
<div className="space-y-1">
<p className="text-xs font-medium">Commit message (optional)</p>
<p className="text-sm font-medium">Commit message (optional)</p>
<Textarea
value={dialogCommitMessage}
onChange={(event) => setDialogCommitMessage(event.target.value)}
@@ -1961,7 +1953,7 @@ export default function GitActionsControl({
/>
</div>
</DialogPanel>
<DialogFooter className="dark:border-transparent dark:bg-transparent">
<DialogFooter variant="bare">
<Button
variant="outline"
size="sm"
@@ -2004,10 +1996,7 @@ export default function GitActionsControl({
}
}}
>
<DialogPopup
backdropClassName="bg-black/40 backdrop-blur-none"
className="workflow-dialog-surface max-w-xl before:hidden"
>
<DialogPopup className="max-w-xl">
<DialogHeader>
<DialogTitle>
{pendingDefaultBranchActionCopy?.title ?? "Run action on default refName?"}
@@ -461,7 +461,7 @@ export default function ProjectScriptsControl({
}}
open={dialogOpen}
>
<DialogPopup className="before:hidden">
<DialogPopup>
<DialogHeader>
<DialogTitle>{isEditing ? "Edit Action" : "Add Action"}</DialogTitle>
<DialogDescription>
@@ -2,13 +2,27 @@ 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";
import {
SERVER_SELF_UPDATE_ALREADY_RUNNING_REASON,
ServerSelfUpdateError,
type EnvironmentId,
} from "@t3tools/contracts";
const testState = vi.hoisted(() => ({
updateServer: vi.fn(),
toast: vi.fn(),
}));
const restartStore = vi.hoisted(() => ({
expect: vi.fn(),
clear: vi.fn(),
expected: vi.fn(() => false),
}));
const environmentState = vi.hoisted(() => ({
useEnvironment: vi.fn(() => ({ connection: { phase: "connected" } })),
}));
const hooks = vi.hoisted(() => {
let cursor = 0;
let slots: unknown[] = [];
@@ -78,6 +92,18 @@ vi.mock("~/state/use-atom-command", () => ({
vi.mock("./ui/toast", () => ({
toastManager: { add: testState.toast },
}));
vi.mock("~/serverRestartStore", async (importOriginal) => {
const actual = await importOriginal<typeof import("~/serverRestartStore")>();
return {
...actual,
expectServerRestart: restartStore.expect,
clearExpectedServerRestart: restartStore.clear,
useServerRestartExpected: restartStore.expected,
};
});
vi.mock("~/state/environments", () => ({
useEnvironment: environmentState.useEnvironment,
}));
import { ServerUpdateAction } from "./ServerUpdateAction";
@@ -118,6 +144,12 @@ describe("ServerUpdateAction", () => {
hooks.reset();
testState.updateServer.mockReset();
testState.toast.mockReset();
restartStore.expect.mockReset();
restartStore.clear.mockReset();
restartStore.expected.mockReset();
restartStore.expected.mockReturnValue(false);
environmentState.useEnvironment.mockReset();
environmentState.useEnvironment.mockReturnValue({ connection: { phase: "connected" } });
});
afterEach(() => {
@@ -195,4 +227,71 @@ describe("ServerUpdateAction", () => {
expect.objectContaining({ title: "Server update failed" }),
);
});
it("re-arms the restart window when a slow install finally succeeds", async () => {
const update =
deferred<
ReturnType<typeof AsyncResult.success<{ targetVersion: string; method: "boot-service" }>>
>();
testState.updateServer.mockReturnValue(update.promise);
renderAction().props.onClick?.();
expect(restartStore.expect).toHaveBeenCalledTimes(1);
// An install can outlast the 90s restart window armed at click time, so
// the acknowledgement must restart the clock or the ensuing disconnect
// would be presented as an outage.
await vi.advanceTimersByTimeAsync(5 * 60_000);
update.resolve(AsyncResult.success({ targetVersion: "0.0.29", method: "boot-service" }));
await flushPromises();
expect(restartStore.expect).toHaveBeenCalledTimes(2);
expect(restartStore.clear).not.toHaveBeenCalled();
});
it("re-arms the restart window on an interrupted restart RPC", async () => {
testState.updateServer.mockResolvedValue(AsyncResult.failure(Cause.interrupt()));
renderAction().props.onClick?.();
await flushPromises();
expect(restartStore.expect).toHaveBeenCalledTimes(2);
expect(restartStore.clear).not.toHaveBeenCalled();
});
it("withdraws the restart expectation when the server reports a real failure", async () => {
testState.updateServer.mockResolvedValue(
AsyncResult.failure(
Cause.fail(
new ServerSelfUpdateError({ reason: "Could not install the requested t3 version." }),
),
),
);
renderAction().props.onClick?.();
await flushPromises();
// The server answered, so it is still alive and no restart is coming.
expect(restartStore.clear).toHaveBeenCalledTimes(1);
expect(testState.toast).toHaveBeenCalledWith(
expect.objectContaining({ title: "Server update failed" }),
);
});
it("keeps the restart expectation when an update is already in progress", async () => {
testState.updateServer.mockResolvedValue(
AsyncResult.failure(
Cause.fail(
new ServerSelfUpdateError({ reason: SERVER_SELF_UPDATE_ALREADY_RUNNING_REASON }),
),
),
);
renderAction().props.onClick?.();
await flushPromises();
// An earlier request is still installing, so a restart really is pending
// — clearing here would restore the harsh reconnect UI mid-restart.
expect(restartStore.clear).not.toHaveBeenCalled();
});
});
+103 -3
View File
@@ -1,11 +1,23 @@
import { useEffect, useRef, useState } from "react";
import type { EnvironmentId, ServerSelfUpdateCapability } from "@t3tools/contracts";
import {
ServerSelfUpdateError,
type EnvironmentId,
type ServerSelfUpdateCapability,
} from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import {
clearExpectedServerRestart,
expectServerRestart,
isExpectedRestartResolved,
useServerRestartExpected,
} from "~/serverRestartStore";
import { useEnvironment } from "~/state/environments";
import { serverEnvironment } from "~/state/server";
import { useAtomCommand } from "~/state/use-atom-command";
import { manualServerUpdateCommand } from "~/versionSkew";
@@ -24,6 +36,18 @@ function updateFailureMessage(error: unknown): string {
return error instanceof Error ? error.message : "Server update failed.";
}
/**
* The server rejects a second update while one is already installing. That
* failure means a restart is still pending from the earlier request, so the
* restart expectation must survive it — unlike every other failure, which
* proves nothing is coming.
*/
const isServerSelfUpdateError = Schema.is(ServerSelfUpdateError);
function isUpdateAlreadyRunning(error: unknown): boolean {
return isServerSelfUpdateError(error) && error.isAlreadyRunning;
}
/**
* 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
@@ -80,6 +104,56 @@ export function ServerUpdateAction({
[],
);
// The restart is scheduled after the RPC is acknowledged, so a rejected
// restart — or a replacement that comes back on the old version — can no
// longer be reported through the call. Without a release path the mismatch
// banner would keep its only action disabled for the full safety window.
//
// The signal is the environment going away and then answering again while
// this component is still mounted: still mounted means the skew is
// unresolved, so whatever restarted did not deliver the new version.
// Deliberately independent of the restart window, which is UI presentation
// state and can lapse or be re-armed for unrelated reasons.
// Two ways that resolves, because a rejected restart may or may not have
// taken the connection down with it:
// - the environment went away and came back, so something restarted but
// did not deliver the new version; or
// - the restart window lapsed with the connection never dropping, so no
// restart ever happened (systemd refused it and rolled back).
const connectionPhase = useEnvironment(environmentId)?.connection.phase ?? null;
const connectionUnavailable = connectionPhase !== null && connectionPhase !== "connected";
const restartExpected = useServerRestartExpected(environmentId);
const wentAwayRef = useRef(false);
const sawWindowRef = useRef(false);
if (connectionUnavailable) {
wentAwayRef.current = true;
}
if (restartExpected) {
// Guards against reading a not-yet-rendered window as "already lapsed"
// in the render between the click and the store update landing.
sawWindowRef.current = true;
}
const restartResolved = isExpectedRestartResolved({
sawRestartWindow: sawWindowRef.current,
restartExpected,
wentAway: wentAwayRef.current,
environmentUnavailable: connectionUnavailable,
});
useEffect(() => {
if (!restartResolved || !inFlightRef.current) {
return;
}
wentAwayRef.current = false;
sawWindowRef.current = false;
if (expiryRef.current !== null) {
clearTimeout(expiryRef.current);
expiryRef.current = null;
}
attemptRef.current += 1;
inFlightRef.current = false;
setPending(false);
}, [restartResolved]);
const handleUpdate = () => {
// Synchronous re-entry guard: setPending is async, so a rapid
// double-click would otherwise dispatch two updates.
@@ -87,6 +161,11 @@ export function ServerUpdateAction({
return;
}
inFlightRef.current = true;
// Only outages observed during this attempt may resolve it. An earlier
// unrelated blip would otherwise satisfy the resolve predicate on the
// very next render and re-enable the button mid-update.
wentAwayRef.current = false;
sawWindowRef.current = false;
const attempt = attemptRef.current + 1;
attemptRef.current = attempt;
const ownsAttempt = () => attemptRef.current === attempt;
@@ -115,7 +194,18 @@ export function ServerUpdateAction({
clearTimeout(expiry);
expiry = armExpiry();
}
// The install can consume most of the request window, so the window
// armed at click time may already have lapsed by the time the restart
// actually begins. Re-arm from the handoff, not from the click.
expectServerRestart(environmentId);
};
// Armed before dispatch: the boot-service path acknowledges and then
// drops every connection, and even the respawn acknowledgement can lose
// the race against the disconnect. An explicit RPC failure proves the
// server stayed alive, so the expectation is withdrawn there; on
// success or interrupt it is re-armed from that point and expires on its
// own if the server never returns.
expectServerRestart(environmentId);
void Promise.resolve()
.then(() =>
updateServer({
@@ -129,14 +219,21 @@ export function ServerUpdateAction({
// 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.
// successful replacement reconnects. Re-arm from here for the same
// reason as the success path: a long install may have outlasted the
// window armed at click time.
if (isAtomCommandInterrupted(result)) {
expectServerRestart(environmentId);
return;
}
const failure = squashAtomCommandFailure(result);
if (!isUpdateAlreadyRunning(failure)) {
clearExpectedServerRestart(environmentId);
}
toastManager.add({
type: "error",
title: "Server update failed",
description: updateFailureMessage(squashAtomCommandFailure(result)),
description: updateFailureMessage(failure),
});
return;
}
@@ -152,6 +249,9 @@ export function ServerUpdateAction({
})
.catch((error: unknown) => {
if (!ownsAttempt()) return;
if (!isUpdateAlreadyRunning(error)) {
clearExpectedServerRestart(environmentId);
}
toastManager.add({
type: "error",
title: "Server update failed",
+181 -110
View File
@@ -14,14 +14,16 @@ import {
isTrailingDoubleClick,
orderItemsByPreferredIds,
resolveProjectStatusIndicator,
resolveSidebarNewThreadSeedContext,
resolveSidebarNewThreadEnvMode,
resolveSidebarStageBadgeLabel,
resolveThreadRowClassName,
resolveSidebarV2Status,
resolveThreadStatusPill,
resolveWorkingStartedAt,
formatWorkingDurationLabel,
shouldNavigateAfterProjectRemoval,
shouldClearThreadSelectionOnMouseDown,
sortLogicalProjectsForSidebar,
sortSettledThreadsForSidebarV2,
sortThreadsForSidebarV2,
sortProjectsForSidebar,
sortScopedProjectsForSidebar,
@@ -34,6 +36,7 @@ import {
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import {
DEFAULT_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
@@ -207,8 +210,10 @@ function makeLatestTurn(overrides?: {
state: "completed",
assistantMessageId: null,
requestedAt: "2026-03-09T10:00:00.000Z",
startedAt: overrides?.startedAt ?? "2026-03-09T10:00:00.000Z",
completedAt: overrides?.completedAt ?? "2026-03-09T10:05: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",
};
}
@@ -364,112 +369,6 @@ 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({
@@ -781,6 +680,141 @@ 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,
@@ -1353,3 +1387,40 @@ 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"]);
});
});
+125 -57
View File
@@ -18,7 +18,6 @@ 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;
@@ -36,6 +35,14 @@ 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<
@@ -238,62 +245,6 @@ 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[];
@@ -494,6 +445,18 @@ 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
@@ -508,6 +471,73 @@ 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 {
@@ -727,6 +757,44 @@ 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
@@ -0,0 +1,94 @@
import { describe, expect, it } from "vite-plus/test";
import { resolveSnoozePresets, snoozeWakeDescription, snoozeWakeLabel } from "./Sidebar.snooze";
// Local-time constructor so preset math is timezone-stable in tests.
function localDate(year: number, month: number, day: number, hour: number, minute = 0): Date {
return new Date(year, month - 1, day, hour, minute, 0, 0);
}
describe("resolveSnoozePresets", () => {
it("offers hour, evening, tomorrow, next week in the morning", () => {
// Wednesday 2026-04-08 10:00 local.
const presets = resolveSnoozePresets(localDate(2026, 4, 8, 10));
expect(presets.map((preset) => preset.id)).toEqual([
"hour",
"evening",
"tomorrow",
"next-week",
]);
const evening = presets.find((preset) => preset.id === "evening");
expect(new Date(evening!.snoozedUntil).getHours()).toBe(18);
const tomorrow = presets.find((preset) => preset.id === "tomorrow");
const tomorrowDate = new Date(tomorrow!.snoozedUntil);
expect(tomorrowDate.getDate()).toBe(9);
expect(tomorrowDate.getHours()).toBe(9);
const nextWeek = presets.find((preset) => preset.id === "next-week");
const nextWeekDate = new Date(nextWeek!.snoozedUntil);
expect(nextWeekDate.getDay()).toBe(1);
expect(nextWeekDate.getDate()).toBe(13);
});
it("whenLabel complements the label instead of repeating it", () => {
const presets = resolveSnoozePresets(localDate(2026, 4, 8, 10));
for (const preset of presets) {
// Day words live in the label column; the time column is time-only
// (plus a weekday for next week, which names a different day).
expect(preset.whenLabel.toLowerCase()).not.toContain("tomorrow");
}
const tomorrow = presets.find((preset) => preset.id === "tomorrow");
expect(tomorrow!.whenLabel).toMatch(/9/);
const nextWeek = presets.find((preset) => preset.id === "next-week");
expect(nextWeek!.whenLabel).toMatch(/Mon/);
});
it("drops the evening preset once evening is near or past", () => {
expect(resolveSnoozePresets(localDate(2026, 4, 8, 17, 30)).map((preset) => preset.id)).toEqual([
"hour",
"tomorrow",
"next-week",
]);
expect(resolveSnoozePresets(localDate(2026, 4, 8, 21)).map((preset) => preset.id)).toEqual([
"hour",
"tomorrow",
"next-week",
]);
});
it("puts next week a full week out when today is Monday", () => {
// Monday 2026-04-06.
const presets = resolveSnoozePresets(localDate(2026, 4, 6, 10));
const nextWeek = new Date(presets.find((preset) => preset.id === "next-week")!.snoozedUntil);
expect(nextWeek.getDay()).toBe(1);
expect(nextWeek.getDate()).toBe(13);
});
});
describe("snoozeWakeLabel", () => {
const now = localDate(2026, 4, 8, 10);
it("formats minutes, hours, and days, rounding up", () => {
expect(snoozeWakeLabel(new Date(now.getTime() + 30 * 60_000).toISOString(), now)).toBe("30m");
expect(snoozeWakeLabel(new Date(now.getTime() + 90 * 60_000).toISOString(), now)).toBe("2h");
expect(snoozeWakeLabel(new Date(now.getTime() + 26 * 3_600_000).toISOString(), now)).toBe("2d");
});
it("reports now for past and malformed wake times", () => {
expect(snoozeWakeLabel(new Date(now.getTime() - 1000).toISOString(), now)).toBe("now");
expect(snoozeWakeLabel("not-a-date", now)).toBe("now");
});
});
describe("snoozeWakeDescription", () => {
const now = localDate(2026, 4, 8, 10);
it("uses bare time today, 'tomorrow' next day, weekday within the week", () => {
expect(snoozeWakeDescription(localDate(2026, 4, 8, 18).toISOString(), now)).not.toContain(
"tomorrow",
);
expect(snoozeWakeDescription(localDate(2026, 4, 9, 9).toISOString(), now)).toContain(
"tomorrow",
);
expect(snoozeWakeDescription(localDate(2026, 4, 13, 9).toISOString(), now)).toMatch(/Mon/);
});
});
+127
View File
@@ -0,0 +1,127 @@
/**
* Snooze preset resolution for the sidebar snooze menu. Pure functions so
* the preset math (evening/tomorrow/next-week boundaries) is unit-testable
* without a DOM.
*
* Presets deliberately skew short: agent-thread rhythms are hours (a CI
* run, a teammate review, the next work session), not days.
*/
import { parseTimestampDate } from "../timestampFormat";
type SnoozePresetId = "hour" | "evening" | "tomorrow" | "next-week";
export interface SnoozePreset {
readonly id: SnoozePresetId;
readonly label: string;
/** Menu-row time column. Complements the label instead of repeating it:
"Tomorrow" pairs with "9:00 AM", not "tomorrow 9:00 AM". */
readonly whenLabel: string;
/** ISO wake time. */
readonly snoozedUntil: string;
}
function timeOfDayLabel(date: Date): string {
return date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
}
const EVENING_HOUR = 18;
const MORNING_HOUR = 9;
const HOUR_MS = 60 * 60 * 1_000;
const DAY_MS = 24 * HOUR_MS;
function atHour(base: Date, hour: number): Date {
const next = new Date(base);
next.setHours(hour, 0, 0, 0);
return next;
}
// Calendar-day advance instead of adding DAY_MS: fixed millisecond offsets
// land on the wrong local day across DST transitions (a spring-forward day
// is 23 hours, so 23:30 + 24h skips the whole next day).
function addDays(base: Date, days: number): Date {
const next = new Date(base);
next.setDate(next.getDate() + days);
return next;
}
/**
* Presets for "snooze until", computed against local time. "This evening"
* only appears while it is still meaningfully before evening; after that
* the list starts at "Tomorrow".
*/
export function resolveSnoozePresets(now: Date): ReadonlyArray<SnoozePreset> {
const inAnHour = new Date(now.getTime() + HOUR_MS);
const presets: SnoozePreset[] = [
{
id: "hour",
label: "In 1 hour",
whenLabel: timeOfDayLabel(inAnHour),
snoozedUntil: inAnHour.toISOString(),
},
];
const evening = atHour(now, EVENING_HOUR);
// Suppress the evening preset once it is within an hour (or past): it
// would duplicate "In 1 hour" or point at the past.
if (evening.getTime() - now.getTime() > HOUR_MS) {
presets.push({
id: "evening",
label: "This evening",
whenLabel: timeOfDayLabel(evening),
snoozedUntil: evening.toISOString(),
});
}
const tomorrow = atHour(addDays(now, 1), MORNING_HOUR);
presets.push({
id: "tomorrow",
label: "Tomorrow",
whenLabel: timeOfDayLabel(tomorrow),
snoozedUntil: tomorrow.toISOString(),
});
// Next Monday 9:00 (a week out when today is Monday).
const daysUntilMonday = (1 - now.getDay() + 7) % 7 || 7;
const nextWeek = atHour(addDays(now, daysUntilMonday), MORNING_HOUR);
presets.push({
id: "next-week",
label: "Next week",
whenLabel: `${nextWeek.toLocaleDateString(undefined, { weekday: "short" })} ${timeOfDayLabel(nextWeek)}`,
snoozedUntil: nextWeek.toISOString(),
});
return presets;
}
/**
* Compact "wakes in" label for snoozed rows: "2h", "18h", "3d". Minutes
* round up so a snooze never reads "0m" while still hidden.
*/
export function snoozeWakeLabel(snoozedUntil: string, now: Date): string {
const wake = parseTimestampDate(snoozedUntil);
if (wake === null) return "now";
const remainingMs = wake.getTime() - now.getTime();
if (remainingMs <= 0) return "now";
if (remainingMs < HOUR_MS) return `${Math.max(1, Math.ceil(remainingMs / 60_000))}m`;
if (remainingMs < DAY_MS) return `${Math.ceil(remainingMs / HOUR_MS)}h`;
return `${Math.ceil(remainingMs / DAY_MS)}d`;
}
/**
* Human wake time for menus and toasts: "tomorrow 9:00", "Mon 9:00",
* "17:30" (today).
*/
export function snoozeWakeDescription(snoozedUntil: string, now: Date): string {
const wake = parseTimestampDate(snoozedUntil);
if (wake === null) return "";
const time = wake.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
const startOfToday = new Date(now);
startOfToday.setHours(0, 0, 0, 0);
const dayDelta = Math.floor((wake.getTime() - startOfToday.getTime()) / DAY_MS);
if (dayDelta === 0) return time;
if (dayDelta === 1) return `tomorrow ${time}`;
const weekday = wake.toLocaleDateString(undefined, { weekday: "short" });
if (dayDelta < 7) return `${weekday} ${time}`;
const date = wake.toLocaleDateString(undefined, { month: "short", day: "numeric" });
return `${date}, ${time}`;
}
+35 -105
View File
@@ -145,15 +145,7 @@ import {
DialogTitle,
} from "./ui/dialog";
import { Input } from "./ui/input";
import {
Menu,
MenuGroup,
MenuPopup,
MenuRadioGroup,
MenuRadioItem,
MenuSeparator,
MenuTrigger,
} from "./ui/menu";
import { Menu, MenuGroup, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "./ui/menu";
import {
NumberField,
NumberFieldDecrement,
@@ -185,8 +177,6 @@ import {
isContextMenuPointerDown,
isTrailingDoubleClick,
resolveProjectStatusIndicator,
resolveSidebarNewThreadSeedContext,
resolveSidebarNewThreadEnvMode,
resolveThreadRowClassName,
resolveThreadStatusPill,
orderItemsByPreferredIds,
@@ -201,7 +191,7 @@ import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { useIsMobile } from "~/hooks/useMediaQuery";
import { CommandDialogTrigger } from "./ui/command";
import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings";
import { primaryServerKeybindingsAtom, primaryServerSettingsAtom } from "../state/server";
import { primaryServerKeybindingsAtom } from "../state/server";
import {
derivePhysicalProjectKey,
deriveProjectGroupingOverrideKey,
@@ -1111,7 +1101,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
(settings) => settings.confirmThreadArchive,
);
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
const primaryServerSettings = useAtomValue(primaryServerSettingsAtom);
const deleteProject = useAtomCommand(projectEnvironment.delete, {
reportFailure: false,
});
@@ -1883,61 +1872,14 @@ 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,
// The default env mode is a user preference stored on the primary
// environment's settings.json; remote environments never carry it.
defaultEnvMode: resolveSidebarNewThreadEnvMode({
defaultEnvMode: primaryServerSettings.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), {
...(seedContext.branch !== undefined ? { branch: seedContext.branch } : {}),
...(seedContext.worktreePath !== undefined
? { worktreePath: seedContext.worktreePath }
: {}),
envMode: seedContext.envMode,
...(seedContext.startFromOrigin !== undefined
? { startFromOrigin: seedContext.startFromOrigin }
: {}),
}),
handleNewThread(scopeProjectRef(member.environmentId, member.id)),
);
if (result._tag === "Failure") {
const error = squashAtomCommandFailure(result);
@@ -1951,7 +1893,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
}
})();
},
[handleNewThread, isMobile, primaryServerSettings.defaultThreadEnvMode, router, setOpenMobile],
[handleNewThread, isMobile, setOpenMobile],
);
const handleCreateThreadClick = useCallback(
@@ -2172,6 +2114,9 @@ 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" },
@@ -2181,6 +2126,30 @@ 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;
@@ -2237,6 +2206,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
copyPathToClipboard,
copyThreadIdToClipboard,
deleteThread,
handleNewThread,
markThreadUnread,
memberProjectByScopedKey,
project.workspaceRoot,
@@ -2601,20 +2571,16 @@ 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(
@@ -2718,30 +2684,6 @@ 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>
);
@@ -2792,7 +2734,6 @@ interface SidebarProjectsContentProps {
handleDesktopUpdateButtonClick: () => void;
projectSortOrder: SidebarProjectSortOrder;
threadSortOrder: SidebarThreadSortOrder;
projectGroupingMode: SidebarProjectGroupingMode;
threadPreviewCount: SidebarThreadPreviewCount;
updateSettings: ReturnType<typeof useUpdateClientSettings>;
openAddProject: () => void;
@@ -2833,7 +2774,6 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
handleDesktopUpdateButtonClick,
projectSortOrder,
threadSortOrder,
projectGroupingMode,
threadPreviewCount,
updateSettings,
openAddProject,
@@ -2875,12 +2815,6 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
},
[updateSettings],
);
const handleProjectGroupingModeChange = useCallback(
(groupingMode: SidebarProjectGroupingMode) => {
updateSettings({ sidebarProjectGroupingMode: groupingMode });
},
[updateSettings],
);
const handleThreadPreviewCountChange = useCallback(
(count: SidebarThreadPreviewCount) => {
updateSettings({ sidebarThreadPreviewCount: count });
@@ -2944,11 +2878,9 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
<ProjectSortMenu
projectSortOrder={projectSortOrder}
threadSortOrder={threadSortOrder}
projectGroupingMode={projectGroupingMode}
threadPreviewCount={threadPreviewCount}
onProjectSortOrderChange={handleProjectSortOrderChange}
onThreadSortOrderChange={handleThreadSortOrderChange}
onProjectGroupingModeChange={handleProjectGroupingModeChange}
onThreadPreviewCountChange={handleThreadPreviewCountChange}
/>
<Tooltip>
@@ -3064,7 +2996,6 @@ 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();
@@ -3608,7 +3539,7 @@ export default function Sidebar() {
if (desktopUpdateButtonAction === "install") {
const confirmed = window.confirm(
getDesktopUpdateInstallConfirmationMessage(desktopUpdateState),
getDesktopUpdateInstallConfirmationMessage(desktopUpdateState, navigator.platform),
);
if (!confirmed) return;
void bridge
@@ -3674,7 +3605,6 @@ 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
@@ -10,23 +10,86 @@ 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('class="sticky top-0 z-10');
expect(markup).not.toContain("self-start");
expect(markup).toContain('data-changed-files-state="expanded"');
expect(markup).toContain('aria-expanded="true"');
expect(markup).toContain("whitespace-nowrap");
expect(markup).toContain("!size-[22px]");
expect(markup).toContain("size-3");
expect(markup).toContain('aria-label="Collapse all"');
expect(markup).toContain('aria-label="View diff"');
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("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", () => {
+139 -50
View File
@@ -19,95 +19,184 @@ 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 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"}
<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"
/>
)}
</span>
{hasNonZeroStat(summaryStat) && (
<DiffStatLabel
additions={summaryStat.additions}
className="text-xs leading-4"
deletions={summaryStat.deletions}
layout="inline"
/>
)}
</p>
<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>
<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="icon-xs"
size="xs"
variant="outline"
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"
aria-label="Open diff"
onClick={() => onOpenTurnDiff(turnId, files[0]?.path)}
/>
}
>
<FileDiffIcon className="size-3" />
<span className="hidden sm:inline">Open diff</span>
</TooltipTrigger>
<TooltipPopup side="top">View diff</TooltipPopup>
<TooltipPopup side="top">Open the full diff</TooltipPopup>
</Tooltip>
</div>
</div>
<ChangedFilesTree
key={`changed-files-tree:${turnId}`}
turnId={turnId}
files={files}
allDirectoriesExpanded={allDirectoriesExpanded}
resolvedTheme={resolvedTheme}
onOpenTurnDiff={onOpenTurnDiff}
/>
{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}
</div>
);
});
+70 -15
View File
@@ -18,14 +18,12 @@ import {
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
} from "@t3tools/contracts";
import {
connectionStatusText,
type EnvironmentConnectionPresentation,
} from "@t3tools/client-runtime/connection";
import 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,
@@ -34,6 +32,7 @@ import {
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import {
clampCollapsedComposerCursor,
type ComposerTrigger,
@@ -93,6 +92,64 @@ 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";
@@ -903,6 +960,7 @@ 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;
@@ -2337,6 +2395,7 @@ 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",
@@ -2344,7 +2403,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
)}
>
{composerMenuOpen && !isComposerApprovalState && (
<div className="absolute inset-x-0 bottom-full z-20 mb-2">
<ComposerCommandMenuLayer anchor={composerMenuAnchor}>
<ComposerCommandMenu
items={composerMenuItems}
resolvedTheme={resolvedTheme}
@@ -2359,7 +2418,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
onHighlightedItemChange={onComposerMenuItemHighlighted}
onSelect={onSelectComposerItem}
/>
</div>
</ComposerCommandMenuLayer>
)}
{!isComposerCollapsedMobile &&
@@ -2515,15 +2574,11 @@ 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"
: 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"
: 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}
/>
@@ -139,10 +139,7 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
);
}}
>
<div
ref={listRef}
className="relative w-full overflow-hidden rounded-[20px] border border-border/80 bg-popover/96 shadow-lg/8 backdrop-blur-xs"
>
<div ref={listRef} className="dropdown-glass relative w-full overflow-hidden rounded-[20px]">
{props.items.length > 0 ? (
<CommandList className="max-h-72">
{groups.map((group, groupIndex) => (
@@ -31,6 +31,8 @@ export const DiffStatLabel = memo(function DiffStatLabel(props: {
<>
{showParentheses && <span className="text-muted-foreground/70">(</span>}
<span
role="group"
aria-label={`${additions} additions, ${deletions} deletions`}
className={cn(
layout === "inline"
? "inline-flex items-center gap-1 tabular-nums align-middle"
@@ -38,8 +40,12 @@ export const DiffStatLabel = memo(function DiffStatLabel(props: {
className,
)}
>
<span className="font-mono text-success">+{formatCompactDiffCount(additions)}</span>
<span className="font-mono text-destructive">-{formatCompactDiffCount(deletions)}</span>
<span aria-hidden="true" className="font-mono text-success">
+{formatCompactDiffCount(additions)}
</span>
<span aria-hidden="true" className="font-mono text-destructive">
-{formatCompactDiffCount(deletions)}
</span>
</span>
{showParentheses && <span className="text-muted-foreground/70">)</span>}
</>
@@ -5,8 +5,15 @@ import { useCallback, useMemo } from "react";
import { openCommandPalette } from "~/commandPaletteBus";
import { useNewThreadHandler } from "~/hooks/useHandleNewThread";
import { useClientSettings } from "~/hooks/useSettings";
import { selectProjectGroupingSettings } from "~/logicalProject";
import {
buildSidebarProjectPickerEntries,
buildSidebarProjectSnapshots,
} from "~/sidebarProjectGrouping";
import { useProjects, useThreadShells } from "~/state/entities";
import { sortScopedProjectsForSidebar } from "../Sidebar.logic";
import { useEnvironments, usePrimaryEnvironmentId } from "~/state/environments";
import { sortLogicalProjectsForSidebar } from "../Sidebar.logic";
import {
Menu,
MenuItem,
@@ -28,29 +35,66 @@ export function DraftHeroHeadline({
}: DraftHeroHeadlineProps) {
const projects = useProjects();
const threads = useThreadShells();
const { environments } = useEnvironments();
const primaryEnvironmentId = usePrimaryEnvironmentId();
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
const projectSortOrder = useClientSettings((settings) => settings.sidebarProjectSortOrder);
const handleNewThread = useNewThreadHandler();
const openAddProject = useCallback(() => openCommandPalette({ open: "add-project" }), []);
const orderedProjects = useMemo(
() => sortScopedProjectsForSidebar(projects, threads, "updated_at"),
[projects, threads],
);
const projectByKey = useMemo(
const environmentLabelById = useMemo(
() =>
new Map(
orderedProjects.map(
(project) =>
[
scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
project,
] as const,
),
environments.map((environment) => [environment.environmentId, environment.label] as const),
),
[orderedProjects],
[environments],
);
const activeProjectKey = activeProjectRef === null ? "" : scopedProjectKey(activeProjectRef);
const projectGroups = useMemo(
() =>
sortLogicalProjectsForSidebar(
buildSidebarProjectSnapshots({
projects,
settings: projectGroupingSettings,
primaryEnvironmentId,
resolveEnvironmentLabel: (environmentId) =>
environmentLabelById.get(environmentId) ?? null,
}),
threads,
projectSortOrder,
),
[
environmentLabelById,
primaryEnvironmentId,
projectGroupingSettings,
projectSortOrder,
projects,
threads,
],
);
const projectPickerEntries = useMemo(
() =>
buildSidebarProjectPickerEntries({
groups: projectGroups,
preferredProjectRef: activeProjectRef,
}),
[activeProjectRef, projectGroups],
);
const projectEntryByKey = useMemo(
() => new Map(projectPickerEntries.map((entry) => [entry.group.projectKey, entry] as const)),
[projectPickerEntries],
);
const activeProjectGroup =
activeProjectRef === null
? null
: (projectGroups.find((group) =>
group.memberProjectRefs.some(
(projectRef) => scopedProjectKey(projectRef) === scopedProjectKey(activeProjectRef),
),
) ?? null);
const activeProjectKey = activeProjectGroup?.projectKey ?? "";
const activeProjectDisplayName = activeProjectGroup?.displayName ?? activeProjectTitle;
const hasResolvedProject = activeProjectTitle !== null;
const canChooseProject = orderedProjects.length > 0;
const canChooseProject = projectPickerEntries.length > 0;
const shouldShowProjectMenu = canChooseProject;
const projectSelector = shouldShowProjectMenu ? (
@@ -59,26 +103,26 @@ export function DraftHeroHeadline({
aria-label={hasResolvedProject ? "Change project" : "Choose a project"}
className="pointer-events-auto inline cursor-pointer border-current border-b border-dotted text-foreground underline-offset-8 transition-opacity hover:opacity-75 focus-visible:rounded-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
>
{activeProjectTitle ?? "Choose a project"}
{activeProjectDisplayName ?? "Choose a project"}
</MenuTrigger>
<MenuPopup align="center" className="max-h-80 w-64 overflow-y-auto">
<MenuRadioGroup
value={activeProjectKey}
onValueChange={(value) => {
const project = projectByKey.get(value as string);
if (!project || value === activeProjectKey) {
const entry = projectEntryByKey.get(value as string);
if (!entry || value === activeProjectKey) {
return;
}
const project = entry.targetProject;
void handleNewThread(scopeProjectRef(project.environmentId, project.id), {
replace: true,
});
}}
>
{orderedProjects.map((project) => {
const key = scopedProjectKey(scopeProjectRef(project.environmentId, project.id));
{projectPickerEntries.map(({ group }) => {
return (
<MenuRadioItem key={key} value={key} closeOnClick>
<span className="min-w-0 truncate">{project.title}</span>
<MenuRadioItem key={group.projectKey} value={group.projectKey} closeOnClick>
<span className="min-w-0 truncate">{group.displayName}</span>
</MenuRadioItem>
);
})}
@@ -245,6 +245,12 @@ describe("MessagesTimeline", () => {
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
latestTurn={{
turnId,
state: "completed",
startedAt: MESSAGE_CREATED_AT,
completedAt: MESSAGE_CREATED_AT,
}}
timelineEntries={[
{
id: "entry-assistant-with-files",
@@ -280,13 +286,13 @@ describe("MessagesTimeline", () => {
/>,
);
expect(markup).toContain('class="sticky top-2 z-10');
expect(markup).toContain("sticky top-2 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"');
expect(markup).toContain('aria-label="View diff"');
expect(markup).toContain('aria-label="Collapse all folders"');
expect(markup).toContain('aria-label="Open diff"');
expect(markup).toContain("1 changed file");
});
@@ -32,7 +32,6 @@ import {
workLogEntryIsToolLike,
} from "../../session-logic";
import { type TurnDiffSummary } from "../../types";
import { summarizeTurnDiffStats } from "../../lib/turnDiffTree";
import {
getRenderablePatch,
resolveDiffThemeName,
@@ -44,11 +43,8 @@ import {
CheckIcon,
ChevronDownIcon,
ChevronRightIcon,
ChevronsDownUpIcon,
ChevronsUpDownIcon,
CircleAlertIcon,
EyeIcon,
FileDiffIcon,
GlobeIcon,
HammerIcon,
MessageCircleIcon,
@@ -65,8 +61,8 @@ import {
import { Button } from "../ui/button";
import { buildExpandedImagePreview, ExpandedImagePreview } from "./ExpandedImagePreview";
import { ProposedPlanCard } from "./ProposedPlanCard";
import { ChangedFilesTree } from "./ChangedFilesTree";
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
import { ChangedFilesCard } from "./ChangedFilesTree";
import { shouldAutoExpandChangedFiles } from "./changedFilesPresentation";
import { MessageCopyButton } from "./MessageCopyButton";
import {
computeStableMessagesTimelineRows,
@@ -145,6 +141,7 @@ interface TimelineRowActivityState {
isWorking: boolean;
isRevertingCheckpoint: boolean;
activeTurnInProgress: boolean;
latestTurnId: TurnId | null;
}
const TimelineRowCtx = createContext<TimelineRowSharedState>(null!);
@@ -454,8 +451,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({
isWorking,
isRevertingCheckpoint,
activeTurnInProgress,
latestTurnId: latestTurn?.turnId ?? null,
}),
[activeTurnInProgress, isRevertingCheckpoint, isWorking],
[activeTurnInProgress, isRevertingCheckpoint, isWorking, latestTurn?.turnId],
);
// Stable renderItem — no closure deps. Row components read shared state
@@ -1278,83 +1276,32 @@ function AssistantChangedFilesSectionInner({
resolvedTheme: "light" | "dark";
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
}) {
const allDirectoriesExpanded = useUiStateStore(
(store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.turnId] ?? true,
const activity = use(TimelineRowActivityCtx);
const isLatestTurn = activity.latestTurnId === turnSummary.turnId;
const persistedExpanded = useUiStateStore(
(store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.turnId],
);
const setExpanded = useUiStateStore((store) => store.setThreadChangedFilesExpanded);
const summaryStat = summarizeTurnDiffStats(checkpointFiles);
const [autoExpanded] = useState(() =>
shouldAutoExpandChangedFiles(checkpointFiles, isLatestTurn),
);
const [allDirectoriesExpanded, setAllDirectoriesExpanded] = useState(autoExpanded);
const expanded = persistedExpanded ?? (isLatestTurn && autoExpanded);
return (
<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-2 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>
{checkpointFiles.length} changed file{checkpointFiles.length === 1 ? "" : "s"}
</span>
{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">
<Tooltip>
<TooltipTrigger
render={
<Button
type="button"
size="icon-xs"
variant="outline"
className="!size-[22px]"
aria-label={allDirectoriesExpanded ? "Collapse all" : "Expand all"}
data-scroll-anchor-ignore
onClick={() =>
setExpanded(routeThreadKey, turnSummary.turnId, !allDirectoriesExpanded)
}
/>
}
>
{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(turnSummary.turnId, checkpointFiles[0]?.path)}
/>
}
>
<FileDiffIcon className="size-3" />
</TooltipTrigger>
<TooltipPopup side="top">View diff</TooltipPopup>
</Tooltip>
</div>
</div>
<ChangedFilesTree
key={`changed-files-tree:${turnSummary.turnId}`}
turnId={turnSummary.turnId}
files={checkpointFiles}
allDirectoriesExpanded={allDirectoriesExpanded}
resolvedTheme={resolvedTheme}
onOpenTurnDiff={onOpenTurnDiff}
/>
</div>
<ChangedFilesCard
turnId={turnSummary.turnId}
files={checkpointFiles}
expanded={expanded}
showCompactPreview={isLatestTurn}
allDirectoriesExpanded={allDirectoriesExpanded}
resolvedTheme={resolvedTheme}
onExpandedChange={(nextExpanded) =>
setExpanded(routeThreadKey, turnSummary.turnId, nextExpanded)
}
onToggleAllDirectories={() => setAllDirectoriesExpanded((current) => !current)}
onOpenTurnDiff={onOpenTurnDiff}
/>
);
}
@@ -0,0 +1,69 @@
import { describe, expect, it } from "vite-plus/test";
import {
changedFileName,
selectChangedFilePreview,
shouldAutoExpandChangedFiles,
summarizeChangedFileScopes,
} from "./changedFilesPresentation";
describe("changed-files presentation", () => {
it("auto-expands only small, low-churn latest changes", () => {
const smallFiles = [
{ path: "src/a.ts", kind: "modified", additions: 80, deletions: 20 },
{ path: "src/b.ts", kind: "modified", additions: 60, deletions: 20 },
];
expect(shouldAutoExpandChangedFiles(smallFiles, true)).toBe(true);
expect(shouldAutoExpandChangedFiles(smallFiles, false)).toBe(false);
expect(
shouldAutoExpandChangedFiles(
[{ path: "src/a.ts", kind: "modified", additions: 201, deletions: 0 }],
true,
),
).toBe(false);
expect(
shouldAutoExpandChangedFiles(
Array.from({ length: 6 }, (_, index) => ({
path: `src/${index}.ts`,
kind: "modified",
additions: 1,
deletions: 0,
})),
true,
),
).toBe(false);
});
it("summarizes the most prominent top-level scopes", () => {
const files = [
{ path: "apps/web/src/App.tsx", kind: "modified", additions: 1, deletions: 0 },
{ path: "README.md", kind: "modified", additions: 1, deletions: 0 },
{ path: "apps/server/src/index.ts", kind: "modified", additions: 1, deletions: 0 },
{ path: "packages/shared/src/git.ts", kind: "modified", additions: 1, deletions: 0 },
{ path: "apps\\mobile\\App.tsx", kind: "modified", additions: 1, deletions: 0 },
];
expect(summarizeChangedFileScopes(files)).toEqual([
{ label: "apps", fileCount: 3 },
{ label: "root", fileCount: 1 },
{ label: "packages", fileCount: 1 },
]);
});
it("previews files across different scopes before filling from one scope", () => {
const files = [
{ path: "apps/web/src/App.tsx", kind: "modified", additions: 1, deletions: 0 },
{ path: "apps/web/src/App.test.tsx", kind: "modified", additions: 1, deletions: 0 },
{ path: "packages/shared/src/git.ts", kind: "modified", additions: 1, deletions: 0 },
{ path: "README.md", kind: "modified", additions: 1, deletions: 0 },
];
expect(selectChangedFilePreview(files).map((file) => file.path)).toEqual([
"apps/web/src/App.tsx",
"packages/shared/src/git.ts",
"README.md",
]);
expect(changedFileName("apps\\web\\src\\App.tsx")).toBe("App.tsx");
});
});
@@ -0,0 +1,102 @@
import { type TurnDiffFileChange } from "../../types";
import { summarizeTurnDiffStats } from "../../lib/turnDiffTree";
export const CHANGED_FILES_AUTO_EXPAND_FILE_LIMIT = 5;
export const CHANGED_FILES_AUTO_EXPAND_LINE_LIMIT = 200;
export const CHANGED_FILES_PREVIEW_FILE_LIMIT = 3;
export const CHANGED_FILES_PREVIEW_SCOPE_LIMIT = 4;
export interface ChangedFilesScopeSummary {
readonly label: string;
readonly fileCount: number;
}
function pathSegments(pathValue: string): string[] {
return pathValue
.replaceAll("\\", "/")
.split("/")
.filter((segment) => segment.length > 0);
}
export function changedFileName(pathValue: string): string {
return pathSegments(pathValue).at(-1) ?? pathValue;
}
function changedFileScope(pathValue: string): string {
const segments = pathSegments(pathValue);
return segments.length > 1 ? (segments[0] ?? "root") : "root";
}
export function shouldAutoExpandChangedFiles(
files: ReadonlyArray<TurnDiffFileChange>,
isLatestTurn: boolean,
): boolean {
if (!isLatestTurn || files.length > CHANGED_FILES_AUTO_EXPAND_FILE_LIMIT) {
return false;
}
const stat = summarizeTurnDiffStats(files);
return stat.additions + stat.deletions <= CHANGED_FILES_AUTO_EXPAND_LINE_LIMIT;
}
export function summarizeChangedFileScopes(
files: ReadonlyArray<TurnDiffFileChange>,
limit = CHANGED_FILES_PREVIEW_SCOPE_LIMIT,
): ChangedFilesScopeSummary[] {
const scopes = new Map<string, { fileCount: number; firstIndex: number }>();
files.forEach((file, index) => {
const label = changedFileScope(file.path);
const current = scopes.get(label);
scopes.set(label, {
fileCount: (current?.fileCount ?? 0) + 1,
firstIndex: current?.firstIndex ?? index,
});
});
return Array.from(scopes, ([label, scope]) => ({
label,
fileCount: scope.fileCount,
firstIndex: scope.firstIndex,
}))
.toSorted(
(left, right) =>
right.fileCount - left.fileCount ||
left.firstIndex - right.firstIndex ||
left.label.localeCompare(right.label),
)
.slice(0, limit)
.map(({ label, fileCount }) => ({ label, fileCount }));
}
export function selectChangedFilePreview(
files: ReadonlyArray<TurnDiffFileChange>,
limit = CHANGED_FILES_PREVIEW_FILE_LIMIT,
): TurnDiffFileChange[] {
const selected: TurnDiffFileChange[] = [];
const selectedPaths = new Set<string>();
const selectedScopes = new Set<string>();
for (const file of files) {
const scope = changedFileScope(file.path);
if (selectedScopes.has(scope)) {
continue;
}
selected.push(file);
selectedPaths.add(file.path);
selectedScopes.add(scope);
if (selected.length === limit) {
return selected;
}
}
for (const file of files) {
if (selectedPaths.has(file.path)) {
continue;
}
selected.push(file);
if (selected.length === limit) {
break;
}
}
return selected;
}
@@ -55,10 +55,10 @@ function ConfiguredT3ConnectSidebarSignIn() {
<SidebarMenuItem>
<SidebarMenuButton
size="sm"
className="gap-2 px-2 py-2 text-xs text-muted-foreground hover:bg-accent hover:text-foreground"
className="h-8 items-center gap-2 rounded-md px-2 py-1.5 text-sm font-medium text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground"
onClick={openAuthPrompt}
>
<LogInIcon className="size-4" />
<LogInIcon className="size-4 shrink-0" />
<span>Sign in to T3 Connect</span>
</SidebarMenuButton>
</SidebarMenuItem>
@@ -7,7 +7,7 @@ function connection(
phase: EnvironmentConnectionPresentation["phase"],
error: string | null = null,
): EnvironmentConnectionPresentation {
return { phase, error, traceId: null };
return { phase, error, reason: null, traceId: null, retryAt: null };
}
describe("saved cloud environment connection presentation", () => {
@@ -225,6 +225,32 @@ describe("desktop update UI helpers", () => {
}),
).toContain("Install update and restart T3 Code?");
});
it("warns Windows users that a silent installation can take several minutes", () => {
const message = getDesktopUpdateInstallConfirmationMessage(
{
availableVersion: "1.1.0",
downloadedVersion: "1.1.0",
},
"Win32",
);
expect(message).toContain("may remain closed for several minutes");
expect(message).toContain("no installer window may appear");
expect(message).toContain("will reopen automatically");
});
it("keeps the additional silent installation warning Windows-specific", () => {
const message = getDesktopUpdateInstallConfirmationMessage(
{
availableVersion: "1.1.0",
downloadedVersion: "1.1.0",
},
"MacIntel",
);
expect(message).not.toContain("may remain closed for several minutes");
});
});
describe("canCheckForUpdate", () => {
@@ -1,4 +1,5 @@
import type { DesktopUpdateActionResult, DesktopUpdateState } from "@t3tools/contracts";
import { isWindowsPlatform } from "../lib/utils";
export type DesktopUpdateButtonAction = "download" | "install" | "none";
@@ -78,9 +79,13 @@ export function getDesktopUpdateButtonTooltip(state: DesktopUpdateState): string
export function getDesktopUpdateInstallConfirmationMessage(
state: Pick<DesktopUpdateState, "availableVersion" | "downloadedVersion">,
platform = "",
): string {
const version = state.downloadedVersion ?? state.availableVersion;
return `Install update${version ? ` ${version}` : ""} and restart T3 Code?\n\nAny running tasks will be interrupted. Make sure you're ready before continuing.`;
const windowsInstallWarning = isWindowsPlatform(platform)
? "\n\nOn Windows, T3 Code may remain closed for several minutes while the update installs, and no installer window may appear. T3 Code will reopen automatically when installation finishes."
: "";
return `Install update${version ? ` ${version}` : ""} and restart T3 Code?\n\nAny running tasks will be interrupted. Make sure you're ready before continuing.${windowsInstallWarning}`;
}
export function getDesktopUpdateActionError(result: DesktopUpdateActionResult): string | null {
@@ -10,6 +10,8 @@ import {
type PreviewAutomationOpenInput,
type PreviewAutomationResizeInput,
type PreviewAutomationResizeResult,
type PreviewAutomationSetColorSchemeInput,
type PreviewAutomationSetColorSchemeResult,
type PreviewAutomationHost as PreviewAutomationHostState,
type PreviewAutomationRequest,
type PreviewAutomationStatus,
@@ -451,6 +453,15 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
viewport,
} satisfies PreviewAutomationResizeResult;
}
case "setColorScheme": {
const ready = await requireReadyTab();
const input = request.input as PreviewAutomationSetColorSchemeInput;
await ready.bridge.setColorScheme(ready.tabId, input.colorScheme);
return {
tabId: ready.tabId,
colorScheme: input.colorScheme,
} satisfies PreviewAutomationSetColorSchemeResult;
}
case "snapshot": {
const ready = await requireReadyTab();
return await ready.bridge.automation.snapshot(ready.tabId);
@@ -1,13 +1,34 @@
"use client";
import type { DesktopPreviewColorScheme } from "@t3tools/contracts";
import { Minus, MoreVertical, Plus as PlusIcon, RotateCcw } from "lucide-react";
import { Button } from "~/components/ui/button";
import { Menu, MenuItem, MenuPopup, MenuSeparator, MenuTrigger } from "~/components/ui/menu";
import {
Menu,
MenuItem,
MenuPopup,
MenuRadioGroup,
MenuRadioItem,
MenuSeparator,
MenuSub,
MenuSubPopup,
MenuSubTrigger,
MenuTrigger,
} from "~/components/ui/menu";
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
import { previewBridge } from "./previewBridge";
const COLOR_SCHEME_OPTIONS: ReadonlyArray<{
value: DesktopPreviewColorScheme;
label: string;
}> = [
{ value: "system", label: "System" },
{ value: "light", label: "Light" },
{ value: "dark", label: "Dark" },
];
interface Props {
/** Active preview tab id. Tab-targeting actions are disabled without it. */
tabId: string | null;
@@ -19,6 +40,8 @@ interface Props {
hasWebContents: boolean;
/** Current zoom factor as a number (1.0 = 100%). */
zoomFactor: number;
/** Emulated `prefers-color-scheme` for the guest page. */
colorScheme: DesktopPreviewColorScheme;
/** Fixed viewport modes expose the device toolbar and resize rails. */
deviceToolbarVisible: boolean;
/** Switches between fill-panel mode and a fixed responsive viewport. */
@@ -34,6 +57,7 @@ export function PreviewMoreMenu({
tabId,
hasWebContents,
zoomFactor,
colorScheme,
deviceToolbarVisible,
onToggleDeviceToolbar,
}: Props) {
@@ -72,6 +96,26 @@ export function PreviewMoreMenu({
<MenuItem onClick={onToggleDeviceToolbar} disabled={tabDisabled}>
{deviceToolbarVisible ? "Hide device toolbar" : "Show device toolbar"}
</MenuItem>
<MenuSub>
<MenuSubTrigger disabled={tabDisabled}>Appearance</MenuSubTrigger>
<MenuSubPopup className="min-w-32">
<MenuRadioGroup
value={colorScheme}
onValueChange={(value) => {
if (!tabId) return;
void bridge
.setColorScheme(tabId, value as DesktopPreviewColorScheme)
.catch(() => undefined);
}}
>
{COLOR_SCHEME_OPTIONS.map((option) => (
<MenuRadioItem key={option.value} value={option.value}>
{option.label}
</MenuRadioItem>
))}
</MenuRadioGroup>
</MenuSubPopup>
</MenuSub>
<MenuSeparator />
{/*
Zoom row: label + inline control cluster. `closeOnClick=false`
@@ -40,6 +40,7 @@ vi.mock("~/previewStateStore", () => ({
canGoForward: false,
loading: false,
zoomFactor: 1,
colorScheme: "system",
controller: "none",
},
},
@@ -610,6 +610,7 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
tabId={tabId}
hasWebContents={desktopOverlay !== null}
zoomFactor={desktopOverlay?.zoomFactor ?? 1}
colorScheme={desktopOverlay?.colorScheme ?? "system"}
deviceToolbarVisible={viewport._tag !== "fill"}
onToggleDeviceToolbar={handleToggleDeviceToolbar}
/>
@@ -77,6 +77,7 @@ function projectDesktopState(state: DesktopPreviewTabState): DesktopPreviewOverl
canGoForward: state.canGoForward,
loading: state.navStatus.kind === "Loading",
zoomFactor: state.zoomFactor,
colorScheme: state.colorScheme,
controller: state.controller,
};
}
@@ -1,6 +1,7 @@
"use client";
import { Radio as RadioPrimitive } from "@base-ui/react/radio";
import { CheckIcon } from "lucide-react";
import { useMemo, useState } from "react";
import {
ProviderInstanceId,
@@ -223,7 +224,7 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogPopup className="max-w-xl overflow-hidden">
<div className="flex min-h-0 flex-col overflow-hidden">
<DialogHeader className="border-b border-border/70">
<DialogHeader>
<DialogTitle>Add provider instance</DialogTitle>
<DialogDescription>
Configure an additional provider instance — for example, a second Codex install
@@ -239,41 +240,37 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
<div
data-slot="dialog-panel"
className="space-y-4 border-b border-border/70 bg-foreground/[0.025] px-6 py-5"
className="space-y-4 bg-zinc-25/80 px-6 py-5 ring-1 ring-black/5 dark:bg-white/2 dark:ring-white/5"
>
<AnimatedHeight>
<div className={cn("grid gap-2", wizardStep !== 0 && "hidden")}>
<span
id="add-instance-driver-label"
className="text-xs font-medium text-foreground"
>
<div id="add-instance-driver-label" className="text-sm font-medium text-foreground">
Driver
</span>
</div>
<RadioGroup
value={driver}
onValueChange={(value) => setDriver(ProviderDriverKind.make(value))}
aria-labelledby="add-instance-driver-label"
className="grid grid-cols-2 gap-2.5"
className="grid grid-cols-1 gap-2 sm:grid-cols-2"
>
{DRIVER_OPTIONS.map((option) => {
const IconComponent = option.icon;
const isSelected = option.value === driver;
return (
<RadioPrimitive.Root
key={option.value}
value={option.value}
className={cn(
"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"
: "border-border bg-background hover:border-foreground/20 hover:bg-muted/50",
)}
className="relative flex cursor-pointer items-center gap-3 rounded-lg bg-card px-3 py-3 text-left text-muted-foreground outline-none ring-1 ring-black/5 hover:bg-zinc-50 focus-visible:ring-2 focus-visible:ring-ring data-checked:bg-primary/8 data-checked:text-foreground data-checked:ring-2 data-checked:ring-primary data-checked:hover:bg-primary/8 dark:bg-white/3 dark:ring-white/5 dark:hover:bg-white/5 dark:data-checked:bg-primary/15 dark:data-checked:ring-primary dark:data-checked:hover:bg-primary/15"
>
<IconComponent className="size-5 shrink-0" aria-hidden />
<IconComponent className="size-4 shrink-0" aria-hidden />
<span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
{option.label}
</span>
<RadioPrimitive.Indicator
className="grid size-5 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground"
aria-hidden
>
<CheckIcon className="size-3.5 shrink-0" />
</RadioPrimitive.Indicator>
{option.badgeLabel ? (
<Badge variant="warning" size="sm">
{option.badgeLabel}
@@ -290,11 +287,11 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
value={option.value}
disabled
className={cn(
"relative flex cursor-not-allowed items-center gap-3 rounded-lg border border-border bg-background px-3 py-3 text-left opacity-55 outline-none",
"relative flex cursor-not-allowed items-center gap-3 rounded-lg bg-card/60 px-3 py-3 text-left opacity-55 outline-none ring-1 ring-black/5 dark:bg-white/2 dark:ring-white/5",
)}
>
<IconComponent
className="size-5 shrink-0 text-muted-foreground"
className="size-4 shrink-0 text-muted-foreground"
aria-hidden
/>
<span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
@@ -409,7 +406,7 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
</AnimatedHeight>
</div>
<DialogFooter className="border-t bg-transparent">
<DialogFooter variant="bare">
<Button
variant="outline"
size="sm"
@@ -9,6 +9,10 @@ interface StepButtonProps {
readonly onClick: () => void;
}
interface StepListItemProps {
readonly children: ReactElement<StepButtonProps>;
}
function renderStepButtons(
currentStep: number,
instanceIdError: string | null,
@@ -21,9 +25,9 @@ function renderStepButtons(
onNavigation,
});
return Children.toArray(header.props.children).filter(
(child): child is ReactElement<StepButtonProps> => isValidElement(child),
);
return Children.toArray(header.props.children)
.filter((child): child is ReactElement<StepListItemProps> => isValidElement(child))
.map((item) => item.props.children);
}
describe("AddProviderInstanceWizardSteps", () => {
@@ -21,50 +21,53 @@ export function AddProviderInstanceWizardSteps({
onNavigation,
}: AddProviderInstanceWizardStepsProps) {
return (
<div className="grid grid-cols-3 gap-2">
<ol
className="grid grid-cols-3 gap-1 rounded-xl bg-zinc-25 p-1 ring-1 ring-black/5 dark:bg-white/4 dark:ring-white/5"
role="list"
>
{ADD_PROVIDER_WIZARD_STEPS.map((step, index) => (
<button
key={step}
type="button"
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 === currentStep
? "border-primary bg-primary/10 ring-1 ring-primary/25"
: index < currentStep
? "border-border bg-background"
: "border-border bg-muted/40",
)}
aria-current={index === currentStep ? "step" : undefined}
onClick={() =>
onNavigation(
resolveWizardNavigation(currentStep, index, ADD_PROVIDER_WIZARD_STEPS.length, {
instanceIdError,
}),
)
}
>
<span
<li key={step} className="min-w-0">
<button
type="button"
className={cn(
"row-span-2 mt-0.5 grid size-4 place-items-center rounded-full border",
index < currentStep
? "border-primary bg-primary text-primary-foreground"
: index === currentStep
? "border-primary bg-background"
: "border-muted-foreground/35 bg-background",
"flex w-full min-w-0 cursor-pointer items-center gap-2 rounded-lg px-2.5 py-2 text-left outline-none hover:bg-card focus-visible:ring-2 focus-visible:ring-ring max-sm:justify-center max-sm:px-2",
index === currentStep &&
"bg-card text-foreground shadow-xs ring-1 ring-black/5 hover:bg-card dark:shadow-none dark:ring-white/5",
)}
aria-hidden
aria-current={index === currentStep ? "step" : undefined}
aria-label={`${step}, step ${index + 1}${index < currentStep && summaries[index] ? `, ${summaries[index]}` : ""}`}
onClick={() =>
onNavigation(
resolveWizardNavigation(currentStep, index, ADD_PROVIDER_WIZARD_STEPS.length, {
instanceIdError,
}),
)
}
>
{index < currentStep ? <CheckIcon className="size-3" /> : null}
</span>
<span className="text-[10px] font-medium uppercase text-muted-foreground">
Step {index + 1}
</span>
<span className="truncate text-xs font-semibold text-foreground">
{step}
{index < currentStep && summaries[index] ? `: ${summaries[index]}` : ""}
</span>
</button>
<span
className={cn(
"grid size-5 shrink-0 place-items-center rounded-full text-sm font-medium ring-1",
index < currentStep
? "bg-primary text-primary-foreground ring-primary"
: index === currentStep
? "bg-primary/10 text-primary ring-primary/30"
: "bg-card text-muted-foreground ring-black/10 dark:bg-white/5 dark:ring-white/10",
)}
aria-hidden
>
{index < currentStep ? <CheckIcon className="size-4 shrink-0" /> : index + 1}
</span>
<span
className={cn(
"min-w-0 truncate text-sm font-medium max-sm:hidden",
index === currentStep ? "text-foreground" : "text-muted-foreground",
)}
>
{step}
</span>
</button>
</li>
))}
</div>
</ol>
);
}
@@ -130,6 +130,7 @@ import {
useEnvironments,
usePrimaryEnvironment,
} from "~/state/environments";
import { isServerRestarting, useServerRestartExpected } from "~/serverRestartStore";
import { useAtomCommand } from "../../state/use-atom-command";
import { ConnectionStatusDot } from "../ConnectionStatusDot";
import { ServerUpdateAction } from "../ServerUpdateAction";
@@ -1353,15 +1354,24 @@ function SavedBackendListRow({
const connectionState = environment.connection.phase;
const isConnected = connectionState === "connected";
const isConnecting = connectionState === "connecting" || connectionState === "reconnecting";
// An update started from this row restarts the server, so present that
// disconnect as the expected restart rather than as a connection failure —
// the same treatment the chat composer's skew banner gives it.
const isRestarting = isServerRestarting({
restartExpected: useServerRestartExpected(environmentId),
environmentUnavailable: !isConnected,
});
const stateDotClassName =
connectionState === "connected"
? "bg-success"
: connectionState === "connecting" || connectionState === "reconnecting"
: isRestarting || connectionState === "connecting" || connectionState === "reconnecting"
? "bg-warning"
: connectionState === "error"
? "bg-destructive"
: "bg-muted-foreground/40";
const statusTooltip = connectionStatusText(environment.connection);
const statusTooltip = isRestarting
? "Restarting to finish the server update..."
: connectionStatusText(environment.connection);
const errorTraceId = environment.connection.traceId;
const { copyToClipboard: copyTraceIdToClipboard } = useCopyToClipboard<{ traceId: string }>({
target: "trace ID",
@@ -1440,7 +1450,13 @@ function SavedBackendListRow({
/>
</div>
) : null}
{environment.connection.error ? (
{isRestarting ? (
<p className="flex min-w-0 items-center gap-2 text-muted-foreground text-xs">
<span className="truncate">
Restarting to finish the server update — reconnecting automatically.
</span>
</p>
) : environment.connection.error ? (
<p className="flex min-w-0 items-center gap-2 text-destructive text-xs">
<span className="truncate">{connectionStatusText(environment.connection)}</span>
{errorTraceId ? (
@@ -8,8 +8,25 @@ import { describe, expect, it } from "vite-plus/test";
import {
buildProviderInstanceUpdatePatch,
formatDiagnosticsDescription,
isProjectGroupingEnabled,
projectGroupingModeFromToggle,
} from "./SettingsPanels.logic";
describe("project grouping toggle", () => {
it("enables repository grouping and disables into separate projects", () => {
expect(isProjectGroupingEnabled("repository")).toBe(true);
expect(isProjectGroupingEnabled("repository_path")).toBe(true);
expect(isProjectGroupingEnabled("separate")).toBe(false);
expect(projectGroupingModeFromToggle(true)).toBe("repository");
expect(projectGroupingModeFromToggle(false)).toBe("separate");
});
it("restores repository path grouping when the toggle is cycled", () => {
expect(projectGroupingModeFromToggle(false, "repository_path")).toBe("separate");
expect(projectGroupingModeFromToggle(true, "repository_path")).toBe("repository_path");
});
});
describe("formatDiagnosticsDescription", () => {
it("collapses trace and metric URLs that share the same OTEL base path", () => {
expect(
@@ -3,10 +3,44 @@ import type {
ProviderInstanceConfig,
ProviderInstanceId,
ServerSettings,
SidebarProjectGroupingMode,
UnifiedSettings,
} from "@t3tools/contracts";
import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
export function isProjectGroupingEnabled(mode: SidebarProjectGroupingMode): boolean {
return mode !== "separate";
}
export function projectGroupingModeFromToggle(
enabled: boolean,
lastEnabledMode: SidebarProjectGroupingMode = "repository",
): SidebarProjectGroupingMode {
if (!enabled) return "separate";
return lastEnabledMode === "repository_path" ? "repository_path" : "repository";
}
const LAST_ENABLED_PROJECT_GROUPING_MODE_KEY = "t3code:last-enabled-project-grouping-mode";
export function readLastEnabledProjectGroupingMode(): SidebarProjectGroupingMode {
try {
return localStorage.getItem(LAST_ENABLED_PROJECT_GROUPING_MODE_KEY) === "repository_path"
? "repository_path"
: "repository";
} catch {
return "repository";
}
}
export function rememberEnabledProjectGroupingMode(mode: SidebarProjectGroupingMode): void {
if (mode === "separate") return;
try {
localStorage.setItem(LAST_ENABLED_PROJECT_GROUPING_MODE_KEY, mode);
} catch {
// Storage can be unavailable in restricted browser contexts.
}
}
function collapseOtelSignalsUrl(input: {
readonly tracesUrl: string;
readonly metricsUrl: string;
@@ -11,6 +11,7 @@ import {
type ProviderInstanceConfig,
type ProviderInstanceId,
type ScopedThreadRef,
type SidebarProjectGroupingMode,
} from "@t3tools/contracts";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
@@ -83,6 +84,10 @@ import { DRIVER_OPTIONS, getDriverOption } from "./providerDriverMeta";
import {
buildProviderInstanceUpdatePatch,
formatDiagnosticsDescription,
isProjectGroupingEnabled,
projectGroupingModeFromToggle,
readLastEnabledProjectGroupingMode,
rememberEnabledProjectGroupingMode,
} from "./SettingsPanels.logic";
import {
SettingResetButton,
@@ -233,6 +238,7 @@ function AboutVersionSection() {
const confirmed = window.confirm(
getDesktopUpdateInstallConfirmationMessage(
updateState ?? { availableVersion: null, downloadedVersion: null },
navigator.platform,
),
);
if (!confirmed) return;
@@ -401,6 +407,10 @@ export function useSettingsRestore(onRestored?: () => void) {
...(settings.sidebarThreadPreviewCount !== DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount
? ["Visible threads"]
: []),
...(settings.sidebarProjectGroupingMode !==
DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode
? ["Project Grouping"]
: []),
...(settings.wordWrap !== DEFAULT_UNIFIED_SETTINGS.wordWrap ? ["Word wrap"] : []),
...(settings.diffIgnoreWhitespace !== DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace
? ["Diff whitespace changes"]
@@ -450,6 +460,7 @@ export function useSettingsRestore(onRestored?: () => void) {
settings.automaticGitFetchInterval,
settings.enableAssistantStreaming,
settings.enableProviderUpdateChecks,
settings.sidebarProjectGroupingMode,
settings.sidebarThreadPreviewCount,
settings.timestampFormat,
settings.wordWrap,
@@ -474,6 +485,7 @@ export function useSettingsRestore(onRestored?: () => void) {
diffIgnoreWhitespace: DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace,
glassOpacity: DEFAULT_UNIFIED_SETTINGS.glassOpacity,
sidebarThreadPreviewCount: DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount,
sidebarProjectGroupingMode: DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode,
autoOpenPlanSidebar: DEFAULT_UNIFIED_SETTINGS.autoOpenPlanSidebar,
enableAssistantStreaming: DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming,
enableProviderUpdateChecks: DEFAULT_UNIFIED_SETTINGS.enableProviderUpdateChecks,
@@ -498,6 +510,9 @@ export function GeneralSettingsPanel() {
const { theme, setTheme } = useTheme();
const settings = usePrimarySettings();
const updateSettings = useUpdatePrimarySettings();
const lastEnabledProjectGroupingMode = useRef<SidebarProjectGroupingMode>(
readLastEnabledProjectGroupingMode(),
);
const observability = useAtomValue(primaryServerObservabilityAtom);
const serverProviders = useAtomValue(primaryServerProvidersAtom);
const glassOpacityRatio =
@@ -619,6 +634,42 @@ export function GeneralSettingsPanel() {
}
/>
<SettingsRow
title="Project Grouping"
description="Combine matching repositories across environments."
resetAction={
settings.sidebarProjectGroupingMode !==
DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode ? (
<SettingResetButton
label="project grouping"
onClick={() =>
updateSettings({
sidebarProjectGroupingMode: DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode,
})
}
/>
) : null
}
control={
<Switch
checked={isProjectGroupingEnabled(settings.sidebarProjectGroupingMode)}
onCheckedChange={(checked) => {
if (!checked && settings.sidebarProjectGroupingMode !== "separate") {
lastEnabledProjectGroupingMode.current = settings.sidebarProjectGroupingMode;
rememberEnabledProjectGroupingMode(settings.sidebarProjectGroupingMode);
}
updateSettings({
sidebarProjectGroupingMode: projectGroupingModeFromToggle(
checked,
lastEnabledProjectGroupingMode.current,
),
});
}}
aria-label="Project Grouping"
/>
}
/>
<SettingsRow
title="Time format"
description="System default follows your browser or OS clock preference."
@@ -110,7 +110,9 @@ export function SidebarUpdatePill() {
}
if (action === "install") {
const confirmed = window.confirm(getDesktopUpdateInstallConfirmationMessage(state));
const confirmed = window.confirm(
getDesktopUpdateInstallConfirmationMessage(state, navigator.platform),
);
if (!confirmed) return;
void bridge
.installUpdate()
Loaded 100 of 149 files, more files were not shown because too many files have changed in this diff. Show more