Compare commits

...
Author SHA1 Message Date
Cursor AgentandTheo Browne 02739bb95f Add sidebar project reordering
Co-authored-by: Theo Browne <[email protected]>
2026-03-06 03:03:40 +00:00
github-actions[bot] d5c97faac5 chore(release): prepare v0.0.0-alpha.20 2026-03-06 00:31:16 +00:00
Julius Marminge 531b12e192 repo too 2026-03-05 16:15:34 -08:00
Julius Marminge b293b083fc add missing bin to published package 2026-03-05 16:15:34 -08:00
Julius Marminge b297e20f4e Fix release target commit and gate version bump steps
- Set `target_commitish` from preflight ref when creating GitHub releases
- Track whether package versions changed and expose it via step output
- Run format, lockfile refresh, and bump commit only when changes exist
2026-03-05 16:15:34 -08:00
Julius MarmingeandClaude Opus 4.6 44be7f3ac3 Run oxfmt on package.json files after version bump
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-05 16:15:34 -08:00
Julius MarmingeandClaude Opus 4.6 ea5a100a74 Defer release commit+tag to finalize job
Move the version bump commit and tag creation out of the preflight job
into a new finalize job that runs only after build, publish, and release
all succeed. This prevents orphaned version commits and tags on main
when downstream jobs fail.

- Preflight: validate version, lint/test only — no commit/tag/push
- Release: softprops/action-gh-release creates tag for workflow_dispatch
- Finalize: bump package.json versions, refresh lockfile, commit to main

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-05 16:15:34 -08:00
Julius Marminge 6841fa17d4 Scope changed-files tree PR to relevant files
- revert unrelated server-side attachment/image changes from this branch\n- keep changed-files tree UX fixes (icons, directory behavior, whitespace-safe paths, stat visibility)\n\nCo-authored-by: codex <[email protected]>
2026-03-05 15:56:40 -08:00
Julius Marminge 5c03804bac Improve changed-files tree UX and harden attachment path handling
- Compact single-directory chains in turn diff trees and preserve branch points
- Add per-turn expand/collapse-all controls and themed VS Code file icons in ChatView
- Centralize attachment route prefix stripping and tighten image/extension normalization helpers
2026-03-05 15:56:40 -08:00
Julius Marminge d6ed393255 Render changed files as expandable tree with aggregated diff stats
- Replace flat changed-files chips in ChatView with a nested, expandable tree
- Extract diff tree/stat logic into turnDiffTree utilities
- Add unit tests for stat aggregation, nesting, and Windows path normalization
2026-03-05 15:56:40 -08:00
Julius Marminge 2d9139767a Refine sidebar thread actions and list preview
- Move "New thread" action to each project header with hover icon + shortcut tooltip
- Limit thread lists to 6 items by default with per-project Show more/Show less controls
- Remove the global sidebar-level new thread button
2026-03-05 15:16:10 -08:00
Julius Marminge 95fcc89074 Prevent toast content overflow in collapsed stack
- Use the larger of shared stack height and per-toast height to avoid clipping
- Make toast content columns flexible with `min-w-0` and `break-words`
- Keep action buttons from shrinking so long text wraps instead of overflowing
2026-03-05 14:43:19 -08:00
Julius Marminge eb59853596 Add Copy Thread ID action to thread context menu
- Add a `Copy Thread ID` item to the thread context menu in the sidebar
- Copy the selected thread ID via Clipboard API
- Show success/error toasts based on copy result
2026-03-05 14:42:02 -08:00
15 changed files with 1106 additions and 276 deletions

No files matched your search

+82 -62
View File
@@ -22,12 +22,10 @@ jobs:
outputs:
version: ${{ steps.release_meta.outputs.version }}
tag: ${{ steps.release_meta.outputs.tag }}
ref: ${{ steps.release_ref.outputs.value }}
ref: ${{ github.sha }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- id: release_meta
name: Resolve release version
@@ -58,32 +56,6 @@ jobs:
with:
node-version-file: package.json
- name: Update version strings
if: github.event_name == 'workflow_dispatch'
env:
RELEASE_VERSION: ${{ steps.release_meta.outputs.version }}
run: |
node --input-type=module -e '
import { readFileSync, writeFileSync } from "node:fs";
const files = [
"apps/server/package.json",
"apps/desktop/package.json",
"apps/web/package.json",
"packages/contracts/package.json",
];
for (const file of files) {
const packageJson = JSON.parse(readFileSync(file, "utf8"));
packageJson.version = process.env.RELEASE_VERSION;
writeFileSync(file, `${JSON.stringify(packageJson, null, 2)}\n`);
}
'
- name: Refresh lockfile
if: github.event_name == 'workflow_dispatch'
run: bun install
- name: Install dependencies
run: bun install --frozen-lockfile
@@ -96,39 +68,6 @@ jobs:
- name: Test
run: bun run test
- name: Commit and push release version + tag
if: github.event_name == 'workflow_dispatch'
shell: bash
env:
RELEASE_TAG: ${{ steps.release_meta.outputs.tag }}
run: |
if git ls-remote --exit-code --tags origin "$RELEASE_TAG" >/dev/null 2>&1; then
echo "Tag $RELEASE_TAG already exists on origin." >&2
exit 1
fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
if ! git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock; then
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
git commit -m "chore(release): prepare $RELEASE_TAG" -m "Co-authored-by: codex <[email protected]>"
fi
git tag "$RELEASE_TAG"
git push origin "HEAD:${GITHUB_REF_NAME}"
git push origin "refs/tags/$RELEASE_TAG"
- id: release_ref
name: Resolve source ref
shell: bash
run: |
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
echo "value=refs/tags/${{ steps.release_meta.outputs.tag }}" >> "$GITHUB_OUTPUT"
else
echo "value=${GITHUB_SHA}" >> "$GITHUB_OUTPUT"
fi
build:
name: Build ${{ matrix.label }}
needs: preflight
@@ -318,8 +257,10 @@ jobs:
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ needs.preflight.outputs.tag }}
target_commitish: ${{ needs.preflight.outputs.ref }}
name: T3 Code v${{ needs.preflight.outputs.version }}
generate_release_notes: true
make_latest: true
files: |
release-assets/*.dmg
release-assets/*.zip
@@ -328,3 +269,82 @@ jobs:
release-assets/*.blockmap
release-assets/latest*.yml
fail_on_unmatched_files: true
finalize:
name: Finalize release
needs: [preflight, release]
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v4
with:
ref: main
fetch-depth: 0
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version-file: package.json
- id: update_versions
name: Update version strings
env:
RELEASE_VERSION: ${{ needs.preflight.outputs.version }}
run: |
node --input-type=module -e '
import { appendFileSync, readFileSync, writeFileSync } from "node:fs";
const files = [
"apps/server/package.json",
"apps/desktop/package.json",
"apps/web/package.json",
"packages/contracts/package.json",
];
let changed = false;
for (const file of files) {
const packageJson = JSON.parse(readFileSync(file, "utf8"));
if (packageJson.version !== process.env.RELEASE_VERSION) {
packageJson.version = process.env.RELEASE_VERSION;
writeFileSync(file, `${JSON.stringify(packageJson, null, 2)}\n`);
changed = true;
}
}
if (!changed) {
console.log("All package.json versions already match release version.");
}
appendFileSync(process.env.GITHUB_OUTPUT, `changed=${changed}\n`);
'
- name: Format package.json files
if: steps.update_versions.outputs.changed == 'true'
run: bunx oxfmt apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
- name: Refresh lockfile
if: steps.update_versions.outputs.changed == 'true'
run: bun install
- name: Commit and push version bump
if: steps.update_versions.outputs.changed == 'true'
shell: bash
env:
RELEASE_TAG: ${{ needs.preflight.outputs.tag }}
run: |
if git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock; then
echo "No version changes to commit."
exit 0
fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
git commit -m "chore(release): prepare $RELEASE_TAG"
git push origin HEAD:main
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.0-alpha.18",
"version": "0.0.0-alpha.20",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
+6 -1
View File
@@ -1,6 +1,11 @@
{
"name": "t3",
"version": "0.0.0-alpha.18",
"version": "0.0.0-alpha.20",
"repository": {
"type": "git",
"url": "https://github.com/pingdotgg/t3code",
"directory": "apps/server"
},
"bin": {
"t3": "./dist/index.mjs"
},
+2
View File
@@ -111,6 +111,8 @@ const publishCmd = Command.make(
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
const pkg = {
name: serverPackageJson.name,
repository: serverPackageJson.repository,
bin: serverPackageJson.bin,
type: serverPackageJson.type,
version,
engines: serverPackageJson.engines,
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/web",
"version": "0.0.0-alpha.18",
"version": "0.0.0-alpha.20",
"private": true,
"type": "module",
"scripts": {
+206 -64
View File
@@ -63,11 +63,17 @@ import {
MAX_THREAD_TERMINAL_COUNT,
type ChatMessage,
type Thread,
type TurnDiffFileChange,
type TurnDiffSummary,
} from "../types";
import { basenameOfPath, getVscodeIconUrlForEntry } from "../vscode-icons";
import { useTheme } from "../hooks/useTheme";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
import {
buildTurnDiffTree,
summarizeTurnDiffStats,
type TurnDiffTreeNode,
} from "../lib/turnDiffTree";
import BranchToolbar from "./BranchToolbar";
import GitActionsControl from "./GitActionsControl";
import {
@@ -334,6 +340,7 @@ const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
pathValue: string;
kind: "file" | "directory";
theme: "light" | "dark";
className?: string;
}) {
const [failedIconUrl, setFailedIconUrl] = useState<string | null>(null);
const iconUrl = useMemo(
@@ -344,9 +351,9 @@ const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
if (failed) {
return props.kind === "directory" ? (
<FolderIcon className="size-4 text-muted-foreground/80" />
<FolderIcon className={cn("size-4 text-muted-foreground/80", props.className)} />
) : (
<FileIcon className="size-4 text-muted-foreground/80" />
<FileIcon className={cn("size-4 text-muted-foreground/80", props.className)} />
);
}
@@ -355,7 +362,7 @@ const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
src={iconUrl}
alt=""
aria-hidden="true"
className="size-4 shrink-0"
className={cn("size-4 shrink-0", props.className)}
loading="lazy"
onError={() => setFailedIconUrl(iconUrl)}
/>
@@ -2548,6 +2555,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
isRevertingCheckpoint={isRevertingCheckpoint}
onImageExpand={onExpandTimelineImage}
markdownCwd={gitCwd ?? undefined}
resolvedTheme={resolvedTheme}
/>
</div>
@@ -3127,6 +3135,156 @@ const MessageCopyButton = memo(function MessageCopyButton({ text }: { text: stri
);
});
function hasNonZeroStat(stat: { additions: number; deletions: number }): boolean {
return stat.additions > 0 || stat.deletions > 0;
}
const DiffStatLabel = memo(function DiffStatLabel(props: {
additions: number;
deletions: number;
showParentheses?: boolean;
}) {
const { additions, deletions, showParentheses = false } = props;
return (
<>
{showParentheses && <span className="text-muted-foreground/70">(</span>}
<span className="text-success">+{additions}</span>
<span className="mx-0.5 text-muted-foreground/70">/</span>
<span className="text-destructive">-{deletions}</span>
{showParentheses && <span className="text-muted-foreground/70">)</span>}
</>
);
});
function collectDirectoryPaths(nodes: ReadonlyArray<TurnDiffTreeNode>): string[] {
const paths: string[] = [];
for (const node of nodes) {
if (node.kind !== "directory") continue;
paths.push(node.path);
paths.push(...collectDirectoryPaths(node.children));
}
return paths;
}
function buildDirectoryExpansionState(
directoryPaths: ReadonlyArray<string>,
expanded: boolean,
): Record<string, boolean> {
const expandedState: Record<string, boolean> = {};
for (const directoryPath of directoryPaths) {
expandedState[directoryPath] = expanded;
}
return expandedState;
}
const ChangedFilesTree = memo(function ChangedFilesTree(props: {
turnId: TurnId;
files: ReadonlyArray<TurnDiffFileChange>;
allDirectoriesExpanded: boolean;
resolvedTheme: "light" | "dark";
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
}) {
const { files, allDirectoriesExpanded, onOpenTurnDiff, resolvedTheme, turnId } = props;
const treeNodes = useMemo(() => buildTurnDiffTree(files), [files]);
const directoryPathsKey = useMemo(() => collectDirectoryPaths(treeNodes).join("\u0000"), [treeNodes]);
const allDirectoryExpansionState = useMemo(
() =>
buildDirectoryExpansionState(
directoryPathsKey ? directoryPathsKey.split("\u0000") : [],
allDirectoriesExpanded,
),
[allDirectoriesExpanded, directoryPathsKey],
);
const [expandedDirectories, setExpandedDirectories] = useState<Record<string, boolean>>(
() => buildDirectoryExpansionState((directoryPathsKey ? directoryPathsKey.split("\u0000") : []), true),
);
useEffect(() => {
setExpandedDirectories(allDirectoryExpansionState);
}, [allDirectoryExpansionState]);
const toggleDirectory = useCallback((pathValue: string, fallbackExpanded: boolean) => {
setExpandedDirectories((current) => ({
...current,
[pathValue]: !(current[pathValue] ?? fallbackExpanded),
}));
}, []);
const renderTreeNode = (node: TurnDiffTreeNode, depth: number) => {
const leftPadding = 8 + depth * 14;
if (node.kind === "directory") {
const isExpanded = expandedDirectories[node.path] ?? depth === 0;
return (
<div key={`dir:${node.path}`}>
<button
type="button"
className="group flex w-full items-center gap-1.5 rounded-md py-1 pr-2 text-left hover:bg-background/80"
style={{ paddingLeft: `${leftPadding}px` }}
onClick={() => toggleDirectory(node.path, depth === 0)}
>
<ChevronRightIcon
aria-hidden="true"
className={cn(
"size-3.5 shrink-0 text-muted-foreground/70 transition-transform group-hover:text-foreground/80",
isExpanded && "rotate-90",
)}
/>
{isExpanded ? (
<FolderIcon className="size-3.5 shrink-0 text-muted-foreground/75" />
) : (
<FolderClosedIcon className="size-3.5 shrink-0 text-muted-foreground/75" />
)}
<span className="truncate font-mono text-[11px] text-muted-foreground/90 group-hover:text-foreground/90">
{node.name}
</span>
{hasNonZeroStat(node.stat) && (
<span className="ml-auto shrink-0 font-mono text-[10px] tabular-nums">
<DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
</span>
)}
</button>
{isExpanded && (
<div className="space-y-0.5">
{node.children.map((childNode) => renderTreeNode(childNode, depth + 1))}
</div>
)}
</div>
);
}
return (
<button
key={`file:${node.path}`}
type="button"
className="group flex w-full items-center gap-1.5 rounded-md py-1 pr-2 text-left hover:bg-background/80"
style={{ paddingLeft: `${leftPadding}px` }}
onClick={() => onOpenTurnDiff(turnId, node.path)}
>
<span aria-hidden="true" className="size-3.5 shrink-0" />
<VscodeEntryIcon
pathValue={node.path}
kind="file"
theme={resolvedTheme}
className="size-3.5 text-muted-foreground/70"
/>
<span className="truncate font-mono text-[11px] text-muted-foreground/80 group-hover:text-foreground/90">
{node.name}
</span>
{node.stat && (
<span className="ml-auto shrink-0 font-mono text-[10px] tabular-nums">
<DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
</span>
)}
</button>
);
};
return (
<div className="space-y-0.5">
{treeNodes.map((node) => renderTreeNode(node, 0))}
</div>
);
});
interface MessagesTimelineProps {
hasMessages: boolean;
isWorking: boolean;
@@ -3146,6 +3304,7 @@ interface MessagesTimelineProps {
isRevertingCheckpoint: boolean;
onImageExpand: (preview: ExpandedImagePreview) => void;
markdownCwd: string | undefined;
resolvedTheme: "light" | "dark";
}
type TimelineEntry = ReturnType<typeof deriveTimelineEntries>[number];
@@ -3186,6 +3345,7 @@ const MessagesTimeline = memo(function MessagesTimeline({
isRevertingCheckpoint,
onImageExpand,
markdownCwd,
resolvedTheme,
}: MessagesTimelineProps) {
const timelineRootRef = useRef<HTMLDivElement | null>(null);
const [timelineWidthPx, setTimelineWidthPx] = useState<number | null>(null);
@@ -3358,6 +3518,15 @@ const MessagesTimeline = memo(function MessagesTimeline({
const virtualRows = rowVirtualizer.getVirtualItems();
const nonVirtualizedRows = rows.slice(virtualizedRowCount);
const [allDirectoriesExpandedByTurnId, setAllDirectoriesExpandedByTurnId] = useState<
Record<string, boolean>
>({});
const onToggleAllDirectories = useCallback((turnId: TurnId) => {
setAllDirectoriesExpandedByTurnId((current) => ({
...current,
[turnId]: !(current[turnId] ?? true),
}));
}, []);
const renderRowContent = (row: TimelineRow) => (
<div
@@ -3531,81 +3700,54 @@ const MessagesTimeline = memo(function MessagesTimeline({
if (!turnSummary) return null;
const checkpointFiles = turnSummary.files;
if (checkpointFiles.length === 0) return null;
const summaryStat = checkpointFiles.reduce(
(acc, file) => {
if (
typeof file.additions !== "number" ||
typeof file.deletions !== "number"
) {
return acc;
}
return {
additions: acc.additions + file.additions,
deletions: acc.deletions + file.deletions,
};
},
{ additions: 0, deletions: 0 },
);
const summaryStat = summarizeTurnDiffStats(checkpointFiles);
const changedFileCountLabel = String(checkpointFiles.length);
const allDirectoriesExpanded =
allDirectoriesExpandedByTurnId[turnSummary.turnId] ?? true;
return (
<div className="mt-2 rounded-lg border border-border/80 bg-card/45 p-2.5">
<div className="mb-1.5 flex items-center justify-between gap-2">
<p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
<span>Changed files ({changedFileCountLabel})</span>
{(summaryStat.additions > 0 || summaryStat.deletions > 0) && (
{hasNonZeroStat(summaryStat) && (
<>
<span className="mx-1">•</span>
<span className="text-success">+{summaryStat.additions}</span>
<span className="mx-0.5 text-muted-foreground/70">/</span>
<span className="text-destructive">-{summaryStat.deletions}</span>
<DiffStatLabel
additions={summaryStat.additions}
deletions={summaryStat.deletions}
/>
</>
)}
</p>
<Button
type="button"
size="xs"
variant="outline"
onClick={() =>
onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)
}
>
View diff
</Button>
</div>
<div className="flex flex-wrap gap-1.5">
{checkpointFiles.map((file) => (
<button
key={`${turnSummary.turnId}:${file.path}`}
<div className="flex items-center gap-1.5">
<Button
type="button"
className="rounded-md border border-border/70 bg-background/70 px-2 py-1 font-mono text-[11px] text-muted-foreground/80 transition-colors hover:border-border hover:text-foreground/90"
onClick={() => onOpenTurnDiff(turnSummary.turnId, file.path)}
size="xs"
variant="outline"
onClick={() => onToggleAllDirectories(turnSummary.turnId)}
>
{(() => {
const stat =
typeof file.additions === "number" &&
typeof file.deletions === "number"
? {
additions: file.additions,
deletions: file.deletions,
}
: null;
if (!stat) {
return file.path;
}
return (
<>
<span>{file.path}</span>
<span className="ml-1 text-muted-foreground/70">(</span>
<span className="text-success">+{stat.additions}</span>
<span className="mx-0.5 text-muted-foreground/70">/</span>
<span className="text-destructive">-{stat.deletions}</span>
<span className="text-muted-foreground/70">)</span>
</>
);
})()}
</button>
))}
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
</Button>
<Button
type="button"
size="xs"
variant="outline"
onClick={() =>
onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)
}
>
View diff
</Button>
</div>
</div>
<ChangedFilesTree
key={`changed-files-tree:${turnSummary.turnId}`}
turnId={turnSummary.turnId}
files={checkpointFiles}
allDirectoriesExpanded={allDirectoriesExpanded}
resolvedTheme={resolvedTheme}
onOpenTurnDiff={onOpenTurnDiff}
/>
</div>
);
})()}
+251 -88
View File
@@ -1,11 +1,13 @@
import {
ChevronRightIcon,
FolderIcon,
GripVerticalIcon,
GitPullRequestIcon,
RocketIcon,
SquarePenIcon,
TerminalIcon,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { type PointerEvent, useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
DEFAULT_MODEL,
type DesktopUpdateState,
@@ -19,9 +21,10 @@ import { useNavigate, useParams } from "@tanstack/react-router";
import { useAppSettings } from "../appSettings";
import { isElectron } from "../env";
import { APP_STAGE_LABEL } from "../branding";
import { resolveServerHttpOrigin } from "../lib/serverOrigin";
import { newCommandId, newProjectId, newThreadId } from "../lib/utils";
import { useStore } from "../store";
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
import { isChatNewLocalShortcut, isChatNewShortcut, shortcutLabelForCommand } from "../keybindings";
import { type Thread } from "../types";
import { derivePendingApprovals } from "../session-logic";
import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/gitReactQuery";
@@ -46,6 +49,7 @@ import {
SidebarFooter,
SidebarGroup,
SidebarHeader,
SidebarMenuAction,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
@@ -59,6 +63,14 @@ import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "
import { isNonEmpty as isNonEmptyString } from "effect/String";
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
const THREAD_PREVIEW_LIMIT = 6;
async function copyTextToClipboard(text: string): Promise<void> {
if (typeof navigator === "undefined" || navigator.clipboard?.writeText === undefined) {
throw new Error("Clipboard API unavailable.");
}
await navigator.clipboard.writeText(text);
}
function formatRelativeTime(iso: string): string {
const diff = Date.now() - new Date(iso).getTime();
@@ -70,6 +82,11 @@ function formatRelativeTime(iso: string): string {
return `${Math.floor(hours / 24)}d ago`;
}
function resolveProjectDropPosition(element: HTMLElement, clientY: number) {
const { top, height } = element.getBoundingClientRect();
return clientY < top + height / 2 ? "before" : "after";
}
interface ThreadStatusPill {
label: "Working" | "Connecting" | "Completed" | "Pending Approval";
colorClass: string;
@@ -202,29 +219,7 @@ function T3Wordmark() {
);
}
/**
* Derives the server's HTTP origin (scheme + host + port) from the same
* sources WsTransport uses, converting ws(s) to http(s).
*/
function getServerHttpOrigin(): string {
const bridgeUrl = window.desktopBridge?.getWsUrl();
const envUrl = import.meta.env.VITE_WS_URL as string | undefined;
const wsUrl =
bridgeUrl && bridgeUrl.length > 0
? bridgeUrl
: envUrl && envUrl.length > 0
? envUrl
: `ws://${window.location.hostname}:${window.location.port}`;
// Parse to extract just the origin, dropping path/query (e.g. ?token=…)
const httpUrl = wsUrl.replace(/^wss:/, "https:").replace(/^ws:/, "http:");
try {
return new URL(httpUrl).origin;
} catch {
return httpUrl;
}
}
const serverHttpOrigin = getServerHttpOrigin();
const serverHttpOrigin = resolveServerHttpOrigin();
function ProjectFavicon({ cwd }: { cwd: string }) {
const [status, setStatus] = useState<"loading" | "loaded" | "error">("loading");
@@ -250,6 +245,7 @@ export default function Sidebar() {
const projects = useStore((store) => store.projects);
const threads = useStore((store) => store.threads);
const markThreadUnread = useStore((store) => store.markThreadUnread);
const moveProject = useStore((store) => store.moveProject);
const toggleProject = useStore((store) => store.toggleProject);
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearThreadDraft);
const getDraftThreadByProjectId = useComposerDraftStore(
@@ -284,6 +280,14 @@ export default function Sidebar() {
const [isAddingProject, setIsAddingProject] = useState(false);
const [renamingThreadId, setRenamingThreadId] = useState<ThreadId | null>(null);
const [renamingTitle, setRenamingTitle] = useState("");
const [draggedProjectId, setDraggedProjectId] = useState<ProjectId | null>(null);
const [projectDropTarget, setProjectDropTarget] = useState<{
projectId: ProjectId;
position: "before" | "after";
} | null>(null);
const [expandedThreadListsByProject, setExpandedThreadListsByProject] = useState<
ReadonlySet<ProjectId>
>(() => new Set());
const renamingCommittedRef = useRef(false);
const renamingInputRef = useRef<HTMLInputElement | null>(null);
const [desktopUpdateState, setDesktopUpdateState] = useState<DesktopUpdateState | null>(null);
@@ -581,6 +585,7 @@ export default function Sidebar() {
[
{ id: "rename", label: "Rename thread" },
{ id: "mark-unread", label: "Mark unread" },
{ id: "copy-thread-id", label: "Copy Thread ID" },
{ id: "delete", label: "Delete", destructive: true },
],
position,
@@ -599,6 +604,23 @@ export default function Sidebar() {
markThreadUnread(threadId);
return;
}
if (clicked === "copy-thread-id") {
try {
await copyTextToClipboard(threadId);
toastManager.add({
type: "success",
title: "Thread ID copied",
description: threadId,
});
} catch (error) {
toastManager.add({
type: "error",
title: "Failed to copy thread ID",
description: error instanceof Error ? error.message : "An error occurred.",
});
}
return;
}
if (clicked !== "delete") return;
if (appSettings.confirmThreadDelete) {
const confirmed = await api.dialogs.confirm(
@@ -832,15 +854,6 @@ export default function Sidebar() {
};
}, []);
const onCreateThreadClick = () => {
if (projects.length === 0) {
setAddingProject(true);
return;
}
const firstProject = projects[0];
if (firstProject) void handleNewThread(firstProject.id);
};
const showDesktopUpdateButton = isElectron && shouldShowDesktopUpdateButton(desktopUpdateState);
const desktopUpdateTooltip = desktopUpdateState
@@ -862,6 +875,12 @@ export default function Sidebar() {
: shouldHighlightDesktopUpdateError(desktopUpdateState)
? "text-rose-500 animate-pulse"
: "text-amber-500 animate-pulse";
const newThreadShortcutLabel = useMemo(
() =>
shortcutLabelForCommand(keybindings, "chat.newLocal") ??
shortcutLabelForCommand(keybindings, "chat.new"),
[keybindings],
);
const handleDesktopUpdateButtonClick = useCallback(() => {
const bridge = window.desktopBridge;
@@ -921,6 +940,83 @@ export default function Sidebar() {
}
}, [desktopUpdateButtonAction, desktopUpdateButtonDisabled, desktopUpdateState]);
const expandThreadListForProject = useCallback((projectId: ProjectId) => {
setExpandedThreadListsByProject((current) => {
if (current.has(projectId)) return current;
const next = new Set(current);
next.add(projectId);
return next;
});
}, []);
const collapseThreadListForProject = useCallback((projectId: ProjectId) => {
setExpandedThreadListsByProject((current) => {
if (!current.has(projectId)) return current;
const next = new Set(current);
next.delete(projectId);
return next;
});
}, []);
useEffect(() => {
if (!draggedProjectId) return;
const previousUserSelect = document.body.style.userSelect;
const previousCursor = document.body.style.cursor;
document.body.style.userSelect = "none";
document.body.style.cursor = "grabbing";
const handlePointerRelease = () => {
setDraggedProjectId(null);
setProjectDropTarget(null);
};
window.addEventListener("pointerup", handlePointerRelease);
window.addEventListener("pointercancel", handlePointerRelease);
return () => {
document.body.style.userSelect = previousUserSelect;
document.body.style.cursor = previousCursor;
window.removeEventListener("pointerup", handlePointerRelease);
window.removeEventListener("pointercancel", handlePointerRelease);
};
}, [draggedProjectId]);
function resetProjectDragState() {
setDraggedProjectId(null);
setProjectDropTarget(null);
}
function handleProjectDragStart(event: PointerEvent<HTMLButtonElement>, projectId: ProjectId) {
if (event.button !== 0) return;
event.preventDefault();
event.stopPropagation();
setDraggedProjectId(projectId);
setProjectDropTarget(null);
}
function handleProjectDragOver(event: PointerEvent<HTMLElement>, projectId: ProjectId) {
if (!draggedProjectId) return;
const position = resolveProjectDropPosition(event.currentTarget, event.clientY);
setProjectDropTarget((current) => {
if (current?.projectId === projectId && current.position === position) {
return current;
}
return { projectId, position };
});
}
function handleProjectDrop(event: PointerEvent<HTMLElement>, projectId: ProjectId) {
if (!draggedProjectId) return;
event.preventDefault();
event.stopPropagation();
const position = resolveProjectDropPosition(event.currentTarget, event.clientY);
moveProject(draggedProjectId, projectId, position);
resetProjectDragState();
}
const wordmark = (
<div className="flex items-center gap-2">
<SidebarTrigger className="shrink-0 md:hidden" />
@@ -936,17 +1032,6 @@ export default function Sidebar() {
</div>
);
const newThreadButton = (
<button
type="button"
className="flex w-full items-center gap-2 rounded-lg border border-border bg-secondary px-3 py-2 text-xs text-muted-foreground transition-colors duration-150 hover:bg-accent"
onClick={onCreateThreadClick}
>
<span className="text-foreground">+</span>
New thread
</button>
);
return (
<>
{isElectron ? (
@@ -973,12 +1058,10 @@ export default function Sidebar() {
</Tooltip>
)}
</SidebarHeader>
<div className="px-4 py-2">{newThreadButton}</div>
</>
) : (
<SidebarHeader className="gap-3 px-3 py-2 sm:gap-2.5 sm:px-4 sm:py-3">
{wordmark}
{newThreadButton}
</SidebarHeader>
)}
@@ -986,13 +1069,25 @@ export default function Sidebar() {
<SidebarGroup className="px-2 py-2">
<SidebarMenu>
{projects.map((project) => {
const visibleThreads = threads
const projectThreads = threads
.filter((thread) => thread.projectId === project.id)
.toSorted((a, b) => {
const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
if (byDate !== 0) return byDate;
return b.id.localeCompare(a.id);
});
const isThreadListExpanded = expandedThreadListsByProject.has(project.id);
const hasHiddenThreads = projectThreads.length > THREAD_PREVIEW_LIMIT;
const visibleThreads =
hasHiddenThreads && !isThreadListExpanded
? projectThreads.slice(0, THREAD_PREVIEW_LIMIT)
: projectThreads;
const dropIndicator =
draggedProjectId !== null &&
draggedProjectId !== project.id &&
projectDropTarget?.projectId === project.id
? projectDropTarget.position
: null;
return (
<Collapsible
@@ -1004,35 +1099,88 @@ export default function Sidebar() {
toggleProject(project.id);
}}
>
<SidebarMenuItem>
<CollapsibleTrigger
render={
<SidebarMenuButton
size="sm"
className="gap-2 px-2 py-1.5 text-left hover:bg-accent"
/>
}
onContextMenu={(event) => {
event.preventDefault();
void handleProjectContextMenu(project.id, {
x: event.clientX,
y: event.clientY,
});
}}
<SidebarMenuItem className={draggedProjectId === project.id ? "opacity-60" : ""}>
{dropIndicator === "before" && (
<div className="pointer-events-none absolute inset-x-2 top-0 h-0.5 rounded-full bg-primary" />
)}
{dropIndicator === "after" && (
<div className="pointer-events-none absolute inset-x-2 bottom-0 h-0.5 rounded-full bg-primary" />
)}
<div
className="group/project-header relative"
onPointerEnter={(event) => handleProjectDragOver(event, project.id)}
onPointerMove={(event) => handleProjectDragOver(event, project.id)}
onPointerUp={(event) => handleProjectDrop(event, project.id)}
>
<ChevronRightIcon
className={`-ml-0.5 size-3.5 shrink-0 text-muted-foreground/70 transition-transform duration-150 ${
project.expanded ? "rotate-90" : ""
<button
type="button"
aria-label={`Reorder ${project.name}`}
aria-grabbed={draggedProjectId === project.id}
className={`absolute top-1/2 left-1 z-10 inline-flex size-5 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground/45 transition-colors hover:bg-accent hover:text-foreground ${
draggedProjectId === project.id ? "cursor-grabbing" : "cursor-grab"
}`}
/>
<ProjectFavicon cwd={project.cwd} />
<span className="flex-1 truncate text-xs font-medium text-foreground/90">
{project.name}
</span>
<span className="text-[10px] text-muted-foreground/60">
{visibleThreads.length}
</span>
</CollapsibleTrigger>
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
}}
onPointerDown={(event) => handleProjectDragStart(event, project.id)}
>
<GripVerticalIcon className="size-3.5" />
</button>
<CollapsibleTrigger
render={
<SidebarMenuButton
size="sm"
className="gap-2 py-1.5 pr-2 pl-7 text-left hover:bg-accent group-hover/project-header:bg-accent group-hover/project-header:text-sidebar-accent-foreground"
/>
}
onContextMenu={(event) => {
event.preventDefault();
void handleProjectContextMenu(project.id, {
x: event.clientX,
y: event.clientY,
});
}}
>
<ChevronRightIcon
className={`-ml-0.5 size-3.5 shrink-0 text-muted-foreground/70 transition-transform duration-150 ${
project.expanded ? "rotate-90" : ""
}`}
/>
<ProjectFavicon cwd={project.cwd} />
<span className="flex-1 truncate text-xs font-medium text-foreground/90">
{project.name}
</span>
</CollapsibleTrigger>
<Tooltip>
<TooltipTrigger
render={
<SidebarMenuAction
render={
<button
type="button"
aria-label={`Create new thread in ${project.name}`}
/>
}
showOnHover
className="top-1 right-1 size-5 rounded-md p-0 text-muted-foreground/70 hover:bg-secondary hover:text-foreground"
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
void handleNewThread(project.id);
}}
>
<SquarePenIcon className="size-3.5" />
</SidebarMenuAction>
}
/>
<TooltipPopup side="top">
{newThreadShortcutLabel
? `New thread (${newThreadShortcutLabel})`
: "New thread"}
</TooltipPopup>
</Tooltip>
</div>
<CollapsibleContent>
<SidebarMenuSub className="mx-1 my-0 w-full translate-x-0 gap-0 px-1.5 py-0">
@@ -1176,19 +1324,34 @@ export default function Sidebar() {
);
})}
<SidebarMenuSubItem className="w-full">
<SidebarMenuSubButton
render={<button type="button" />}
size="sm"
className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80"
onClick={() => {
void handleNewThread(project.id);
}}
>
<span>+</span>
<span>New thread</span>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
{hasHiddenThreads && !isThreadListExpanded && (
<SidebarMenuSubItem className="w-full">
<SidebarMenuSubButton
render={<button type="button" />}
size="sm"
className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80"
onClick={() => {
expandThreadListForProject(project.id);
}}
>
<span>Show more</span>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
)}
{hasHiddenThreads && isThreadListExpanded && (
<SidebarMenuSubItem className="w-full">
<SidebarMenuSubButton
render={<button type="button" />}
size="sm"
className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80"
onClick={() => {
collapseThreadListForProject(project.id);
}}
>
<span>Show less</span>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
)}
</SidebarMenuSub>
</CollapsibleContent>
</SidebarMenuItem>
+23 -11
View File
@@ -206,7 +206,10 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
"data-[position*=top]:after:top-full",
"data-[position*=bottom]:after:bottom-full",
// Define some variables
"[--toast-calc-height:var(--toast-frontmost-height,var(--toast-height))] [--toast-gap:--spacing(3)] [--toast-peek:--spacing(3)] [--toast-scale:calc(max(0,1-(var(--toast-index)*.1)))] [--toast-shrink:calc(1-var(--toast-scale))]",
// Base UI exposes a shared front-most height for the collapsed stack.
// If that shared measurement is briefly stale, long content can render
// outside the card until hover expands the toast and swaps to its own height.
"[--toast-calc-height:max(var(--toast-frontmost-height,var(--toast-height)),var(--toast-height))] [--toast-gap:--spacing(3)] [--toast-peek:--spacing(3)] [--toast-scale:calc(max(0,1-(var(--toast-index)*.1)))] [--toast-shrink:calc(1-var(--toast-scale))]",
// Define offset-y variable
"data-[position*=top]:[--toast-calc-offset-y:calc(var(--toast-offset-y)+var(--toast-index)*var(--toast-gap)+var(--toast-swipe-movement-y))]",
"data-[position*=bottom]:[--toast-calc-offset-y:calc(var(--toast-offset-y)*-1+var(--toast-index)*var(--toast-gap)*-1+var(--toast-swipe-movement-y))]",
@@ -258,7 +261,7 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
"not-data-expanded:pointer-events-none not-data-expanded:opacity-0",
)}
>
<div className="flex gap-2">
<div className="flex min-w-0 flex-1 gap-2">
{Icon && (
<div
className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
@@ -268,16 +271,22 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
</div>
)}
<div className="flex flex-col gap-0.5">
<Toast.Title className="font-medium" data-slot="toast-title" />
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
<Toast.Title
className="min-w-0 break-words font-medium"
data-slot="toast-title"
/>
<Toast.Description
className="text-muted-foreground"
className="min-w-0 break-words text-muted-foreground"
data-slot="toast-description"
/>
</div>
</div>
{toast.actionProps && (
<Toast.Action className={buttonVariants({ size: "xs" })} data-slot="toast-action">
<Toast.Action
className={cn(buttonVariants({ size: "xs" }), "shrink-0")}
data-slot="toast-action"
>
{toast.actionProps.children}
</Toast.Action>
)}
@@ -341,7 +350,7 @@ function AnchoredToasts() {
</Toast.Content>
) : (
<Toast.Content className="pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm">
<div className="flex gap-2">
<div className="flex min-w-0 flex-1 gap-2">
{Icon && (
<div
className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
@@ -351,17 +360,20 @@ function AnchoredToasts() {
</div>
)}
<div className="flex flex-col gap-0.5">
<Toast.Title className="font-medium" data-slot="toast-title" />
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
<Toast.Title
className="min-w-0 break-words font-medium"
data-slot="toast-title"
/>
<Toast.Description
className="text-muted-foreground"
className="min-w-0 break-words text-muted-foreground"
data-slot="toast-description"
/>
</div>
</div>
{toast.actionProps && (
<Toast.Action
className={buttonVariants({ size: "xs" })}
className={cn(buttonVariants({ size: "xs" }), "shrink-0")}
data-slot="toast-action"
>
{toast.actionProps.children}
+19
View File
@@ -0,0 +1,19 @@
export function resolveServerHttpOrigin(): string {
if (typeof window === "undefined") return "";
const bridgeWsUrl = window.desktopBridge?.getWsUrl?.();
const envWsUrl = import.meta.env.VITE_WS_URL as string | undefined;
const wsUrl =
typeof bridgeWsUrl === "string" && bridgeWsUrl.length > 0
? bridgeWsUrl
: typeof envWsUrl === "string" && envWsUrl.length > 0
? envWsUrl
: `ws://${window.location.hostname}:${window.location.port}`;
const httpUrl = wsUrl.replace(/^wss:/, "https:").replace(/^ws:/, "http:");
try {
return new URL(httpUrl).origin;
} catch {
return httpUrl;
}
}
+165
View File
@@ -0,0 +1,165 @@
import { describe, expect, it } from "vitest";
import { buildTurnDiffTree, summarizeTurnDiffStats } from "./turnDiffTree";
describe("summarizeTurnDiffStats", () => {
it("sums only files with numeric additions/deletions", () => {
const stat = summarizeTurnDiffStats([
{ path: "README.md", additions: 3, deletions: 1 },
{ path: "docs/notes.md" },
{ path: "src/index.ts", additions: 5, deletions: 2 },
]);
expect(stat).toEqual({ additions: 8, deletions: 3 });
});
});
describe("buildTurnDiffTree", () => {
it("builds nested directory nodes with aggregated stats", () => {
const tree = buildTurnDiffTree([
{ path: "src/index.ts", additions: 2, deletions: 1 },
{ path: "src/components/Button.tsx", additions: 4, deletions: 2 },
{ path: "README.md", additions: 1, deletions: 0 },
]);
expect(tree).toEqual([
{
kind: "directory",
name: "src",
path: "src",
stat: { additions: 6, deletions: 3 },
children: [
{
kind: "directory",
name: "components",
path: "src/components",
stat: { additions: 4, deletions: 2 },
children: [
{
kind: "file",
name: "Button.tsx",
path: "src/components/Button.tsx",
stat: { additions: 4, deletions: 2 },
},
],
},
{
kind: "file",
name: "index.ts",
path: "src/index.ts",
stat: { additions: 2, deletions: 1 },
},
],
},
{
kind: "file",
name: "README.md",
path: "README.md",
stat: { additions: 1, deletions: 0 },
},
]);
});
it("keeps files without stat values and excludes them from directory totals", () => {
const tree = buildTurnDiffTree([
{ path: "docs/notes.md" },
{ path: "docs/todo.md", additions: 1, deletions: 1 },
]);
expect(tree).toEqual([
{
kind: "directory",
name: "docs",
path: "docs",
stat: { additions: 1, deletions: 1 },
children: [
{
kind: "file",
name: "notes.md",
path: "docs/notes.md",
stat: null,
},
{
kind: "file",
name: "todo.md",
path: "docs/todo.md",
stat: { additions: 1, deletions: 1 },
},
],
},
]);
});
it("normalizes file paths with windows separators", () => {
const tree = buildTurnDiffTree([{ path: "apps\\web\\src\\index.ts", additions: 2, deletions: 1 }]);
expect(tree).toEqual([
{
kind: "directory",
name: "apps/web/src",
path: "apps/web/src",
stat: { additions: 2, deletions: 1 },
children: [
{
kind: "file",
name: "index.ts",
path: "apps/web/src/index.ts",
stat: { additions: 2, deletions: 1 },
},
],
},
]);
});
it("compacts only single-directory chains and stops at branch points", () => {
const tree = buildTurnDiffTree([
{ path: "apps/server/src/index.ts", additions: 2, deletions: 1 },
{ path: "apps/server/main.ts", additions: 4, deletions: 0 },
]);
expect(tree).toEqual([
{
kind: "directory",
name: "apps/server",
path: "apps/server",
stat: { additions: 6, deletions: 1 },
children: [
{
kind: "directory",
name: "src",
path: "apps/server/src",
stat: { additions: 2, deletions: 1 },
children: [
{
kind: "file",
name: "index.ts",
path: "apps/server/src/index.ts",
stat: { additions: 2, deletions: 1 },
},
],
},
{
kind: "file",
name: "main.ts",
path: "apps/server/main.ts",
stat: { additions: 4, deletions: 0 },
},
],
},
]);
});
it("preserves leading/trailing whitespace in path segments", () => {
const tree = buildTurnDiffTree([
{ path: "a/file.ts", additions: 1, deletions: 0 },
{ path: " a/file.ts", additions: 2, deletions: 0 },
]);
expect(tree).toHaveLength(2);
const directoryNodes = tree.filter(
(node): node is Extract<(typeof tree)[number], { kind: "directory" }> => node.kind === "directory",
);
expect(directoryNodes.map((node) => node.name).toSorted()).toEqual([" a", "a"]);
expect(directoryNodes.map((node) => node.path).toSorted()).toEqual([" a", "a"]);
});
});
+172
View File
@@ -0,0 +1,172 @@
import type { TurnDiffFileChange } from "../types";
export interface TurnDiffStat {
additions: number;
deletions: number;
}
export interface TurnDiffTreeDirectoryNode {
kind: "directory";
name: string;
path: string;
stat: TurnDiffStat;
children: TurnDiffTreeNode[];
}
export interface TurnDiffTreeFileNode {
kind: "file";
name: string;
path: string;
stat: TurnDiffStat | null;
}
export type TurnDiffTreeNode = TurnDiffTreeDirectoryNode | TurnDiffTreeFileNode;
interface MutableDirectoryNode {
name: string;
path: string;
stat: TurnDiffStat;
directories: Map<string, MutableDirectoryNode>;
files: TurnDiffTreeFileNode[];
}
const SORT_LOCALE_OPTIONS: Intl.CollatorOptions = { numeric: true, sensitivity: "base" };
function normalizePathSegments(pathValue: string): string[] {
return pathValue
.replaceAll("\\", "/")
.split("/")
.filter((segment) => segment.length > 0);
}
function compareByName(a: { name: string }, b: { name: string }): number {
return a.name.localeCompare(b.name, undefined, SORT_LOCALE_OPTIONS);
}
function readStat(file: TurnDiffFileChange): TurnDiffStat | null {
if (typeof file.additions !== "number" || typeof file.deletions !== "number") {
return null;
}
return {
additions: file.additions,
deletions: file.deletions,
};
}
function compactDirectoryNode(node: TurnDiffTreeDirectoryNode): TurnDiffTreeDirectoryNode {
const compactedChildren = node.children.map((child) =>
child.kind === "directory" ? compactDirectoryNode(child) : child,
);
let compactedNode: TurnDiffTreeDirectoryNode = {
...node,
children: compactedChildren,
};
while (compactedNode.children.length === 1 && compactedNode.children[0]?.kind === "directory") {
const onlyChild = compactedNode.children[0];
compactedNode = {
kind: "directory",
name: `${compactedNode.name}/${onlyChild.name}`,
path: onlyChild.path,
stat: onlyChild.stat,
children: onlyChild.children,
};
}
return compactedNode;
}
function toTreeNodes(directory: MutableDirectoryNode): TurnDiffTreeNode[] {
const subdirectories: TurnDiffTreeDirectoryNode[] = Array.from(directory.directories.values())
.toSorted(compareByName)
.map<TurnDiffTreeDirectoryNode>((subdirectory) => ({
kind: "directory",
name: subdirectory.name,
path: subdirectory.path,
stat: {
additions: subdirectory.stat.additions,
deletions: subdirectory.stat.deletions,
},
children: toTreeNodes(subdirectory),
}))
.map((subdirectory) => compactDirectoryNode(subdirectory));
const files = directory.files.toSorted(compareByName);
return [...subdirectories, ...files];
}
export function summarizeTurnDiffStats(files: ReadonlyArray<TurnDiffFileChange>): TurnDiffStat {
return files.reduce(
(acc, file) => {
const stat = readStat(file);
if (!stat) return acc;
return {
additions: acc.additions + stat.additions,
deletions: acc.deletions + stat.deletions,
};
},
{ additions: 0, deletions: 0 },
);
}
export function buildTurnDiffTree(files: ReadonlyArray<TurnDiffFileChange>): TurnDiffTreeNode[] {
const root: MutableDirectoryNode = {
name: "",
path: "",
stat: { additions: 0, deletions: 0 },
directories: new Map(),
files: [],
};
for (const file of files) {
const segments = normalizePathSegments(file.path);
if (segments.length === 0) {
continue;
}
const filePath = segments.join("/");
const fileName = segments.at(-1);
if (!fileName) {
continue;
}
const stat = readStat(file);
const ancestors: MutableDirectoryNode[] = [root];
let currentDirectory = root;
for (const segment of segments.slice(0, -1)) {
const nextPath = currentDirectory.path ? `${currentDirectory.path}/${segment}` : segment;
const existing = currentDirectory.directories.get(segment);
if (existing) {
currentDirectory = existing;
} else {
const created: MutableDirectoryNode = {
name: segment,
path: nextPath,
stat: { additions: 0, deletions: 0 },
directories: new Map(),
files: [],
};
currentDirectory.directories.set(segment, created);
currentDirectory = created;
}
ancestors.push(currentDirectory);
}
currentDirectory.files.push({
kind: "file",
name: fileName,
path: filePath,
stat,
});
if (stat) {
for (const ancestor of ancestors) {
ancestor.stat.additions += stat.additions;
ancestor.stat.deletions += stat.deletions;
}
}
}
return toTreeNodes(root);
}
+90 -12
View File
@@ -1,7 +1,9 @@
import type { OrchestrationReadModel } from "@t3tools/contracts";
import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { markThreadUnread, type AppState } from "./store";
import { markThreadUnread, moveProject, syncServerReadModel, type AppState } from "./store";
import type { Project } from "./types";
import type { Thread } from "./types";
function makeThread(overrides: Partial<Thread> = {}): Thread {
@@ -24,18 +26,22 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
};
}
function makeState(thread: Thread): AppState {
function makeProject(overrides: Partial<Project> = {}): Project {
return {
projects: [
{
id: ProjectId.makeUnsafe("project-1"),
name: "Project",
cwd: "/tmp/project",
model: "gpt-5-codex",
expanded: true,
scripts: [],
},
],
id: ProjectId.makeUnsafe("project-1"),
name: "Project",
cwd: "/tmp/project",
model: "gpt-5-codex",
expanded: true,
scripts: [],
...overrides,
};
}
function makeState(thread: Thread, projects: Project[] = [makeProject()]): AppState {
return {
projects,
projectOrder: projects.map((project) => project.id),
threads: [thread],
threadsHydrated: true,
runtimeMode: "full-access",
@@ -81,4 +87,76 @@ describe("store pure functions", () => {
expect(next).toEqual(initialState);
});
it("moveProject reorders projects and persists the new order", () => {
const firstProject = makeProject({
id: ProjectId.makeUnsafe("project-1"),
name: "First",
cwd: "/tmp/first",
});
const secondProject = makeProject({
id: ProjectId.makeUnsafe("project-2"),
name: "Second",
cwd: "/tmp/second",
});
const thirdProject = makeProject({
id: ProjectId.makeUnsafe("project-3"),
name: "Third",
cwd: "/tmp/third",
});
const initialState = makeState(makeThread(), [firstProject, secondProject, thirdProject]);
const next = moveProject(
initialState,
ProjectId.makeUnsafe("project-3"),
ProjectId.makeUnsafe("project-1"),
"before",
);
expect(next.projects.map((project) => project.id)).toEqual([
ProjectId.makeUnsafe("project-3"),
ProjectId.makeUnsafe("project-1"),
ProjectId.makeUnsafe("project-2"),
]);
expect(next.projectOrder).toEqual(next.projects.map((project) => project.id));
});
it("syncServerReadModel reapplies a persisted project order to fresh snapshots", () => {
const initialState = {
...makeState(makeThread(), []),
projectOrder: [
ProjectId.makeUnsafe("project-2"),
ProjectId.makeUnsafe("project-1"),
],
};
const readModel = {
projects: [
{
id: ProjectId.makeUnsafe("project-1"),
title: "First",
workspaceRoot: "/tmp/first",
defaultModel: null,
scripts: [],
deletedAt: null,
},
{
id: ProjectId.makeUnsafe("project-2"),
title: "Second",
workspaceRoot: "/tmp/second",
defaultModel: null,
scripts: [],
deletedAt: null,
},
],
threads: [],
} as unknown as OrchestrationReadModel;
const next = syncServerReadModel(initialState, readModel);
expect(next.projects.map((project) => project.id)).toEqual([
ProjectId.makeUnsafe("project-2"),
ProjectId.makeUnsafe("project-1"),
]);
expect(next.projectOrder).toEqual(next.projects.map((project) => project.id));
});
});
+83 -31
View File
@@ -1,6 +1,7 @@
import { Fragment, type ReactNode, createElement, useEffect } from "react";
import {
DEFAULT_MODEL,
ProjectId,
ProviderSessionId,
ThreadId,
type OrchestrationReadModel,
@@ -15,11 +16,13 @@ import {
type RuntimeMode,
type Thread,
} from "./types";
import { resolveServerHttpOrigin } from "./lib/serverOrigin";
// ── State ────────────────────────────────────────────────────────────
export interface AppState {
projects: Project[];
projectOrder: Project["id"][];
threads: Thread[];
threadsHydrated: boolean;
runtimeMode: RuntimeMode;
@@ -39,15 +42,19 @@ const LEGACY_PERSISTED_STATE_KEYS = [
const initialState: AppState = {
projects: [],
projectOrder: [],
threads: [],
threadsHydrated: false,
runtimeMode: DEFAULT_RUNTIME_MODE,
};
const persistedExpandedProjectCwds = new Set<string>();
const persistedProjectOrder: Project["id"][] = [];
// ── Persist helpers ──────────────────────────────────────────────────
function readPersistedState(): AppState {
persistedExpandedProjectCwds.clear();
persistedProjectOrder.length = 0;
if (typeof window === "undefined") return initialState;
try {
const raw = window.localStorage.getItem(PERSISTED_STATE_KEY);
@@ -55,15 +62,21 @@ function readPersistedState(): AppState {
const parsed = JSON.parse(raw) as {
runtimeMode?: RuntimeMode;
expandedProjectCwds?: string[];
projectOrder?: string[];
};
persistedExpandedProjectCwds.clear();
for (const cwd of parsed.expandedProjectCwds ?? []) {
if (typeof cwd === "string" && cwd.length > 0) {
persistedExpandedProjectCwds.add(cwd);
}
}
for (const projectId of parsed.projectOrder ?? []) {
if (typeof projectId === "string" && projectId.length > 0) {
persistedProjectOrder.push(ProjectId.makeUnsafe(projectId));
}
}
return {
...initialState,
projectOrder: [...persistedProjectOrder],
runtimeMode:
parsed.runtimeMode === "approval-required" || parsed.runtimeMode === "full-access"
? parsed.runtimeMode
@@ -84,6 +97,7 @@ function persistState(state: AppState): void {
expandedProjectCwds: state.projects
.filter((project) => project.expanded)
.map((project) => project.cwd),
projectOrder: state.projects.map((project) => project.id),
}),
);
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
@@ -134,6 +148,28 @@ function mapProjectsFromReadModel(
});
}
function applyProjectOrder(projects: Project[], projectOrder: Project["id"][]): Project[] {
if (projects.length < 2 || projectOrder.length === 0) {
return projects;
}
const remainingProjects = new Map(projects.map((project) => [project.id, project] as const));
const orderedProjects: Project[] = [];
for (const projectId of projectOrder) {
const project = remainingProjects.get(projectId);
if (!project) continue;
orderedProjects.push(project);
remainingProjects.delete(projectId);
}
const nextProjects = [
...orderedProjects,
...projects.filter((project) => remainingProjects.has(project.id)),
];
const orderChanged = nextProjects.some((project, index) => project !== projects[index]);
return orderChanged ? nextProjects : projects;
}
function toLegacySessionStatus(
status: OrchestrationSessionStatus,
): "connecting" | "ready" | "running" | "error" | "closed" {
@@ -157,34 +193,9 @@ function toLegacyProvider(providerName: string | null): "codex" | "claudeCode" {
return providerName === "claudeCode" ? "claudeCode" : "codex";
}
function resolveWsHttpOrigin(): string {
if (typeof window === "undefined") return "";
const bridgeWsUrl = window.desktopBridge?.getWsUrl?.();
const envWsUrl = import.meta.env.VITE_WS_URL as string | undefined;
const wsCandidate =
typeof bridgeWsUrl === "string" && bridgeWsUrl.length > 0
? bridgeWsUrl
: typeof envWsUrl === "string" && envWsUrl.length > 0
? envWsUrl
: null;
if (!wsCandidate) return window.location.origin;
try {
const wsUrl = new URL(wsCandidate);
const protocol =
wsUrl.protocol === "wss:"
? "https:"
: wsUrl.protocol === "ws:"
? "http:"
: wsUrl.protocol;
return `${protocol}//${wsUrl.host}`;
} catch {
return window.location.origin;
}
}
function toAttachmentPreviewUrl(rawUrl: string): string {
if (rawUrl.startsWith("/")) {
return `${resolveWsHttpOrigin()}${rawUrl}`;
return `${resolveServerHttpOrigin()}${rawUrl}`;
}
return rawUrl;
}
@@ -199,9 +210,10 @@ export function syncServerReadModel(
state: AppState,
readModel: OrchestrationReadModel,
): AppState {
const projects = mapProjectsFromReadModel(
readModel.projects.filter((project) => project.deletedAt === null),
state.projects,
const activeReadModelProjects = readModel.projects.filter((project) => project.deletedAt === null);
const projects = applyProjectOrder(
mapProjectsFromReadModel(activeReadModelProjects, state.projects),
state.projectOrder,
);
const existingThreadById = new Map(
state.threads.map((thread) => [thread.id, thread] as const),
@@ -272,6 +284,7 @@ export function syncServerReadModel(
return {
...state,
projects,
projectOrder: projects.map((project) => project.id),
threads,
threadsHydrated: true,
};
@@ -333,6 +346,38 @@ export function setProjectExpanded(
return changed ? { ...state, projects } : state;
}
export function moveProject(
state: AppState,
projectId: Project["id"],
targetProjectId: Project["id"],
position: "before" | "after",
): AppState {
if (projectId === targetProjectId) return state;
const currentIndex = state.projects.findIndex((project) => project.id === projectId);
const targetIndex = state.projects.findIndex((project) => project.id === targetProjectId);
if (currentIndex < 0 || targetIndex < 0) return state;
const projects = [...state.projects];
const [project] = projects.splice(currentIndex, 1);
if (!project) return state;
const adjustedTargetIndex = projects.findIndex((entry) => entry.id === targetProjectId);
if (adjustedTargetIndex < 0) return state;
const insertionIndex = position === "before" ? adjustedTargetIndex : adjustedTargetIndex + 1;
projects.splice(insertionIndex, 0, project);
const orderChanged = projects.some((entry, index) => entry !== state.projects[index]);
if (!orderChanged) return state;
return {
...state,
projects,
projectOrder: projects.map((entry) => entry.id),
};
}
export function setError(state: AppState, threadId: ThreadId, error: string | null): AppState {
const threads = updateThread(state.threads, threadId, (t) => {
if (t.error === error) return t;
@@ -372,6 +417,11 @@ interface AppStore extends AppState {
markThreadVisited: (threadId: ThreadId, visitedAt?: string) => void;
markThreadUnread: (threadId: ThreadId) => void;
toggleProject: (projectId: Project["id"]) => void;
moveProject: (
projectId: Project["id"],
targetProjectId: Project["id"],
position: "before" | "after",
) => void;
setProjectExpanded: (projectId: Project["id"], expanded: boolean) => void;
setError: (threadId: ThreadId, error: string | null) => void;
setThreadBranch: (
@@ -392,6 +442,8 @@ export const useStore = create<AppStore>((set) => ({
set((state) => markThreadUnread(state, threadId)),
toggleProject: (projectId) =>
set((state) => toggleProject(state, projectId)),
moveProject: (projectId, targetProjectId, position) =>
set((state) => moveProject(state, projectId, targetProjectId, position)),
setProjectExpanded: (projectId, expanded) =>
set((state) => setProjectExpanded(state, projectId, expanded)),
setError: (threadId, error) =>
@@ -402,7 +454,7 @@ export const useStore = create<AppStore>((set) => ({
set((state) => setRuntimeMode(state, mode)),
}));
// Persist on every state change (only runtimeMode + expandedProjectCwds)
// Persist on every state change (runtimeMode + expanded projects + project order)
useStore.subscribe((state) => persistState(state));
export function StoreProvider({ children }: { children: ReactNode }) {
+4 -4
View File
@@ -14,7 +14,7 @@
},
"apps/desktop": {
"name": "@t3tools/desktop",
"version": "0.0.0-alpha.18",
"version": "0.0.0-alpha.20",
"dependencies": {
"effect": "catalog:",
"electron": "40.6.0",
@@ -32,7 +32,7 @@
},
"apps/server": {
"name": "t3",
"version": "0.0.0-alpha.18",
"version": "0.0.0-alpha.20",
"bin": {
"t3": "./dist/index.mjs",
},
@@ -61,7 +61,7 @@
},
"apps/web": {
"name": "@t3tools/web",
"version": "0.0.0-alpha.18",
"version": "0.0.0-alpha.20",
"dependencies": {
"@base-ui/react": "^1.2.0",
"@lexical/react": "^0.41.0",
@@ -105,7 +105,7 @@
},
"packages/contracts": {
"name": "@t3tools/contracts",
"version": "0.0.0-alpha.18",
"version": "0.0.0-alpha.20",
"dependencies": {
"effect": "catalog:",
},
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/contracts",
"version": "0.0.0-alpha.18",
"version": "0.0.0-alpha.20",
"private": true,
"files": [
"dist"