Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a950fde73a | ||
|
|
0ea7755363 |
No files matched your search
@@ -4,6 +4,7 @@ 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
|
||||
|
||||
@@ -32,6 +33,7 @@ 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
|
||||
@@ -49,6 +51,9 @@ 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
|
||||
|
||||
@@ -68,6 +73,7 @@ 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`
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
# 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
|
||||
@@ -0,0 +1,3 @@
|
||||
import "./src/global.css";
|
||||
|
||||
export { default } from "./src/App";
|
||||
@@ -0,0 +1,37 @@
|
||||
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;
|
||||
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 77 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 384 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 1.3 MiB |
|
After Width: | Height: | Size: 1.1 MiB |
@@ -0,0 +1,13 @@
|
||||
module.exports = function (api) {
|
||||
api.cache(true);
|
||||
return {
|
||||
presets: [
|
||||
[
|
||||
"babel-preset-expo",
|
||||
{
|
||||
unstable_transformImportMeta: true,
|
||||
},
|
||||
],
|
||||
],
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
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);
|
||||
@@ -0,0 +1,9 @@
|
||||
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",
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,500 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
@import "tailwindcss";
|
||||
@import "uniwind";
|
||||
@@ -0,0 +1,60 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"extends": "expo/tsconfig.base",
|
||||
"compilerOptions": {
|
||||
"strict": true,
|
||||
"types": ["react", "react-native"],
|
||||
"paths": {
|
||||
"~/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": ["**/*.ts", "**/*.tsx", "metro.config.js"]
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"$schema": "https://turbo.build/schema.json",
|
||||
"extends": ["//"],
|
||||
"tasks": {
|
||||
"dev": {
|
||||
"persistent": true,
|
||||
"cache": false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -972,135 +972,6 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("computes ahead count against base branch when no upstream is configured", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const core = yield* GitCore;
|
||||
|
||||
yield* core.createBranch({ cwd: tmp, branch: "feature/no-upstream-ahead" });
|
||||
yield* core.checkoutBranch({ cwd: tmp, branch: "feature/no-upstream-ahead" });
|
||||
yield* writeTextFile(path.join(tmp, "feature.txt"), "ahead of base\n");
|
||||
yield* git(tmp, ["add", "feature.txt"]);
|
||||
yield* git(tmp, ["commit", "-m", "feature commit"]);
|
||||
|
||||
const details = yield* core.statusDetails(tmp);
|
||||
expect(details.branch).toBe("feature/no-upstream-ahead");
|
||||
expect(details.hasUpstream).toBe(false);
|
||||
expect(details.aheadCount).toBe(1);
|
||||
expect(details.behindCount).toBe(0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"computes ahead count against origin/default when local default branch is missing",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
|
||||
yield* initRepoWithCommit(source);
|
||||
const initialBranch = (yield* listGitBranches({ cwd: source })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
yield* git(source, ["remote", "add", "origin", remote]);
|
||||
yield* git(source, ["push", "-u", "origin", initialBranch]);
|
||||
yield* git(source, ["checkout", "-b", "feature/remote-base-only"]);
|
||||
yield* writeTextFile(
|
||||
path.join(source, "feature.txt"),
|
||||
`ahead of origin/${initialBranch}\n`,
|
||||
);
|
||||
yield* git(source, ["add", "feature.txt"]);
|
||||
yield* git(source, ["commit", "-m", "feature commit"]);
|
||||
yield* git(source, ["branch", "-D", initialBranch]);
|
||||
|
||||
const core = yield* GitCore;
|
||||
const details = yield* core.statusDetails(source);
|
||||
expect(details.branch).toBe("feature/remote-base-only");
|
||||
expect(details.hasUpstream).toBe(false);
|
||||
expect(details.aheadCount).toBe(1);
|
||||
expect(details.behindCount).toBe(0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips push when no upstream is configured and branch is not ahead of base", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const core = yield* GitCore;
|
||||
|
||||
yield* core.createBranch({ cwd: tmp, branch: "feature/no-upstream-no-ahead" });
|
||||
yield* core.checkoutBranch({ cwd: tmp, branch: "feature/no-upstream-no-ahead" });
|
||||
|
||||
const pushed = yield* core.pushCurrentBranch(tmp, null);
|
||||
expect(pushed.status).toBe("skipped_up_to_date");
|
||||
expect(pushed.branch).toBe("feature/no-upstream-no-ahead");
|
||||
expect(pushed.setUpstream).toBeUndefined();
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("pushes with upstream setup when no comparable base branch exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const remote = yield* makeTmpDir();
|
||||
yield* git(tmp, ["init", "--initial-branch=trunk"]);
|
||||
yield* git(tmp, ["config", "user.email", "[email protected]"]);
|
||||
yield* git(tmp, ["config", "user.name", "Test"]);
|
||||
yield* writeTextFile(path.join(tmp, "README.md"), "hello\n");
|
||||
yield* git(tmp, ["add", "README.md"]);
|
||||
yield* git(tmp, ["commit", "-m", "initial"]);
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
yield* git(tmp, ["remote", "add", "origin", remote]);
|
||||
yield* git(tmp, ["checkout", "-b", "feature/no-base"]);
|
||||
|
||||
const core = yield* GitCore;
|
||||
const pushed = yield* core.pushCurrentBranch(tmp, null);
|
||||
expect(pushed.status).toBe("pushed");
|
||||
expect(pushed.setUpstream).toBe(true);
|
||||
expect(pushed.upstreamBranch).toBe("origin/feature/no-base");
|
||||
expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
|
||||
"origin/feature/no-base",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"pushes with upstream setup when comparable base exists but remote branch is missing",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const remote = yield* makeTmpDir();
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const initialBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
yield* git(tmp, ["remote", "add", "origin", remote]);
|
||||
yield* git(tmp, ["push", "-u", "origin", initialBranch]);
|
||||
|
||||
yield* writeTextFile(path.join(tmp, "default-ahead.txt"), "ahead on default\n");
|
||||
yield* git(tmp, ["add", "default-ahead.txt"]);
|
||||
yield* git(tmp, ["commit", "-m", "default ahead"]);
|
||||
|
||||
const featureBranch = "feature/publish-no-upstream";
|
||||
yield* git(tmp, ["checkout", "-b", featureBranch]);
|
||||
|
||||
const core = yield* GitCore;
|
||||
const pushed = yield* core.pushCurrentBranch(tmp, null);
|
||||
expect(pushed.status).toBe("pushed");
|
||||
expect(pushed.setUpstream).toBe(true);
|
||||
expect(pushed.upstreamBranch).toBe(`origin/${featureBranch}`);
|
||||
expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
|
||||
`origin/${featureBranch}`,
|
||||
);
|
||||
expect(yield* git(tmp, ["ls-remote", "--heads", "origin", featureBranch])).toContain(
|
||||
featureBranch,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("includes command context when worktree removal fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
|
||||
@@ -7,7 +7,6 @@ import { GitCore, type GitCoreShape } from "../Services/GitCore.ts";
|
||||
const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
|
||||
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
|
||||
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
|
||||
const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const;
|
||||
|
||||
class StatusUpstreamRefreshCacheKey extends Data.Class<{
|
||||
cwd: string;
|
||||
@@ -81,16 +80,6 @@ function commandLabel(args: readonly string[]): string {
|
||||
return `git ${args.join(" ")}`;
|
||||
}
|
||||
|
||||
function parseDefaultBranchFromRemoteHeadRef(value: string): string | null {
|
||||
const trimmed = value.trim();
|
||||
const prefix = "refs/remotes/origin/";
|
||||
if (!trimmed.startsWith(prefix)) {
|
||||
return null;
|
||||
}
|
||||
const branch = trimmed.slice(prefix.length).trim();
|
||||
return branch.length > 0 ? branch : null;
|
||||
}
|
||||
|
||||
function createGitCommandError(
|
||||
operation: string,
|
||||
cwd: string,
|
||||
@@ -270,108 +259,6 @@ const makeGitCore = Effect.gen(function* () {
|
||||
yield* fetchUpstreamRef(cwd, upstream);
|
||||
});
|
||||
|
||||
const resolveDefaultBranchName = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
|
||||
executeGit("GitCore.resolveDefaultBranchName", cwd, ["symbolic-ref", "refs/remotes/origin/HEAD"], {
|
||||
allowNonZeroExit: true,
|
||||
}).pipe(
|
||||
Effect.map((result) => {
|
||||
if (result.code !== 0) {
|
||||
return null;
|
||||
}
|
||||
return parseDefaultBranchFromRemoteHeadRef(result.stdout);
|
||||
}),
|
||||
);
|
||||
|
||||
const branchExists = (cwd: string, branch: string): Effect.Effect<boolean, GitCommandError> =>
|
||||
executeGit("GitCore.branchExists", cwd, ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`], {
|
||||
allowNonZeroExit: true,
|
||||
}).pipe(Effect.map((result) => result.code === 0));
|
||||
|
||||
const remoteBranchExists = (
|
||||
cwd: string,
|
||||
branch: string,
|
||||
): Effect.Effect<boolean, GitCommandError> =>
|
||||
executeGit(
|
||||
"GitCore.remoteBranchExists",
|
||||
cwd,
|
||||
["show-ref", "--verify", "--quiet", `refs/remotes/origin/${branch}`],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(Effect.map((result) => result.code === 0));
|
||||
|
||||
const originRemoteExists = (cwd: string): Effect.Effect<boolean, GitCommandError> =>
|
||||
executeGit("GitCore.originRemoteExists", cwd, ["remote", "get-url", "origin"], {
|
||||
allowNonZeroExit: true,
|
||||
}).pipe(Effect.map((result) => result.code === 0));
|
||||
|
||||
const resolveBaseBranchForNoUpstream = (
|
||||
cwd: string,
|
||||
branch: string,
|
||||
): Effect.Effect<string | null, GitCommandError> =>
|
||||
Effect.gen(function* () {
|
||||
const configuredBaseBranch = yield* runGitStdout(
|
||||
"GitCore.resolveBaseBranchForNoUpstream.config",
|
||||
cwd,
|
||||
["config", "--get", `branch.${branch}.gh-merge-base`],
|
||||
true,
|
||||
).pipe(Effect.map((stdout) => stdout.trim()));
|
||||
|
||||
const defaultBranch = yield* resolveDefaultBranchName(cwd);
|
||||
const candidates = [
|
||||
configuredBaseBranch.length > 0 ? configuredBaseBranch : null,
|
||||
defaultBranch,
|
||||
...DEFAULT_BASE_BRANCH_CANDIDATES,
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (!candidate) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const normalizedCandidate = candidate.startsWith("origin/")
|
||||
? candidate.slice("origin/".length)
|
||||
: candidate;
|
||||
if (normalizedCandidate.length === 0 || normalizedCandidate === branch) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (yield* branchExists(cwd, normalizedCandidate)) {
|
||||
return normalizedCandidate;
|
||||
}
|
||||
|
||||
if (yield* remoteBranchExists(cwd, normalizedCandidate)) {
|
||||
return `origin/${normalizedCandidate}`;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
const computeAheadCountAgainstBase = (
|
||||
cwd: string,
|
||||
branch: string,
|
||||
): Effect.Effect<number, GitCommandError> =>
|
||||
Effect.gen(function* () {
|
||||
const baseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch);
|
||||
if (!baseBranch) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const result = yield* executeGit(
|
||||
"GitCore.computeAheadCountAgainstBase",
|
||||
cwd,
|
||||
["rev-list", "--count", `${baseBranch}..HEAD`],
|
||||
{ allowNonZeroExit: true },
|
||||
);
|
||||
if (result.code !== 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const parsed = Number.parseInt(result.stdout.trim(), 10);
|
||||
return Number.isFinite(parsed) ? Math.max(0, parsed) : 0;
|
||||
});
|
||||
|
||||
const readBranchRecency = (cwd: string): Effect.Effect<Map<string, number>, GitCommandError> =>
|
||||
Effect.gen(function* () {
|
||||
const branchRecency = yield* executeGit(
|
||||
@@ -456,14 +343,6 @@ const makeGitCore = Effect.gen(function* () {
|
||||
if (pathValue) changedFilesWithoutNumstat.add(pathValue);
|
||||
}
|
||||
}
|
||||
|
||||
if (!upstreamRef && branch) {
|
||||
aheadCount = yield* computeAheadCountAgainstBase(cwd, branch).pipe(
|
||||
Effect.catch(() => Effect.succeed(0)),
|
||||
);
|
||||
behindCount = 0;
|
||||
}
|
||||
|
||||
const stagedEntries = parseNumstatEntries(stagedNumstatStdout);
|
||||
const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout);
|
||||
const fileStatMap = new Map<string, { insertions: number; deletions: number }>();
|
||||
@@ -573,40 +452,12 @@ const makeGitCore = Effect.gen(function* () {
|
||||
);
|
||||
}
|
||||
|
||||
const hasNoLocalDelta = details.aheadCount === 0 && details.behindCount === 0;
|
||||
if (hasNoLocalDelta) {
|
||||
if (details.hasUpstream) {
|
||||
return {
|
||||
status: "skipped_up_to_date" as const,
|
||||
branch,
|
||||
...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
const comparableBaseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch).pipe(
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
);
|
||||
if (comparableBaseBranch) {
|
||||
const hasOriginRemote = yield* originRemoteExists(cwd).pipe(
|
||||
Effect.catch(() => Effect.succeed(false)),
|
||||
);
|
||||
if (!hasOriginRemote) {
|
||||
return {
|
||||
status: "skipped_up_to_date" as const,
|
||||
branch,
|
||||
};
|
||||
}
|
||||
|
||||
const hasRemoteBranch = yield* remoteBranchExists(cwd, branch).pipe(
|
||||
Effect.catch(() => Effect.succeed(false)),
|
||||
);
|
||||
if (hasRemoteBranch) {
|
||||
return {
|
||||
status: "skipped_up_to_date" as const,
|
||||
branch,
|
||||
};
|
||||
}
|
||||
}
|
||||
if (details.hasUpstream && details.aheadCount === 0 && details.behindCount === 0) {
|
||||
return {
|
||||
status: "skipped_up_to_date" as const,
|
||||
branch,
|
||||
...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
if (!details.hasUpstream) {
|
||||
|
||||
@@ -551,56 +551,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"pushes and creates PR from a no-upstream branch when local commits are ahead of base",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/no-upstream-pr"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
fs.writeFileSync(path.join(repoDir, "feature.txt"), "feature\n");
|
||||
|
||||
const { manager, ghCalls } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
"[]",
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 77,
|
||||
title: "Add no-upstream PR flow",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/77",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/no-upstream-pr",
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit_push_pr",
|
||||
});
|
||||
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.push.status).toBe("pushed");
|
||||
expect(result.push.setUpstream).toBe(true);
|
||||
expect(result.pr.status).toBe("created");
|
||||
expect(
|
||||
yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"]).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
),
|
||||
).toBe("origin/feature/no-upstream-pr");
|
||||
expect(
|
||||
ghCalls.some((call) =>
|
||||
call.includes("pr create --base main --head feature/no-upstream-pr"),
|
||||
),
|
||||
).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips push when branch is already up to date", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
|
||||
@@ -4,8 +4,6 @@ import {
|
||||
buildGitActionProgressStages,
|
||||
buildMenuItems,
|
||||
requiresDefaultBranchConfirmation,
|
||||
resolveAutoFeatureBranchName,
|
||||
resolveDefaultBranchActionDialogCopy,
|
||||
resolveQuickAction,
|
||||
summarizeGitResult,
|
||||
} from "./GitActionsControl.logic";
|
||||
@@ -516,20 +514,19 @@ describe("when: HEAD is detached and there are no local changes", () => {
|
||||
});
|
||||
|
||||
describe("when: branch has no upstream configured", () => {
|
||||
it("resolveQuickAction is disabled when clean, no upstream, and no local commits are ahead", () => {
|
||||
it("resolveQuickAction returns disabled commit state when clean and no commits are ahead", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({ hasUpstream: false, pr: null, aheadCount: 0 }),
|
||||
false,
|
||||
);
|
||||
assert.deepInclude(quick, {
|
||||
kind: "show_hint",
|
||||
label: "Push",
|
||||
hint: "No local commits to push.",
|
||||
label: "Commit",
|
||||
disabled: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("resolveQuickAction opens PR when clean, no upstream, no local commits are ahead, and PR exists", () => {
|
||||
it("resolveQuickAction remains disabled when clean, no upstream, and no local commits ahead", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
hasUpstream: false,
|
||||
@@ -546,9 +543,9 @@ describe("when: branch has no upstream configured", () => {
|
||||
false,
|
||||
);
|
||||
assert.deepInclude(quick, {
|
||||
kind: "open_pr",
|
||||
label: "Open PR",
|
||||
disabled: false,
|
||||
kind: "show_hint",
|
||||
label: "Commit",
|
||||
disabled: true,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -608,132 +605,6 @@ describe("when: branch has no upstream configured", () => {
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("resolveQuickAction runs push and create PR when no upstream and commits are ahead", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
hasUpstream: false,
|
||||
aheadCount: 2,
|
||||
pr: null,
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.deepInclude(quick, {
|
||||
kind: "run_action",
|
||||
action: "commit_push_pr",
|
||||
label: "Push & create PR",
|
||||
disabled: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("buildMenuItems enables create PR when no upstream and commits are ahead", () => {
|
||||
const items = buildMenuItems(
|
||||
status({ hasUpstream: false, pr: null, aheadCount: 2 }),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(items, [
|
||||
{
|
||||
id: "commit",
|
||||
label: "Commit",
|
||||
disabled: true,
|
||||
icon: "commit",
|
||||
kind: "open_dialog",
|
||||
dialogAction: "commit",
|
||||
},
|
||||
{
|
||||
id: "push",
|
||||
label: "Push",
|
||||
disabled: false,
|
||||
icon: "push",
|
||||
kind: "open_dialog",
|
||||
dialogAction: "push",
|
||||
},
|
||||
{
|
||||
id: "pr",
|
||||
label: "Create PR",
|
||||
disabled: false,
|
||||
icon: "pr",
|
||||
kind: "open_dialog",
|
||||
dialogAction: "create_pr",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("resolveQuickAction is disabled on default branch when no upstream exists and no commits are ahead", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
branch: "main",
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
pr: null,
|
||||
}),
|
||||
false,
|
||||
true,
|
||||
);
|
||||
assert.deepInclude(quick, {
|
||||
kind: "show_hint",
|
||||
label: "Push",
|
||||
hint: "No local commits to push.",
|
||||
disabled: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("resolveQuickAction uses push-only on default branch when no upstream exists and commits are ahead", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
branch: "main",
|
||||
hasUpstream: false,
|
||||
aheadCount: 1,
|
||||
pr: null,
|
||||
}),
|
||||
false,
|
||||
true,
|
||||
);
|
||||
assert.deepInclude(quick, {
|
||||
kind: "run_action",
|
||||
action: "commit_push",
|
||||
label: "Push",
|
||||
disabled: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("buildMenuItems still disables push and create PR when branch is behind", () => {
|
||||
const items = buildMenuItems(
|
||||
status({
|
||||
hasUpstream: false,
|
||||
behindCount: 1,
|
||||
aheadCount: 0,
|
||||
pr: null,
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(items, [
|
||||
{
|
||||
id: "commit",
|
||||
label: "Commit",
|
||||
disabled: true,
|
||||
icon: "commit",
|
||||
kind: "open_dialog",
|
||||
dialogAction: "commit",
|
||||
},
|
||||
{
|
||||
id: "push",
|
||||
label: "Push",
|
||||
disabled: true,
|
||||
icon: "push",
|
||||
kind: "open_dialog",
|
||||
dialogAction: "push",
|
||||
},
|
||||
{
|
||||
id: "pr",
|
||||
label: "Create PR",
|
||||
disabled: true,
|
||||
icon: "pr",
|
||||
kind: "open_dialog",
|
||||
dialogAction: "create_pr",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("requiresDefaultBranchConfirmation", () => {
|
||||
@@ -745,53 +616,6 @@ describe("requiresDefaultBranchConfirmation", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveDefaultBranchActionDialogCopy", () => {
|
||||
it("uses push-only copy when pushing without a commit", () => {
|
||||
const copy = resolveDefaultBranchActionDialogCopy({
|
||||
action: "commit_push",
|
||||
branchName: "main",
|
||||
includesCommit: false,
|
||||
});
|
||||
|
||||
assert.deepEqual(copy, {
|
||||
title: "Push to default branch?",
|
||||
description:
|
||||
'This action will push local commits on "main". You can continue on this branch or create a feature branch and run the same action there.',
|
||||
continueLabel: "Push to main",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses push-and-pr copy when creating a PR without a commit", () => {
|
||||
const copy = resolveDefaultBranchActionDialogCopy({
|
||||
action: "commit_push_pr",
|
||||
branchName: "main",
|
||||
includesCommit: false,
|
||||
});
|
||||
|
||||
assert.deepEqual(copy, {
|
||||
title: "Push & create PR from default branch?",
|
||||
description:
|
||||
'This action will push local commits and create a PR on "main". You can continue on this branch or create a feature branch and run the same action there.',
|
||||
continueLabel: "Push & create PR",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps commit copy when the action includes a commit", () => {
|
||||
const copy = resolveDefaultBranchActionDialogCopy({
|
||||
action: "commit_push_pr",
|
||||
branchName: "main",
|
||||
includesCommit: true,
|
||||
});
|
||||
|
||||
assert.deepEqual(copy, {
|
||||
title: "Commit, push & create PR from default branch?",
|
||||
description:
|
||||
'This action will commit, push, and create a PR on "main". You can continue on this branch or create a feature branch and run the same action there.',
|
||||
continueLabel: "Commit, push & create PR",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildGitActionProgressStages", () => {
|
||||
it("shows only push progress when push-only is forced", () => {
|
||||
const stages = buildGitActionProgressStages({
|
||||
@@ -908,20 +732,3 @@ describe("summarizeGitResult", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveAutoFeatureBranchName", () => {
|
||||
const day = new Date("2026-03-01T12:00:00.000Z");
|
||||
|
||||
it("returns the base auto feature branch name when available", () => {
|
||||
const branch = resolveAutoFeatureBranchName(["main", "feature/other"], day);
|
||||
assert.equal(branch, "feature/stacked-20260301");
|
||||
});
|
||||
|
||||
it("increments suffix when the base name already exists", () => {
|
||||
const branch = resolveAutoFeatureBranchName(
|
||||
["main", "feature/stacked-20260301", "feature/stacked-20260301-2"],
|
||||
day,
|
||||
);
|
||||
assert.equal(branch, "feature/stacked-20260301-3");
|
||||
});
|
||||
});
|
||||
@@ -25,17 +25,8 @@ export interface GitQuickAction {
|
||||
hint?: string;
|
||||
}
|
||||
|
||||
export interface DefaultBranchActionDialogCopy {
|
||||
title: string;
|
||||
description: string;
|
||||
continueLabel: string;
|
||||
}
|
||||
|
||||
export type DefaultBranchConfirmableAction = "commit_push" | "commit_push_pr";
|
||||
|
||||
const SHORT_SHA_LENGTH = 7;
|
||||
const TOAST_DESCRIPTION_MAX = 72;
|
||||
const AUTO_FEATURE_BRANCH_PREFIX = "feature/stacked";
|
||||
|
||||
function shortenSha(sha: string | undefined): string | null {
|
||||
if (!sha) return null;
|
||||
@@ -127,6 +118,7 @@ export function buildMenuItems(
|
||||
!hasChanges &&
|
||||
!hasOpenPr &&
|
||||
gitStatus.aheadCount > 0 &&
|
||||
gitStatus.hasUpstream &&
|
||||
!isBehind;
|
||||
const canOpenPr = !isBusy && hasOpenPr;
|
||||
|
||||
@@ -212,29 +204,6 @@ export function resolveQuickAction(
|
||||
};
|
||||
}
|
||||
|
||||
if (!gitStatus.hasUpstream) {
|
||||
if (!isAhead) {
|
||||
if (hasOpenPr) {
|
||||
return { label: "Open PR", disabled: false, kind: "open_pr" };
|
||||
}
|
||||
return {
|
||||
label: "Push",
|
||||
disabled: true,
|
||||
kind: "show_hint",
|
||||
hint: "No local commits to push.",
|
||||
};
|
||||
}
|
||||
if (hasOpenPr || isDefaultBranch) {
|
||||
return { label: "Push", disabled: false, kind: "run_action", action: "commit_push" };
|
||||
}
|
||||
return {
|
||||
label: "Push & create PR",
|
||||
disabled: false,
|
||||
kind: "run_action",
|
||||
action: "commit_push_pr",
|
||||
};
|
||||
}
|
||||
|
||||
if (isDiverged) {
|
||||
return {
|
||||
label: "Sync branch",
|
||||
@@ -283,67 +252,3 @@ export function requiresDefaultBranchConfirmation(
|
||||
if (!isDefaultBranch) return false;
|
||||
return action === "commit_push" || action === "commit_push_pr";
|
||||
}
|
||||
|
||||
export function resolveDefaultBranchActionDialogCopy(input: {
|
||||
action: DefaultBranchConfirmableAction;
|
||||
branchName: string;
|
||||
includesCommit: boolean;
|
||||
}): DefaultBranchActionDialogCopy {
|
||||
const branchLabel = input.branchName;
|
||||
const suffix = ` on "${branchLabel}". You can continue on this branch or create a feature branch and run the same action there.`;
|
||||
|
||||
if (input.action === "commit_push") {
|
||||
if (input.includesCommit) {
|
||||
return {
|
||||
title: "Commit & push to default branch?",
|
||||
description: `This action will commit and push changes${suffix}`,
|
||||
continueLabel: `Commit & push to ${branchLabel}`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
title: "Push to default branch?",
|
||||
description: `This action will push local commits${suffix}`,
|
||||
continueLabel: `Push to ${branchLabel}`,
|
||||
};
|
||||
}
|
||||
|
||||
if (input.includesCommit) {
|
||||
return {
|
||||
title: "Commit, push & create PR from default branch?",
|
||||
description: `This action will commit, push, and create a PR${suffix}`,
|
||||
continueLabel: `Commit, push & create PR`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
title: "Push & create PR from default branch?",
|
||||
description: `This action will push local commits and create a PR${suffix}`,
|
||||
continueLabel: "Push & create PR",
|
||||
};
|
||||
}
|
||||
|
||||
function formatDateForBranch(now: Date): string {
|
||||
const year = now.getUTCFullYear();
|
||||
const month = String(now.getUTCMonth() + 1).padStart(2, "0");
|
||||
const day = String(now.getUTCDate()).padStart(2, "0");
|
||||
return `${year}${month}${day}`;
|
||||
}
|
||||
|
||||
export function resolveAutoFeatureBranchName(
|
||||
existingBranchNames: readonly string[],
|
||||
now = new Date(),
|
||||
): string {
|
||||
const daySlug = formatDateForBranch(now);
|
||||
const base = `${AUTO_FEATURE_BRANCH_PREFIX}-${daySlug}`;
|
||||
const existingNames = new Set(existingBranchNames);
|
||||
|
||||
if (!existingNames.has(base)) {
|
||||
return base;
|
||||
}
|
||||
|
||||
let suffix = 2;
|
||||
while (existingNames.has(`${base}-${suffix}`)) {
|
||||
suffix += 1;
|
||||
}
|
||||
|
||||
return `${base}-${suffix}`;
|
||||
}
|
||||
@@ -8,11 +8,9 @@ import {
|
||||
buildMenuItems,
|
||||
type GitActionIconName,
|
||||
type GitActionMenuItem,
|
||||
type GitDialogAction,
|
||||
type GitQuickAction,
|
||||
type DefaultBranchConfirmableAction,
|
||||
requiresDefaultBranchConfirmation,
|
||||
resolveAutoFeatureBranchName,
|
||||
resolveDefaultBranchActionDialogCopy,
|
||||
resolveQuickAction,
|
||||
summarizeGitResult,
|
||||
} from "./GitActionsControl.logic";
|
||||
@@ -34,7 +32,6 @@ import { Textarea } from "~/components/ui/textarea";
|
||||
import { toastManager } from "~/components/ui/toast";
|
||||
import {
|
||||
gitBranchesQueryOptions,
|
||||
gitCreateBranchAndCheckoutMutationOptions,
|
||||
gitInitMutationOptions,
|
||||
gitMutationKeys,
|
||||
gitPullMutationOptions,
|
||||
@@ -50,17 +47,6 @@ interface GitActionsControlProps {
|
||||
activeThreadId: ThreadId | null;
|
||||
}
|
||||
|
||||
interface PendingDefaultBranchAction {
|
||||
action: DefaultBranchConfirmableAction;
|
||||
branchName: string;
|
||||
includesCommit: boolean;
|
||||
commitMessage?: string;
|
||||
forcePushOnlyProgress: boolean;
|
||||
onConfirmed?: () => void;
|
||||
}
|
||||
|
||||
type GitActionToastId = ReturnType<typeof toastManager.add>;
|
||||
|
||||
function getMenuActionDisabledReason(
|
||||
item: GitActionMenuItem,
|
||||
gitStatus: GitStatusResult | null,
|
||||
@@ -111,15 +97,26 @@ function getMenuActionDisabledReason(
|
||||
if (!isAhead) {
|
||||
return "No local commits to include in a PR.";
|
||||
}
|
||||
if (!gitStatus.hasUpstream) {
|
||||
return "Set an upstream branch before creating a PR.";
|
||||
}
|
||||
if (isBehind) {
|
||||
return "Branch is behind upstream. Pull/rebase before creating a PR.";
|
||||
}
|
||||
return "Create PR is currently unavailable.";
|
||||
}
|
||||
|
||||
const COMMIT_DIALOG_TITLE = "Commit changes";
|
||||
const COMMIT_DIALOG_DESCRIPTION =
|
||||
"Review and confirm your commit. Leave the message blank to auto-generate one.";
|
||||
const DIALOG_TITLE_BY_ACTION = {
|
||||
commit: "Commit changes",
|
||||
push: "Push branch",
|
||||
create_pr: "Create pull request",
|
||||
};
|
||||
|
||||
const DIALOG_DESCRIPTION_BY_ACTION = {
|
||||
commit: "Review and confirm your commit. Leave the message blank to auto-generate one.",
|
||||
push: "Push this branch now.",
|
||||
create_pr: "Create a pull request using generated title/body content.",
|
||||
};
|
||||
|
||||
function GitActionItemIcon({ icon }: { icon: GitActionIconName }) {
|
||||
if (icon === "commit") return <GitCommitIcon />;
|
||||
@@ -146,10 +143,8 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
[activeThreadId],
|
||||
);
|
||||
const queryClient = useQueryClient();
|
||||
const [isCommitDialogOpen, setIsCommitDialogOpen] = useState(false);
|
||||
const [activeDialogAction, setActiveDialogAction] = useState<GitDialogAction | null>(null);
|
||||
const [dialogCommitMessage, setDialogCommitMessage] = useState("");
|
||||
const [pendingDefaultBranchAction, setPendingDefaultBranchAction] =
|
||||
useState<PendingDefaultBranchAction | null>(null);
|
||||
|
||||
const { data: gitStatus = null, error: gitStatusError } = useQuery(gitStatusQueryOptions(gitCwd));
|
||||
|
||||
@@ -172,18 +167,12 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
const runImmediateGitActionMutation = useMutation(
|
||||
gitRunStackedActionMutationOptions({ cwd: gitCwd, queryClient }),
|
||||
);
|
||||
const createBranchAndCheckoutMutation = useMutation(
|
||||
gitCreateBranchAndCheckoutMutationOptions({ cwd: gitCwd, queryClient }),
|
||||
);
|
||||
const pullMutation = useMutation(gitPullMutationOptions({ cwd: gitCwd, queryClient }));
|
||||
|
||||
const isRunStackedActionRunning =
|
||||
useIsMutating({ mutationKey: gitMutationKeys.runStackedAction(gitCwd) }) > 0;
|
||||
const isCreateBranchAndCheckoutRunning =
|
||||
useIsMutating({ mutationKey: gitMutationKeys.createBranchAndCheckout(gitCwd) }) > 0;
|
||||
const isPullRunning = useIsMutating({ mutationKey: gitMutationKeys.pull(gitCwd) }) > 0;
|
||||
const isGitActionRunning =
|
||||
isRunStackedActionRunning || isCreateBranchAndCheckoutRunning || isPullRunning;
|
||||
const isGitActionRunning = isRunStackedActionRunning || isPullRunning;
|
||||
const isDefaultBranch = useMemo(() => {
|
||||
const branchName = gitStatusForActions?.branch;
|
||||
if (!branchName) return false;
|
||||
@@ -202,13 +191,23 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
const quickActionDisabledReason = quickAction.disabled
|
||||
? (quickAction.hint ?? "This action is currently unavailable.")
|
||||
: null;
|
||||
const pendingDefaultBranchActionCopy = pendingDefaultBranchAction
|
||||
? resolveDefaultBranchActionDialogCopy({
|
||||
action: pendingDefaultBranchAction.action,
|
||||
branchName: pendingDefaultBranchAction.branchName,
|
||||
includesCommit: pendingDefaultBranchAction.includesCommit,
|
||||
})
|
||||
: null;
|
||||
|
||||
const maybeConfirmPushToDefaultBranch = useCallback(
|
||||
async (action: GitStackedAction): Promise<boolean> => {
|
||||
const api = readNativeApi();
|
||||
if (!api) return false;
|
||||
if (
|
||||
!requiresDefaultBranchConfirmation(action, isDefaultBranch) ||
|
||||
!gitStatusForActions?.branch
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return api.dialogs.confirm(
|
||||
`You're about to push to the default branch "${gitStatusForActions.branch}". Continue?`,
|
||||
);
|
||||
},
|
||||
[gitStatusForActions?.branch, isDefaultBranch],
|
||||
);
|
||||
|
||||
const openExistingPr = useCallback(async () => {
|
||||
const api = readNativeApi();
|
||||
@@ -238,82 +237,43 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
});
|
||||
});
|
||||
}, [gitStatusForActions?.pr?.state, gitStatusForActions?.pr?.url, threadToastData]);
|
||||
|
||||
const runGitActionWithToast = useCallback(
|
||||
async ({
|
||||
action,
|
||||
commitMessage,
|
||||
forcePushOnlyProgress = false,
|
||||
onConfirmed,
|
||||
skipDefaultBranchPrompt = false,
|
||||
statusOverride,
|
||||
isDefaultBranchOverride,
|
||||
progressToastId,
|
||||
}: {
|
||||
action: GitStackedAction;
|
||||
commitMessage?: string;
|
||||
forcePushOnlyProgress?: boolean;
|
||||
onConfirmed?: () => void;
|
||||
skipDefaultBranchPrompt?: boolean;
|
||||
statusOverride?: GitStatusResult | null;
|
||||
isDefaultBranchOverride?: boolean;
|
||||
progressToastId?: GitActionToastId;
|
||||
}) => {
|
||||
const actionStatus = statusOverride ?? gitStatusForActions;
|
||||
const actionIsDefaultBranch = isDefaultBranchOverride ?? isDefaultBranch;
|
||||
const actionBranch = actionStatus?.branch ?? null;
|
||||
const includesCommit =
|
||||
!forcePushOnlyProgress && (action === "commit" || !!actionStatus?.hasWorkingTreeChanges);
|
||||
if (
|
||||
!skipDefaultBranchPrompt &&
|
||||
requiresDefaultBranchConfirmation(action, actionIsDefaultBranch) &&
|
||||
actionBranch
|
||||
) {
|
||||
if (action !== "commit_push" && action !== "commit_push_pr") {
|
||||
return;
|
||||
}
|
||||
setPendingDefaultBranchAction({
|
||||
action,
|
||||
branchName: actionBranch,
|
||||
includesCommit,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
forcePushOnlyProgress,
|
||||
...(onConfirmed ? { onConfirmed } : {}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
const confirmed = await maybeConfirmPushToDefaultBranch(action);
|
||||
if (!confirmed) return;
|
||||
onConfirmed?.();
|
||||
|
||||
const pushTarget = actionBranch ? `origin/${actionBranch}` : undefined;
|
||||
const pushTarget = gitStatusForActions?.branch
|
||||
? `origin/${gitStatusForActions.branch}`
|
||||
: undefined;
|
||||
const progressStages = buildGitActionProgressStages({
|
||||
action,
|
||||
hasCustomCommitMessage: !!commitMessage?.trim(),
|
||||
hasWorkingTreeChanges: !!actionStatus?.hasWorkingTreeChanges,
|
||||
hasWorkingTreeChanges: !!gitStatusForActions?.hasWorkingTreeChanges,
|
||||
forcePushOnly: forcePushOnlyProgress,
|
||||
...(pushTarget ? { pushTarget } : {}),
|
||||
});
|
||||
const resolvedProgressToastId =
|
||||
progressToastId ??
|
||||
toastManager.add({
|
||||
type: "loading",
|
||||
title: progressStages[0] ?? "Running git action...",
|
||||
timeout: 0,
|
||||
data: threadToastData,
|
||||
});
|
||||
|
||||
if (progressToastId) {
|
||||
toastManager.update(progressToastId, {
|
||||
type: "loading",
|
||||
title: progressStages[0] ?? "Running git action...",
|
||||
timeout: 0,
|
||||
data: threadToastData,
|
||||
});
|
||||
}
|
||||
const progressToastId = toastManager.add({
|
||||
type: "loading",
|
||||
title: progressStages[0] ?? "Running git action...",
|
||||
timeout: 0,
|
||||
data: threadToastData,
|
||||
});
|
||||
|
||||
let stageIndex = 0;
|
||||
const stageInterval = setInterval(() => {
|
||||
stageIndex = Math.min(stageIndex + 1, progressStages.length - 1);
|
||||
toastManager.update(resolvedProgressToastId, {
|
||||
toastManager.update(progressToastId, {
|
||||
title: progressStages[stageIndex] ?? "Running git action...",
|
||||
type: "loading",
|
||||
timeout: 0,
|
||||
@@ -335,23 +295,19 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
stopProgressUpdates();
|
||||
const resultToast = summarizeGitResult(result);
|
||||
|
||||
const existingOpenPrUrl = actionStatus?.pr?.state === "open" ? actionStatus.pr.url : undefined;
|
||||
const existingOpenPrUrl =
|
||||
gitStatusForActions?.pr?.state === "open" ? gitStatusForActions.pr.url : undefined;
|
||||
const prUrl = result.pr.url ?? existingOpenPrUrl;
|
||||
const shouldOfferPushCta = action === "commit" && result.commit.status === "created";
|
||||
const shouldOfferOpenPrCta =
|
||||
(action === "commit_push" || action === "commit_push_pr") &&
|
||||
!!prUrl &&
|
||||
!actionIsDefaultBranch;
|
||||
(action === "commit_push" || action === "commit_push_pr") && !!prUrl && !isDefaultBranch;
|
||||
const shouldOfferCreatePrCta =
|
||||
action === "commit_push" &&
|
||||
!prUrl &&
|
||||
result.push.status === "pushed" &&
|
||||
!actionIsDefaultBranch;
|
||||
action === "commit_push" && !prUrl && result.push.status === "pushed" && !isDefaultBranch;
|
||||
const closeResultToast = () => {
|
||||
toastManager.close(resolvedProgressToastId);
|
||||
toastManager.close(progressToastId);
|
||||
};
|
||||
|
||||
toastManager.update(resolvedProgressToastId, {
|
||||
toastManager.update(progressToastId, {
|
||||
type: "success",
|
||||
title: resultToast.title,
|
||||
description: resultToast.description,
|
||||
@@ -369,8 +325,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
action: "commit_push",
|
||||
forcePushOnlyProgress: true,
|
||||
onConfirmed: closeResultToast,
|
||||
statusOverride: actionStatus,
|
||||
isDefaultBranchOverride: actionIsDefaultBranch,
|
||||
});
|
||||
},
|
||||
},
|
||||
@@ -393,11 +347,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
children: "Create PR",
|
||||
onClick: () => {
|
||||
closeResultToast();
|
||||
void runGitActionWithToast({
|
||||
action: "commit_push_pr",
|
||||
statusOverride: actionStatus,
|
||||
isDefaultBranchOverride: actionIsDefaultBranch,
|
||||
});
|
||||
setActiveDialogAction("create_pr");
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -405,7 +355,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
});
|
||||
} catch (err) {
|
||||
stopProgressUpdates();
|
||||
toastManager.update(resolvedProgressToastId, {
|
||||
toastManager.update(progressToastId, {
|
||||
type: "error",
|
||||
title: "Action failed",
|
||||
description: err instanceof Error ? err.message : "An error occurred.",
|
||||
@@ -415,109 +365,17 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
},
|
||||
|
||||
[
|
||||
gitStatusForActions?.branch,
|
||||
gitStatusForActions?.hasWorkingTreeChanges,
|
||||
gitStatusForActions?.pr,
|
||||
isDefaultBranch,
|
||||
maybeConfirmPushToDefaultBranch,
|
||||
runImmediateGitActionMutation,
|
||||
setPendingDefaultBranchAction,
|
||||
threadToastData,
|
||||
gitStatusForActions,
|
||||
],
|
||||
);
|
||||
|
||||
const continuePendingDefaultBranchAction = useCallback(() => {
|
||||
if (!pendingDefaultBranchAction) return;
|
||||
const { action, commitMessage, forcePushOnlyProgress, onConfirmed } = pendingDefaultBranchAction;
|
||||
setPendingDefaultBranchAction(null);
|
||||
void runGitActionWithToast({
|
||||
action,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
forcePushOnlyProgress,
|
||||
...(onConfirmed ? { onConfirmed } : {}),
|
||||
skipDefaultBranchPrompt: true,
|
||||
});
|
||||
}, [pendingDefaultBranchAction, runGitActionWithToast]);
|
||||
|
||||
const checkoutNewBranchAndRunAction = useCallback(
|
||||
(actionParams: {
|
||||
action: GitStackedAction;
|
||||
commitMessage?: string;
|
||||
forcePushOnlyProgress?: boolean;
|
||||
onConfirmed?: () => void;
|
||||
}) => {
|
||||
const branchName = resolveAutoFeatureBranchName(
|
||||
branchList?.branches.map((branch) => branch.name) ?? [],
|
||||
);
|
||||
|
||||
const checkoutPromise = createBranchAndCheckoutMutation.mutateAsync(branchName);
|
||||
const checkoutToastId = toastManager.add({
|
||||
type: "loading",
|
||||
title: `Creating ${branchName}...`,
|
||||
timeout: 0,
|
||||
data: threadToastData,
|
||||
});
|
||||
|
||||
void checkoutPromise
|
||||
.then(() => {
|
||||
const statusOverride = gitStatusForActions
|
||||
? {
|
||||
...gitStatusForActions,
|
||||
branch: branchName,
|
||||
pr: null,
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
}
|
||||
: null;
|
||||
return runGitActionWithToast({
|
||||
...actionParams,
|
||||
skipDefaultBranchPrompt: true,
|
||||
statusOverride,
|
||||
isDefaultBranchOverride: false,
|
||||
progressToastId: checkoutToastId,
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
toastManager.update(checkoutToastId, {
|
||||
type: "error",
|
||||
title: "Failed to checkout feature branch",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
data: threadToastData,
|
||||
});
|
||||
});
|
||||
},
|
||||
[
|
||||
branchList?.branches,
|
||||
createBranchAndCheckoutMutation,
|
||||
gitStatusForActions,
|
||||
runGitActionWithToast,
|
||||
setActiveDialogAction,
|
||||
threadToastData,
|
||||
],
|
||||
);
|
||||
|
||||
const checkoutFeatureBranchAndContinuePendingAction = useCallback(() => {
|
||||
if (!pendingDefaultBranchAction) return;
|
||||
const { action, commitMessage, forcePushOnlyProgress, onConfirmed } = pendingDefaultBranchAction;
|
||||
setPendingDefaultBranchAction(null);
|
||||
checkoutNewBranchAndRunAction({
|
||||
action,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
forcePushOnlyProgress,
|
||||
...(onConfirmed ? { onConfirmed } : {}),
|
||||
});
|
||||
}, [pendingDefaultBranchAction, checkoutNewBranchAndRunAction]);
|
||||
|
||||
const runDialogActionOnNewBranch = useCallback(() => {
|
||||
if (!isCommitDialogOpen) return;
|
||||
const commitMessage = dialogCommitMessage.trim();
|
||||
|
||||
setIsCommitDialogOpen(false);
|
||||
setDialogCommitMessage("");
|
||||
|
||||
checkoutNewBranchAndRunAction({
|
||||
action: "commit",
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
});
|
||||
}, [isCommitDialogOpen, dialogCommitMessage, checkoutNewBranchAndRunAction]);
|
||||
|
||||
const runQuickAction = useCallback(() => {
|
||||
if (quickAction.kind === "open_pr") {
|
||||
void openExistingPr();
|
||||
@@ -569,31 +427,30 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
void runGitActionWithToast({ action: "commit_push", forcePushOnlyProgress: true });
|
||||
return;
|
||||
}
|
||||
if (item.dialogAction === "create_pr") {
|
||||
void runGitActionWithToast({ action: "commit_push_pr" });
|
||||
return;
|
||||
if (item.dialogAction) {
|
||||
setActiveDialogAction(item.dialogAction);
|
||||
}
|
||||
setIsCommitDialogOpen(true);
|
||||
},
|
||||
[openExistingPr, runGitActionWithToast, setIsCommitDialogOpen],
|
||||
[openExistingPr, runGitActionWithToast],
|
||||
);
|
||||
|
||||
const runDialogAction = useCallback(() => {
|
||||
if (!isCommitDialogOpen) return;
|
||||
const commitMessage = dialogCommitMessage.trim();
|
||||
setIsCommitDialogOpen(false);
|
||||
setDialogCommitMessage("");
|
||||
if (!activeDialogAction) return;
|
||||
const action: GitStackedAction =
|
||||
activeDialogAction === "commit"
|
||||
? "commit"
|
||||
: activeDialogAction === "push"
|
||||
? "commit_push"
|
||||
: "commit_push_pr";
|
||||
const commitMessage = activeDialogAction === "commit" ? dialogCommitMessage.trim() : "";
|
||||
const forcePushOnlyProgress = activeDialogAction === "push";
|
||||
setActiveDialogAction(null);
|
||||
void runGitActionWithToast({
|
||||
action: "commit",
|
||||
action,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(forcePushOnlyProgress ? { forcePushOnlyProgress } : {}),
|
||||
});
|
||||
}, [
|
||||
dialogCommitMessage,
|
||||
isCommitDialogOpen,
|
||||
runGitActionWithToast,
|
||||
setDialogCommitMessage,
|
||||
setIsCommitDialogOpen,
|
||||
]);
|
||||
}, [activeDialogAction, dialogCommitMessage, runGitActionWithToast]);
|
||||
|
||||
const openChangedFileInEditor = useCallback(
|
||||
(filePath: string) => {
|
||||
@@ -749,29 +606,68 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
)}
|
||||
|
||||
<Dialog
|
||||
open={isCommitDialogOpen}
|
||||
open={activeDialogAction !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
setIsCommitDialogOpen(false);
|
||||
setActiveDialogAction(null);
|
||||
setDialogCommitMessage("");
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogPopup>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{COMMIT_DIALOG_TITLE}</DialogTitle>
|
||||
<DialogDescription>{COMMIT_DIALOG_DESCRIPTION}</DialogDescription>
|
||||
<DialogTitle>{DIALOG_TITLE_BY_ACTION[activeDialogAction ?? "commit"]}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{DIALOG_DESCRIPTION_BY_ACTION[activeDialogAction ?? "commit"]}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogPanel className="space-y-4">
|
||||
<div className="space-y-3 rounded-lg border border-input bg-muted/40 p-3 text-xs">
|
||||
<div className="grid grid-cols-[auto_1fr] items-center gap-x-2 gap-y-1">
|
||||
<span className="text-muted-foreground">Branch</span>
|
||||
<span className="flex items-center justify-between gap-2">
|
||||
<span className="font-medium">{gitStatusForActions?.branch ?? "(detached HEAD)"}</span>
|
||||
{isDefaultBranch && (
|
||||
<span className="text-right text-warning text-xs">Warning: default branch</span>
|
||||
)}
|
||||
<span className="font-medium">
|
||||
{gitStatusForActions?.branch ?? "(detached HEAD)"}
|
||||
</span>
|
||||
{activeDialogAction !== "commit" && (
|
||||
<>
|
||||
<span className="text-muted-foreground">Upstream</span>
|
||||
<span className="font-medium">
|
||||
{!gitStatusForActions || !gitStatusForActions.hasUpstream
|
||||
? "No upstream configured"
|
||||
: gitStatusForActions.aheadCount === 0 &&
|
||||
gitStatusForActions.behindCount === 0
|
||||
? "Up to date"
|
||||
: gitStatusForActions.aheadCount > 0 &&
|
||||
gitStatusForActions.behindCount > 0
|
||||
? `Diverged (+${gitStatusForActions.aheadCount} / -${gitStatusForActions.behindCount})`
|
||||
: gitStatusForActions.aheadCount > 0
|
||||
? `Ahead by ${gitStatusForActions.aheadCount}`
|
||||
: `Behind by ${gitStatusForActions.behindCount}`}
|
||||
</span>
|
||||
<span className="text-muted-foreground">Working tree</span>
|
||||
<span className="font-medium">
|
||||
{!gitStatusForActions || !gitStatusForActions.hasWorkingTreeChanges
|
||||
? "Clean"
|
||||
: `${gitStatusForActions.workingTree.files.length} file(s)`}
|
||||
</span>
|
||||
<span className="text-muted-foreground">Diff</span>
|
||||
<span className="font-mono">
|
||||
{!gitStatusForActions || !gitStatusForActions.hasWorkingTreeChanges ? (
|
||||
"none"
|
||||
) : (
|
||||
<>
|
||||
<span className="text-success">
|
||||
+{gitStatusForActions.workingTree.insertions}
|
||||
</span>
|
||||
<span className="text-muted-foreground"> / </span>
|
||||
<span className="text-destructive">
|
||||
-{gitStatusForActions.workingTree.deletions}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<p className="text-muted-foreground">Files</p>
|
||||
@@ -811,61 +707,35 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs font-medium">Commit message (optional)</p>
|
||||
<Textarea
|
||||
value={dialogCommitMessage}
|
||||
onChange={(event) => setDialogCommitMessage(event.target.value)}
|
||||
placeholder="Leave empty to auto-generate"
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
{activeDialogAction === "commit" && (
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs font-medium">Commit message (optional)</p>
|
||||
<Textarea
|
||||
value={dialogCommitMessage}
|
||||
onChange={(event) => setDialogCommitMessage(event.target.value)}
|
||||
placeholder="Leave empty to auto-generate"
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</DialogPanel>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setIsCommitDialogOpen(false);
|
||||
setActiveDialogAction(null);
|
||||
setDialogCommitMessage("");
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={runDialogActionOnNewBranch}>
|
||||
Commit on new branch
|
||||
</Button>
|
||||
<Button size="sm" onClick={runDialogAction}>
|
||||
Commit
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
|
||||
<Dialog
|
||||
open={pendingDefaultBranchAction !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
setPendingDefaultBranchAction(null);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogPopup className="max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{pendingDefaultBranchActionCopy?.title ?? "Run action on default branch?"}
|
||||
</DialogTitle>
|
||||
<DialogDescription>{pendingDefaultBranchActionCopy?.description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" size="sm" onClick={() => setPendingDefaultBranchAction(null)}>
|
||||
Abort
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={continuePendingDefaultBranchAction}>
|
||||
{pendingDefaultBranchActionCopy?.continueLabel ?? "Continue"}
|
||||
</Button>
|
||||
<Button size="sm" onClick={checkoutFeatureBranchAndContinuePendingAction}>
|
||||
Checkout feature branch & continue
|
||||
{activeDialogAction === "commit"
|
||||
? "Commit"
|
||||
: activeDialogAction === "push"
|
||||
? "Push"
|
||||
: "Create PR"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogPopup>
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
"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",
|
||||
|
||||
@@ -20,6 +20,7 @@ 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 },
|
||||
@@ -190,7 +191,7 @@ export function createDevRunnerEnv({ mode, env, offset, envOverrides }) {
|
||||
}
|
||||
output.VITE_WS_URL = `ws://localhost:${parsedServerPort}`;
|
||||
|
||||
if (mode === "dev" || mode === "dev:server" || mode === "dev:web") {
|
||||
if (mode === "dev" || mode === "dev:server" || mode === "dev:web" || mode === "dev:mobile") {
|
||||
// Running server/web in browser mode should not inherit desktop launcher state.
|
||||
output.T3CODE_MODE = "web";
|
||||
if (!("T3CODE_NO_BROWSER" in envOverrides)) {
|
||||
|
||||