Compare commits

..
Author SHA1 Message Date
Julius Marminge 9a129b7b8a Add "Small Arrival" poem in new poem.md file
- Create `poem.md` with an original 11-line poem
- Introduce a reflective coding-themed piece titled "Small Arrival"
2026-02-13 15:18:24 -08:00
Julius Marminge 4fff00c8c3 run backend as node 2026-02-13 00:19:32 -08:00
Julius Marmingeandcodex 6b916d3a6f Handle branch recency lookup failures in branch listing
- move branch recency parsing into `readBranchRecency`
- fall back to an empty recency map if lookup fails
- add test to ensure branches still list when recency read times out

Co-authored-by: codex <[email protected]>
2026-02-12 23:29:44 -08:00
Julius Marmingeandcodex 21580dc1b0 Prioritize current and default branches in branch list ordering
- Keep the current branch first
- Place the default branch second
- Sort remaining branches by most recent commit and update tests for this behavior

Co-authored-by: codex <[email protected]>
2026-02-12 23:29:44 -08:00
Julius Marminge ba9585966c Sort git branches by latest commit timestamp
- Order `listGitBranches` by each branch's most recent commit date
- Keep current/default/name tiebreakers for stable ordering
- Add integration test coverage with dated commits to verify recency sort
2026-02-12 23:29:44 -08:00
Julius Marminge 293f7b1507 Guard orphaned worktree deletion behind project context
- Require both orphaned worktree path and thread project before prompting delete
- Prevents delete confirmation when project metadata is unavailable
2026-02-12 22:57:56 -08:00
Julius Marminge 4f5eb3be4d Show worktree name in thread delete confirmation
- Format orphaned worktree paths to display only the final segment
- Apply formatting in Sidebar delete prompt for cleaner UX
- Add tests for Unix, Windows, trailing slash, and fallback cases
2026-02-12 22:57:56 -08:00
Julius Marmingeandcodex b6523a15dc Use Yes/No labels for desktop worktree confirm
Co-authored-by: codex <[email protected]>
2026-02-12 22:57:56 -08:00
Julius Marmingeandcodex 8a4fed1bf2 Guard worktree cleanup on missing project
Co-authored-by: codex <[email protected]>
2026-02-12 22:57:56 -08:00
Julius Marminge 0068a93cfa Add desktop-backed confirm dialog API for worktree deletion
- add `dialogs.confirm` to native IPC/contracts and desktop preload/main bridge
- switch sidebar worktree deletion prompt from `window.confirm` to native API
- add `showDesktopConfirmDialog` helper with unit tests for dialog behavior
2026-02-12 22:57:56 -08:00
Julius Marminge dd912666f2 Delete orphaned worktree when deleting a thread
- Prompt to remove the worktree when a deleted thread is its only reference
- Best-effort cleanup via `api.git.removeWorktree` after thread deletion
- Add `getOrphanedWorktreePathForThread` helper with unit tests
2026-02-12 22:57:56 -08:00
Julius Marminge 521238cf8e Simplify terminal toggle to only update visibility state
- Remove terminal close/exit API calls from `toggleTerminalVisibility`
- Keep toggle behavior as a pure UI state change for active thread
2026-02-12 22:44:14 -08:00
13 changed files with 445 additions and 10 deletions

No files matched your search

+57
View File
@@ -0,0 +1,57 @@
import type { BrowserWindow } from "electron";
import { beforeEach, describe, expect, it, vi } from "vitest";
const { showMessageBoxMock } = vi.hoisted(() => ({
showMessageBoxMock: vi.fn(),
}));
vi.mock("electron", () => ({
dialog: {
showMessageBox: showMessageBoxMock,
},
}));
import { showDesktopConfirmDialog } from "./confirmDialog";
describe("showDesktopConfirmDialog", () => {
beforeEach(() => {
showMessageBoxMock.mockReset();
});
it("returns false and does not open a dialog for empty messages", async () => {
const result = await showDesktopConfirmDialog(" ", null);
expect(result).toBe(false);
expect(showMessageBoxMock).not.toHaveBeenCalled();
});
it("opens a dialog for the focused window and returns true on confirm", async () => {
const ownerWindow = { id: 1 } as BrowserWindow;
showMessageBoxMock.mockResolvedValue({ response: 1 });
const result = await showDesktopConfirmDialog("Delete worktree?", ownerWindow);
expect(result).toBe(true);
expect(showMessageBoxMock).toHaveBeenCalledWith(
ownerWindow,
expect.objectContaining({
buttons: ["No", "Yes"],
message: "Delete worktree?",
}),
);
});
it("opens an app-level dialog when there is no focused window", async () => {
showMessageBoxMock.mockResolvedValue({ response: 0 });
const result = await showDesktopConfirmDialog("Delete worktree?", null);
expect(result).toBe(false);
expect(showMessageBoxMock).toHaveBeenCalledWith(
expect.objectContaining({
buttons: ["No", "Yes"],
message: "Delete worktree?",
}),
);
});
});
+26
View File
@@ -0,0 +1,26 @@
import { type BrowserWindow, dialog } from "electron";
const CONFIRM_BUTTON_INDEX = 1;
export async function showDesktopConfirmDialog(
message: string,
ownerWindow: BrowserWindow | null,
): Promise<boolean> {
const normalizedMessage = message.trim();
if (normalizedMessage.length === 0) {
return false;
}
const options = {
type: "question" as const,
buttons: ["No", "Yes"],
defaultId: CONFIRM_BUTTON_INDEX,
cancelId: 0,
noLink: true,
message: normalizedMessage,
};
const result = ownerWindow
? await dialog.showMessageBox(ownerWindow, options)
: await dialog.showMessageBox(options);
return result.response === CONFIRM_BUTTON_INDEX;
}
+18 -1
View File
@@ -7,11 +7,13 @@ import path from "node:path";
import { app, BrowserWindow, dialog, ipcMain, Menu, shell } from "electron";
import { showDesktopConfirmDialog } from "./confirmDialog";
import { fixPath } from "./fixPath";
fixPath();
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const ROOT_DIR = path.resolve(__dirname, "../../..");
@@ -81,7 +83,12 @@ function startBackend(): void {
const child = spawn(process.execPath, [BACKEND_ENTRY], {
cwd: ROOT_DIR,
env: backendEnv(),
// In Electron main, process.execPath points to the Electron binary.
// Run the child in Node mode so this backend process does not become a GUI app instance.
env: {
...backendEnv(),
ELECTRON_RUN_AS_NODE: "1",
},
stdio: "inherit",
});
backendProcess = child;
@@ -142,6 +149,16 @@ function registerIpcHandlers(): void {
return result.filePaths[0] ?? null;
});
ipcMain.removeHandler(CONFIRM_CHANNEL);
ipcMain.handle(CONFIRM_CHANNEL, async (_event, message: unknown) => {
if (typeof message !== "string") {
return false;
}
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
return showDesktopConfirmDialog(message, owner);
});
ipcMain.removeHandler(CONTEXT_MENU_CHANNEL);
ipcMain.handle(CONTEXT_MENU_CHANNEL, async (_event, items: { id: string; label: string }[]) => {
const window = BrowserWindow.getFocusedWindow() ?? mainWindow;
+2
View File
@@ -1,6 +1,7 @@
import { contextBridge, ipcRenderer } from "electron";
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
@@ -8,6 +9,7 @@ const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
contextBridge.exposeInMainWorld("desktopBridge", {
getWsUrl: () => wsUrl,
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL) as Promise<string | null>,
confirm: (message: string) => ipcRenderer.invoke(CONFIRM_CHANNEL, message) as Promise<boolean>,
showContextMenu: (items: { id: string; label: string }[]) =>
ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items) as Promise<string | null>,
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url) as Promise<boolean>,
+108 -5
View File
@@ -2,7 +2,7 @@ import { existsSync } from "node:fs";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import {
GitCoreService,
@@ -51,6 +51,25 @@ async function initRepoWithCommit(cwd: string): Promise<void> {
await git(cwd, "commit -m 'initial commit'");
}
async function commitWithDate(
cwd: string,
fileName: string,
fileContents: string,
dateIsoString: string,
message: string,
): Promise<void> {
await writeFile(path.join(cwd, fileName), fileContents);
await git(cwd, `add ${fileName}`);
const commitResult = await runTerminalCommand({
command: `GIT_AUTHOR_DATE="${dateIsoString}" GIT_COMMITTER_DATE="${dateIsoString}" git commit -m "${message}"`,
cwd,
timeoutMs: 10_000,
});
if (commitResult.code !== 0) {
throw new Error(`git dated commit failed: ${commitResult.stderr}`);
}
}
// ── Tests ──
describe("git integration", () => {
@@ -106,14 +125,82 @@ describe("git integration", () => {
expect(current!.current).toBe(true);
});
it("sorts current branch first", async () => {
it("keeps current branch first and sorts the remaining branches by recency", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "aaa-first-alpha" });
await createGitBranch({ cwd: tmp.path, branch: "zzz-last" });
const initialBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(branch) => branch.current,
)!.name;
await createGitBranch({ cwd: tmp.path, branch: "older-branch" });
await checkoutGitBranch({ cwd: tmp.path, branch: "older-branch" });
await commitWithDate(
tmp.path,
"older.txt",
"older branch change\n",
"Thu, 1 Jan 2037 00:00:00 +0000",
"older branch change",
);
await checkoutGitBranch({ cwd: tmp.path, branch: initialBranch });
await createGitBranch({ cwd: tmp.path, branch: "newer-branch" });
await checkoutGitBranch({ cwd: tmp.path, branch: "newer-branch" });
await commitWithDate(
tmp.path,
"newer.txt",
"newer branch change\n",
"Fri, 1 Jan 2038 00:00:00 +0000",
"newer branch change",
);
// Switch away to show current branch is pinned, then remaining branches are recency-sorted.
await checkoutGitBranch({ cwd: tmp.path, branch: "older-branch" });
const result = await listGitBranches({ cwd: tmp.path });
expect(result.branches[0]!.current).toBe(true);
expect(result.branches[0]!.name).toBe("older-branch");
expect(result.branches[1]!.name).toBe("newer-branch");
});
it("keeps default branch right after current branch", async () => {
await using tmp = await makeTmpDir();
await using remote = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const defaultBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(branch) => branch.current,
)!.name;
await git(remote.path, "init --bare");
await git(tmp.path, `remote add origin ${JSON.stringify(remote.path)}`);
await git(tmp.path, `push -u origin ${defaultBranch}`);
await git(tmp.path, `remote set-head origin ${defaultBranch}`);
await createGitBranch({ cwd: tmp.path, branch: "current-branch" });
await checkoutGitBranch({ cwd: tmp.path, branch: "current-branch" });
await commitWithDate(
tmp.path,
"current.txt",
"current change\n",
"Thu, 1 Jan 2037 00:00:00 +0000",
"current change",
);
await checkoutGitBranch({ cwd: tmp.path, branch: defaultBranch });
await createGitBranch({ cwd: tmp.path, branch: "newer-branch" });
await checkoutGitBranch({ cwd: tmp.path, branch: "newer-branch" });
await commitWithDate(
tmp.path,
"newer.txt",
"newer change\n",
"Fri, 1 Jan 2038 00:00:00 +0000",
"newer change",
);
await checkoutGitBranch({ cwd: tmp.path, branch: "current-branch" });
const result = await listGitBranches({ cwd: tmp.path });
expect(result.branches[0]!.name).toBe("current-branch");
expect(result.branches[1]!.name).toBe(defaultBranch);
expect(result.branches[2]!.name).toBe("newer-branch");
});
it("lists multiple branches after creating them", async () => {
@@ -516,5 +603,21 @@ describe("git integration", () => {
const skipped = await core.pushCurrentBranch(tmp.path, null);
expect(skipped.status).toBe("skipped_up_to_date");
});
it("lists branches when recency lookup fails", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const core = new GitCoreService();
const recencySpy = vi
.spyOn(core as any, "readBranchRecency")
.mockRejectedValueOnce(new Error("timeout"));
const result = await core.listBranches({ cwd: tmp.path });
expect(result.isRepo).toBe(true);
expect(result.branches.length).toBeGreaterThan(0);
expect(result.branches[0]?.current).toBe(true);
recencySpy.mockRestore();
});
});
});
+42 -3
View File
@@ -312,7 +312,40 @@ export class GitCoreService {
return value.length > 0 ? value : null;
}
private async readBranchRecency(cwd: string): Promise<Map<string, number>> {
const branchRecency = await executeGit(
cwd,
["for-each-ref", "--format=%(refname:short)%09%(committerdate:unix)", "refs/heads"],
{
timeoutMs: 15_000,
allowNonZeroExit: true,
},
);
const branchLastCommit = new Map<string, number>();
if (branchRecency.code !== 0) {
return branchLastCommit;
}
for (const line of branchRecency.stdout.split("\n")) {
if (line.length === 0) {
continue;
}
const [name, lastCommitRaw] = line.split("\t");
if (!name) {
continue;
}
const lastCommit = Number.parseInt(lastCommitRaw ?? "0", 10);
branchLastCommit.set(name, Number.isFinite(lastCommit) ? lastCommit : 0);
}
return branchLastCommit;
}
async listBranches(input: GitListBranchesInput): Promise<GitListBranchesResult> {
const branchRecencyPromise = this.readBranchRecency(input.cwd).catch(
() => new Map<string, number>(),
);
const result = await executeGit(input.cwd, ["branch", "--no-color"], {
timeoutMs: 10_000,
allowNonZeroExit: true,
@@ -326,7 +359,7 @@ export class GitCoreService {
throw new Error(stderr || "git branch failed");
}
const [defaultRef, worktreeList] = await Promise.all([
const [defaultRef, worktreeList, branchLastCommit] = await Promise.all([
executeGit(input.cwd, ["symbolic-ref", "refs/remotes/origin/HEAD"], {
timeoutMs: 5_000,
allowNonZeroExit: true,
@@ -335,6 +368,7 @@ export class GitCoreService {
timeoutMs: 5_000,
allowNonZeroExit: true,
}),
branchRecencyPromise,
]);
const defaultBranch =
defaultRef.code === 0
@@ -370,8 +404,13 @@ export class GitCoreService {
};
})
.toSorted((a, b) => {
if (a.current !== b.current) return a.current ? -1 : 1;
if (a.isDefault !== b.isDefault) return a.isDefault ? -1 : 1;
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
if (aPriority !== bPriority) return aPriority - bPriority;
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
return a.name.localeCompare(b.name);
});
+31 -1
View File
@@ -12,6 +12,7 @@ import {
type Thread,
} from "../types";
import { useNativeApi } from "../hooks/useNativeApi";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
const THEME_CYCLE = { system: "light", light: "dark", dark: "system" } as const;
function formatRelativeTime(iso: string): string {
@@ -262,6 +263,22 @@ export default function Sidebar() {
const thread = state.threads.find((t) => t.id === threadId);
if (!thread) return;
const threadProject = state.projects.find((project) => project.id === thread.projectId);
const orphanedWorktreePath = getOrphanedWorktreePathForThread(state.threads, threadId);
const displayWorktreePath = orphanedWorktreePath
? formatWorktreePathForDisplay(orphanedWorktreePath)
: null;
const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== undefined;
const shouldDeleteWorktree =
canDeleteWorktree &&
(await api.dialogs.confirm(
[
"This thread is the only one linked to this worktree:",
displayWorktreePath ?? orphanedWorktreePath,
"",
"Delete the worktree too?",
].join("\n"),
));
// Stop active session if running
if (thread.session?.sessionId) {
@@ -284,8 +301,21 @@ export default function Sidebar() {
}
dispatch({ type: "DELETE_THREAD", threadId });
if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
return;
}
try {
await api.git.removeWorktree({
cwd: threadProject.cwd,
path: orphanedWorktreePath,
});
} catch {
// Worktree deletion is best-effort and should not block thread deletion.
}
},
[api, dispatch, state.threads],
[api, dispatch, state.projects, state.threads],
);
useEffect(() => {
+1
View File
@@ -5,6 +5,7 @@ import type { NativeApi } from "@t3tools/contracts";
interface DesktopBridge {
getWsUrl: () => string | null;
pickFolder: () => Promise<string | null>;
confirm: (message: string) => Promise<boolean>;
showContextMenu: (items: readonly { id: string; label: string }[]) => Promise<string | null>;
openExternal: (url: string) => Promise<boolean>;
}
+97
View File
@@ -0,0 +1,97 @@
import { describe, expect, it } from "vitest";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, type Thread } from "./types";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "./worktreeCleanup";
function makeThread(overrides: Partial<Thread> = {}): Thread {
return {
id: "thread-1",
codexThreadId: null,
projectId: "project-1",
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: false,
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: [],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
session: null,
messages: [],
events: [],
error: null,
createdAt: "2026-02-13T00:00:00.000Z",
branch: null,
worktreePath: null,
...overrides,
};
}
describe("getOrphanedWorktreePathForThread", () => {
it("returns null when the target thread does not exist", () => {
const result = getOrphanedWorktreePathForThread([], "missing-thread");
expect(result).toBeNull();
});
it("returns null when the target thread has no worktree", () => {
const threads = [makeThread()];
const result = getOrphanedWorktreePathForThread(threads, "thread-1");
expect(result).toBeNull();
});
it("returns the path when no other thread links to that worktree", () => {
const threads = [makeThread({ worktreePath: "/tmp/repo/worktrees/feature-a" })];
const result = getOrphanedWorktreePathForThread(threads, "thread-1");
expect(result).toBe("/tmp/repo/worktrees/feature-a");
});
it("returns null when another thread links to the same worktree", () => {
const threads = [
makeThread({ id: "thread-1", worktreePath: "/tmp/repo/worktrees/feature-a" }),
makeThread({ id: "thread-2", worktreePath: "/tmp/repo/worktrees/feature-a" }),
];
const result = getOrphanedWorktreePathForThread(threads, "thread-1");
expect(result).toBeNull();
});
it("ignores threads linked to different worktrees", () => {
const threads = [
makeThread({ id: "thread-1", worktreePath: "/tmp/repo/worktrees/feature-a" }),
makeThread({ id: "thread-2", worktreePath: "/tmp/repo/worktrees/feature-b" }),
];
const result = getOrphanedWorktreePathForThread(threads, "thread-1");
expect(result).toBe("/tmp/repo/worktrees/feature-a");
});
});
describe("formatWorktreePathForDisplay", () => {
it("shows only the last path segment for unix-like paths", () => {
const result = formatWorktreePathForDisplay(
"/Users/julius/.t3/worktrees/codething-mvp/codething-4e609bb8",
);
expect(result).toBe("codething-4e609bb8");
});
it("normalizes windows separators before selecting the final segment", () => {
const result = formatWorktreePathForDisplay(
"C:\\Users\\julius\\.t3\\worktrees\\codething-mvp\\codething-4e609bb8",
);
expect(result).toBe("codething-4e609bb8");
});
it("uses the final segment even when outside ~/.t3/worktrees", () => {
const result = formatWorktreePathForDisplay("/tmp/custom-worktrees/my-worktree");
expect(result).toBe("my-worktree");
});
it("ignores trailing slashes", () => {
const result = formatWorktreePathForDisplay("/tmp/custom-worktrees/my-worktree/");
expect(result).toBe("my-worktree");
});
});
+45
View File
@@ -0,0 +1,45 @@
import type { Thread } from "./types";
function normalizeWorktreePath(path: string | null): string | null {
const trimmed = path?.trim();
if (!trimmed) {
return null;
}
return trimmed;
}
export function getOrphanedWorktreePathForThread(
threads: readonly Thread[],
threadId: string,
): string | null {
const targetThread = threads.find((thread) => thread.id === threadId);
if (!targetThread) {
return null;
}
const targetWorktreePath = normalizeWorktreePath(targetThread.worktreePath);
if (!targetWorktreePath) {
return null;
}
const isShared = threads.some((thread) => {
if (thread.id === threadId) {
return false;
}
return normalizeWorktreePath(thread.worktreePath) === targetWorktreePath;
});
return isShared ? null : targetWorktreePath;
}
export function formatWorktreePathForDisplay(worktreePath: string): string {
const trimmed = worktreePath.trim();
if (!trimmed) {
return worktreePath;
}
const normalized = trimmed.replace(/\\/g, "/").replace(/\/+$/, "");
const parts = normalized.split("/");
const lastPart = parts[parts.length - 1]?.trim() ?? "";
return lastPart.length > 0 ? lastPart : trimmed;
}
+6
View File
@@ -60,6 +60,12 @@ export function createWsNativeApi(): NativeApi {
if (!window.desktopBridge) return null;
return window.desktopBridge.pickFolder();
},
confirm: async (message) => {
if (window.desktopBridge) {
return window.desktopBridge.confirm(message);
}
return window.confirm(message);
},
},
terminal: {
open: (input) => transport.request(WS_METHODS.terminalOpen, input),
+1
View File
@@ -56,6 +56,7 @@ export interface NativeApi {
};
dialogs: {
pickFolder: () => Promise<string | null>;
confirm: (message: string) => Promise<boolean>;
};
terminal: {
open: (input: TerminalOpenInput) => Promise<TerminalSessionSnapshot>;
+11
View File
@@ -0,0 +1,11 @@
# Small Arrival
Morning unbuttons at the edge of glass,
a cursor blinks like a held breath.
We name this day in lowercase hope,
and let new lines find their rhythm.
The room is quiet, but not empty.
Keys become rain, steady and kind.
Somewhere between intent and syntax,
something bright begins.