Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge cffc3013cd fix: use consistent border-box measurement in composer ResizeObserver
The initial height was seeded via getBoundingClientRect().height (border-box)
but the ResizeObserver callback read entry.contentRect.height (content-box).
This mismatch would cause a spurious height change detection on the first
callback if the form element ever acquired padding or border.

Use entry.borderBoxSize[0].blockSize (with contentRect fallback) to keep both
measurements in border-box space.

Co-authored-by: Julius Marminge <[email protected]>
2026-03-02 18:26:03 +00:00
Julius Marminge 61a8ca2c31 refactor: remove redundant workLogCount stick-to-bottom effect
timelineEntries is derived from workLogEntries; the timelineEntries
effect already runs when work log changes. Dropped duplicate effect
and unused workLogCount variable.

Made-with: Cursor
2026-03-02 10:10:15 -08:00
Julius Marminge 8294392062 fix: align handoff preview URLs with image attachment index
collectUserMessageBlobPreviewUrls returns a compact array (image+blob only).
Consumer now indexes by image position, not full attachment index, so
blob URLs apply to the correct server attachments when some are skipped.

Made-with: Cursor
2026-03-02 09:53:08 -08:00
Julius Marminge b58b8fd0fd Stabilize chat scroll restoration across thread switches
- Keep auto-scroll pinned to bottom during thread changes, composer resize, and streaming updates
- Improve virtualized timeline measurement/keying to prevent stale height reuse between threads
- Hand off blob image preview URLs from optimistic to server messages to avoid flicker/revocation races
2026-03-02 00:46:01 -08:00
Julius Marminge 9f068356a4 Allow non-required dev ports to exceed max in offset search
- Stop `findFirstAvailableOffset` only when a required port exceeds `MAX_PORT`
- Add test covering offsets where only non-required ports are out of range
2026-03-01 23:53:31 -08:00
Julius Marminge f239c90628 Auto-select next available dev ports per mode
- Probe localhost ports and increment offsets when base ports are taken
- Resolve server/web offsets by mode while honoring explicit port/dev-url overrides
- Add tests for offset selection and per-mode fallback behavior
2026-03-01 23:53:31 -08:00
Julius Marminge 991dd05e72 Use forkScoped for background upstream refresh
- replace `Effect.forkDetach` with `Effect.forkScoped` when refreshing checked-out branch upstream refs
- keep checkout responsive while ensuring the background task stays tied to scope lifecycle
2026-03-01 23:24:22 -08:00
Julius Marminge 96bf54e293 Serve fallback project favicon when no icon file is found
- return an inline SVG favicon instead of 404 when project/icon files are missing
- add route test coverage for fallback response status and MIME type
2026-03-01 23:18:45 -08:00
Julius Marminge 5ca9b54d66 Preserve $defs in Codex output schema and refine sidebar header
- include JSON Schema `$defs` when writing Codex output schema files
- tighten sidebar wordmark sizing and spacing in Electron/web layouts
2026-03-01 23:11:44 -08:00
Julius Marminge 4ab5fca4ca Preserve draft env mode across thread and branch context updates
- Track and persist `envMode` in composer draft thread state
- Keep worktree mode for local drafts even when `worktreePath` is null
- Update branch toolbar/chat/sidebar to use effective draft env mode
- Add tests for env mode persistence and undefined option merges
2026-03-01 22:36:35 -08:00
Julius Marmingeandcodex 69a4fa8215 Show branch toolbar for local draft threads
Co-authored-by: codex <[email protected]>
2026-03-01 22:36:35 -08:00
Julius Marminge 9e04bad0a5 Run setup script after promoting local draft threads
- allow `runProjectScript` for local draft threads when explicitly enabled
- move setup script execution to run after server thread creation
- gate setup script on worktree/base-branch availability and pass resolved worktree cwd
2026-03-01 22:36:35 -08:00
Julius Marminge a574d9c936 Cover runtime undefined draft thread options in store test
- Build options object with runtime `undefined` values via cast
- Pass object into `setProjectDraftThreadId` to verify handling path
2026-03-01 22:36:35 -08:00
Julius Marminge 005e13089a Preserve draft branch/worktree when update options are undefined
- Keep existing `branch` and `worktreePath` values when `setProjectDraftThreadId` receives `undefined`
- Add a regression test covering the undefined-update case
2026-03-01 22:36:35 -08:00
Julius Marminge d9cce6402a Clean up orphaned composer drafts and harden draft checks
- Remove stale `draftsByThreadId` entries when project-thread mappings are replaced or cleared
- Preserve drafts when a thread is still mapped to another project
- Parse persisted image `dataUrl` payloads more defensively and use `Object.hasOwn` for draft-thread existence checks
2026-03-01 22:36:35 -08:00
Julius Marmingeandcodex 508872e04b Preserve explicit DEFAULT_MODEL draft overrides
Co-authored-by: codex <[email protected]>
2026-03-01 22:36:35 -08:00
Julius Marmingeandcodex aced302b63 Address PR review feedback for draft model/error/persistence handling
Co-authored-by: codex <[email protected]>
2026-03-01 22:36:35 -08:00
Julius Marminge 0b8dfee17b Simplify composer draft persistence and remove debug instrumentation
- Remove ChatView draft persistence debug logging and storage size plumbing
- Drop in-memory persisted draft cache; use JSON storage directly
- Reconcile attachment IDs from localStorage and streamline image hydration
2026-03-01 22:36:35 -08:00
Julius Marminge 6ab246676e Refactor draft thread lookups and cache persisted draft state
- replace `read*` draft selectors with `getDraftThread`/`getDraftThreadByProjectId`
- centralize persisted localStorage parsing/caching in `composerDraftStore`
- make ChatView fallback read persisted attachments from in-memory store state
2026-03-01 22:36:35 -08:00
Julius Marminge 122c94a24a Defer thread creation until first message send
- Track draft thread metadata in composer draft store
- Reuse and update local draft threads from Sidebar/ChatView
- Create server thread only when sending first message, with rollback on failure
- Add/expand draft-thread store tests for mapping and context updates
2026-03-01 22:36:35 -08:00
Julius Marminge b59c6d6ab1 Unify project draft thread state in composer draft store
- move project draft thread ID persistence/actions into `composerDraftStore`
- remove legacy `projectDraftThreads` module and update `ChatView`/`Sidebar` callers
- keep image dedupe stable across hydration and avoid revoking blob URLs on composer clear
- add store tests for project-thread mapping and composer clear behavior
- drop deprecated model slug aliases (`gpt-5`, `gpt-5-codex`, `gpt-5-codex-spark`)
2026-03-01 22:36:35 -08:00
Julius Marminge c9995995a4 Preserve draft metadata and dedupe composer image retries
- Reuse hidden draft threads while applying requested branch/worktree updates before navigation
- Export composer draft storage key and clone blob preview URLs when re-adding images after retry
- Deduplicate composer images by file signature (within and across calls) and add store tests for URL revoke behavior
2026-03-01 22:36:35 -08:00
Julius Marminge 545a9193e2 Persist per-thread composer drafts and reuse project draft threads
- add a zustand-backed composer draft store with localStorage persistence for prompt, cursor, model/effort, and image attachments
- wire ChatView to draft state, restore/clear drafts correctly, and warn when an attachment cannot be persisted
- track per-project draft thread IDs so Sidebar reuses hidden draft threads and excludes empty drafts from thread lists
2026-03-01 22:36:35 -08:00
Julius Marminge fa0205cba3 Run checks before release commit and set desktop buildVersion
- Move install, lint, typecheck, and test steps ahead of release commit/tag in `release.yml`
- Add `buildVersion` to staged desktop `package.json` and set it to the app version
2026-03-01 20:33:00 -08:00
github-actions[bot]andcodex 8a20bd7f54 chore(release): prepare v0.0.0-alpha.4
Co-authored-by: codex <[email protected]>
2026-03-02 04:23:28 +00:00
15 changed files with 587 additions and 80 deletions

No files matched your search

+12 -12
View File
@@ -84,6 +84,18 @@ jobs:
if: github.event_name == 'workflow_dispatch'
run: bun install
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Lint
run: bun run lint
- name: Typecheck
run: bun run typecheck
- name: Test
run: bun run test
- name: Commit and push release version + tag
if: github.event_name == 'workflow_dispatch'
shell: bash
@@ -117,18 +129,6 @@ jobs:
echo "value=${GITHUB_SHA}" >> "$GITHUB_OUTPUT"
fi
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Lint
run: bun run lint
- name: Typecheck
run: bun run typecheck
- name: Test
run: bun run test
build:
name: Build ${{ matrix.label }}
needs: preflight
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.0",
"version": "0.0.0-alpha.4",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.1.0",
"version": "0.0.0-alpha.4",
"bin": {
"t3": "./dist/index.mjs"
},
@@ -19,6 +19,17 @@ const CODEX_MODEL = "gpt-5.3-codex";
const CODEX_REASONING_EFFORT = "low";
const CODEX_TIMEOUT_MS = 180_000;
function toCodexOutputJsonSchema(schema: Schema.Top): unknown {
const document = Schema.toJsonSchemaDocument(schema);
if (document.definitions && Object.keys(document.definitions).length > 0) {
return {
...document.schema,
$defs: document.definitions,
};
}
return document.schema;
}
function normalizeCodexError(
operation: string,
error: unknown,
@@ -204,7 +215,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
const schemaPath = yield* writeTempFile(
operation,
"codex-schema",
JSON.stringify(Schema.toJsonSchemaDocument(outputSchemaJson).schema),
JSON.stringify(toCodexOutputJsonSchema(outputSchemaJson)),
);
const outputPath = yield* writeTempFile(operation, "codex-output", "");
+1 -1
View File
@@ -1162,7 +1162,7 @@ const makeGitCore = Effect.gen(function* () {
});
// Refresh upstream refs in the background so checkout remains responsive.
yield* Effect.forkDetach(
yield* Effect.forkScoped(
refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.catch(() => Effect.void)),
);
});
@@ -152,4 +152,16 @@ describe("tryHandleProjectFaviconRequest", () => {
expect(response.body).toBe("<svg>brand-obj-order</svg>");
});
});
it("serves a fallback favicon when no icon exists", async () => {
const projectDir = makeTempDir("t3code-favicon-route-fallback-");
await withRouteServer(async (baseUrl) => {
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
const response = await request(baseUrl, pathname);
expect(response.statusCode).toBe(200);
expect(response.contentType).toContain("image/svg+xml");
expect(response.body).toContain('data-fallback="project-favicon"');
});
});
});
+11 -2
View File
@@ -9,6 +9,8 @@ const FAVICON_MIME_TYPES: Record<string, string> = {
".ico": "image/x-icon",
};
const FALLBACK_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
// Well-known favicon paths checked in order.
const FAVICON_CANDIDATES = [
"favicon.svg",
@@ -85,6 +87,14 @@ function serveFaviconFile(filePath: string, res: http.ServerResponse): void {
});
}
function serveFallbackFavicon(res: http.ServerResponse): void {
res.writeHead(200, {
"Content-Type": "image/svg+xml",
"Cache-Control": "public, max-age=3600",
});
res.end(FALLBACK_FAVICON_SVG);
}
export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerResponse): boolean {
if (url.pathname !== "/api/project-favicon") {
return false;
@@ -118,8 +128,7 @@ export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerRespons
const trySourceFiles = (index: number): void => {
if (index >= ICON_SOURCE_FILES.length) {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("No favicon found");
serveFallbackFavicon(res);
return;
}
const sourceFile = path.join(projectCwd, ICON_SOURCE_FILES[index]!);
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/web",
"version": "0.0.0",
"version": "0.0.0-alpha.4",
"private": true,
"type": "module",
"scripts": {
+257 -31
View File
@@ -24,7 +24,11 @@ import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useStat
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useDebouncedValue } from "@tanstack/react-pacer";
import { useNavigate, useSearch } from "@tanstack/react-router";
import { type VirtualItem, useVirtualizer } from "@tanstack/react-virtual";
import {
measureElement as measureVirtualElement,
type VirtualItem,
useVirtualizer,
} from "@tanstack/react-virtual";
import { gitBranchesQueryOptions, gitCreateWorktreeMutationOptions } from "~/lib/gitReactQuery";
import { projectSearchEntriesQueryOptions } from "~/lib/projectReactQuery";
import { serverConfigQueryOptions, serverQueryKeys } from "~/lib/serverReactQuery";
@@ -47,7 +51,7 @@ import {
formatElapsed,
formatTimestamp,
} from "../session-logic";
import { isScrollContainerNearBottom } from "../chat-scroll";
import { AUTO_SCROLL_BOTTOM_THRESHOLD_PX, isScrollContainerNearBottom } from "../chat-scroll";
import { useStore } from "../store";
import { truncateTitle } from "../truncateTitle";
import {
@@ -130,6 +134,8 @@ function formatMessageMeta(createdAt: string, duration: string | null): string {
const LAST_EDITOR_KEY = "t3code:last-editor";
const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
const ALWAYS_UNVIRTUALIZED_TAIL_ROWS = 8;
const ATTACHMENT_PREVIEW_HANDOFF_TTL_MS = 5000;
const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`;
const IMAGE_ONLY_BOOTSTRAP_PROMPT =
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
@@ -251,6 +257,19 @@ function revokeUserMessagePreviewUrls(message: ChatMessage): void {
}
}
function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[] {
if (message.role !== "user" || !message.attachments) {
return [];
}
const previewUrls: string[] = [];
for (const attachment of message.attachments) {
if (attachment.type !== "image") continue;
if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
previewUrls.push(attachment.previewUrl);
}
return previewUrls;
}
type ComposerCommandItem =
| {
id: string;
@@ -485,14 +504,22 @@ export default function ChatView({ threadId }: ChatViewProps) {
const [nowTick, setNowTick] = useState(() => Date.now());
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
const [composerHighlightedItemId, setComposerHighlightedItemId] = useState<string | null>(null);
const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState<
Record<string, string[]>
>({});
const [lastInvokedScriptByProjectId, setLastInvokedScriptByProjectId] = useState<
Record<string, string>
>(() => readLastInvokedScriptByProjectFromStorage());
const messagesScrollRef = useRef<HTMLDivElement>(null);
const shouldAutoScrollRef = useRef(true);
const pendingAutoScrollFrameRef = useRef<number | null>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const composerFormRef = useRef<HTMLFormElement>(null);
const composerFormHeightRef = useRef(0);
const composerCommandInputRef = useRef<HTMLInputElement>(null);
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
const attachmentPreviewHandoffByMessageIdRef = useRef<Record<string, string[]>>({});
const attachmentPreviewHandoffTimeoutByMessageIdRef = useRef<Record<string, number>>({});
const sendInFlightRef = useRef(false);
const dragDepthRef = useRef(0);
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
@@ -614,18 +641,105 @@ export default function ChatView({ threadId }: ChatViewProps) {
() => derivePendingApprovals(threadActivities),
[threadActivities],
);
useEffect(() => {
attachmentPreviewHandoffByMessageIdRef.current = attachmentPreviewHandoffByMessageId;
}, [attachmentPreviewHandoffByMessageId]);
const clearAttachmentPreviewHandoffs = useCallback(() => {
for (const timeoutId of Object.values(attachmentPreviewHandoffTimeoutByMessageIdRef.current)) {
window.clearTimeout(timeoutId);
}
attachmentPreviewHandoffTimeoutByMessageIdRef.current = {};
for (const previewUrls of Object.values(attachmentPreviewHandoffByMessageIdRef.current)) {
for (const previewUrl of previewUrls) {
revokeBlobPreviewUrl(previewUrl);
}
}
attachmentPreviewHandoffByMessageIdRef.current = {};
setAttachmentPreviewHandoffByMessageId({});
}, []);
const handoffAttachmentPreviews = useCallback((messageId: MessageId, previewUrls: string[]) => {
if (previewUrls.length === 0) return;
const previousPreviewUrls = attachmentPreviewHandoffByMessageIdRef.current[messageId] ?? [];
for (const previewUrl of previousPreviewUrls) {
if (!previewUrls.includes(previewUrl)) {
revokeBlobPreviewUrl(previewUrl);
}
}
setAttachmentPreviewHandoffByMessageId((existing) => {
const next = {
...existing,
[messageId]: previewUrls,
};
attachmentPreviewHandoffByMessageIdRef.current = next;
return next;
});
const existingTimeout = attachmentPreviewHandoffTimeoutByMessageIdRef.current[messageId];
if (typeof existingTimeout === "number") {
window.clearTimeout(existingTimeout);
}
attachmentPreviewHandoffTimeoutByMessageIdRef.current[messageId] = window.setTimeout(() => {
const currentPreviewUrls = attachmentPreviewHandoffByMessageIdRef.current[messageId];
if (currentPreviewUrls) {
for (const previewUrl of currentPreviewUrls) {
revokeBlobPreviewUrl(previewUrl);
}
}
setAttachmentPreviewHandoffByMessageId((existing) => {
if (!(messageId in existing)) return existing;
const { [messageId]: _removed, ...rest } = existing;
attachmentPreviewHandoffByMessageIdRef.current = rest;
return rest;
});
delete attachmentPreviewHandoffTimeoutByMessageIdRef.current[messageId];
}, ATTACHMENT_PREVIEW_HANDOFF_TTL_MS);
}, []);
const timelineMessages = useMemo(() => {
const serverMessages = activeThread?.messages ?? [];
const serverMessagesWithPreviewHandoff =
Object.keys(attachmentPreviewHandoffByMessageId).length === 0
? serverMessages
: serverMessages.map((message) => {
if (message.role !== "user" || !message.attachments || message.attachments.length === 0) {
return message;
}
const handoffPreviewUrls = attachmentPreviewHandoffByMessageId[message.id];
if (!handoffPreviewUrls || handoffPreviewUrls.length === 0) {
return message;
}
let changed = false;
let imageIndex = 0;
const attachments = message.attachments.map((attachment) => {
if (attachment.type !== "image") {
return attachment;
}
const handoffPreviewUrl = handoffPreviewUrls[imageIndex];
imageIndex += 1;
if (!handoffPreviewUrl || attachment.previewUrl === handoffPreviewUrl) {
return attachment;
}
changed = true;
return {
...attachment,
previewUrl: handoffPreviewUrl,
};
});
return changed ? { ...message, attachments } : message;
});
if (optimisticUserMessages.length === 0) {
return serverMessages;
return serverMessagesWithPreviewHandoff;
}
const serverIds = new Set(serverMessages.map((message) => message.id));
const serverIds = new Set(serverMessagesWithPreviewHandoff.map((message) => message.id));
const pendingMessages = optimisticUserMessages.filter((message) => !serverIds.has(message.id));
if (pendingMessages.length === 0) {
return serverMessages;
return serverMessagesWithPreviewHandoff;
}
return [...serverMessages, ...pendingMessages];
}, [activeThread?.messages, optimisticUserMessages]);
return [...serverMessagesWithPreviewHandoff, ...pendingMessages];
}, [activeThread?.messages, attachmentPreviewHandoffByMessageId, optimisticUserMessages]);
const timelineEntries = useMemo(
() => deriveTimelineEntries(timelineMessages, workLogEntries),
[timelineMessages, workLogEntries],
@@ -1170,31 +1284,80 @@ export default function ChatView({ threadId }: ChatViewProps) {
// Auto-scroll on new messages
const messageCount = timelineMessages.length;
const workLogCount = workLogEntries.length;
const scrollMessagesToBottom = useCallback((behavior: ScrollBehavior = "auto") => {
const scrollContainer = messagesScrollRef.current;
if (!scrollContainer) return;
scrollContainer.scrollTo({ top: scrollContainer.scrollHeight, behavior });
shouldAutoScrollRef.current = true;
}, []);
const scheduleStickToBottom = useCallback(() => {
if (pendingAutoScrollFrameRef.current !== null) return;
pendingAutoScrollFrameRef.current = window.requestAnimationFrame(() => {
pendingAutoScrollFrameRef.current = null;
scrollMessagesToBottom();
});
}, [scrollMessagesToBottom]);
const onMessagesScroll = useCallback(() => {
const scrollContainer = messagesScrollRef.current;
if (!scrollContainer) return;
shouldAutoScrollRef.current = isScrollContainerNearBottom(scrollContainer);
}, []);
useEffect(() => {
return () => {
const frame = pendingAutoScrollFrameRef.current;
if (frame !== null) {
window.cancelAnimationFrame(frame);
}
};
}, []);
useLayoutEffect(() => {
if (!activeThread?.id) return;
scrollMessagesToBottom();
}, [activeThread?.id, scrollMessagesToBottom]);
shouldAutoScrollRef.current = true;
scheduleStickToBottom();
const timeout = window.setTimeout(() => {
const scrollContainer = messagesScrollRef.current;
if (!scrollContainer) return;
if (isScrollContainerNearBottom(scrollContainer)) return;
scheduleStickToBottom();
}, 96);
return () => {
window.clearTimeout(timeout);
};
}, [activeThread?.id, scheduleStickToBottom]);
useLayoutEffect(() => {
const composerForm = composerFormRef.current;
if (!composerForm) return;
composerFormHeightRef.current = composerForm.getBoundingClientRect().height;
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver((entries) => {
const [entry] = entries;
if (!entry) return;
const nextHeight = entry.borderBoxSize[0]?.blockSize ?? entry.contentRect.height;
const previousHeight = composerFormHeightRef.current;
composerFormHeightRef.current = nextHeight;
if (previousHeight > 0 && Math.abs(nextHeight - previousHeight) < 0.5) return;
if (!shouldAutoScrollRef.current) return;
scheduleStickToBottom();
});
observer.observe(composerForm);
return () => {
observer.disconnect();
};
}, [activeThread?.id, scheduleStickToBottom]);
useEffect(() => {
if (!shouldAutoScrollRef.current) return;
scrollMessagesToBottom("smooth");
}, [messageCount, scrollMessagesToBottom]);
scheduleStickToBottom();
}, [messageCount, scheduleStickToBottom]);
useEffect(() => {
if (phase !== "running") return;
if (!shouldAutoScrollRef.current) return;
scrollMessagesToBottom("smooth");
}, [phase, workLogCount, scrollMessagesToBottom]);
scheduleStickToBottom();
}, [phase, scheduleStickToBottom, timelineEntries]);
useEffect(() => {
setExpandedWorkGroups({});
@@ -1230,6 +1393,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
useEffect(() => {
if (!activeThread?.id) {
clearAttachmentPreviewHandoffs();
setOptimisticUserMessages((existing) => {
for (const message of existing) {
revokeUserMessagePreviewUrls(message);
@@ -1242,21 +1406,33 @@ export default function ChatView({ threadId }: ChatViewProps) {
return;
}
const serverIds = new Set(activeThread.messages.map((message) => message.id));
setOptimisticUserMessages((existing) => {
const removed = existing.filter((message) => serverIds.has(message.id));
for (const message of removed) {
revokeUserMessagePreviewUrls(message);
const removedMessages = optimisticUserMessages.filter((message) => serverIds.has(message.id));
if (removedMessages.length === 0) {
return;
}
setOptimisticUserMessages((existing) => existing.filter((message) => !serverIds.has(message.id)));
for (const removedMessage of removedMessages) {
const previewUrls = collectUserMessageBlobPreviewUrls(removedMessage);
if (previewUrls.length > 0) {
handoffAttachmentPreviews(removedMessage.id, previewUrls);
continue;
}
const next = existing.filter((message) => !serverIds.has(message.id));
return next.length === existing.length ? existing : next;
});
}, [activeThread?.id, activeThread?.messages]);
revokeUserMessagePreviewUrls(removedMessage);
}
}, [
activeThread?.id,
activeThread?.messages,
clearAttachmentPreviewHandoffs,
handoffAttachmentPreviews,
optimisticUserMessages,
]);
useEffect(() => {
promptRef.current = prompt;
}, [prompt]);
useEffect(() => {
clearAttachmentPreviewHandoffs();
setOptimisticUserMessages((existing) => {
for (const message of existing) {
revokeUserMessagePreviewUrls(message);
@@ -1268,7 +1444,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
dragDepthRef.current = 0;
setIsDragOverComposer(false);
setExpandedImage(null);
}, [threadId]);
}, [clearAttachmentPreviewHandoffs, threadId]);
useEffect(() => {
let cancelled = false;
@@ -1760,6 +1936,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
streaming: false,
},
]);
// Sending a message should always bring the latest user turn into view.
shouldAutoScrollRef.current = true;
scheduleStickToBottom();
setThreadError(threadIdForSend, null);
promptRef.current = "";
@@ -2185,6 +2364,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
onScroll={onMessagesScroll}
>
<MessagesTimeline
key={activeThread.id}
hasMessages={timelineMessages.length > 0}
isWorking={isWorking}
activeTurnInProgress={!latestTurnSettled}
@@ -2209,6 +2389,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
{/* Input bar */}
<div className={cn("px-3 pt-1.5 sm:px-5 sm:pt-2", isGitRepo ? "pb-1" : "pb-3 sm:pb-4")}>
<form
ref={composerFormRef}
onSubmit={onSend}
className="mx-auto w-full min-w-fit max-w-3xl"
data-chat-composer-form="true"
@@ -2804,6 +2985,20 @@ type TimelineRow =
}
| { kind: "working"; id: string; createdAt: string | null };
function estimateTimelineMessageHeight(message: TimelineMessage): number {
const textLength = message.text.length;
if (message.role === "assistant") {
const estimatedLines = Math.max(1, Math.ceil(textLength / 72));
return 78 + Math.min(estimatedLines * 22, 820);
}
const estimatedLines = Math.max(1, Math.ceil(textLength / 56));
const attachmentCount = message.attachments?.length ?? 0;
const attachmentRows = Math.ceil(attachmentCount / 2);
const attachmentHeight = attachmentRows * 124;
return 96 + Math.min(estimatedLines * 22, 620) + attachmentHeight;
}
const MessagesTimeline = memo(function MessagesTimeline({
hasMessages,
isWorking,
@@ -2875,7 +3070,8 @@ const MessagesTimeline = memo(function MessagesTimeline({
}, [timelineEntries, completionDividerBeforeEntryId, isWorking, activeTurnStartedAt]);
const firstUnvirtualizedRowIndex = useMemo(() => {
if (!activeTurnInProgress) return rows.length;
const firstTailRowIndex = Math.max(rows.length - ALWAYS_UNVIRTUALIZED_TAIL_ROWS, 0);
if (!activeTurnInProgress) return firstTailRowIndex;
const turnStartedAtMs =
typeof activeTurnStartedAt === "string" ? Date.parse(activeTurnStartedAt) : Number.NaN;
@@ -2895,22 +3091,20 @@ const MessagesTimeline = memo(function MessagesTimeline({
);
}
if (firstCurrentTurnRowIndex < 0) {
return rows.length;
}
if (firstCurrentTurnRowIndex < 0) return firstTailRowIndex;
for (let index = firstCurrentTurnRowIndex - 1; index >= 0; index -= 1) {
const previousRow = rows[index];
if (!previousRow || previousRow.kind !== "message") continue;
if (previousRow.message.role === "user") {
return index;
return Math.min(index, firstTailRowIndex);
}
if (previousRow.message.role === "assistant" && !previousRow.message.streaming) {
break;
}
}
return firstCurrentTurnRowIndex;
return Math.min(firstCurrentTurnRowIndex, firstTailRowIndex);
}, [activeTurnInProgress, activeTurnStartedAt, rows]);
const virtualizedRowCount = clamp(firstUnvirtualizedRowIndex, {
@@ -2921,16 +3115,46 @@ const MessagesTimeline = memo(function MessagesTimeline({
const rowVirtualizer = useVirtualizer({
count: virtualizedRowCount,
getScrollElement: () => scrollContainerRef.current,
// Use stable row ids so virtual measurements do not leak across thread switches.
getItemKey: (index: number) => rows[index]?.id ?? index,
estimateSize: (index: number) => {
const row = rows[index];
if (!row) return 96;
if (row.kind === "work") return 112;
if (row.kind === "working") return 40;
return row.message.role === "assistant" ? 220 : 170;
return estimateTimelineMessageHeight(row.message);
},
measureElement: (element: HTMLElement) => element.getBoundingClientRect().height,
measureElement: measureVirtualElement,
useAnimationFrameWithResizeObserver: true,
overscan: 8,
});
useEffect(() => {
rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = (_item, _delta, instance) => {
const viewportHeight = instance.scrollRect?.height ?? 0;
const scrollOffset = instance.scrollOffset ?? 0;
const remainingDistance = instance.getTotalSize() - (scrollOffset + viewportHeight);
return remainingDistance > AUTO_SCROLL_BOTTOM_THRESHOLD_PX;
};
return () => {
rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = undefined;
};
}, [rowVirtualizer]);
const pendingMeasureFrameRef = useRef<number | null>(null);
const onTimelineImageLoad = useCallback(() => {
if (pendingMeasureFrameRef.current !== null) return;
pendingMeasureFrameRef.current = window.requestAnimationFrame(() => {
pendingMeasureFrameRef.current = null;
rowVirtualizer.measure();
});
}, [rowVirtualizer]);
useEffect(() => {
return () => {
const frame = pendingMeasureFrameRef.current;
if (frame !== null) {
window.cancelAnimationFrame(frame);
}
};
}, []);
const virtualRows = rowVirtualizer.getVirtualItems();
const nonVirtualizedRows = rows.slice(virtualizedRowCount);
@@ -3022,6 +3246,8 @@ const MessagesTimeline = memo(function MessagesTimeline({
src={image.previewUrl}
alt={image.name}
className="h-full max-h-[220px] w-full cursor-zoom-in object-cover"
onLoad={onTimelineImageLoad}
onError={onTimelineImageLoad}
onClick={() => {
const preview = buildExpandedImagePreview(userImages, image.id);
if (!preview) return;
+9 -11
View File
@@ -171,7 +171,7 @@ function T3Wordmark() {
return (
<svg
aria-label="T3"
className="h-3 w-auto shrink-0 text-foreground"
className="h-2.5 w-auto shrink-0 text-foreground"
viewBox="15.5309 37 94.3941 56.96"
xmlns="http://www.w3.org/2000/svg"
>
@@ -312,7 +312,7 @@ export default function Sidebar() {
const status = target.cwd ? statusByCwd.get(target.cwd) : undefined;
const branchMatches =
target.branch !== null && status?.branch !== null && status?.branch === target.branch;
map.set(target.threadId, branchMatches ? status?.pr ?? null : null);
map.set(target.threadId, branchMatches ? (status?.pr ?? null) : null);
}
return map;
}, [threadGitStatusCwds, threadGitStatusQueries, threadGitTargets]);
@@ -689,9 +689,7 @@ export default function Sidebar() {
void handleNewThread(projectId, {
branch: activeThread?.branch ?? activeDraftThread?.branch ?? null,
worktreePath: activeThread?.worktreePath ?? activeDraftThread?.worktreePath ?? null,
envMode:
activeDraftThread?.envMode ??
(activeThread?.worktreePath ? "worktree" : "local"),
envMode: activeDraftThread?.envMode ?? (activeThread?.worktreePath ? "worktree" : "local"),
});
};
@@ -711,14 +709,14 @@ export default function Sidebar() {
};
const wordmark = (
<div className={`flex items-center gap-2 ${isElectron ? "-translate-y-px" : ""}`}>
<div className="flex items-center gap-2">
<SidebarTrigger className="shrink-0 md:hidden" />
<div className="flex min-w-0 flex-1 items-center gap-1">
<div className="flex min-w-0 flex-1 items-center gap-1 mt-2 ml-1">
<T3Wordmark />
<span className="truncate text-base font-medium tracking-tight text-muted-foreground">
<span className="truncate text-sm font-medium tracking-tight text-muted-foreground">
Code
</span>
<span className="rounded-full bg-muted/50 px-1.5 py-0.5 text-[9px] font-medium uppercase tracking-widest text-muted-foreground/60">
<span className="rounded-full bg-muted/50 px-1.5 py-0.5 text-[8px] font-medium uppercase tracking-[0.18em] text-muted-foreground/60">
{APP_STAGE_LABEL}
</span>
</div>
@@ -740,10 +738,10 @@ export default function Sidebar() {
<>
{isElectron ? (
<>
<SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[88px]">
<SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[82px]">
{wordmark}
</SidebarHeader>
<div className="px-4 pb-2">{newThreadButton}</div>
<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">
+4 -4
View File
@@ -16,7 +16,7 @@
},
"apps/desktop": {
"name": "@t3tools/desktop",
"version": "0.0.0",
"version": "0.0.0-alpha.4",
"dependencies": {
"electron": "40.6.0",
},
@@ -32,7 +32,7 @@
},
"apps/server": {
"name": "t3",
"version": "0.1.0",
"version": "0.0.0-alpha.4",
"bin": {
"t3": "./dist/index.mjs",
},
@@ -60,7 +60,7 @@
},
"apps/web": {
"name": "@t3tools/web",
"version": "0.0.0",
"version": "0.0.0-alpha.4",
"dependencies": {
"@base-ui/react": "^1.2.0",
"@pierre/diffs": "^1.1.0-beta.16",
@@ -96,7 +96,7 @@
},
"packages/contracts": {
"name": "@t3tools/contracts",
"version": "0.0.0",
"version": "0.0.0-alpha.4",
"dependencies": {
"effect": "catalog:",
},
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/contracts",
"version": "0.0.0",
"version": "0.0.0-alpha.4",
"private": true,
"files": [
"dist"
+2
View File
@@ -99,6 +99,7 @@ interface ResolvedBuildOptions {
interface StagePackageJson {
readonly name: string;
readonly version: string;
readonly buildVersion: string;
readonly private: true;
readonly description: string;
readonly author: string;
@@ -488,6 +489,7 @@ const buildDesktopArtifact = Effect.fn(function* (options: ResolvedBuildOptions)
const stagePackageJson: StagePackageJson = {
name: "t3-code-desktop",
version: appVersion,
buildVersion: appVersion,
private: true,
description: "T3 Code desktop build",
author: "T3 Tools",
+165 -14
View File
@@ -1,4 +1,5 @@
import { spawn } from "node:child_process";
import net from "node:net";
import { homedir } from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
@@ -6,6 +7,7 @@ import { pathToFileURL } from "node:url";
const BASE_SERVER_PORT = 3773;
const BASE_WEB_PORT = 5733;
const MAX_HASH_OFFSET = 3000;
const MAX_PORT = 65535;
export const DEFAULT_DEV_STATE_DIR = path.join(homedir(), ".t3", "dev");
const MODE_ARGS = {
dev: [
@@ -209,7 +211,133 @@ export function createDevRunnerEnv({ mode, env, offset, envOverrides }) {
return output;
}
export function runDevRunner(argv = process.argv) {
function portPairForOffset(offset) {
return {
serverPort: BASE_SERVER_PORT + offset,
webPort: BASE_WEB_PORT + offset,
};
}
async function canListenOnHost(port, host) {
return await new Promise((resolve) => {
const server = net.createServer();
server.unref();
server.once("error", (error) => {
const code = error?.code;
if (code === "EADDRNOTAVAIL") {
// Host family unavailable on this machine (for example, no IPv6 loopback).
resolve(true);
return;
}
resolve(false);
});
server.once("listening", () => {
server.close(() => {
resolve(true);
});
});
server.listen({ host, port });
});
}
async function isPortAvailable(port) {
// Vite/dev traffic uses localhost loopback. Verify both IPv4 and IPv6 loopback
// so we don't pick a port that fails later on one address family.
const [ipv4, ipv6] = await Promise.all([
canListenOnHost(port, "127.0.0.1"),
canListenOnHost(port, "::1"),
]);
return ipv4 && ipv6;
}
const defaultCheckPortAvailability = isPortAvailable;
export async function findFirstAvailableOffset({
startOffset,
requireServerPort,
requireWebPort,
checkPortAvailability = defaultCheckPortAvailability,
}) {
for (let candidate = startOffset; ; candidate += 1) {
const { serverPort, webPort } = portPairForOffset(candidate);
const serverPortOutOfRange = serverPort > MAX_PORT;
const webPortOutOfRange = webPort > MAX_PORT;
if (
(requireServerPort && serverPortOutOfRange) ||
(requireWebPort && webPortOutOfRange) ||
(!requireServerPort && !requireWebPort && (serverPortOutOfRange || webPortOutOfRange))
) {
break;
}
const checks = [];
if (requireServerPort) {
checks.push(checkPortAvailability(serverPort));
}
if (requireWebPort) {
checks.push(checkPortAvailability(webPort));
}
if (checks.length === 0) {
return candidate;
}
const availability = await Promise.all(checks);
if (availability.every(Boolean)) {
return candidate;
}
}
throw new Error(
`No available dev ports found from offset ${startOffset}. Tried server=${BASE_SERVER_PORT}+n web=${BASE_WEB_PORT}+n up to port ${MAX_PORT}.`,
);
}
export async function resolveModePortOffsets({
mode,
startOffset,
envOverrides,
checkPortAvailability,
}) {
const hasExplicitServerPort = typeof envOverrides.T3CODE_PORT === "string";
const hasExplicitDevUrl = typeof envOverrides.VITE_DEV_SERVER_URL === "string";
if (mode === "dev:web") {
if (hasExplicitDevUrl) {
return { serverOffset: startOffset, webOffset: startOffset };
}
const webOffset = await findFirstAvailableOffset({
startOffset,
requireServerPort: false,
requireWebPort: true,
checkPortAvailability,
});
return { serverOffset: startOffset, webOffset };
}
if (mode === "dev:server") {
if (hasExplicitServerPort) {
return { serverOffset: startOffset, webOffset: startOffset };
}
const serverOffset = await findFirstAvailableOffset({
startOffset,
requireServerPort: true,
requireWebPort: false,
checkPortAvailability,
});
return { serverOffset, webOffset: serverOffset };
}
const sharedOffset = await findFirstAvailableOffset({
startOffset,
requireServerPort: !hasExplicitServerPort,
requireWebPort: !hasExplicitDevUrl,
checkPortAvailability,
});
return { serverOffset: sharedOffset, webOffset: sharedOffset };
}
export async function runDevRunner(argv = process.argv) {
const mode = argv[2];
const parsedArgs = parseDevRunnerArgs(argv.slice(3));
if (!mode || !(mode in MODE_ARGS)) {
@@ -218,24 +346,49 @@ export function runDevRunner(argv = process.argv) {
}
const { offset, source } = resolveOffset();
const serverPort = BASE_SERVER_PORT + offset;
const webPort = BASE_WEB_PORT + offset;
const { serverOffset, webOffset } = await resolveModePortOffsets({
mode,
startOffset: offset,
envOverrides: parsedArgs.envOverrides,
});
if (serverPort > 65535 || webPort > 65535) {
throw new Error(
`Port offset too large (${offset}). Computed ports: server=${serverPort}, web=${webPort}`,
);
const mergedEnvOverrides = { ...parsedArgs.envOverrides };
if (!("VITE_DEV_SERVER_URL" in mergedEnvOverrides)) {
const { webPort } = portPairForOffset(webOffset);
mergedEnvOverrides.PORT = String(webPort);
mergedEnvOverrides.ELECTRON_RENDERER_PORT = String(webPort);
mergedEnvOverrides.VITE_DEV_SERVER_URL = `http://localhost:${webPort}`;
}
const env = createDevRunnerEnv({
mode,
env: process.env,
offset,
envOverrides: parsedArgs.envOverrides,
offset: serverOffset,
envOverrides: mergedEnvOverrides,
});
const parsedServerPort = Number(env.T3CODE_PORT);
const parsedWebPort = Number(env.PORT);
if (
!Number.isInteger(parsedServerPort) ||
parsedServerPort < 1 ||
parsedServerPort > MAX_PORT ||
!Number.isInteger(parsedWebPort) ||
parsedWebPort < 1 ||
parsedWebPort > MAX_PORT
) {
throw new Error(
`Invalid computed dev ports: server='${String(env.T3CODE_PORT)}' web='${String(env.PORT)}'.`,
);
}
const selectionSuffix =
serverOffset !== offset || webOffset !== offset
? ` selectedOffset(server=${serverOffset},web=${webOffset})`
: "";
console.info(
`[dev-runner] mode=${mode} source=${source} serverPort=${serverPort} webPort=${webPort} stateDir=${env.T3CODE_STATE_DIR}`,
`[dev-runner] mode=${mode} source=${source}${selectionSuffix} serverPort=${parsedServerPort} webPort=${parsedWebPort} stateDir=${env.T3CODE_STATE_DIR}`,
);
if (parsedArgs.isDryRun) {
@@ -265,10 +418,8 @@ export function runDevRunner(argv = process.argv) {
const entrypointPath = process.argv[1] ? pathToFileURL(process.argv[1]).href : "";
if (import.meta.url === entrypointPath) {
try {
runDevRunner();
} catch (error) {
runDevRunner().catch((error) => {
console.error("[dev-runner]", error);
process.exit(1);
}
});
}
+98
View File
@@ -3,7 +3,9 @@ import { describe, expect, it } from "vitest";
import {
DEFAULT_DEV_STATE_DIR,
createDevRunnerEnv,
findFirstAvailableOffset,
parseDevRunnerArgs,
resolveModePortOffsets,
} from "./dev-runner.mjs";
describe("parseDevRunnerArgs", () => {
@@ -123,3 +125,99 @@ describe("createDevRunnerEnv", () => {
).toThrow("Invalid T3CODE_PORT override");
});
});
describe("findFirstAvailableOffset", () => {
it("returns the starting offset when required ports are available", async () => {
const offset = await findFirstAvailableOffset({
startOffset: 0,
requireServerPort: true,
requireWebPort: true,
checkPortAvailability: async () => true,
});
expect(offset).toBe(0);
});
it("advances until all required ports are available", async () => {
const taken = new Set([3773, 5733, 3774, 5734]);
const offset = await findFirstAvailableOffset({
startOffset: 0,
requireServerPort: true,
requireWebPort: true,
checkPortAvailability: async (port) => !taken.has(port),
});
expect(offset).toBe(2);
});
it("allows offsets where only non-required ports exceed max", async () => {
const offset = await findFirstAvailableOffset({
startOffset: 59_803,
requireServerPort: true,
requireWebPort: false,
checkPortAvailability: async () => true,
});
expect(offset).toBe(59_803);
});
});
describe("resolveModePortOffsets", () => {
it("uses a shared fallback offset for dev mode", async () => {
const taken = new Set([3773, 5733]);
const offsets = await resolveModePortOffsets({
mode: "dev",
startOffset: 0,
envOverrides: {},
checkPortAvailability: async (port) => !taken.has(port),
});
expect(offsets).toEqual({ serverOffset: 1, webOffset: 1 });
});
it("keeps server offset stable for dev:web and only shifts web offset", async () => {
const taken = new Set([5733]);
const offsets = await resolveModePortOffsets({
mode: "dev:web",
startOffset: 0,
envOverrides: {},
checkPortAvailability: async (port) => !taken.has(port),
});
expect(offsets).toEqual({ serverOffset: 0, webOffset: 1 });
});
it("shifts only server offset for dev:server", async () => {
const taken = new Set([3773]);
const offsets = await resolveModePortOffsets({
mode: "dev:server",
startOffset: 0,
envOverrides: {},
checkPortAvailability: async (port) => !taken.has(port),
});
expect(offsets).toEqual({ serverOffset: 1, webOffset: 1 });
});
it("respects explicit dev-url override for dev:web", async () => {
const offsets = await resolveModePortOffsets({
mode: "dev:web",
startOffset: 0,
envOverrides: { VITE_DEV_SERVER_URL: "http://localhost:9999" },
checkPortAvailability: async () => false,
});
expect(offsets).toEqual({ serverOffset: 0, webOffset: 0 });
});
it("respects explicit server port override for dev:server", async () => {
const offsets = await resolveModePortOffsets({
mode: "dev:server",
startOffset: 0,
envOverrides: { T3CODE_PORT: "4888" },
checkPortAvailability: async () => false,
});
expect(offsets).toEqual({ serverOffset: 0, webOffset: 0 });
});
});