Compare commits

..
Author SHA1 Message Date
Julius Marminge d3aa5ae0aa Fix diff panel padding and top spacing for virtualized files
- Use horizontal and bottom padding on the diff render surface
- Add top margin to the first diff file for consistent spacing
2026-03-01 10:30:46 -08:00
Julius Marminge 540e7a3995 Keep diff panel header sticky while scrolling
- Make the diffs header stick to the top of the panel
- Add header background and bottom border for readability
2026-02-28 23:28:38 -08:00
Julius Marminge 1af43dbf90 Handle remote checkout conflicts without duplicate local branch
- fall back to plain checkout (detached HEAD) when `--track` would clash with an existing local branch
- add GitCore coverage for the conflict fallback path
- simplify branch-name derivation in BranchToolbar to consistently strip the first remote segment
2026-02-28 21:56:22 -08:00
Julius Marminge 16fed12dcc Handle remote lookup failures in branch listing
- Fall back to empty remote branch and remote name data when git remote queries fail
- Log warnings instead of failing `listBranches`
- Add integration test covering remote lookup failure fallback
2026-02-28 21:56:22 -08:00
Julius Marminge 29825f2f8a Filter detached HEAD pseudo-refs from branch listings
- ignore branch lines starting with `(` when parsing `git branch` output
- add integration test to verify detached HEAD does not appear as a branch
2026-02-28 21:56:22 -08:00
Julius Marminge efcee4b863 Handle branch checkout and dedupe for slash-named remotes
- add `remoteName` to git branch contract metadata
- resolve remote refs using full remote names (including slashes)
- avoid fallback to wrong local checkout when remote ref is missing
- update branch toolbar logic/tests to map and dedupe remote branches correctly
2026-02-28 21:56:22 -08:00
Julius Marminge 26edcab8b4 Reorder sidebar thread status badges and title layout
- Move PR status indicator into the main thread info row
- Keep thread status badge and title grouped for consistent alignment
2026-02-28 21:56:22 -08:00
Julius Marminge c626892adf Hide duplicate remote branches when local branch exists
- Deduplicate branch list by removing remote refs that match an existing local branch
- Move remote-ref local-name derivation into shared BranchToolbar logic
- Add logic tests for remote-ref parsing and deduplication behavior
2026-02-28 21:56:22 -08:00
Julius Marminge 3c66cdf2fe Support remote branch listing and tracking checkout flow
- Include remote refs in branch listings, ordered after local branches
- Auto-track remote branches on checkout when no local branch exists
- Update branch picker to label remote branches and store local branch name after checkout
2026-02-28 21:56:22 -08:00
Julius Marminge db31c36213 Open diff files in editor from diff header clicks
- Add click handling on diff file headers (`data-title`) to open files via native `openInEditor`
- Resolve file paths against active thread/project cwd before launching editor
- Add header hover affordance and tighten diff panel spacing
2026-02-28 21:30:05 -08:00
Julius Marminge cafe3352f1 Remove redundant PR status title attribute
- Drop `title` from the PR status button in `Sidebar` to avoid duplicate tooltip text
2026-02-28 16:24:03 -08:00
Julius Marminge 7a39ce34fa Avoid popup-open false errors on mobile browsers
- Stop throwing when `window.open` returns `null` in `wsNativeApi`
- Keep opening external links in a new tab and rely on browser popup policy
2026-02-28 16:24:03 -08:00
Julius Marmingeandcodex 483702df77 Add clickable PR status tooltip in sidebar threads
- Show PR number/title in a tooltip on each thread PR icon
- Open PR links externally from the sidebar and show error toasts on failure
- Improve thread row keyboard handling after switching to a non-button render

Co-authored-by: codex <[email protected]>
2026-02-28 16:24:03 -08:00
37 changed files with 846 additions and 2454 deletions

No files matched your search

-6
View File
@@ -4,7 +4,6 @@ T3 Code is a minimal web GUI for coding agents. Currently Codex-first, with Clau
Run `npx t3` in any project directory to launch the web interface.
Run `bun run dev:desktop` to launch the Electron desktop app in this monorepo.
Run `bun run dev:mobile` to launch the Expo mobile client alongside the backend.
## Architecture
@@ -33,7 +32,6 @@ T3 Code runs as a **Node.js WebSocket server** that wraps `codex app-server` (JS
- `/apps/server`: Node.js WebSocket server. Wraps Codex app-server, serves the built web app, and opens the browser on start.
- `/apps/web`: React + Vite UI. Session control, conversation, and provider event rendering. Connects to the server via WebSocket.
- `/apps/desktop`: Electron shell. Spawns a desktop-scoped `t3` backend process and loads the shared web app.
- `/apps/mobile`: Expo React Native client with Uniwind styling. Supports saved backend profiles and connects directly to the server over WebSocket.
- `/packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
## Codex prerequisites
@@ -51,9 +49,6 @@ bun run dev
# Desktop development
bun run dev:desktop
# Mobile development (Expo + backend server)
bun run dev:mobile
# Desktop development on an isolated port set
T3CODE_DEV_INSTANCE=feature-xyz bun run dev:desktop
@@ -73,7 +68,6 @@ npx t3
- `bun run dev` — Starts contracts, server, and web in `turbo watch` mode.
- `bun run dev:server` — Starts just the WebSocket server (uses Bun TypeScript execution).
- `bun run dev:web` — Starts just the Vite dev server for the web app.
- `bun run dev:mobile` — Starts the backend server and Expo mobile app in parallel.
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
`bun run dev -- --state-dir ~/.t3/another-dev-state`
-41
View File
@@ -1,41 +0,0 @@
# Learn more https://docs.github.com/en/get-started/getting-started-with-git/ignoring-files
# dependencies
node_modules/
# Expo
.expo/
dist/
web-build/
expo-env.d.ts
# Native
.kotlin/
*.orig.*
*.jks
*.p8
*.p12
*.key
*.mobileprovision
# Metro
.metro-health-check*
# debug
npm-debug.*
yarn-debug.*
yarn-error.*
# macOS
.DS_Store
*.pem
# local env files
.env*.local
# typescript
*.tsbuildinfo
# generated native folders
/ios
/android
-3
View File
@@ -1,3 +0,0 @@
import "./src/global.css";
export { default } from "./src/App";
-37
View File
@@ -1,37 +0,0 @@
import type { ExpoConfig } from "expo/config";
const DEV_ICON = "./assets/t3-blueprint-icon.png";
const PROD_ICON = "./assets/t3-icon.png";
const isDevelopment = process.env.NODE_ENV !== "production";
const iconPath = isDevelopment ? DEV_ICON : PROD_ICON;
const config: ExpoConfig = {
name: "T3 Code Mobile",
slug: "t3-code-mobile",
version: "0.1.0",
orientation: "portrait",
icon: iconPath,
userInterfaceStyle: "automatic",
splash: {
image: iconPath,
resizeMode: "contain",
backgroundColor: "#f8fafc",
},
ios: {
supportsTablet: true,
},
android: {
adaptiveIcon: {
backgroundColor: "#E6F4FE",
foregroundImage: iconPath,
monochromeImage: iconPath,
},
predictiveBackGestureEnabled: false,
},
web: {
favicon: iconPath,
},
};
export default config;
Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 384 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

-13
View File
@@ -1,13 +0,0 @@
module.exports = function (api) {
api.cache(true);
return {
presets: [
[
"babel-preset-expo",
{
unstable_transformImportMeta: true,
},
],
],
};
};
-8
View File
@@ -1,8 +0,0 @@
import { registerRootComponent } from 'expo';
import App from './App';
// registerRootComponent calls AppRegistry.registerComponent('main', () => App);
// It also ensures that whether you load the app in Expo Go or in a native build,
// the environment is set up appropriately
registerRootComponent(App);
-9
View File
@@ -1,9 +0,0 @@
const { getDefaultConfig } = require("expo/metro-config");
const { withUniwindConfig } = require("uniwind/metro");
const config = getDefaultConfig(__dirname);
module.exports = withUniwindConfig(config, {
cssEntryFile: "./src/global.css",
dtsFile: "./.expo/uniwind-types.d.ts",
});
-33
View File
@@ -1,33 +0,0 @@
{
"name": "@t3tools/mobile",
"version": "0.0.0",
"private": true,
"main": "index.ts",
"scripts": {
"dev": "expo start",
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web",
"typecheck": "tsc --noEmit",
"test": "vitest run --passWithNoTests"
},
"dependencies": {
"@react-native-async-storage/async-storage": "^2.2.0",
"@t3tools/contracts": "workspace:*",
"@tanstack/react-query": "^5.90.0",
"effect": "catalog:",
"expo": "~55.0.4",
"expo-status-bar": "~55.0.4",
"react": "19.2.0",
"react-native": "0.83.2",
"tailwindcss": "^4.1.17",
"uniwind": "^1.4.0"
},
"devDependencies": {
"babel-preset-expo": "^55.0.10",
"@types/react": "~19.2.2",
"typescript": "~5.9.2",
"vitest": "^4.0.0"
}
}
-500
View File
@@ -1,500 +0,0 @@
import { QueryClient, QueryClientProvider, useQuery, useQueryClient } from "@tanstack/react-query";
import type { OrchestrationEvent, OrchestrationReadModel, WsWelcomePayload } from "@t3tools/contracts";
import { StatusBar } from "expo-status-bar";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
ActivityIndicator,
Pressable,
SafeAreaView,
ScrollView,
Text,
TextInput,
View,
} from "react-native";
import {
createBackendProfileId,
loadBackendState,
normalizeBackendInput,
saveBackendProfiles,
setActiveBackendProfileId,
type BackendProfile,
} from "./backendProfiles";
import { T3MobileClient } from "./t3MobileClient";
import type { TransportStatus } from "./wsTransport";
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 5_000,
retry: 1,
},
},
});
type ThemeButtonVariant = "primary" | "ghost" | "danger";
function ThemeButton(props: {
readonly label: string;
readonly onPress: () => void;
readonly disabled?: boolean;
readonly variant?: ThemeButtonVariant;
}) {
const { label, onPress, disabled = false, variant = "primary" } = props;
const backgroundClassName =
variant === "primary"
? "bg-blue-600"
: variant === "danger"
? "bg-red-600"
: "bg-slate-200";
const textClassName = variant === "ghost" ? "text-slate-700" : "text-white";
return (
<Pressable
className={`h-11 items-center justify-center rounded-xl px-4 ${backgroundClassName} ${disabled ? "opacity-50" : "opacity-100"}`}
disabled={disabled}
onPress={onPress}
>
<Text className={`text-sm font-semibold ${textClassName}`}>{label}</Text>
</Pressable>
);
}
function SectionCard(props: { readonly title: string; readonly children: React.ReactNode }) {
return (
<View className="gap-3 rounded-2xl border border-slate-200 bg-white p-4">
<Text className="text-xs font-semibold uppercase tracking-[1.5px] text-slate-500">{props.title}</Text>
{props.children}
</View>
);
}
function statusLabel(status: TransportStatus): string {
if (status.state === "connected") return "Connected";
if (status.state === "connecting") return "Connecting";
if (status.state === "error") return "Connection Error";
return "Disconnected";
}
function statusClassName(status: TransportStatus): string {
if (status.state === "connected") return "bg-emerald-100 text-emerald-700";
if (status.state === "connecting") return "bg-amber-100 text-amber-700";
if (status.state === "error") return "bg-red-100 text-red-700";
return "bg-slate-200 text-slate-700";
}
function formatDate(iso: string | null | undefined): string {
if (!iso) return "-";
const value = new Date(iso);
if (Number.isNaN(value.getTime())) return "-";
return value.toLocaleString();
}
function formatEventType(event: OrchestrationEvent): string {
const eventRecord = event as Record<string, unknown>;
if (typeof eventRecord.type === "string") return eventRecord.type;
return "event";
}
function formatEventTimestamp(event: OrchestrationEvent): string {
const eventRecord = event as Record<string, unknown>;
if (typeof eventRecord.createdAt === "string") return formatDate(eventRecord.createdAt);
return "";
}
function eventKey(event: OrchestrationEvent): string {
const eventRecord = event as Record<string, unknown>;
if (typeof eventRecord.eventId === "string") return eventRecord.eventId;
if (typeof eventRecord.id === "string") return eventRecord.id;
return `${formatEventType(event)}-${formatEventTimestamp(event)}`;
}
function AppContent() {
const queryClient = useQueryClient();
const cleanupRef = useRef<(() => void) | null>(null);
const [profiles, setProfiles] = useState<BackendProfile[]>([]);
const [activeProfileId, setActiveProfileId] = useState<string | null>(null);
const [initialActiveProfileId, setInitialActiveProfileId] = useState<string | null>(null);
const [loadingProfiles, setLoadingProfiles] = useState(true);
const [wsUrlInput, setWsUrlInput] = useState("");
const [authTokenInput, setAuthTokenInput] = useState("");
const [client, setClient] = useState<T3MobileClient | null>(null);
const [connectionStatus, setConnectionStatus] = useState<TransportStatus>({
state: "disconnected",
});
const [welcome, setWelcome] = useState<WsWelcomePayload | null>(null);
const [recentEvents, setRecentEvents] = useState<OrchestrationEvent[]>([]);
const [uiError, setUiError] = useState<string | null>(null);
const activeProfile = useMemo(
() => profiles.find((profile) => profile.id === activeProfileId) ?? null,
[activeProfileId, profiles],
);
const snapshotQuery = useQuery<OrchestrationReadModel>({
queryKey: ["orchestration.snapshot", activeProfileId],
queryFn: async () => {
if (!client) {
throw new Error("No active backend connection.");
}
return client.getSnapshot();
},
enabled: client !== null && activeProfileId !== null,
refetchInterval: connectionStatus.state === "connected" ? 10_000 : false,
});
const disconnectFromBackend = useCallback(async () => {
cleanupRef.current?.();
cleanupRef.current = null;
setClient(null);
setActiveProfileId(null);
setWelcome(null);
setRecentEvents([]);
setConnectionStatus({ state: "disconnected" });
await setActiveBackendProfileId(null);
queryClient.removeQueries({ queryKey: ["orchestration.snapshot"] });
}, [queryClient]);
const connectToProfile = useCallback(
async (profile: BackendProfile) => {
setUiError(null);
cleanupRef.current?.();
cleanupRef.current = null;
setWelcome(null);
setRecentEvents([]);
setConnectionStatus({ state: "connecting" });
const nextClient = new T3MobileClient({
profile,
onStatus: (status) => {
setConnectionStatus(status);
},
});
const unsubscribeWelcome = nextClient.onWelcome((payload) => {
setWelcome(payload);
});
const unsubscribeDomainEvents = nextClient.onDomainEvent((event) => {
setRecentEvents((current) => [event, ...current].slice(0, 60));
void queryClient.invalidateQueries({ queryKey: ["orchestration.snapshot", profile.id] });
});
cleanupRef.current = () => {
unsubscribeWelcome();
unsubscribeDomainEvents();
nextClient.dispose();
};
setClient(nextClient);
setActiveProfileId(profile.id);
await setActiveBackendProfileId(profile.id);
const now = new Date().toISOString();
setProfiles((current) => {
const nextProfiles = current.map((candidate) =>
candidate.id === profile.id ? { ...candidate, lastConnectedAt: now } : candidate,
);
void saveBackendProfiles(nextProfiles);
return nextProfiles;
});
void queryClient.invalidateQueries({ queryKey: ["orchestration.snapshot", profile.id] });
},
[queryClient],
);
const saveAndConnectProfile = useCallback(async () => {
try {
setUiError(null);
const normalized = normalizeBackendInput(wsUrlInput, authTokenInput);
const now = new Date().toISOString();
const existing = profiles.find(
(profile) => profile.url === normalized.url && (profile.authToken ?? "") === (normalized.authToken ?? ""),
);
const profile: BackendProfile = existing
? {
...existing,
name: normalized.name,
}
: {
id: createBackendProfileId(),
name: normalized.name,
url: normalized.url,
authToken: normalized.authToken,
createdAt: now,
lastConnectedAt: null,
};
const nextProfiles = existing
? profiles.map((candidate) => (candidate.id === existing.id ? profile : candidate))
: [profile, ...profiles];
setProfiles(nextProfiles);
await saveBackendProfiles(nextProfiles);
await connectToProfile(profile);
setWsUrlInput("");
setAuthTokenInput("");
} catch (error) {
setUiError(error instanceof Error ? error.message : "Unable to save backend profile.");
}
}, [authTokenInput, connectToProfile, profiles, wsUrlInput]);
const removeProfile = useCallback(
async (profileId: string) => {
const nextProfiles = profiles.filter((profile) => profile.id !== profileId);
setProfiles(nextProfiles);
await saveBackendProfiles(nextProfiles);
if (activeProfileId === profileId) {
await disconnectFromBackend();
}
if (initialActiveProfileId === profileId) {
setInitialActiveProfileId(null);
}
},
[activeProfileId, disconnectFromBackend, initialActiveProfileId, profiles],
);
useEffect(() => {
let cancelled = false;
void (async () => {
const state = await loadBackendState();
if (cancelled) return;
setProfiles(state.profiles);
setInitialActiveProfileId(state.activeProfileId);
setLoadingProfiles(false);
})();
return () => {
cancelled = true;
cleanupRef.current?.();
cleanupRef.current = null;
};
}, []);
useEffect(() => {
if (loadingProfiles || !initialActiveProfileId) return;
const profile = profiles.find((candidate) => candidate.id === initialActiveProfileId);
setInitialActiveProfileId(null);
if (profile) {
void connectToProfile(profile);
}
}, [connectToProfile, initialActiveProfileId, loadingProfiles, profiles]);
const snapshotError = snapshotQuery.error instanceof Error ? snapshotQuery.error.message : null;
const snapshot = snapshotQuery.data;
if (loadingProfiles) {
return (
<SafeAreaView className="flex-1 items-center justify-center bg-slate-100">
<ActivityIndicator size="small" color="#334155" />
<Text className="mt-3 text-sm text-slate-600">Loading servers...</Text>
</SafeAreaView>
);
}
if (client && activeProfile) {
return (
<SafeAreaView className="flex-1 bg-slate-100">
<StatusBar />
<ScrollView contentContainerStyle={{ padding: 16, gap: 14, paddingBottom: 40 }}>
<View className="rounded-2xl border border-slate-200 bg-white p-4">
<View className="flex-row items-start justify-between">
<View className="max-w-[75%] gap-1">
<Text className="text-xl font-semibold text-slate-900">T3 Code Mobile</Text>
<Text className="text-xs text-slate-600">{activeProfile.name}</Text>
<Text className="text-[11px] text-slate-500">{activeProfile.url}</Text>
</View>
<View className={`rounded-full px-3 py-1 ${statusClassName(connectionStatus)}`}>
<Text className="text-xs font-semibold">{statusLabel(connectionStatus)}</Text>
</View>
</View>
{connectionStatus.detail ? (
<Text className="mt-3 text-[11px] text-slate-500">{connectionStatus.detail}</Text>
) : null}
<View className="mt-4 flex-row gap-2">
<View className="flex-1">
<ThemeButton
label={snapshotQuery.isFetching ? "Refreshing..." : "Refresh Snapshot"}
onPress={() => {
void snapshotQuery.refetch();
}}
disabled={snapshotQuery.isFetching}
/>
</View>
<View className="flex-1">
<ThemeButton label="Switch Server" variant="ghost" onPress={() => void disconnectFromBackend()} />
</View>
</View>
</View>
<SectionCard title="Session">
<Text className="text-sm text-slate-700">Project: {welcome?.projectName ?? "Waiting for welcome event..."}</Text>
<Text className="text-sm text-slate-700">Workspace: {welcome?.cwd ?? "-"}</Text>
<Text className="text-sm text-slate-700">
Bootstrap Thread: {welcome?.bootstrapThreadId ?? "not provided"}
</Text>
</SectionCard>
<SectionCard title="Orchestration Snapshot">
{snapshotQuery.isLoading ? (
<View className="items-start gap-2">
<ActivityIndicator size="small" color="#334155" />
<Text className="text-sm text-slate-600">Loading snapshot...</Text>
</View>
) : snapshotError ? (
<Text className="text-sm text-red-700">{snapshotError}</Text>
) : snapshot ? (
<View className="gap-2">
<Text className="text-sm text-slate-700">Projects: {snapshot.projects.length}</Text>
<Text className="text-sm text-slate-700">Threads: {snapshot.threads.length}</Text>
<Text className="text-sm text-slate-700">Updated: {formatDate(snapshot.updatedAt)}</Text>
<View className="mt-1 gap-2 rounded-xl border border-slate-200 bg-slate-50 p-3">
{snapshot.projects.slice(0, 4).map((project) => (
<View key={project.id} className="gap-0.5">
<Text className="text-sm font-medium text-slate-800">{project.title}</Text>
<Text className="text-[11px] text-slate-500">{project.workspaceRoot}</Text>
</View>
))}
{snapshot.projects.length === 0 ? (
<Text className="text-sm text-slate-500">No projects available.</Text>
) : null}
</View>
</View>
) : (
<Text className="text-sm text-slate-600">No snapshot data available.</Text>
)}
</SectionCard>
<SectionCard title="Recent Domain Events">
{recentEvents.length === 0 ? (
<Text className="text-sm text-slate-500">No events received yet.</Text>
) : (
<View className="gap-2">
{recentEvents.slice(0, 25).map((event) => (
<View
key={eventKey(event)}
className="rounded-lg border border-slate-200 bg-slate-50 px-3 py-2"
>
<Text className="text-xs font-semibold uppercase text-slate-700">{formatEventType(event)}</Text>
<Text className="mt-1 text-[11px] text-slate-500">{formatEventTimestamp(event)}</Text>
</View>
))}
</View>
)}
</SectionCard>
</ScrollView>
</SafeAreaView>
);
}
return (
<SafeAreaView className="flex-1 bg-slate-100">
<StatusBar />
<ScrollView contentContainerStyle={{ padding: 16, gap: 14, paddingBottom: 40 }}>
<View className="rounded-2xl border border-slate-200 bg-white p-4">
<Text className="text-2xl font-semibold text-slate-900">Connect T3 Code</Text>
<Text className="mt-2 text-sm leading-5 text-slate-600">
Enter your websocket server URL and optional auth token. Saved servers appear below.
</Text>
<View className="mt-4 gap-3">
<View className="gap-1.5">
<Text className="text-xs font-semibold uppercase tracking-[1.4px] text-slate-500">Server URL</Text>
<TextInput
className="h-11 rounded-xl border border-slate-300 bg-white px-3 text-sm text-slate-900"
autoCapitalize="none"
autoCorrect={false}
keyboardType="url"
placeholder="ws://localhost:3773"
placeholderTextColor="#94a3b8"
value={wsUrlInput}
onChangeText={setWsUrlInput}
/>
</View>
<View className="gap-1.5">
<Text className="text-xs font-semibold uppercase tracking-[1.4px] text-slate-500">Auth Token (Optional)</Text>
<TextInput
className="h-11 rounded-xl border border-slate-300 bg-white px-3 text-sm text-slate-900"
autoCapitalize="none"
autoCorrect={false}
placeholder="token"
placeholderTextColor="#94a3b8"
value={authTokenInput}
onChangeText={setAuthTokenInput}
/>
</View>
<ThemeButton label="Save and Connect" onPress={() => void saveAndConnectProfile()} />
</View>
{uiError ? <Text className="mt-3 text-sm text-red-700">{uiError}</Text> : null}
</View>
<SectionCard title="Saved Backends">
{profiles.length === 0 ? (
<Text className="text-sm text-slate-500">No servers saved yet.</Text>
) : (
<View className="gap-3">
{profiles.map((profile) => (
<View key={profile.id} className="gap-3 rounded-xl border border-slate-200 bg-slate-50 p-3">
<View className="gap-1">
<Text className="text-sm font-semibold text-slate-900">{profile.name}</Text>
<Text className="text-[11px] text-slate-600">{profile.url}</Text>
<Text className="text-[11px] text-slate-500">
Token: {profile.authToken ? "configured" : "none"}
</Text>
<Text className="text-[11px] text-slate-500">
Last connected: {formatDate(profile.lastConnectedAt)}
</Text>
</View>
<View className="flex-row gap-2">
<View className="flex-1">
<ThemeButton
label="Connect"
onPress={() => {
void connectToProfile(profile);
}}
/>
</View>
<View className="flex-1">
<ThemeButton
label="Delete"
variant="danger"
onPress={() => {
void removeProfile(profile.id);
}}
/>
</View>
</View>
</View>
))}
</View>
)}
</SectionCard>
</ScrollView>
</SafeAreaView>
);
}
export default function App() {
return (
<QueryClientProvider client={queryClient}>
<AppContent />
</QueryClientProvider>
);
}
-161
View File
@@ -1,161 +0,0 @@
import AsyncStorage from "@react-native-async-storage/async-storage";
const BACKEND_PROFILES_KEY = "t3.mobile.backendProfiles.v1";
const ACTIVE_BACKEND_ID_KEY = "t3.mobile.activeBackendId.v1";
const URL_PROTOCOL_PATTERN = /^[a-zA-Z][a-zA-Z\d+.-]*:\/\//;
export interface BackendProfile {
readonly id: string;
readonly name: string;
readonly url: string;
readonly authToken: string | null;
readonly createdAt: string;
readonly lastConnectedAt: string | null;
}
interface StoredBackendState {
readonly profiles: BackendProfile[];
readonly activeProfileId: string | null;
}
interface NormalizedBackendInput {
readonly name: string;
readonly url: string;
readonly authToken: string | null;
}
function isString(input: unknown): input is string {
return typeof input === "string";
}
function toBackendProfile(input: unknown): BackendProfile | null {
if (!input || typeof input !== "object") return null;
const value = input as Record<string, unknown>;
if (!isString(value.id) || !isString(value.name) || !isString(value.url) || !isString(value.createdAt)) {
return null;
}
const authToken = isString(value.authToken) ? value.authToken : null;
const lastConnectedAt = isString(value.lastConnectedAt) ? value.lastConnectedAt : null;
return {
id: value.id,
name: value.name,
url: value.url,
authToken: authToken && authToken.length > 0 ? authToken : null,
createdAt: value.createdAt,
lastConnectedAt,
};
}
function parseStoredProfiles(raw: string | null): BackendProfile[] {
if (!raw) return [];
try {
const parsed = JSON.parse(raw) as unknown;
if (!Array.isArray(parsed)) return [];
const profiles: BackendProfile[] = [];
for (const candidate of parsed) {
const profile = toBackendProfile(candidate);
if (profile) {
profiles.push(profile);
}
}
return profiles;
} catch {
return [];
}
}
function toWsUrl(input: string): URL {
const trimmed = input.trim();
if (trimmed.length === 0) {
throw new Error("Server URL is required.");
}
const withProtocol = URL_PROTOCOL_PATTERN.test(trimmed) ? trimmed : `ws://${trimmed}`;
let parsed: URL;
try {
parsed = new URL(withProtocol);
} catch {
throw new Error("Enter a valid server URL.");
}
if (parsed.protocol === "http:") {
parsed.protocol = "ws:";
} else if (parsed.protocol === "https:") {
parsed.protocol = "wss:";
}
if (parsed.protocol !== "ws:" && parsed.protocol !== "wss:") {
throw new Error("Server URL must use ws:// or wss://.");
}
parsed.hash = "";
return parsed;
}
function buildBackendName(url: URL): string {
const path = url.pathname.replace(/\/$/, "");
if (!path || path === "/") {
return url.host;
}
return `${url.host}${path}`;
}
export function createBackendProfileId(): string {
return `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
}
export function normalizeBackendInput(urlInput: string, authTokenInput: string): NormalizedBackendInput {
const parsed = toWsUrl(urlInput);
const tokenFromUrl = parsed.searchParams.get("token")?.trim() || "";
parsed.searchParams.delete("token");
const inputToken = authTokenInput.trim();
const authToken = inputToken.length > 0 ? inputToken : tokenFromUrl.length > 0 ? tokenFromUrl : null;
return {
name: buildBackendName(parsed),
url: parsed.toString(),
authToken,
};
}
export function buildSocketUrl(profile: Pick<BackendProfile, "url" | "authToken">): string {
const parsed = new URL(profile.url);
const token = profile.authToken?.trim();
if (token) {
parsed.searchParams.set("token", token);
} else {
parsed.searchParams.delete("token");
}
return parsed.toString();
}
export async function loadBackendState(): Promise<StoredBackendState> {
const [rawProfiles, rawActiveProfileId] = await Promise.all([
AsyncStorage.getItem(BACKEND_PROFILES_KEY),
AsyncStorage.getItem(ACTIVE_BACKEND_ID_KEY),
]);
return {
profiles: parseStoredProfiles(rawProfiles),
activeProfileId: rawActiveProfileId && rawActiveProfileId.length > 0 ? rawActiveProfileId : null,
};
}
export async function saveBackendProfiles(profiles: readonly BackendProfile[]): Promise<void> {
await AsyncStorage.setItem(BACKEND_PROFILES_KEY, JSON.stringify(profiles));
}
export async function setActiveBackendProfileId(profileId: string | null): Promise<void> {
if (!profileId) {
await AsyncStorage.removeItem(ACTIVE_BACKEND_ID_KEY);
return;
}
await AsyncStorage.setItem(ACTIVE_BACKEND_ID_KEY, profileId);
}
-27
View File
@@ -1,27 +0,0 @@
import "react-native";
declare module "react-native" {
interface ViewProps {
className?: string;
}
interface TextProps {
className?: string;
}
interface TextInputProps {
className?: string;
}
interface ScrollViewProps {
className?: string;
}
interface PressableProps {
className?: string;
}
interface ActivityIndicatorProps {
className?: string;
}
}
-2
View File
@@ -1,2 +0,0 @@
@import "tailwindcss";
@import "uniwind";
-60
View File
@@ -1,60 +0,0 @@
import {
OrchestrationEvent,
OrchestrationReadModel,
ORCHESTRATION_WS_CHANNELS,
ORCHESTRATION_WS_METHODS,
WS_CHANNELS,
WsWelcomePayload,
} from "@t3tools/contracts";
import { Cause, Schema } from "effect";
import { buildSocketUrl, type BackendProfile } from "./backendProfiles";
import { type TransportStatus, WsTransport } from "./wsTransport";
const decodeWelcomePayload = Schema.decodeUnknownExit(WsWelcomePayload);
const decodeOrchestrationEvent = Schema.decodeUnknownExit(OrchestrationEvent);
const decodeOrchestrationReadModel = Schema.decodeUnknownExit(OrchestrationReadModel);
export class T3MobileClient {
private readonly transport: WsTransport;
constructor(options: {
readonly profile: Pick<BackendProfile, "url" | "authToken">;
readonly onStatus?: (status: TransportStatus) => void;
}) {
this.transport = new WsTransport(buildSocketUrl(options.profile), options.onStatus);
}
getSnapshot = async (): Promise<typeof OrchestrationReadModel.Type> => {
const raw = await this.transport.request(ORCHESTRATION_WS_METHODS.getSnapshot);
const decoded = decodeOrchestrationReadModel(raw);
if (decoded._tag === "Failure") {
throw new Error(`Invalid orchestration snapshot payload: ${Cause.pretty(decoded.cause)}`);
}
return decoded.value;
};
onWelcome = (callback: (payload: typeof WsWelcomePayload.Type) => void): (() => void) =>
this.transport.subscribe(WS_CHANNELS.serverWelcome, (data) => {
const decoded = decodeWelcomePayload(data);
if (decoded._tag === "Failure") {
console.warn("Dropped server welcome payload", { issue: Cause.pretty(decoded.cause) });
return;
}
callback(decoded.value);
});
onDomainEvent = (callback: (event: typeof OrchestrationEvent.Type) => void): (() => void) =>
this.transport.subscribe(ORCHESTRATION_WS_CHANNELS.domainEvent, (data) => {
const decoded = decodeOrchestrationEvent(data);
if (decoded._tag === "Failure") {
console.warn("Dropped orchestration domain event", { issue: Cause.pretty(decoded.cause) });
return;
}
callback(decoded.value);
});
dispose(): void {
this.transport.dispose();
}
}
-256
View File
@@ -1,256 +0,0 @@
import { WebSocketResponse, WsPush, WsResponse } from "@t3tools/contracts";
import { Cause, Schema } from "effect";
type PushListener = (data: unknown) => void;
interface PendingRequest {
resolve: (result: unknown) => void;
reject: (error: Error) => void;
timeout: ReturnType<typeof setTimeout>;
}
export interface TransportStatus {
readonly state: "connecting" | "connected" | "disconnected" | "error";
readonly detail?: string;
readonly reconnectInMs?: number;
}
interface WsRequestEnvelope {
readonly id: string;
readonly body: {
readonly _tag: string;
readonly [key: string]: unknown;
};
}
const REQUEST_TIMEOUT_MS = 20_000;
const RECONNECT_DELAYS_MS = [500, 1_000, 2_000, 4_000, 8_000];
const decodeWsResponseFromJson = Schema.decodeUnknownExit(Schema.fromJsonString(WsResponse));
const isWsPushEnvelope = Schema.is(WsPush);
const isWebSocketResponseEnvelope = Schema.is(WebSocketResponse);
function websocketRawToString(raw: unknown): string | null {
if (typeof raw === "string") {
return raw;
}
if (raw instanceof ArrayBuffer) {
return new TextDecoder().decode(raw);
}
if (ArrayBuffer.isView(raw)) {
return new TextDecoder().decode(raw);
}
return null;
}
export class WsTransport {
private ws: WebSocket | null = null;
private nextId = 1;
private readonly pending = new Map<string, PendingRequest>();
private readonly listeners = new Map<string, Set<PushListener>>();
private reconnectAttempt = 0;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private disposed = false;
private readonly url: string;
private readonly onStatus?: (status: TransportStatus) => void;
constructor(url: string, onStatus?: (status: TransportStatus) => void) {
this.url = url;
this.onStatus = onStatus;
this.connect();
}
async request<T = unknown>(method: string, params?: unknown): Promise<T> {
if (method.length === 0) {
throw new Error("Request method is required");
}
const id = String(this.nextId++);
const body = params != null ? { ...params, _tag: method } : { _tag: method };
const message: WsRequestEnvelope = { id, body };
return new Promise<T>((resolve, reject) => {
const timeout = setTimeout(() => {
this.pending.delete(id);
reject(new Error(`Request timed out: ${method}`));
}, REQUEST_TIMEOUT_MS);
this.pending.set(id, {
resolve: resolve as (result: unknown) => void,
reject,
timeout,
});
this.send(message);
});
}
subscribe(channel: string, listener: PushListener): () => void {
let channelListeners = this.listeners.get(channel);
if (!channelListeners) {
channelListeners = new Set();
this.listeners.set(channel, channelListeners);
}
channelListeners.add(listener);
return () => {
channelListeners?.delete(listener);
if (channelListeners && channelListeners.size === 0) {
this.listeners.delete(channel);
}
};
}
dispose(): void {
this.disposed = true;
if (this.reconnectTimer !== null) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
for (const pending of this.pending.values()) {
clearTimeout(pending.timeout);
pending.reject(new Error("Transport disposed"));
}
this.pending.clear();
this.ws?.close();
this.ws = null;
this.emitStatus({ state: "disconnected", detail: "Connection closed" });
}
private emitStatus(status: TransportStatus): void {
this.onStatus?.(status);
}
private connect(): void {
if (this.disposed) return;
this.emitStatus({ state: "connecting" });
const ws = new WebSocket(this.url);
this.ws = ws;
const handleOpen = () => {
this.reconnectAttempt = 0;
this.emitStatus({ state: "connected" });
};
const handleMessage = (event: MessageEvent) => {
this.handleMessage(event.data);
};
const handleError = () => {
this.emitStatus({ state: "error", detail: "WebSocket transport error" });
};
const handleClose = (event: CloseEvent) => {
this.ws = null;
const detail = event.reason || `Code ${event.code}`;
this.emitStatus({ state: "disconnected", detail });
this.scheduleReconnect(detail);
};
ws.addEventListener("open", handleOpen);
ws.addEventListener("message", handleMessage);
ws.addEventListener("error", handleError);
ws.addEventListener("close", handleClose);
}
private handleMessage(raw: unknown): void {
const messageText = websocketRawToString(raw);
if (!messageText) {
return;
}
const decoded = decodeWsResponseFromJson(messageText);
if (decoded._tag === "Failure") {
console.warn("Dropped inbound WebSocket envelope", {
reason: "decode-failed",
issue: Cause.pretty(decoded.cause),
});
return;
}
const message = decoded.value;
if (isWsPushEnvelope(message)) {
const channelListeners = this.listeners.get(message.channel);
if (!channelListeners) return;
for (const listener of channelListeners) {
try {
listener(message.data);
} catch {
// Swallow listener errors.
}
}
return;
}
if (!isWebSocketResponseEnvelope(message)) {
return;
}
const pending = this.pending.get(message.id);
if (!pending) return;
clearTimeout(pending.timeout);
this.pending.delete(message.id);
if (message.error) {
pending.reject(new Error(message.error.message));
return;
}
pending.resolve(message.result);
}
private send(message: WsRequestEnvelope): void {
if (this.ws?.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify(message));
return;
}
const check = setInterval(() => {
if (this.disposed) {
clearInterval(check);
return;
}
if (this.ws?.readyState === WebSocket.OPEN) {
clearInterval(check);
this.ws.send(JSON.stringify(message));
}
}, 50);
setTimeout(() => {
clearInterval(check);
}, REQUEST_TIMEOUT_MS);
}
private scheduleReconnect(detail: string): void {
if (this.disposed || this.reconnectTimer !== null) return;
const reconnectInMs =
RECONNECT_DELAYS_MS[Math.min(this.reconnectAttempt, RECONNECT_DELAYS_MS.length - 1)] ??
RECONNECT_DELAYS_MS[0]!;
this.reconnectAttempt += 1;
this.emitStatus({
state: "disconnected",
detail,
reconnectInMs,
});
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null;
this.connect();
}, reconnectInMs);
}
}
-11
View File
@@ -1,11 +0,0 @@
{
"extends": "expo/tsconfig.base",
"compilerOptions": {
"strict": true,
"types": ["react", "react-native"],
"paths": {
"~/*": ["./src/*"]
}
},
"include": ["**/*.ts", "**/*.tsx", "metro.config.js"]
}
-10
View File
@@ -1,10 +0,0 @@
{
"$schema": "https://turbo.build/schema.json",
"extends": ["//"],
"tasks": {
"dev": {
"persistent": true,
"cache": false
}
}
}
+218
View File
@@ -266,6 +266,18 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("does not include detached HEAD pseudo-refs as branches", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
yield* git(tmp, ["checkout", "--detach", "HEAD"]);
const result = yield* listGitBranches({ cwd: tmp });
expect(result.branches.some((branch) => branch.name.startsWith("("))).toBe(false);
expect(result.branches.some((branch) => branch.current)).toBe(false);
}),
);
it.effect("keeps current branch first and sorts the remaining branches by recency", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
@@ -370,6 +382,82 @@ it.layer(TestLayer)("git integration", (it) => {
expect(result.branches.every((b) => b.isDefault === false)).toBe(true);
}),
);
it.effect("lists local branches first and remote branches last", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const tmp = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(tmp);
const defaultBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(tmp, ["remote", "add", "origin", remote]);
yield* git(tmp, ["push", "-u", "origin", defaultBranch]);
yield* createGitBranch({ cwd: tmp, branch: "feature/local-only" });
const remoteOnlyBranch = "feature/remote-only";
yield* checkoutGitBranch({ cwd: tmp, branch: defaultBranch });
yield* git(tmp, ["checkout", "-b", remoteOnlyBranch]);
yield* git(tmp, ["push", "-u", "origin", remoteOnlyBranch]);
yield* git(tmp, ["checkout", defaultBranch]);
yield* git(tmp, ["branch", "-D", remoteOnlyBranch]);
const result = yield* listGitBranches({ cwd: tmp });
const firstRemoteIndex = result.branches.findIndex((branch) => branch.isRemote);
expect(firstRemoteIndex).toBeGreaterThan(0);
expect(result.branches.slice(0, firstRemoteIndex).every((branch) => !branch.isRemote)).toBe(
true,
);
expect(result.branches.slice(firstRemoteIndex).every((branch) => branch.isRemote)).toBe(
true,
);
expect(
result.branches.some((branch) => branch.name === "feature/local-only" && !branch.isRemote),
).toBe(true);
expect(
result.branches.some(
(branch) => branch.name === "origin/feature/remote-only" && branch.isRemote,
),
).toBe(true);
}),
);
it.effect("includes remoteName metadata for remotes with slash in the name", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const tmp = yield* makeTmpDir();
const remoteName = "my-org/upstream";
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(tmp);
const defaultBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(tmp, ["remote", "add", remoteName, remote]);
yield* git(tmp, ["push", "-u", remoteName, defaultBranch]);
const remoteOnlyBranch = "feature/remote-with-remote-name";
yield* git(tmp, ["checkout", "-b", remoteOnlyBranch]);
yield* git(tmp, ["push", "-u", remoteName, remoteOnlyBranch]);
yield* git(tmp, ["checkout", defaultBranch]);
yield* git(tmp, ["branch", "-D", remoteOnlyBranch]);
const result = yield* listGitBranches({ cwd: tmp });
const remoteBranch = result.branches.find(
(branch) => branch.name === `${remoteName}/${remoteOnlyBranch}`,
);
expect(remoteBranch).toBeDefined();
expect(remoteBranch?.isRemote).toBe(true);
expect(remoteBranch?.remoteName).toBe(remoteName);
}),
);
});
// ── checkoutGitBranch ──
@@ -592,6 +680,87 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect(
"does not silently checkout a local branch when a remote ref no longer exists",
() =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", defaultBranch]);
yield* createGitBranch({ cwd: source, branch: "feature" });
const checkoutResult = yield* Effect.result(
checkoutGitBranch({ cwd: source, branch: "origin/feature" }),
);
expect(checkoutResult._tag).toBe("Failure");
expect(yield* git(source, ["branch", "--show-current"])).toBe(defaultBranch);
}),
);
it.effect("checks out a remote tracking branch when remote name contains slashes", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
const remoteName = "my-org/upstream";
const featureBranch = "feature";
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", remoteName, remote]);
yield* git(source, ["push", "-u", remoteName, defaultBranch]);
yield* git(source, ["checkout", "-b", featureBranch]);
yield* writeTextFile(path.join(source, "feature.txt"), "feature content\n");
yield* git(source, ["add", "feature.txt"]);
yield* git(source, ["commit", "-m", "feature commit"]);
yield* git(source, ["push", "-u", remoteName, featureBranch]);
yield* git(source, ["checkout", defaultBranch]);
yield* git(source, ["branch", "-D", featureBranch]);
yield* checkoutGitBranch({ cwd: source, branch: `${remoteName}/${featureBranch}` });
expect(yield* git(source, ["branch", "--show-current"])).toBe("upstream/feature");
}),
);
it.effect(
"falls back to detached checkout when --track would conflict with an existing local branch",
() =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", defaultBranch]);
// Keep local branch but remove tracking so `--track origin/<branch>`
// would attempt to create an already-existing local branch.
yield* git(source, ["branch", "--unset-upstream"]);
yield* checkoutGitBranch({ cwd: source, branch: `origin/${defaultBranch}` });
const core = yield* GitCore;
const status = yield* core.statusDetails(source);
expect(status.branch).toBeNull();
}),
);
it.effect("throws when checkout would overwrite uncommitted changes", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
@@ -1153,5 +1322,54 @@ it.layer(TestLayer)("git integration", (it) => {
expect(didFailRecency).toBe(true);
}),
);
it.effect("falls back to empty remote branch data when remote lookups fail", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const remote = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
yield* git(remote, ["init", "--bare"]);
yield* git(tmp, ["remote", "add", "origin", remote]);
const realGitService = yield* GitService;
let didFailRemoteBranches = false;
let didFailRemoteNames = false;
const core = yield* makeIsolatedGitCore({
execute: (input) => {
if (input.args.join(" ") === "branch --no-color --remotes") {
didFailRemoteBranches = true;
return Effect.fail(
new GitCommandError({
operation: "git.test.listBranchesRemoteBranches",
command: `git ${input.args.join(" ")}`,
cwd: input.cwd,
detail: "remote unavailable",
}),
);
}
if (input.args.join(" ") === "remote") {
didFailRemoteNames = true;
return Effect.fail(
new GitCommandError({
operation: "git.test.listBranchesRemoteNames",
command: `git ${input.args.join(" ")}`,
cwd: input.cwd,
detail: "remote unavailable",
}),
);
}
return realGitService.execute(input);
},
});
const result = yield* core.listBranches({ cwd: tmp });
expect(result.isRepo).toBe(true);
expect(result.branches.length).toBeGreaterThan(0);
expect(result.branches.every((branch) => !branch.isRemote)).toBe(true);
expect(didFailRemoteBranches).toBe(true);
expect(didFailRemoteNames).toBe(true);
}),
);
});
});
+254 -18
View File
@@ -76,6 +76,87 @@ function parsePorcelainPath(line: string): string | null {
return filePath.length > 0 ? filePath : null;
}
function parseBranchLine(line: string): { name: string; current: boolean } | null {
const trimmed = line.trim();
if (trimmed.length === 0) return null;
const name = trimmed.replace(/^[*+]\s+/, "");
// Exclude symbolic refs like: "origin/HEAD -> origin/main".
// Exclude detached HEAD pseudo-refs like: "(HEAD detached at origin/main)".
if (name.includes(" -> ") || name.startsWith("(")) return null;
return {
name,
current: trimmed.startsWith("* "),
};
}
function parseRemoteNames(stdout: string): ReadonlyArray<string> {
return stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0)
.toSorted((a, b) => b.length - a.length);
}
function parseRemoteRefWithRemoteNames(
branchName: string,
remoteNames: ReadonlyArray<string>,
): { remoteRef: string; remoteName: string; localBranch: string } | null {
const trimmedBranchName = branchName.trim();
if (trimmedBranchName.length === 0) return null;
for (const remoteName of remoteNames) {
const remotePrefix = `${remoteName}/`;
if (!trimmedBranchName.startsWith(remotePrefix)) {
continue;
}
const localBranch = trimmedBranchName.slice(remotePrefix.length).trim();
if (localBranch.length === 0) {
return null;
}
return {
remoteRef: trimmedBranchName,
remoteName,
localBranch,
};
}
return null;
}
function parseTrackingBranchByUpstreamRef(
stdout: string,
upstreamRef: string,
): string | null {
for (const line of stdout.split("\n")) {
const trimmedLine = line.trim();
if (trimmedLine.length === 0) {
continue;
}
const [branchNameRaw, upstreamBranchRaw = ""] = trimmedLine.split("\t");
const branchName = branchNameRaw?.trim() ?? "";
const upstreamBranch = upstreamBranchRaw.trim();
if (branchName.length === 0 || upstreamBranch.length === 0) {
continue;
}
if (upstreamBranch === upstreamRef) {
return branchName;
}
}
return null;
}
function deriveLocalBranchNameFromRemoteRef(branchName: string): string | null {
const separatorIndex = branchName.indexOf("/");
if (separatorIndex <= 0 || separatorIndex === branchName.length - 1) {
return null;
}
const localBranch = branchName.slice(separatorIndex + 1).trim();
return localBranch.length > 0 ? localBranch : null;
}
function commandLabel(args: readonly string[]): string {
return `git ${args.join(" ")}`;
}
@@ -264,7 +345,12 @@ const makeGitCore = Effect.gen(function* () {
const branchRecency = yield* executeGit(
"GitCore.readBranchRecency",
cwd,
["for-each-ref", "--format=%(refname:short)%09%(committerdate:unix)", "refs/heads"],
[
"for-each-ref",
"--format=%(refname:short)%09%(committerdate:unix)",
"refs/heads",
"refs/remotes",
],
{
timeoutMs: 15_000,
allowNonZeroExit: true,
@@ -564,7 +650,7 @@ const makeGitCore = Effect.gen(function* () {
const branchRecencyPromise = readBranchRecency(input.cwd).pipe(
Effect.catch(() => Effect.succeed(new Map<string, number>())),
);
const result = yield* executeGit(
const localBranchResult = yield* executeGit(
"GitCore.listBranches.branchNoColor",
input.cwd,
["branch", "--no-color"],
@@ -574,8 +660,8 @@ const makeGitCore = Effect.gen(function* () {
},
);
if (result.code !== 0) {
const stderr = result.stderr.trim();
if (localBranchResult.code !== 0) {
const stderr = localBranchResult.stderr.trim();
if (stderr.toLowerCase().includes("not a git repository")) {
return { branches: [], isRepo: false };
}
@@ -587,7 +673,40 @@ const makeGitCore = Effect.gen(function* () {
);
}
const [defaultRef, worktreeList, branchLastCommit] = yield* Effect.all(
const remoteBranchResultEffect = executeGit(
"GitCore.listBranches.remoteBranches",
input.cwd,
["branch", "--no-color", "--remotes"],
{
timeoutMs: 10_000,
allowNonZeroExit: true,
},
).pipe(
Effect.catch((error) =>
Effect.logWarning(
`GitCore.listBranches: remote branch lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote branch list.`,
).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })),
),
);
const remoteNamesResultEffect = executeGit(
"GitCore.listBranches.remoteNames",
input.cwd,
["remote"],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
).pipe(
Effect.catch((error) =>
Effect.logWarning(
`GitCore.listBranches: remote name lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote name list.`,
).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })),
),
);
const [defaultRef, worktreeList, remoteBranchResult, remoteNamesResult, branchLastCommit] =
yield* Effect.all(
[
executeGit(
"GitCore.listBranches.defaultRef",
@@ -607,11 +726,25 @@ const makeGitCore = Effect.gen(function* () {
allowNonZeroExit: true,
},
),
remoteBranchResultEffect,
remoteNamesResultEffect,
branchRecencyPromise,
],
{ concurrency: "unbounded" },
);
const remoteNames = remoteNamesResult.code === 0 ? parseRemoteNames(remoteNamesResult.stdout) : [];
if (remoteBranchResult.code !== 0 && remoteBranchResult.stderr.trim().length > 0) {
yield* Effect.logWarning(
`GitCore.listBranches: remote branch lookup returned code ${remoteBranchResult.code} for ${input.cwd}: ${remoteBranchResult.stderr.trim()}. Falling back to an empty remote branch list.`,
);
}
if (remoteNamesResult.code !== 0 && remoteNamesResult.stderr.trim().length > 0) {
yield* Effect.logWarning(
`GitCore.listBranches: remote name lookup returned code ${remoteNamesResult.code} for ${input.cwd}: ${remoteNamesResult.stderr.trim()}. Falling back to an empty remote name list.`,
);
}
const defaultBranch =
defaultRef.code === 0
? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
@@ -636,19 +769,17 @@ const makeGitCore = Effect.gen(function* () {
}
}
const branches = result.stdout
const localBranches = localBranchResult.stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0)
.map((line) => {
const name = line.replace(/^[*+]\s+/, "");
return {
name,
current: line.startsWith("* "),
isDefault: name === defaultBranch,
worktreePath: worktreeMap.get(name) ?? null,
};
})
.map(parseBranchLine)
.filter((branch): branch is { name: string; current: boolean } => branch !== null)
.map((branch) => ({
name: branch.name,
current: branch.current,
isRemote: false,
isDefault: branch.name === defaultBranch,
worktreePath: worktreeMap.get(branch.name) ?? null,
}))
.toSorted((a, b) => {
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
@@ -660,6 +791,43 @@ const makeGitCore = Effect.gen(function* () {
return a.name.localeCompare(b.name);
});
const remoteBranches =
remoteBranchResult.code === 0
? remoteBranchResult.stdout
.split("\n")
.map(parseBranchLine)
.filter((branch): branch is { name: string; current: boolean } => branch !== null)
.map((branch) => {
const parsedRemoteRef = parseRemoteRefWithRemoteNames(branch.name, remoteNames);
const remoteBranch: {
name: string;
current: boolean;
isRemote: boolean;
remoteName?: string;
isDefault: boolean;
worktreePath: string | null;
} = {
name: branch.name,
current: false,
isRemote: true,
isDefault: false,
worktreePath: null,
};
if (parsedRemoteRef) {
remoteBranch.remoteName = parsedRemoteRef.remoteName;
}
return remoteBranch;
})
.toSorted((a, b) => {
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
return a.name.localeCompare(b.name);
})
: [];
const branches = [...localBranches, ...remoteBranches];
return { branches, isRepo: true };
});
@@ -719,7 +887,75 @@ const makeGitCore = Effect.gen(function* () {
const checkoutBranch: GitCoreShape["checkoutBranch"] = (input) =>
Effect.gen(function* () {
yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, ["checkout", input.branch], {
const [localInputExists, remoteExists] = yield* Effect.all(
[
executeGit(
"GitCore.checkoutBranch.localInputExists",
input.cwd,
["show-ref", "--verify", "--quiet", `refs/heads/${input.branch}`],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
).pipe(Effect.map((result) => result.code === 0)),
executeGit(
"GitCore.checkoutBranch.remoteExists",
input.cwd,
["show-ref", "--verify", "--quiet", `refs/remotes/${input.branch}`],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
).pipe(Effect.map((result) => result.code === 0)),
],
{ concurrency: "unbounded" },
);
const localTrackingBranch =
remoteExists
? yield* executeGit(
"GitCore.checkoutBranch.localTrackingBranch",
input.cwd,
["for-each-ref", "--format=%(refname:short)\t%(upstream:short)", "refs/heads"],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
).pipe(
Effect.map((result) =>
result.code === 0
? parseTrackingBranchByUpstreamRef(result.stdout, input.branch)
: null,
),
)
: null;
const localTrackedBranchCandidate = deriveLocalBranchNameFromRemoteRef(input.branch);
const localTrackedBranchTargetExists =
remoteExists && localTrackedBranchCandidate
? yield* executeGit(
"GitCore.checkoutBranch.localTrackedBranchTargetExists",
input.cwd,
["show-ref", "--verify", "--quiet", `refs/heads/${localTrackedBranchCandidate}`],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
).pipe(Effect.map((result) => result.code === 0))
: false;
const checkoutArgs =
localInputExists
? ["checkout", input.branch]
: remoteExists && !localTrackingBranch && localTrackedBranchTargetExists
? ["checkout", input.branch]
: remoteExists && !localTrackingBranch
? ["checkout", "--track", input.branch]
: remoteExists && localTrackingBranch
? ["checkout", localTrackingBranch]
: ["checkout", input.branch];
yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, checkoutArgs, {
timeoutMs: 10_000,
fallbackErrorMessage: "git checkout failed",
});
+1 -1
View File
@@ -101,7 +101,7 @@ export interface GitCoreShape {
) => Effect.Effect<string | null, GitCommandError>;
/**
* List local branches and branch metadata.
* List local + remote branches and branch metadata.
*/
readonly listBranches: (
input: GitListBranchesInput,
@@ -1,6 +1,10 @@
import { ThreadId, type GitBranch } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
import {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
deriveSyncedLocalBranch,
} from "./BranchToolbar.logic";
const branches: GitBranch[] = [
{
@@ -57,3 +61,124 @@ describe("deriveSyncedLocalBranch", () => {
expect(result).toBeNull();
});
});
describe("deriveLocalBranchNameFromRemoteRef", () => {
it("strips the remote prefix from a remote ref", () => {
expect(deriveLocalBranchNameFromRemoteRef("origin/feature/demo")).toBe("feature/demo");
});
it("supports remote names that contain slashes", () => {
expect(deriveLocalBranchNameFromRemoteRef("my-org/upstream/feature/demo")).toBe(
"upstream/feature/demo",
);
});
it("returns the original name when ref is malformed", () => {
expect(deriveLocalBranchNameFromRemoteRef("origin/")).toBe("origin/");
expect(deriveLocalBranchNameFromRemoteRef("/feature/demo")).toBe("/feature/demo");
});
});
describe("dedupeRemoteBranchesWithLocalMatches", () => {
it("hides remote refs when the matching local branch exists", () => {
const input: GitBranch[] = [
{
name: "feature/demo",
current: false,
isDefault: false,
worktreePath: null,
},
{
name: "origin/feature/demo",
isRemote: true,
remoteName: "origin",
current: false,
isDefault: false,
worktreePath: null,
},
{
name: "origin/feature/remote-only",
isRemote: true,
remoteName: "origin",
current: false,
isDefault: false,
worktreePath: null,
},
];
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
"feature/demo",
"origin/feature/remote-only",
]);
});
it("keeps all entries when no local match exists for a remote ref", () => {
const input: GitBranch[] = [
{
name: "feature/local",
current: false,
isDefault: false,
worktreePath: null,
},
{
name: "origin/feature/remote-only",
isRemote: true,
remoteName: "origin",
current: false,
isDefault: false,
worktreePath: null,
},
];
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
"feature/local",
"origin/feature/remote-only",
]);
});
it("dedupes remote refs for remotes whose names contain slashes", () => {
const input: GitBranch[] = [
{
name: "feature/demo",
current: false,
isDefault: false,
worktreePath: null,
},
{
name: "my-org/upstream/feature/demo",
isRemote: true,
remoteName: "my-org/upstream",
current: false,
isDefault: false,
worktreePath: null,
},
];
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
"feature/demo",
]);
});
it("dedupes remote refs when git tracks with first-slash local naming", () => {
const input: GitBranch[] = [
{
name: "upstream/feature",
current: false,
isDefault: false,
worktreePath: null,
},
{
name: "my-org/upstream/feature",
isRemote: true,
remoteName: "my-org/upstream",
current: false,
isDefault: false,
worktreePath: null,
},
];
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
"upstream/feature",
]);
});
});
@@ -8,6 +8,54 @@ interface DeriveSyncedLocalBranchInput {
queryBranches: ReadonlyArray<GitBranch> | undefined;
}
export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
const firstSeparatorIndex = branchName.indexOf("/");
if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) {
return branchName;
}
return branchName.slice(firstSeparatorIndex + 1);
}
function deriveLocalBranchNameCandidatesFromRemoteRef(
branchName: string,
remoteName?: string,
): ReadonlyArray<string> {
const candidates = new Set<string>();
const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);
if (firstSlashCandidate.length > 0) {
candidates.add(firstSlashCandidate);
}
if (remoteName) {
const remotePrefix = `${remoteName}/`;
if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {
candidates.add(branchName.slice(remotePrefix.length));
}
}
return [...candidates];
}
export function dedupeRemoteBranchesWithLocalMatches(
branches: ReadonlyArray<GitBranch>,
): ReadonlyArray<GitBranch> {
const localBranchNames = new Set(
branches.filter((branch) => !branch.isRemote).map((branch) => branch.name),
);
return branches.filter((branch) => {
if (!branch.isRemote) {
return true;
}
const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(
branch.name,
branch.remoteName,
);
return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
});
}
export function deriveSyncedLocalBranch({
activeThreadId,
activeWorktreePath,
+29 -9
View File
@@ -10,7 +10,11 @@ import {
} from "../lib/gitReactQuery";
import { readNativeApi } from "../nativeApi";
import { useStore } from "../store";
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
import {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
deriveSyncedLocalBranch,
} from "./BranchToolbar.logic";
import { Button } from "./ui/button";
import {
Combobox,
@@ -55,7 +59,7 @@ export default function BranchToolbar({
const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
const branches = branchesQuery.data?.branches ?? [];
const branches = dedupeRemoteBranchesWithLocalMatches(branchesQuery.data?.branches ?? []);
const branchNames = branches.map((branch) => branch.name);
const branchByName = new Map(branches.map((branch) => [branch.name, branch]));
const trimmedBranchQuery = branchQuery.trim();
@@ -174,10 +178,21 @@ export default function BranchToolbar({
return;
}
const selectedBranchName = branch.isRemote
? deriveLocalBranchNameFromRemoteRef(branch.name)
: branch.name;
checkoutMutation.mutate(branch.name, {
onSuccess: () => {
onSuccess: async () => {
setThreadError(null);
setThreadBranch(branch.name, activeWorktreePath);
let nextBranchName = selectedBranchName;
if (branch.isRemote) {
const status = await api.git.status({ cwd: branchCwd }).catch(() => null);
if (status?.branch) {
nextBranchName = status.branch;
}
}
setThreadBranch(nextBranchName, activeWorktreePath);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
},
@@ -283,6 +298,15 @@ export default function BranchToolbar({
const hasSecondaryWorktree =
branch.worktreePath && branch.worktreePath !== activeProject.cwd;
const badge = branch.current
? "current"
: hasSecondaryWorktree
? "worktree"
: branch.isRemote
? "remote"
: branch.isDefault
? "default"
: null;
return (
<ComboboxItem
hideIndicator
@@ -295,11 +319,7 @@ export default function BranchToolbar({
>
<div className="flex w-full items-center justify-between gap-2">
<span className="truncate">{itemValue}</span>
{(branch.current || branch.isDefault || hasSecondaryWorktree) && (
<span className="shrink-0 text-[10px] text-muted-foreground/45">
{branch.current ? "current" : hasSecondaryWorktree ? "worktree" : "default"}
</span>
)}
{badge && <span className="shrink-0 text-[10px] text-muted-foreground/45">{badge}</span>}
</div>
</ComboboxItem>
);
+52 -3
View File
@@ -7,6 +7,8 @@ import { ChevronLeftIcon, ChevronRightIcon, Columns2Icon, Rows3Icon } from "luci
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
import { cn } from "~/lib/utils";
import { readNativeApi } from "../nativeApi";
import { preferredTerminalEditor, resolvePathLinkTarget } from "../terminal-links";
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
import { isElectron } from "../env";
import { useTheme } from "../hooks/useTheme";
@@ -58,6 +60,29 @@ const DIFF_PANEL_UNSAFE_CSS = `
border-block-color: var(--border) !important;
color: var(--foreground) !important;
}
[data-diffs-header] {
position: sticky !important;
top: 0;
z-index: 4;
background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important;
border-bottom: 1px solid var(--border) !important;
}
[data-title] {
cursor: pointer;
transition:
color 120ms ease,
text-decoration-color 120ms ease;
text-decoration: underline;
text-decoration-color: transparent;
text-underline-offset: 2px;
}
[data-title]:hover {
color: color-mix(in srgb, var(--foreground) 84%, var(--primary)) !important;
text-decoration-color: currentColor;
}
`;
type RenderablePatch =
@@ -144,6 +169,8 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
const diffSearch = useSearch({ strict: false, select: (search) => parseDiffRouteSearch(search) });
const activeThreadId = routeThreadId;
const activeThread = state.threads.find((thread) => thread.id === activeThreadId);
const activeProject = state.projects.find((project) => project.id === activeThread?.projectId);
const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
useTurnDiffSummaries(activeThread);
const orderedTurnDiffSummaries = useMemo(
@@ -264,6 +291,18 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
target?.scrollIntoView({ block: "nearest" });
}, [selectedFilePath, renderableFiles]);
const openDiffFileInEditor = useCallback(
(filePath: string) => {
const api = readNativeApi();
if (!api) return;
const targetPath = activeCwd ? resolvePathLinkTarget(filePath, activeCwd) : filePath;
void api.shell.openInEditor(targetPath, preferredTerminalEditor()).catch((error) => {
console.warn("Failed to open diff file in editor.", error);
});
},
[activeCwd],
);
const selectTurn = (turnId: TurnId) => {
if (!activeThread) return;
void navigate({
@@ -508,7 +547,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
</div>
) : renderablePatch.kind === "files" ? (
<Virtualizer
className="diff-render-surface h-full min-h-0 overflow-auto px-3 py-2"
className="diff-render-surface h-full min-h-0 overflow-auto px-2 pb-2"
config={{
overscrollSize: 600,
intersectionObserverMargin: 1200,
@@ -522,7 +561,17 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
<div
key={themedFileKey}
data-diff-file-path={filePath}
className="diff-render-file rounded-md"
className="diff-render-file mb-2 rounded-md first:mt-2 last:mb-0"
onClickCapture={(event) => {
const nativeEvent = event.nativeEvent as MouseEvent;
const composedPath = nativeEvent.composedPath?.() ?? [];
const clickedHeader = composedPath.some((node) => {
if (!(node instanceof Element)) return false;
return node.hasAttribute("data-title");
});
if (!clickedHeader) return;
openDiffFileInEditor(filePath);
}}
>
<FileDiff
fileDiff={fileDiff}
@@ -539,7 +588,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
})}
</Virtualizer>
) : (
<div className="h-full overflow-auto px-3 py-2">
<div className="h-full overflow-auto p-2">
<div className="space-y-2">
<p className="text-[11px] text-muted-foreground/75">{renderablePatch.reason}</p>
<pre className="max-h-[72vh] overflow-auto rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90">
+70 -20
View File
@@ -22,6 +22,7 @@ import { serverConfigQueryOptions } from "../lib/serverReactQuery";
import { readNativeApi } from "../nativeApi";
import { toastManager } from "./ui/toast";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import {
SidebarContent,
SidebarFooter,
@@ -67,9 +68,11 @@ interface TerminalStatusIndicator {
interface PrStatusIndicator {
label: "PR open" | "PR closed" | "PR merged";
colorClass: string;
tooltip: string;
url: string;
}
type ThreadPrState = NonNullable<GitStatusResult["pr"]>["state"] | null;
type ThreadPr = GitStatusResult["pr"];
function hasUnseenCompletion(thread: Thread): boolean {
if (!thread.latestTurn?.completedAt) return false;
@@ -133,23 +136,31 @@ function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null
};
}
function prStatusIndicator(prState: ThreadPrState): PrStatusIndicator | null {
if (prState === "open") {
function prStatusIndicator(pr: ThreadPr): PrStatusIndicator | null {
if (!pr) return null;
if (pr.state === "open") {
return {
label: "PR open",
colorClass: "text-emerald-600 dark:text-emerald-300/90",
tooltip: `#${pr.number} PR open: ${pr.title}`,
url: pr.url,
};
}
if (prState === "closed") {
if (pr.state === "closed") {
return {
label: "PR closed",
colorClass: "text-zinc-500 dark:text-zinc-400/80",
tooltip: `#${pr.number} PR closed: ${pr.title}`,
url: pr.url,
};
}
if (prState === "merged") {
if (pr.state === "merged") {
return {
label: "PR merged",
colorClass: "text-violet-600 dark:text-violet-300/90",
tooltip: `#${pr.number} PR merged: ${pr.title}`,
url: pr.url,
};
}
return null;
@@ -272,7 +283,7 @@ export default function Sidebar() {
refetchInterval: 60_000,
})),
});
const prStateByThreadId = useMemo(() => {
const prByThreadId = useMemo(() => {
const statusByCwd = new Map<string, GitStatusResult>();
for (let index = 0; index < threadGitStatusCwds.length; index += 1) {
const cwd = threadGitStatusCwds[index];
@@ -283,16 +294,38 @@ export default function Sidebar() {
}
}
const map = new Map<ThreadId, ThreadPrState>();
const map = new Map<ThreadId, ThreadPr>();
for (const target of threadGitTargets) {
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?.state ?? null : null);
map.set(target.threadId, branchMatches ? status?.pr ?? null : null);
}
return map;
}, [threadGitStatusCwds, threadGitStatusQueries, threadGitTargets]);
const openPrLink = useCallback((event: React.MouseEvent<HTMLElement>, prUrl: string) => {
event.preventDefault();
event.stopPropagation();
const api = readNativeApi();
if (!api) {
toastManager.add({
type: "error",
title: "Link opening is unavailable.",
});
return;
}
void api.shell.openExternal(prUrl).catch((error) => {
toastManager.add({
type: "error",
title: "Unable to open PR link",
description: error instanceof Error ? error.message : "An error occurred.",
});
});
}, []);
const handleNewThread = useCallback(
(
projectId: ProjectId,
@@ -714,13 +747,13 @@ export default function Sidebar() {
thread,
pendingApprovalByThreadId.get(thread.id) === true,
);
const prStatus = prStatusIndicator(prStateByThreadId.get(thread.id) ?? null);
const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null);
const terminalStatus = terminalStatusIndicator(thread);
return (
<SidebarMenuSubItem key={thread.id} className="w-full">
<SidebarMenuSubButton
render={<button type="button" />}
render={<div role="button" tabIndex={0} />}
size="sm"
isActive={isActive}
className={`h-7 w-full translate-x-0 justify-start px-2 text-left hover:bg-accent hover:text-foreground ${
@@ -734,6 +767,14 @@ export default function Sidebar() {
params: { threadId: thread.id },
});
}}
onKeyDown={(event) => {
if (event.key !== "Enter" && event.key !== " ") return;
event.preventDefault();
void navigate({
to: "/$threadId",
params: { threadId: thread.id },
});
}}
onContextMenu={(event) => {
event.preventDefault();
void handleThreadContextMenu(thread.id, {
@@ -743,6 +784,25 @@ export default function Sidebar() {
}}
>
<div className="flex min-w-0 flex-1 items-center gap-1.5 text-left">
{prStatus && (
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
aria-label={prStatus.tooltip}
className={`inline-flex items-center justify-center ${prStatus.colorClass} cursor-pointer rounded-sm outline-hidden focus-visible:ring-1 focus-visible:ring-ring`}
onClick={(event) => {
openPrLink(event, prStatus.url);
}}
>
<GitPullRequestIcon className="size-3" />
</button>
}
/>
<TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
</Tooltip>
)}
{threadStatus && (
<span
className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}
@@ -760,16 +820,6 @@ export default function Sidebar() {
</span>
</div>
<div className="ml-auto flex shrink-0 items-center gap-1.5">
{prStatus && (
<span
role="img"
aria-label={prStatus.label}
title={prStatus.label}
className={`inline-flex items-center justify-center ${prStatus.colorClass}`}
>
<GitPullRequestIcon className="size-3" />
</span>
)}
{terminalStatus && (
<span
role="img"
+3 -4
View File
@@ -153,10 +153,9 @@ export function createWsNativeApi(): NativeApi {
return;
}
const popup = window.open(url, "_blank", "noopener,noreferrer");
if (!popup) {
throw new Error("Unable to open link. Allow popups and try again.");
}
// Some mobile browsers can return null here even when the tab opens.
// Avoid false negatives and let the browser handle popup policy.
window.open(url, "_blank", "noopener,noreferrer");
},
},
git: {
+42 -1218
View File
File diff suppressed because it is too large. Load diff
-1
View File
@@ -19,7 +19,6 @@
"dev:server": "bun run scripts/dev-runner.mjs dev:server",
"dev:web": "bun run scripts/dev-runner.mjs dev:web",
"dev:desktop": "bun run scripts/dev-runner.mjs dev:desktop",
"dev:mobile": "bun run scripts/dev-runner.mjs dev:mobile",
"start": "turbo run start --filter=t3",
"start:desktop": "turbo run start --filter=@t3tools/desktop",
"build": "turbo run build",
+2
View File
@@ -23,6 +23,8 @@ export type GitStatusPrState = typeof GitStatusPrState.Type;
export const GitBranch = Schema.Struct({
name: TrimmedNonEmptyStringSchema,
isRemote: Schema.optional(Schema.Boolean),
remoteName: Schema.optional(TrimmedNonEmptyStringSchema),
current: Schema.Boolean,
isDefault: Schema.Boolean,
worktreePath: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr),
+1 -2
View File
@@ -20,7 +20,6 @@ const MODE_ARGS = {
"dev:server": ["run", "dev", "--filter=t3"],
"dev:web": ["run", "dev", "--filter=@t3tools/web"],
"dev:desktop": ["run", "dev", "--filter=@t3tools/desktop", "--filter=@t3tools/web", "--parallel"],
"dev:mobile": ["run", "dev", "--filter=@t3tools/mobile", "--filter=t3", "--parallel"],
};
const FORWARDED_ENV_FLAGS = {
"state-dir": { envName: "T3CODE_STATE_DIR", expectsValue: true },
@@ -191,7 +190,7 @@ export function createDevRunnerEnv({ mode, env, offset, envOverrides }) {
}
output.VITE_WS_URL = `ws://localhost:${parsedServerPort}`;
if (mode === "dev" || mode === "dev:server" || mode === "dev:web" || mode === "dev:mobile") {
if (mode === "dev" || mode === "dev:server" || mode === "dev:web") {
// Running server/web in browser mode should not inherit desktop launcher state.
output.T3CODE_MODE = "web";
if (!("T3CODE_NO_BROWSER" in envOverrides)) {