Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a950fde73a | ||
|
|
0ea7755363 | ||
|
|
206eb6a785 | ||
|
|
de9ec2bc73 | ||
|
|
1a66e517cd | ||
|
|
33e6f35ce9 | ||
|
|
e8896fe02d | ||
|
|
e89b053269 | ||
|
|
d052d481d8 | ||
|
|
fcbb494af7 | ||
|
|
2980a853e5 | ||
|
|
56de1465fa | ||
|
|
b500106fde | ||
|
|
7f2a95fe14 | ||
|
|
4b3825e500 | ||
|
|
e8dfc42f44 | ||
|
|
37e17e9207 | ||
|
|
fe86836b43 | ||
|
|
973e62373e | ||
|
|
dcdb9ac923 | ||
|
|
46347e2bd2 |
No files matched your search
@@ -1,264 +0,0 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
bump:
|
||||
description: "Semantic version bump to apply before release"
|
||||
required: true
|
||||
default: patch
|
||||
type: choice
|
||||
options:
|
||||
- patch
|
||||
- minor
|
||||
- major
|
||||
release_name:
|
||||
description: "Display name for the GitHub release"
|
||||
required: false
|
||||
type: string
|
||||
draft:
|
||||
description: "Create release as draft"
|
||||
required: true
|
||||
default: true
|
||||
type: boolean
|
||||
prerelease:
|
||||
description: "Mark release as pre-release"
|
||||
required: true
|
||||
default: true
|
||||
type: boolean
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
concurrency:
|
||||
group: release-${{ github.ref_name }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
prepare-release:
|
||||
name: Bump versions, commit, and tag
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
tag: ${{ steps.bump-version.outputs.tag }}
|
||||
version: ${{ steps.bump-version.outputs.version }}
|
||||
steps:
|
||||
- name: Ensure workflow runs from a branch
|
||||
run: |
|
||||
if [ "${GITHUB_REF_TYPE}" != "branch" ]; then
|
||||
echo "workflow_dispatch must be run from a branch ref, got: ${GITHUB_REF_TYPE}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ github.ref_name }}
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Bump app versions and infer release tag
|
||||
id: bump-version
|
||||
run: |
|
||||
node --input-type=module <<'EOF'
|
||||
import fs from "node:fs";
|
||||
|
||||
const bump = process.env.RELEASE_BUMP;
|
||||
const files = [
|
||||
"apps/server/package.json",
|
||||
"apps/desktop/package.json",
|
||||
"apps/web/package.json",
|
||||
];
|
||||
const sourceVersionFile = "apps/server/package.json";
|
||||
|
||||
const semverRegex = /^(\d+)\.(\d+)\.(\d+)$/;
|
||||
const versions = files.map((file) => {
|
||||
const json = JSON.parse(fs.readFileSync(file, "utf8"));
|
||||
return { file, version: json.version };
|
||||
});
|
||||
|
||||
const source = versions.find((entry) => entry.file === sourceVersionFile);
|
||||
if (!source) {
|
||||
throw new Error(`Could not find source version file '${sourceVersionFile}'.`);
|
||||
}
|
||||
const outOfSync = versions.filter((entry) => entry.version !== source.version);
|
||||
if (outOfSync.length > 0) {
|
||||
const details = outOfSync.map((entry) => `${entry.file}=${entry.version}`).join(", ");
|
||||
console.warn(
|
||||
`Detected out-of-sync app versions. Using ${sourceVersionFile}=${source.version} as source of truth. Others: ${details}`,
|
||||
);
|
||||
}
|
||||
|
||||
const currentVersion = source.version;
|
||||
const match = semverRegex.exec(currentVersion);
|
||||
if (!match) {
|
||||
throw new Error(
|
||||
`Version '${currentVersion}' is not a supported plain semver (x.y.z).`,
|
||||
);
|
||||
}
|
||||
|
||||
let major = Number.parseInt(match[1], 10);
|
||||
let minor = Number.parseInt(match[2], 10);
|
||||
let patch = Number.parseInt(match[3], 10);
|
||||
|
||||
if (bump === "patch") {
|
||||
patch += 1;
|
||||
} else if (bump === "minor") {
|
||||
minor += 1;
|
||||
patch = 0;
|
||||
} else if (bump === "major") {
|
||||
major += 1;
|
||||
minor = 0;
|
||||
patch = 0;
|
||||
} else {
|
||||
throw new Error(`Unsupported bump type '${bump}'.`);
|
||||
}
|
||||
|
||||
const version = `${major}.${minor}.${patch}`;
|
||||
const tag = `v${version}`;
|
||||
|
||||
for (const file of files) {
|
||||
const json = JSON.parse(fs.readFileSync(file, "utf8"));
|
||||
json.version = version;
|
||||
fs.writeFileSync(file, `${JSON.stringify(json, null, 2)}\n`, "utf8");
|
||||
}
|
||||
|
||||
const outputPath = process.env.GITHUB_OUTPUT;
|
||||
fs.appendFileSync(outputPath, `version=${version}\n`);
|
||||
fs.appendFileSync(outputPath, `tag=${tag}\n`);
|
||||
|
||||
console.log(`Bumped version ${currentVersion} -> ${version}`);
|
||||
console.log(`Inferred release tag: ${tag}`);
|
||||
EOF
|
||||
env:
|
||||
RELEASE_BUMP: ${{ inputs.bump }}
|
||||
|
||||
- name: Validate inferred tag does not already exist
|
||||
run: |
|
||||
tag="${{ steps.bump-version.outputs.tag }}"
|
||||
if git rev-parse --verify --quiet "refs/tags/${tag}"; then
|
||||
echo "Tag ${tag} already exists locally."
|
||||
exit 1
|
||||
fi
|
||||
if git ls-remote --tags origin "${tag}" | grep -q .; then
|
||||
echo "Tag ${tag} already exists on origin."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Commit version bump
|
||||
run: |
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git add apps/server/package.json apps/desktop/package.json apps/web/package.json
|
||||
if git diff --cached --quiet; then
|
||||
echo "No version change detected; refusing to create empty release commit."
|
||||
exit 1
|
||||
fi
|
||||
git commit -m "chore(release): bump app versions to ${{ steps.bump-version.outputs.version }}
|
||||
|
||||
Co-authored-by: codex <[email protected]>"
|
||||
|
||||
- name: Create and push release tag
|
||||
run: |
|
||||
git tag -a "${{ steps.bump-version.outputs.tag }}" -m "Release ${{ steps.bump-version.outputs.tag }}"
|
||||
git push origin "${{ github.ref_name }}"
|
||||
git push origin "refs/tags/${{ steps.bump-version.outputs.tag }}"
|
||||
|
||||
build-macos:
|
||||
name: Build and package macOS (${{ matrix.arch }})
|
||||
runs-on: macos-14
|
||||
needs: prepare-release
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
arch:
|
||||
- arm64
|
||||
- x64
|
||||
env:
|
||||
CI: "true"
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ needs.prepare-release.outputs.tag }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Cache Bun and Turbo
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.bun/install/cache
|
||||
.turbo
|
||||
key: ${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-${{ hashFiles('turbo.json') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Build and package macOS artifact
|
||||
run: |
|
||||
bun run dist:desktop:dmg -- --arch "${{ matrix.arch }}" --version "${{ needs.prepare-release.outputs.version }}"
|
||||
ls -lah release
|
||||
# TODO: Add production macOS signing and notarization in CI:
|
||||
# - Import Developer ID Application certificate + private key into keychain.
|
||||
# - Provide APPLE_ID / APPLE_TEAM_ID / APPLE_APP_SPECIFIC_PASSWORD secrets.
|
||||
# - Build with signing enabled and notarize + staple before release upload.
|
||||
|
||||
- name: Generate SHA256 checksums
|
||||
run: |
|
||||
checksum_file="release/SHA256SUMS-${{ matrix.arch }}.txt"
|
||||
find release -maxdepth 1 -type f ! -name "SHA256SUMS-*.txt" -print0 \
|
||||
| xargs -0 shasum -a 256 > "$checksum_file"
|
||||
cat "$checksum_file"
|
||||
|
||||
- name: Upload packaged artifacts to workflow run
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: release-assets-${{ needs.prepare-release.outputs.tag }}-${{ matrix.arch }}
|
||||
path: release/*
|
||||
if-no-files-found: error
|
||||
|
||||
publish-release:
|
||||
name: Create GitHub release
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- prepare-release
|
||||
- build-macos
|
||||
steps:
|
||||
- name: Download packaged artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
pattern: release-assets-${{ needs.prepare-release.outputs.tag }}-*
|
||||
merge-multiple: true
|
||||
path: release-assets
|
||||
|
||||
- name: Create GitHub release and upload assets
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ needs.prepare-release.outputs.tag }}
|
||||
target_commitish: ${{ needs.prepare-release.outputs.tag }}
|
||||
name: ${{ inputs.release_name != '' && inputs.release_name || needs.prepare-release.outputs.tag }}
|
||||
draft: ${{ inputs.draft }}
|
||||
prerelease: ${{ inputs.prerelease }}
|
||||
generate_release_notes: true
|
||||
files: release-assets/*
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
# TODO: Add a multi-platform release matrix and publish Linux/Windows installers:
|
||||
# - Linux: build/sign AppImage/deb/rpm artifacts on ubuntu runners.
|
||||
# - Windows: build/sign MSI/NSIS artifacts on windows runners.
|
||||
# - Consider per-platform updater metadata/signature publishing strategy.
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -393,7 +393,7 @@ const makeGitCore = Effect.gen(function* () {
|
||||
hasUpstream: details.hasUpstream,
|
||||
aheadCount: details.aheadCount,
|
||||
behindCount: details.behindCount,
|
||||
openPr: null,
|
||||
pr: null,
|
||||
})),
|
||||
);
|
||||
|
||||
|
||||
@@ -297,7 +297,7 @@ function makeManager(input?: {
|
||||
const GitManagerTestLayer = Layer.provideMerge(GitServiceLive, NodeServices.layer);
|
||||
|
||||
it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
it.effect("status includes open PR metadata when branch already has an open PR", () =>
|
||||
it.effect("status includes PR metadata when branch already has an open PR", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -324,17 +324,103 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("feature/status-open-pr");
|
||||
expect(status.openPr).toEqual({
|
||||
expect(status.pr).toEqual({
|
||||
number: 13,
|
||||
title: "Existing PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-open-pr",
|
||||
state: "open",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status is resilient to gh lookup failures and returns openPr null", () =>
|
||||
it.effect("status returns merged PR state when latest PR was merged", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/status-merged-pr"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 22,
|
||||
title: "Merged PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/22",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/status-merged-pr",
|
||||
state: "MERGED",
|
||||
mergedAt: "2026-01-30T10:00:00Z",
|
||||
updatedAt: "2026-01-30T10:00:00Z",
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("feature/status-merged-pr");
|
||||
expect(status.pr).toEqual({
|
||||
number: 22,
|
||||
title: "Merged PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/22",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-merged-pr",
|
||||
state: "merged",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status prefers open PR when merged PR has newer updatedAt", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/status-open-over-merged"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 45,
|
||||
title: "Merged PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/45",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/status-open-over-merged",
|
||||
state: "MERGED",
|
||||
mergedAt: "2026-01-31T10:00:00Z",
|
||||
updatedAt: "2026-02-01T10:00:00Z",
|
||||
},
|
||||
{
|
||||
number: 46,
|
||||
title: "Open PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/46",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/status-open-over-merged",
|
||||
state: "OPEN",
|
||||
updatedAt: "2026-01-30T10:00:00Z",
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("feature/status-open-over-merged");
|
||||
expect(status.pr).toEqual({
|
||||
number: 46,
|
||||
title: "Open PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/46",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-open-over-merged",
|
||||
state: "open",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status is resilient to gh lookup failures and returns pr null", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -354,7 +440,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("feature/status-no-gh");
|
||||
expect(status.openPr).toBeNull();
|
||||
expect(status.pr).toBeNull();
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -16,6 +16,62 @@ interface OpenPrInfo {
|
||||
headRefName: string;
|
||||
}
|
||||
|
||||
interface PullRequestInfo extends OpenPrInfo {
|
||||
state: "open" | "closed" | "merged";
|
||||
updatedAt: string | null;
|
||||
}
|
||||
|
||||
function parsePullRequestList(raw: unknown): PullRequestInfo[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
|
||||
const parsed: PullRequestInfo[] = [];
|
||||
for (const entry of raw) {
|
||||
if (!entry || typeof entry !== "object") continue;
|
||||
const record = entry as Record<string, unknown>;
|
||||
const number = record.number;
|
||||
const title = record.title;
|
||||
const url = record.url;
|
||||
const baseRefName = record.baseRefName;
|
||||
const headRefName = record.headRefName;
|
||||
const state = record.state;
|
||||
const mergedAt = record.mergedAt;
|
||||
const updatedAt = record.updatedAt;
|
||||
if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
typeof title !== "string" ||
|
||||
typeof url !== "string" ||
|
||||
typeof baseRefName !== "string" ||
|
||||
typeof headRefName !== "string"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let normalizedState: "open" | "closed" | "merged";
|
||||
if ((typeof mergedAt === "string" && mergedAt.trim().length > 0) || state === "MERGED") {
|
||||
normalizedState = "merged";
|
||||
} else if (state === "OPEN" || state === undefined || state === null) {
|
||||
normalizedState = "open";
|
||||
} else if (state === "CLOSED") {
|
||||
normalizedState = "closed";
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
|
||||
parsed.push({
|
||||
number,
|
||||
title,
|
||||
url,
|
||||
baseRefName,
|
||||
headRefName,
|
||||
state: normalizedState,
|
||||
updatedAt: typeof updatedAt === "string" && updatedAt.trim().length > 0 ? updatedAt : null,
|
||||
});
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function gitManagerError(operation: string, detail: string, cause?: unknown): GitManagerError {
|
||||
return new GitManagerError({
|
||||
operation,
|
||||
@@ -79,12 +135,13 @@ function extractBranchFromRef(ref: string): string {
|
||||
return normalized.slice(firstSlash + 1).trim();
|
||||
}
|
||||
|
||||
function toStatusOpenPr(pr: OpenPrInfo): {
|
||||
function toStatusPr(pr: PullRequestInfo): {
|
||||
number: number;
|
||||
title: string;
|
||||
url: string;
|
||||
baseBranch: string;
|
||||
headBranch: string;
|
||||
state: "open" | "closed" | "merged";
|
||||
} {
|
||||
return {
|
||||
number: pr.number,
|
||||
@@ -92,6 +149,7 @@ function toStatusOpenPr(pr: OpenPrInfo): {
|
||||
url: pr.url,
|
||||
baseBranch: pr.baseRefName,
|
||||
headBranch: pr.headRefName,
|
||||
state: pr.state,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -123,10 +181,56 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
url: first.url,
|
||||
baseRefName: first.baseRefName,
|
||||
headRefName: first.headRefName,
|
||||
} satisfies OpenPrInfo;
|
||||
state: "open",
|
||||
updatedAt: null,
|
||||
} satisfies PullRequestInfo;
|
||||
}),
|
||||
);
|
||||
|
||||
const findLatestPr = (cwd: string, branch: string) =>
|
||||
Effect.gen(function* () {
|
||||
const stdout = yield* gitHubCli
|
||||
.execute({
|
||||
cwd,
|
||||
args: [
|
||||
"pr",
|
||||
"list",
|
||||
"--head",
|
||||
branch,
|
||||
"--state",
|
||||
"all",
|
||||
"--limit",
|
||||
"20",
|
||||
"--json",
|
||||
"number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt",
|
||||
],
|
||||
})
|
||||
.pipe(Effect.map((result) => result.stdout));
|
||||
|
||||
const raw = stdout.trim();
|
||||
if (raw.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parsedJson = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) =>
|
||||
gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause),
|
||||
});
|
||||
|
||||
const parsed = parsePullRequestList(parsedJson).toSorted((a, b) => {
|
||||
const left = a.updatedAt ? Date.parse(a.updatedAt) : 0;
|
||||
const right = b.updatedAt ? Date.parse(b.updatedAt) : 0;
|
||||
return right - left;
|
||||
});
|
||||
|
||||
const latestOpenPr = parsed.find((pr) => pr.state === "open");
|
||||
if (latestOpenPr) {
|
||||
return latestOpenPr;
|
||||
}
|
||||
return parsed[0] ?? null;
|
||||
});
|
||||
|
||||
const resolveBaseBranch = (cwd: string, branch: string, upstreamRef: string | null) =>
|
||||
Effect.gen(function* () {
|
||||
const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
|
||||
@@ -258,10 +362,10 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
const status: GitManagerShape["status"] = Effect.fnUntraced(function* (input) {
|
||||
const details = yield* gitCore.statusDetails(input.cwd);
|
||||
|
||||
const openPr =
|
||||
details.branch && details.hasUpstream
|
||||
? yield* findOpenPr(input.cwd, details.branch).pipe(
|
||||
Effect.map((pr) => (pr ? toStatusOpenPr(pr) : null)),
|
||||
const pr =
|
||||
details.branch !== null
|
||||
? yield* findLatestPr(input.cwd, details.branch).pipe(
|
||||
Effect.map((latest) => (latest ? toStatusPr(latest) : null)),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
)
|
||||
: null;
|
||||
@@ -273,7 +377,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
hasUpstream: details.hasUpstream,
|
||||
aheadCount: details.aheadCount,
|
||||
behindCount: details.behindCount,
|
||||
openPr,
|
||||
pr,
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ import type {
|
||||
|
||||
import type { GitCommandError } from "../Errors.ts";
|
||||
|
||||
export interface GitStatusDetails extends Omit<GitStatusResult, "openPr"> {
|
||||
export interface GitStatusDetails extends Omit<GitStatusResult, "pr"> {
|
||||
upstreamRef: string | null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1521,7 +1521,7 @@ describe("WebSocket Server", () => {
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
openPr: null,
|
||||
pr: null,
|
||||
};
|
||||
|
||||
const status = vi.fn(() => Effect.succeed(statusResult));
|
||||
|
||||
@@ -22,12 +22,10 @@
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"effect": "catalog:",
|
||||
"highlight.js": "^11.11.1",
|
||||
"lucide-react": "^0.564.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-markdown": "^10.1.0",
|
||||
"rehype-highlight": "^7.0.2",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"tailwind-merge": "^3.4.0"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { getAppModelOptions, normalizeCustomModelSlugs } from "./appSettings";
|
||||
|
||||
describe("normalizeCustomModelSlugs", () => {
|
||||
it("normalizes aliases, removes built-ins, and deduplicates values", () => {
|
||||
expect(
|
||||
normalizeCustomModelSlugs([
|
||||
" custom/internal-model ",
|
||||
"gpt-5.3-codex",
|
||||
"5.3",
|
||||
"custom/internal-model",
|
||||
"",
|
||||
null,
|
||||
]),
|
||||
).toEqual(["custom/internal-model"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getAppModelOptions", () => {
|
||||
it("appends saved custom models after the built-in options", () => {
|
||||
const options = getAppModelOptions(["custom/internal-model"]);
|
||||
|
||||
expect(options.map((option) => option.slug)).toEqual([
|
||||
"gpt-5.3-codex",
|
||||
"gpt-5.3-codex-spark",
|
||||
"gpt-5.2-codex",
|
||||
"gpt-5.2",
|
||||
"custom/internal-model",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps the currently selected custom model available even if it is no longer saved", () => {
|
||||
const options = getAppModelOptions([], "custom/selected-model");
|
||||
|
||||
expect(options.at(-1)).toEqual({
|
||||
slug: "custom/selected-model",
|
||||
name: "custom/selected-model",
|
||||
isCustom: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,11 @@
|
||||
import { useCallback, useSyncExternalStore } from "react";
|
||||
import { Option, Schema } from "effect";
|
||||
import { MODEL_OPTIONS, normalizeModelSlug } from "@t3tools/contracts";
|
||||
|
||||
const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
|
||||
const MAX_CUSTOM_MODEL_COUNT = 32;
|
||||
export const MAX_CUSTOM_MODEL_LENGTH = 256;
|
||||
const BUILT_IN_MODEL_SLUGS = new Set<string>(MODEL_OPTIONS.map((option) => option.slug));
|
||||
|
||||
const AppSettingsSchema = Schema.Struct({
|
||||
codexBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(
|
||||
@@ -14,8 +18,16 @@ const AppSettingsSchema = Schema.Struct({
|
||||
enableAssistantStreaming: Schema.Boolean.pipe(
|
||||
Schema.withConstructorDefault(() => Option.some(false)),
|
||||
),
|
||||
customCodexModels: Schema.Array(Schema.String).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some([])),
|
||||
),
|
||||
});
|
||||
export type AppSettings = typeof AppSettingsSchema.Type;
|
||||
export interface AppModelOption {
|
||||
slug: string;
|
||||
name: string;
|
||||
isCustom: boolean;
|
||||
}
|
||||
|
||||
const DEFAULT_APP_SETTINGS = AppSettingsSchema.makeUnsafe({});
|
||||
|
||||
@@ -23,6 +35,76 @@ let listeners: Array<() => void> = [];
|
||||
let cachedRawSettings: string | null | undefined;
|
||||
let cachedSnapshot: AppSettings = DEFAULT_APP_SETTINGS;
|
||||
|
||||
export function normalizeCustomModelSlugs(
|
||||
models: Iterable<string | null | undefined>,
|
||||
): AppSettings["customCodexModels"] {
|
||||
const normalizedModels: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (const candidate of models) {
|
||||
const normalized = normalizeModelSlug(candidate);
|
||||
if (
|
||||
!normalized ||
|
||||
normalized.length > MAX_CUSTOM_MODEL_LENGTH ||
|
||||
BUILT_IN_MODEL_SLUGS.has(normalized) ||
|
||||
seen.has(normalized)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
seen.add(normalized);
|
||||
normalizedModels.push(normalized);
|
||||
if (normalizedModels.length >= MAX_CUSTOM_MODEL_COUNT) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return normalizedModels;
|
||||
}
|
||||
|
||||
function normalizeAppSettings(settings: AppSettings): AppSettings {
|
||||
return {
|
||||
...settings,
|
||||
customCodexModels: normalizeCustomModelSlugs(settings.customCodexModels),
|
||||
};
|
||||
}
|
||||
|
||||
export function getAppModelOptions(
|
||||
customModels: readonly string[],
|
||||
selectedModel?: string | null,
|
||||
): AppModelOption[] {
|
||||
const options: AppModelOption[] = MODEL_OPTIONS.map(({ slug, name }) => ({
|
||||
slug,
|
||||
name,
|
||||
isCustom: false,
|
||||
}));
|
||||
const seen = new Set(options.map((option) => option.slug));
|
||||
|
||||
for (const slug of normalizeCustomModelSlugs(customModels)) {
|
||||
if (seen.has(slug)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
seen.add(slug);
|
||||
options.push({
|
||||
slug,
|
||||
name: slug,
|
||||
isCustom: true,
|
||||
});
|
||||
}
|
||||
|
||||
const normalizedSelectedModel = normalizeModelSlug(selectedModel);
|
||||
if (normalizedSelectedModel && !seen.has(normalizedSelectedModel)) {
|
||||
options.push({
|
||||
slug: normalizedSelectedModel,
|
||||
name: normalizedSelectedModel,
|
||||
isCustom: true,
|
||||
});
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
function emitChange(): void {
|
||||
for (const listener of listeners) {
|
||||
listener();
|
||||
@@ -35,7 +117,7 @@ function parsePersistedSettings(value: string | null): AppSettings {
|
||||
}
|
||||
|
||||
try {
|
||||
return Schema.decodeSync(Schema.fromJsonString(AppSettingsSchema))(value);
|
||||
return normalizeAppSettings(Schema.decodeSync(Schema.fromJsonString(AppSettingsSchema))(value));
|
||||
} catch {
|
||||
return DEFAULT_APP_SETTINGS;
|
||||
}
|
||||
@@ -96,10 +178,12 @@ export function useAppSettings() {
|
||||
);
|
||||
|
||||
const updateSettings = useCallback((patch: Partial<AppSettings>) => {
|
||||
const next = Schema.decodeSync(AppSettingsSchema)({
|
||||
...getAppSettingsSnapshot(),
|
||||
...patch,
|
||||
});
|
||||
const next = normalizeAppSettings(
|
||||
Schema.decodeSync(AppSettingsSchema)({
|
||||
...getAppSettingsSnapshot(),
|
||||
...patch,
|
||||
}),
|
||||
);
|
||||
persistSettings(next);
|
||||
emitChange();
|
||||
}, []);
|
||||
|
||||
@@ -1,18 +1,207 @@
|
||||
import { memo, useMemo } from "react";
|
||||
import {
|
||||
getSharedHighlighter,
|
||||
type DiffsHighlighter,
|
||||
type SupportedLanguages,
|
||||
} from "@pierre/diffs";
|
||||
import { CheckIcon, CopyIcon } from "lucide-react";
|
||||
import {
|
||||
Children,
|
||||
Suspense,
|
||||
isValidElement,
|
||||
use,
|
||||
useCallback,
|
||||
memo,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import type { Components } from "react-markdown";
|
||||
import ReactMarkdown from "react-markdown";
|
||||
import rehypeHighlight from "rehype-highlight";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
|
||||
import { fnv1a32 } from "../lib/diffRendering";
|
||||
import { LRUCache } from "../lib/lruCache";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { resolveMarkdownFileLinkTarget } from "../markdown-links";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { preferredTerminalEditor } from "../terminal-links";
|
||||
|
||||
interface ChatMarkdownProps {
|
||||
text: string;
|
||||
cwd: string | undefined;
|
||||
isStreaming?: boolean;
|
||||
}
|
||||
|
||||
function ChatMarkdown({ text, cwd }: ChatMarkdownProps) {
|
||||
const CODE_FENCE_LANGUAGE_REGEX = /(?:^|\s)language-([^\s]+)/;
|
||||
const MAX_HIGHLIGHT_CACHE_ENTRIES = 500;
|
||||
const MAX_HIGHLIGHT_CACHE_MEMORY_BYTES = 50 * 1024 * 1024;
|
||||
const highlightedCodeCache = new LRUCache<string>(
|
||||
MAX_HIGHLIGHT_CACHE_ENTRIES,
|
||||
MAX_HIGHLIGHT_CACHE_MEMORY_BYTES,
|
||||
);
|
||||
const highlighterPromiseCache = new Map<string, Promise<DiffsHighlighter>>();
|
||||
|
||||
function extractFenceLanguage(className: string | undefined): string {
|
||||
const match = className?.match(CODE_FENCE_LANGUAGE_REGEX);
|
||||
return match?.[1] ?? "text";
|
||||
}
|
||||
|
||||
function nodeToPlainText(node: ReactNode): string {
|
||||
if (typeof node === "string" || typeof node === "number") {
|
||||
return String(node);
|
||||
}
|
||||
if (Array.isArray(node)) {
|
||||
return node.map((child) => nodeToPlainText(child)).join("");
|
||||
}
|
||||
if (isValidElement<{ children?: ReactNode }>(node)) {
|
||||
return nodeToPlainText(node.props.children);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function extractCodeBlock(
|
||||
children: ReactNode,
|
||||
): { className: string | undefined; code: string } | null {
|
||||
const childNodes = Children.toArray(children);
|
||||
if (childNodes.length !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const onlyChild = childNodes[0];
|
||||
if (
|
||||
!isValidElement<{ className?: string; children?: ReactNode }>(onlyChild) ||
|
||||
onlyChild.type !== "code"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
className: onlyChild.props.className,
|
||||
code: nodeToPlainText(onlyChild.props.children),
|
||||
};
|
||||
}
|
||||
|
||||
function createHighlightCacheKey(code: string, language: string, themeName: DiffThemeName): string {
|
||||
return `${fnv1a32(code).toString(36)}:${code.length}:${language}:${themeName}`;
|
||||
}
|
||||
|
||||
function estimateHighlightedSize(html: string, code: string): number {
|
||||
return Math.max(html.length * 2, code.length * 3);
|
||||
}
|
||||
|
||||
function getHighlighterPromise(language: string): Promise<DiffsHighlighter> {
|
||||
const cached = highlighterPromiseCache.get(language);
|
||||
if (cached) return cached;
|
||||
|
||||
const promise = getSharedHighlighter({
|
||||
themes: [resolveDiffThemeName("dark"), resolveDiffThemeName("light")],
|
||||
langs: [language as SupportedLanguages],
|
||||
preferredHighlighter: "shiki-js",
|
||||
});
|
||||
highlighterPromiseCache.set(language, promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
function MarkdownCodeBlock({ code, children }: { code: string; children: ReactNode }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const handleCopy = useCallback(() => {
|
||||
if (typeof navigator === "undefined" || navigator.clipboard == null) {
|
||||
return;
|
||||
}
|
||||
void navigator.clipboard
|
||||
.writeText(code)
|
||||
.then(() => {
|
||||
if (copiedTimerRef.current != null) {
|
||||
clearTimeout(copiedTimerRef.current);
|
||||
}
|
||||
setCopied(true);
|
||||
copiedTimerRef.current = setTimeout(() => {
|
||||
setCopied(false);
|
||||
copiedTimerRef.current = null;
|
||||
}, 1200);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}, [code]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (copiedTimerRef.current != null) {
|
||||
clearTimeout(copiedTimerRef.current);
|
||||
copiedTimerRef.current = null;
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="chat-markdown-codeblock">
|
||||
<button
|
||||
type="button"
|
||||
className="chat-markdown-copy-button"
|
||||
onClick={handleCopy}
|
||||
title={copied ? "Copied" : "Copy code"}
|
||||
aria-label={copied ? "Copied" : "Copy code"}
|
||||
>
|
||||
{copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />}
|
||||
</button>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface SuspenseShikiCodeBlockProps {
|
||||
className: string | undefined;
|
||||
code: string;
|
||||
themeName: DiffThemeName;
|
||||
isStreaming: boolean;
|
||||
}
|
||||
|
||||
function SuspenseShikiCodeBlock({
|
||||
className,
|
||||
code,
|
||||
themeName,
|
||||
isStreaming,
|
||||
}: SuspenseShikiCodeBlockProps) {
|
||||
const language = extractFenceLanguage(className);
|
||||
const cacheKey = createHighlightCacheKey(code, language, themeName);
|
||||
const cachedHighlightedHtml = !isStreaming ? highlightedCodeCache.get(cacheKey) : null;
|
||||
|
||||
if (cachedHighlightedHtml != null) {
|
||||
return (
|
||||
<div
|
||||
className="chat-markdown-shiki"
|
||||
dangerouslySetInnerHTML={{ __html: cachedHighlightedHtml }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const highlighter = use(getHighlighterPromise(language));
|
||||
const highlightedHtml = useMemo(
|
||||
() => highlighter.codeToHtml(code, { lang: language, theme: themeName }),
|
||||
[code, highlighter, language, themeName],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isStreaming) {
|
||||
highlightedCodeCache.set(
|
||||
cacheKey,
|
||||
highlightedHtml,
|
||||
estimateHighlightedSize(highlightedHtml, code),
|
||||
);
|
||||
}
|
||||
}, [cacheKey, code, highlightedHtml, isStreaming]);
|
||||
|
||||
return (
|
||||
<div className="chat-markdown-shiki" dangerouslySetInnerHTML={{ __html: highlightedHtml }} />
|
||||
);
|
||||
}
|
||||
|
||||
function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
|
||||
const { resolvedTheme } = useTheme();
|
||||
const diffThemeName = resolveDiffThemeName(resolvedTheme);
|
||||
const markdownComponents = useMemo<Components>(
|
||||
() => ({
|
||||
a({ node: _node, href, ...props }) {
|
||||
@@ -38,17 +227,32 @@ function ChatMarkdown({ text, cwd }: ChatMarkdownProps) {
|
||||
/>
|
||||
);
|
||||
},
|
||||
pre({ node: _node, children, ...props }) {
|
||||
const codeBlock = extractCodeBlock(children);
|
||||
if (!codeBlock) {
|
||||
return <pre {...props}>{children}</pre>;
|
||||
}
|
||||
|
||||
return (
|
||||
<MarkdownCodeBlock code={codeBlock.code}>
|
||||
<Suspense fallback={<pre {...props}>{children}</pre>}>
|
||||
<SuspenseShikiCodeBlock
|
||||
className={codeBlock.className}
|
||||
code={codeBlock.code}
|
||||
themeName={diffThemeName}
|
||||
isStreaming={isStreaming}
|
||||
/>
|
||||
</Suspense>
|
||||
</MarkdownCodeBlock>
|
||||
);
|
||||
},
|
||||
}),
|
||||
[cwd],
|
||||
[cwd, diffThemeName, isStreaming],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="chat-markdown w-full min-w-0 text-sm leading-relaxed text-foreground/80">
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
rehypePlugins={[[rehypeHighlight, { detect: true, ignoreMissing: true }]]}
|
||||
components={markdownComponents}
|
||||
>
|
||||
<ReactMarkdown remarkPlugins={[remarkGfm]} components={markdownComponents}>
|
||||
{text}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
|
||||
@@ -6,11 +6,9 @@ import {
|
||||
type EditorId,
|
||||
type KeybindingCommand,
|
||||
type MessageId,
|
||||
MODEL_OPTIONS,
|
||||
type ProjectId,
|
||||
type ProjectEntry,
|
||||
type ProjectScript,
|
||||
ModelSlug,
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
REASONING_OPTIONS,
|
||||
@@ -112,7 +110,7 @@ import { Toggle } from "./ui/toggle";
|
||||
import { SidebarTrigger } from "./ui/sidebar";
|
||||
import { newCommandId, newMessageId } from "~/lib/utils";
|
||||
import { readNativeApi } from "~/nativeApi";
|
||||
import { useAppSettings } from "../appSettings";
|
||||
import { getAppModelOptions, useAppSettings } from "../appSettings";
|
||||
import { clamp } from "effect/Number";
|
||||
|
||||
function formatMessageMeta(createdAt: string, duration: string | null): string {
|
||||
@@ -129,12 +127,6 @@ const IMAGE_ONLY_BOOTSTRAP_PROMPT =
|
||||
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
|
||||
const EMPTY_PROJECT_ENTRIES: ProjectEntry[] = [];
|
||||
const COMPOSER_PATH_QUERY_DEBOUNCE_MS = 120;
|
||||
const SEARCHABLE_MODEL_OPTIONS = MODEL_OPTIONS.map(({ slug, name }) => ({
|
||||
slug,
|
||||
name,
|
||||
searchSlug: slug.toLowerCase(),
|
||||
searchName: name.toLowerCase(),
|
||||
}));
|
||||
const SCRIPT_TERMINAL_COLS = 120;
|
||||
const SCRIPT_TERMINAL_ROWS = 30;
|
||||
|
||||
@@ -216,7 +208,7 @@ type ComposerCommandItem =
|
||||
| {
|
||||
id: string;
|
||||
type: "model";
|
||||
model: ModelSlug;
|
||||
model: string;
|
||||
label: string;
|
||||
description: string;
|
||||
};
|
||||
@@ -438,6 +430,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const selectedModel = resolveModelSlug(
|
||||
activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL,
|
||||
);
|
||||
const modelOptions = useMemo(
|
||||
() => getAppModelOptions(settings.customCodexModels, selectedModel),
|
||||
[selectedModel, settings.customCodexModels],
|
||||
);
|
||||
const phase = derivePhase(activeThread?.session ?? null);
|
||||
const isSendBusy = sendPhase !== "idle";
|
||||
const isPreparingWorktree = sendPhase === "preparing-worktree";
|
||||
@@ -614,18 +610,26 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
];
|
||||
}
|
||||
|
||||
return SEARCHABLE_MODEL_OPTIONS.filter(({ searchSlug, searchName }) => {
|
||||
const query = composerTrigger.query.trim().toLowerCase();
|
||||
if (!query) return true;
|
||||
return searchSlug.includes(query) || searchName.includes(query);
|
||||
}).map(({ slug, name }) => ({
|
||||
id: `model:${slug}`,
|
||||
type: "model",
|
||||
model: slug,
|
||||
label: name,
|
||||
description: slug,
|
||||
}));
|
||||
}, [composerTrigger, workspaceEntries]);
|
||||
return modelOptions
|
||||
.map(({ slug, name }) => ({
|
||||
slug,
|
||||
name,
|
||||
searchSlug: slug.toLowerCase(),
|
||||
searchName: name.toLowerCase(),
|
||||
}))
|
||||
.filter(({ searchSlug, searchName }) => {
|
||||
const query = composerTrigger.query.trim().toLowerCase();
|
||||
if (!query) return true;
|
||||
return searchSlug.includes(query) || searchName.includes(query);
|
||||
})
|
||||
.map(({ slug, name }) => ({
|
||||
id: `model:${slug}`,
|
||||
type: "model" as const,
|
||||
model: slug,
|
||||
label: name,
|
||||
description: slug,
|
||||
}));
|
||||
}, [composerTrigger, modelOptions, workspaceEntries]);
|
||||
const composerMenuOpen = Boolean(composerTrigger);
|
||||
const activeComposerMenuItem = useMemo(
|
||||
() =>
|
||||
@@ -1660,7 +1664,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
);
|
||||
|
||||
const onModelSelect = useCallback(
|
||||
(model: ModelSlug) => {
|
||||
(model: string) => {
|
||||
const api = readNativeApi();
|
||||
if (!activeThread) return;
|
||||
if (api) {
|
||||
@@ -2012,7 +2016,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 px-2.5 pb-2.5 sm:flex-nowrap sm:gap-0 sm:px-3 sm:pb-3">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden sm:min-w-max sm:overflow-visible">
|
||||
{/* Model picker */}
|
||||
<ModelPicker model={selectedModel} onModelChange={onModelSelect} />
|
||||
<ModelPicker
|
||||
model={selectedModel}
|
||||
options={modelOptions}
|
||||
onModelChange={onModelSelect}
|
||||
/>
|
||||
|
||||
{/* Divider */}
|
||||
<Separator orientation="vertical" className="mx-0.5 hidden h-4 sm:block" />
|
||||
@@ -2759,7 +2767,11 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0 px-1 py-0.5">
|
||||
<ChatMarkdown text={messageText} cwd={markdownCwd} />
|
||||
<ChatMarkdown
|
||||
text={messageText}
|
||||
cwd={markdownCwd}
|
||||
isStreaming={Boolean(row.message.streaming)}
|
||||
/>
|
||||
{(() => {
|
||||
const turnSummary = turnDiffSummaryByAssistantMessageId.get(row.message.id);
|
||||
if (!turnSummary) return null;
|
||||
@@ -2912,12 +2924,13 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
});
|
||||
|
||||
const ModelPicker = memo(function ModelPicker(props: {
|
||||
model: ModelSlug;
|
||||
onModelChange: (model: ModelSlug) => void;
|
||||
model: string;
|
||||
options: ReadonlyArray<{ slug: string; name: string }>;
|
||||
onModelChange: (model: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<Select
|
||||
items={MODEL_OPTIONS.map((option) => ({ label: option.name, value: option.slug }))}
|
||||
items={props.options.map((option) => ({ label: option.name, value: option.slug }))}
|
||||
value={props.model}
|
||||
onValueChange={(value) => (value ? props.onModelChange(value) : undefined)}
|
||||
>
|
||||
@@ -2925,7 +2938,7 @@ const ModelPicker = memo(function ModelPicker(props: {
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectPopup alignItemWithTrigger={false}>
|
||||
{MODEL_OPTIONS.map(({ slug, name }) => (
|
||||
{props.options.map(({ slug, name }) => (
|
||||
<SelectItem key={slug} value={slug}>
|
||||
{name}
|
||||
</SelectItem>
|
||||
|
||||
@@ -11,6 +11,7 @@ import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch"
|
||||
import { isElectron } from "../env";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { buildPatchCacheKey } from "../lib/diffRendering";
|
||||
import { resolveDiffThemeName } from "../lib/diffRendering";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import { useStore } from "../store";
|
||||
import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
||||
@@ -18,10 +19,47 @@ import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
||||
type DiffRenderMode = "stacked" | "split";
|
||||
type DiffThemeType = "light" | "dark";
|
||||
|
||||
function resolveDiffThemeName(theme: "light" | "dark") {
|
||||
return theme === "dark" ? "pierre-dark" : "pierre-light";
|
||||
const DIFF_PANEL_UNSAFE_CSS = `
|
||||
[data-diffs-header],
|
||||
[data-diff],
|
||||
[data-file],
|
||||
[data-error-wrapper],
|
||||
[data-virtualizer-buffer] {
|
||||
--diffs-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
|
||||
--diffs-light-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
|
||||
--diffs-dark-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
|
||||
--diffs-token-light-bg: transparent;
|
||||
--diffs-token-dark-bg: transparent;
|
||||
|
||||
--diffs-bg-context-override: color-mix(in srgb, var(--background) 97%, var(--foreground));
|
||||
--diffs-bg-hover-override: color-mix(in srgb, var(--background) 94%, var(--foreground));
|
||||
--diffs-bg-separator-override: color-mix(in srgb, var(--background) 95%, var(--foreground));
|
||||
--diffs-bg-buffer-override: color-mix(in srgb, var(--background) 90%, var(--foreground));
|
||||
|
||||
--diffs-bg-addition-override: color-mix(in srgb, var(--background) 92%, var(--success));
|
||||
--diffs-bg-addition-number-override: color-mix(in srgb, var(--background) 88%, var(--success));
|
||||
--diffs-bg-addition-hover-override: color-mix(in srgb, var(--background) 85%, var(--success));
|
||||
--diffs-bg-addition-emphasis-override: color-mix(in srgb, var(--background) 80%, var(--success));
|
||||
|
||||
--diffs-bg-deletion-override: color-mix(in srgb, var(--background) 92%, var(--destructive));
|
||||
--diffs-bg-deletion-number-override: color-mix(in srgb, var(--background) 88%, var(--destructive));
|
||||
--diffs-bg-deletion-hover-override: color-mix(in srgb, var(--background) 85%, var(--destructive));
|
||||
--diffs-bg-deletion-emphasis-override: color-mix(
|
||||
in srgb,
|
||||
var(--background) 80%,
|
||||
var(--destructive)
|
||||
);
|
||||
|
||||
background-color: var(--diffs-bg) !important;
|
||||
}
|
||||
|
||||
[data-file-info] {
|
||||
background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important;
|
||||
border-block-color: var(--border) !important;
|
||||
color: var(--foreground) !important;
|
||||
}
|
||||
`;
|
||||
|
||||
type RenderablePatch =
|
||||
| {
|
||||
kind: "files";
|
||||
@@ -425,7 +463,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex h-full min-w-0 flex-col bg-card",
|
||||
"flex h-full min-w-0 flex-col bg-background",
|
||||
mode === "inline"
|
||||
? "w-[42vw] min-w-[360px] max-w-[560px] shrink-0 border-l border-border"
|
||||
: "w-full",
|
||||
@@ -449,7 +487,10 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div ref={patchViewportRef} className="min-h-0 min-w-0 flex-1 overflow-hidden">
|
||||
<div
|
||||
ref={patchViewportRef}
|
||||
className="diff-panel-viewport min-h-0 min-w-0 flex-1 overflow-hidden"
|
||||
>
|
||||
{checkpointDiffError && !renderablePatch && (
|
||||
<div className="px-3">
|
||||
<p className="mb-2 text-[11px] text-red-500/80">{checkpointDiffError}</p>
|
||||
@@ -467,7 +508,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
</div>
|
||||
) : renderablePatch.kind === "files" ? (
|
||||
<Virtualizer
|
||||
className="h-full min-h-0 overflow-auto px-3 py-2"
|
||||
className="diff-render-surface h-full min-h-0 overflow-auto px-3 py-2"
|
||||
config={{
|
||||
overscrollSize: 600,
|
||||
intersectionObserverMargin: 1200,
|
||||
@@ -478,7 +519,11 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const fileKey = buildFileDiffRenderKey(fileDiff);
|
||||
const themedFileKey = `${fileKey}:${resolvedTheme}`;
|
||||
return (
|
||||
<div key={themedFileKey} data-diff-file-path={filePath} className="rounded-md">
|
||||
<div
|
||||
key={themedFileKey}
|
||||
data-diff-file-path={filePath}
|
||||
className="diff-render-file rounded-md"
|
||||
>
|
||||
<FileDiff
|
||||
fileDiff={fileDiff}
|
||||
options={{
|
||||
@@ -486,6 +531,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
lineDiffType: "none",
|
||||
theme: resolveDiffThemeName(resolvedTheme),
|
||||
themeType: resolvedTheme as DiffThemeType,
|
||||
unsafeCSS: DIFF_PANEL_UNSAFE_CSS,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -2,12 +2,9 @@ import { WorkerPoolContextProvider, useWorkerPool } from "@pierre/diffs/react";
|
||||
import DiffsWorker from "@pierre/diffs/worker/worker.js?worker";
|
||||
import { useEffect, useMemo, type ReactNode } from "react";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
|
||||
|
||||
function resolveDiffThemeName(theme: "light" | "dark") {
|
||||
return theme === "dark" ? "pierre-dark" : "pierre-light";
|
||||
}
|
||||
|
||||
function DiffWorkerThemeSync({ themeName }: { themeName: "pierre-light" | "pierre-dark" }) {
|
||||
function DiffWorkerThemeSync({ themeName }: { themeName: DiffThemeName }) {
|
||||
const workerPool = useWorkerPool();
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -20,7 +20,7 @@ function status(overrides: Partial<GitStatusResult> = {}): GitStatusResult {
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
openPr: null,
|
||||
pr: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
@@ -29,12 +29,13 @@ describe("when: branch is clean and has an open PR", () => {
|
||||
it("resolveQuickAction opens the existing PR", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
openPr: {
|
||||
pr: {
|
||||
number: 10,
|
||||
title: "Open PR",
|
||||
url: "https://example.com/pr/10",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
false,
|
||||
@@ -45,12 +46,13 @@ describe("when: branch is clean and has an open PR", () => {
|
||||
it("buildMenuItems disables commit/push and enables open PR", () => {
|
||||
const items = buildMenuItems(
|
||||
status({
|
||||
openPr: {
|
||||
pr: {
|
||||
number: 11,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/11",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
false,
|
||||
@@ -147,12 +149,13 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
aheadCount: 3,
|
||||
openPr: {
|
||||
pr: {
|
||||
number: 13,
|
||||
title: "Open PR",
|
||||
url: "https://example.com/pr/13",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
false,
|
||||
@@ -164,12 +167,13 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
|
||||
const items = buildMenuItems(
|
||||
status({
|
||||
aheadCount: 2,
|
||||
openPr: {
|
||||
pr: {
|
||||
number: 12,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/12",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
false,
|
||||
@@ -204,7 +208,7 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
|
||||
|
||||
describe("when: branch is clean, ahead, and has no open PR", () => {
|
||||
it("resolveQuickAction pushes and creates a PR", () => {
|
||||
const quick = resolveQuickAction(status({ aheadCount: 2, openPr: null }), false);
|
||||
const quick = resolveQuickAction(status({ aheadCount: 2, pr: null }), false);
|
||||
assert.deepInclude(quick, {
|
||||
kind: "run_action",
|
||||
action: "commit_push_pr",
|
||||
@@ -213,7 +217,7 @@ describe("when: branch is clean, ahead, and has no open PR", () => {
|
||||
});
|
||||
|
||||
it("buildMenuItems enables push and create PR, with commit disabled", () => {
|
||||
const items = buildMenuItems(status({ aheadCount: 2, openPr: null }), false);
|
||||
const items = buildMenuItems(status({ aheadCount: 2, pr: null }), false);
|
||||
assert.deepEqual(items, [
|
||||
{
|
||||
id: "commit",
|
||||
@@ -246,14 +250,14 @@ describe("when: branch is clean, ahead, and has no open PR", () => {
|
||||
describe("when: branch is clean, up to date, and has no open PR", () => {
|
||||
it("resolveQuickAction returns disabled no-action state", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({ aheadCount: 0, behindCount: 0, hasWorkingTreeChanges: false, openPr: null }),
|
||||
status({ aheadCount: 0, behindCount: 0, hasWorkingTreeChanges: false, pr: null }),
|
||||
false,
|
||||
);
|
||||
assert.deepInclude(quick, { kind: "show_hint", label: "Commit", disabled: true });
|
||||
});
|
||||
|
||||
it("buildMenuItems disables commit, push, and create PR", () => {
|
||||
const items = buildMenuItems(status({ aheadCount: 0, behindCount: 0, openPr: null }), false);
|
||||
const items = buildMenuItems(status({ aheadCount: 0, behindCount: 0, pr: null }), false);
|
||||
assert.deepEqual(items, [
|
||||
{
|
||||
id: "commit",
|
||||
@@ -290,7 +294,7 @@ describe("when: branch is behind upstream", () => {
|
||||
});
|
||||
|
||||
it("buildMenuItems disables push and create PR", () => {
|
||||
const items = buildMenuItems(status({ behindCount: 1, openPr: null }), false);
|
||||
const items = buildMenuItems(status({ behindCount: 1, pr: null }), false);
|
||||
assert.deepEqual(items, [
|
||||
{
|
||||
id: "commit",
|
||||
@@ -346,12 +350,13 @@ describe("when: working tree has local changes", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
hasWorkingTreeChanges: true,
|
||||
openPr: {
|
||||
pr: {
|
||||
number: 16,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/16",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
false,
|
||||
@@ -411,7 +416,7 @@ describe("when: on default branch without open PR", () => {
|
||||
|
||||
it("resolveQuickAction returns push when branch is ahead", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({ branch: "main", aheadCount: 2, openPr: null }),
|
||||
status({ branch: "main", aheadCount: 2, pr: null }),
|
||||
false,
|
||||
true,
|
||||
);
|
||||
@@ -511,7 +516,7 @@ describe("when: HEAD is detached and there are no local changes", () => {
|
||||
describe("when: branch has no upstream configured", () => {
|
||||
it("resolveQuickAction returns disabled commit state when clean and no commits are ahead", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({ hasUpstream: false, openPr: null, aheadCount: 0 }),
|
||||
status({ hasUpstream: false, pr: null, aheadCount: 0 }),
|
||||
false,
|
||||
);
|
||||
assert.deepInclude(quick, {
|
||||
@@ -526,12 +531,13 @@ describe("when: branch has no upstream configured", () => {
|
||||
status({
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
openPr: {
|
||||
pr: {
|
||||
number: 14,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/14",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
false,
|
||||
@@ -548,12 +554,13 @@ describe("when: branch has no upstream configured", () => {
|
||||
status({
|
||||
hasUpstream: false,
|
||||
aheadCount: 1,
|
||||
openPr: {
|
||||
pr: {
|
||||
number: 15,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/15",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
false,
|
||||
@@ -568,7 +575,7 @@ describe("when: branch has no upstream configured", () => {
|
||||
|
||||
it("buildMenuItems disables push and create PR when no commits are ahead", () => {
|
||||
const items = buildMenuItems(
|
||||
status({ hasUpstream: false, openPr: null, aheadCount: 0 }),
|
||||
status({ hasUpstream: false, pr: null, aheadCount: 0 }),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(items, [
|
||||
|
||||
@@ -108,7 +108,7 @@ export function buildMenuItems(
|
||||
|
||||
const hasBranch = gitStatus.branch !== null;
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
const hasOpenPr = gitStatus.openPr !== null;
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const isBehind = gitStatus.behindCount > 0;
|
||||
const canCommit = !isBusy && hasChanges;
|
||||
const canPush = !isBusy && hasBranch && !hasChanges && !isBehind && gitStatus.aheadCount > 0;
|
||||
@@ -178,7 +178,7 @@ export function resolveQuickAction(
|
||||
|
||||
const hasBranch = gitStatus.branch !== null;
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
const hasOpenPr = gitStatus.openPr !== null;
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const isAhead = gitStatus.aheadCount > 0;
|
||||
const isBehind = gitStatus.behindCount > 0;
|
||||
const isDiverged = isAhead && isBehind;
|
||||
|
||||
@@ -58,7 +58,7 @@ function getMenuActionDisabledReason(
|
||||
|
||||
const hasBranch = gitStatus.branch !== null;
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
const hasOpenPr = gitStatus.openPr !== null;
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const isAhead = gitStatus.aheadCount > 0;
|
||||
const isBehind = gitStatus.behindCount > 0;
|
||||
|
||||
@@ -219,7 +219,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
});
|
||||
return;
|
||||
}
|
||||
const prUrl = gitStatusForActions?.openPr?.url ?? null;
|
||||
const prUrl = gitStatusForActions?.pr?.state === "open" ? gitStatusForActions.pr.url : null;
|
||||
if (!prUrl) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
@@ -236,7 +236,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
data: threadToastData,
|
||||
});
|
||||
});
|
||||
}, [gitStatusForActions?.openPr?.url, threadToastData]);
|
||||
}, [gitStatusForActions?.pr?.state, gitStatusForActions?.pr?.url, threadToastData]);
|
||||
const runGitActionWithToast = useCallback(
|
||||
async ({
|
||||
action,
|
||||
@@ -295,7 +295,9 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
stopProgressUpdates();
|
||||
const resultToast = summarizeGitResult(result);
|
||||
|
||||
const prUrl = result.pr.url ?? gitStatusForActions?.openPr?.url;
|
||||
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 && !isDefaultBranch;
|
||||
@@ -365,7 +367,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
[
|
||||
gitStatusForActions?.branch,
|
||||
gitStatusForActions?.hasWorkingTreeChanges,
|
||||
gitStatusForActions?.openPr?.url,
|
||||
gitStatusForActions?.pr,
|
||||
isDefaultBranch,
|
||||
maybeConfirmPushToDefaultBranch,
|
||||
runImmediateGitActionMutation,
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { ChevronRightIcon, FolderIcon, TerminalIcon } from "lucide-react";
|
||||
import { ChevronRightIcon, FolderIcon, GitPullRequestIcon, TerminalIcon } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
DEFAULT_MODEL,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
type GitStatusResult,
|
||||
type ResolvedKeybindingsConfig,
|
||||
} from "@t3tools/contracts";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useNavigate, useParams } from "@tanstack/react-router";
|
||||
import { useAppSettings } from "../appSettings";
|
||||
import { isElectron } from "../env";
|
||||
@@ -16,7 +17,7 @@ import { useStore } from "../store";
|
||||
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
|
||||
import { type Thread } from "../types";
|
||||
import { derivePendingApprovals } from "../session-logic";
|
||||
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
|
||||
import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/gitReactQuery";
|
||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { toastManager } from "./ui/toast";
|
||||
@@ -63,6 +64,13 @@ interface TerminalStatusIndicator {
|
||||
pulse: boolean;
|
||||
}
|
||||
|
||||
interface PrStatusIndicator {
|
||||
label: "PR open" | "PR closed" | "PR merged";
|
||||
colorClass: string;
|
||||
}
|
||||
|
||||
type ThreadPrState = NonNullable<GitStatusResult["pr"]>["state"] | null;
|
||||
|
||||
function hasUnseenCompletion(thread: Thread): boolean {
|
||||
if (!thread.latestTurn?.completedAt) return false;
|
||||
const completedAt = Date.parse(thread.latestTurn.completedAt);
|
||||
@@ -125,6 +133,28 @@ function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null
|
||||
};
|
||||
}
|
||||
|
||||
function prStatusIndicator(prState: ThreadPrState): PrStatusIndicator | null {
|
||||
if (prState === "open") {
|
||||
return {
|
||||
label: "PR open",
|
||||
colorClass: "text-emerald-600 dark:text-emerald-300/90",
|
||||
};
|
||||
}
|
||||
if (prState === "closed") {
|
||||
return {
|
||||
label: "PR closed",
|
||||
colorClass: "text-zinc-500 dark:text-zinc-400/80",
|
||||
};
|
||||
}
|
||||
if (prState === "merged") {
|
||||
return {
|
||||
label: "PR merged",
|
||||
colorClass: "text-violet-600 dark:text-violet-300/90",
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function T3Wordmark() {
|
||||
return (
|
||||
<svg
|
||||
@@ -210,6 +240,58 @@ export default function Sidebar() {
|
||||
}
|
||||
return map;
|
||||
}, [state.threads]);
|
||||
const projectCwdById = useMemo(
|
||||
() => new Map(state.projects.map((project) => [project.id, project.cwd] as const)),
|
||||
[state.projects],
|
||||
);
|
||||
const threadGitTargets = useMemo(
|
||||
() =>
|
||||
state.threads.map((thread) => ({
|
||||
threadId: thread.id,
|
||||
branch: thread.branch,
|
||||
cwd: thread.worktreePath ?? projectCwdById.get(thread.projectId) ?? null,
|
||||
})),
|
||||
[projectCwdById, state.threads],
|
||||
);
|
||||
const threadGitStatusCwds = useMemo(
|
||||
() =>
|
||||
[
|
||||
...new Set(
|
||||
threadGitTargets
|
||||
.filter((target) => target.branch !== null)
|
||||
.map((target) => target.cwd)
|
||||
.filter((cwd): cwd is string => cwd !== null),
|
||||
),
|
||||
],
|
||||
[threadGitTargets],
|
||||
);
|
||||
const threadGitStatusQueries = useQueries({
|
||||
queries: threadGitStatusCwds.map((cwd) => ({
|
||||
...gitStatusQueryOptions(cwd),
|
||||
staleTime: 30_000,
|
||||
refetchInterval: 60_000,
|
||||
})),
|
||||
});
|
||||
const prStateByThreadId = useMemo(() => {
|
||||
const statusByCwd = new Map<string, GitStatusResult>();
|
||||
for (let index = 0; index < threadGitStatusCwds.length; index += 1) {
|
||||
const cwd = threadGitStatusCwds[index];
|
||||
if (!cwd) continue;
|
||||
const status = threadGitStatusQueries[index]?.data;
|
||||
if (status) {
|
||||
statusByCwd.set(cwd, status);
|
||||
}
|
||||
}
|
||||
|
||||
const map = new Map<ThreadId, ThreadPrState>();
|
||||
for (const target of threadGitTargets) {
|
||||
const status = target.cwd ? statusByCwd.get(target.cwd) : undefined;
|
||||
const branchMatches =
|
||||
target.branch !== null && status?.branch !== null && status?.branch === target.branch;
|
||||
map.set(target.threadId, branchMatches ? status?.pr?.state ?? null : null);
|
||||
}
|
||||
return map;
|
||||
}, [threadGitStatusCwds, threadGitStatusQueries, threadGitTargets]);
|
||||
|
||||
const handleNewThread = useCallback(
|
||||
(
|
||||
@@ -632,6 +714,7 @@ export default function Sidebar() {
|
||||
thread,
|
||||
pendingApprovalByThreadId.get(thread.id) === true,
|
||||
);
|
||||
const prStatus = prStatusIndicator(prStateByThreadId.get(thread.id) ?? null);
|
||||
const terminalStatus = terminalStatusIndicator(thread);
|
||||
|
||||
return (
|
||||
@@ -677,6 +760,16 @@ export default function Sidebar() {
|
||||
</span>
|
||||
</div>
|
||||
<div className="ml-auto flex shrink-0 items-center gap-1.5">
|
||||
{prStatus && (
|
||||
<span
|
||||
role="img"
|
||||
aria-label={prStatus.label}
|
||||
title={prStatus.label}
|
||||
className={`inline-flex items-center justify-center ${prStatus.colorClass}`}
|
||||
>
|
||||
<GitPullRequestIcon className="size-3" />
|
||||
</span>
|
||||
)}
|
||||
{terminalStatus && (
|
||||
<span
|
||||
role="img"
|
||||
|
||||
@@ -314,6 +314,52 @@ label:has(> select#reasoning-effort) select {
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-codeblock {
|
||||
position: relative;
|
||||
margin: 0.65rem 0;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-codeblock pre {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-copy-button {
|
||||
position: absolute;
|
||||
top: 0.5rem;
|
||||
right: 0.5rem;
|
||||
z-index: 1;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 1.5rem;
|
||||
width: 1.5rem;
|
||||
border-radius: 0.375rem;
|
||||
border: 1px solid var(--border);
|
||||
background: color-mix(in srgb, var(--background) 82%, transparent);
|
||||
color: var(--muted-foreground);
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition:
|
||||
opacity 120ms ease,
|
||||
color 120ms ease,
|
||||
border-color 120ms ease;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-codeblock:hover .chat-markdown-copy-button,
|
||||
.chat-markdown .chat-markdown-codeblock:focus-within .chat-markdown-copy-button {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-copy-button:hover {
|
||||
color: var(--foreground);
|
||||
border-color: color-mix(in srgb, var(--border) 70%, var(--foreground));
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-shiki .shiki {
|
||||
background: color-mix(in srgb, var(--muted) 78%, var(--background)) !important;
|
||||
}
|
||||
|
||||
.chat-markdown table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
@@ -325,3 +371,15 @@ label:has(> select#reasoning-effort) select {
|
||||
padding: 0.35rem 0.45rem;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
/* Diffs theme bridge (match diff surfaces to app palette) */
|
||||
.diff-panel-viewport {
|
||||
background: color-mix(in srgb, var(--background) 94%, var(--card));
|
||||
}
|
||||
|
||||
.diff-render-file {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 0.5rem;
|
||||
overflow: clip;
|
||||
background: color-mix(in srgb, var(--card) 92%, var(--background));
|
||||
}
|
||||
@@ -1,9 +1,24 @@
|
||||
export const DIFF_THEME_NAMES = {
|
||||
light: "pierre-light",
|
||||
dark: "pierre-dark",
|
||||
} as const;
|
||||
|
||||
export type DiffThemeName = (typeof DIFF_THEME_NAMES)[keyof typeof DIFF_THEME_NAMES];
|
||||
|
||||
export function resolveDiffThemeName(theme: "light" | "dark"): DiffThemeName {
|
||||
return theme === "dark" ? DIFF_THEME_NAMES.dark : DIFF_THEME_NAMES.light;
|
||||
}
|
||||
|
||||
const FNV_OFFSET_BASIS_32 = 0x811c9dc5;
|
||||
const FNV_PRIME_32 = 0x01000193;
|
||||
const SECONDARY_HASH_SEED = 0x9e3779b9;
|
||||
const SECONDARY_HASH_MULTIPLIER = 0x85ebca6b;
|
||||
|
||||
function fnv1a32(input: string, seed: number, multiplier: number): number {
|
||||
export function fnv1a32(
|
||||
input: string,
|
||||
seed = FNV_OFFSET_BASIS_32,
|
||||
multiplier = FNV_PRIME_32,
|
||||
): number {
|
||||
let hash = seed >>> 0;
|
||||
for (let index = 0; index < input.length; index += 1) {
|
||||
hash ^= input.charCodeAt(index);
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { LRUCache } from "./lruCache";
|
||||
|
||||
describe("LRUCache", () => {
|
||||
it("returns null for missing keys", () => {
|
||||
const cache = new LRUCache<string>(2, 100);
|
||||
expect(cache.get("missing")).toBeNull();
|
||||
});
|
||||
|
||||
it("evicts oldest by max entries", () => {
|
||||
const cache = new LRUCache<string>(2, 1_000);
|
||||
cache.set("a", "A", 10);
|
||||
cache.set("b", "B", 10);
|
||||
cache.set("c", "C", 10);
|
||||
|
||||
expect(cache.get("a")).toBeNull();
|
||||
expect(cache.get("b")).toBe("B");
|
||||
expect(cache.get("c")).toBe("C");
|
||||
});
|
||||
|
||||
it("promotes on get and evicts least recently used", () => {
|
||||
const cache = new LRUCache<string>(2, 1_000);
|
||||
cache.set("a", "A", 10);
|
||||
cache.set("b", "B", 10);
|
||||
expect(cache.get("a")).toBe("A");
|
||||
|
||||
cache.set("c", "C", 10);
|
||||
expect(cache.get("a")).toBe("A");
|
||||
expect(cache.get("b")).toBeNull();
|
||||
expect(cache.get("c")).toBe("C");
|
||||
});
|
||||
|
||||
it("evicts by memory budget", () => {
|
||||
const cache = new LRUCache<string>(10, 25);
|
||||
cache.set("a", "A", 10);
|
||||
cache.set("b", "B", 10);
|
||||
cache.set("c", "C", 10);
|
||||
|
||||
expect(cache.get("a")).toBeNull();
|
||||
expect(cache.get("b")).toBe("B");
|
||||
expect(cache.get("c")).toBe("C");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
interface CacheEntry<T> {
|
||||
value: T;
|
||||
approximateSize: number;
|
||||
}
|
||||
|
||||
export class LRUCache<T> {
|
||||
private cache = new Map<string, CacheEntry<T>>();
|
||||
private totalSize = 0;
|
||||
|
||||
constructor(
|
||||
private readonly maxEntries: number,
|
||||
private readonly maxMemoryBytes: number,
|
||||
) {}
|
||||
|
||||
get(key: string): T | null {
|
||||
const entry = this.cache.get(key);
|
||||
if (!entry) {
|
||||
return null;
|
||||
}
|
||||
|
||||
this.promote(key, entry);
|
||||
return entry.value;
|
||||
}
|
||||
|
||||
set(key: string, value: T, approximateSize: number): void {
|
||||
const existing = this.cache.get(key);
|
||||
if (existing) {
|
||||
this.totalSize -= existing.approximateSize;
|
||||
this.cache.delete(key);
|
||||
}
|
||||
|
||||
this.evictIfNeeded(approximateSize);
|
||||
this.cache.set(key, { value, approximateSize });
|
||||
this.totalSize += approximateSize;
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.cache.clear();
|
||||
this.totalSize = 0;
|
||||
}
|
||||
|
||||
private promote(key: string, entry: CacheEntry<T>): void {
|
||||
this.cache.delete(key);
|
||||
this.cache.set(key, entry);
|
||||
}
|
||||
|
||||
private evictIfNeeded(incomingSize: number): void {
|
||||
while (
|
||||
(this.cache.size >= this.maxEntries || this.totalSize + incomingSize > this.maxMemoryBytes) &&
|
||||
this.cache.size > 0
|
||||
) {
|
||||
const oldestKey = this.cache.keys().next().value;
|
||||
if (oldestKey === undefined) {
|
||||
break;
|
||||
}
|
||||
|
||||
const oldestEntry = this.cache.get(oldestKey);
|
||||
if (oldestEntry) {
|
||||
this.totalSize -= oldestEntry.approximateSize;
|
||||
}
|
||||
this.cache.delete(oldestKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import { createHashHistory, createRouter, createBrowserHistory } from "@tanstack
|
||||
import { StoreProvider } from "./store";
|
||||
|
||||
import "@xterm/xterm/css/xterm.css";
|
||||
import "highlight.js/styles/github-dark.css";
|
||||
import "./index.css";
|
||||
|
||||
import { APP_DISPLAY_NAME } from "./branding";
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useCallback, useState } from "react";
|
||||
import { MODEL_OPTIONS, normalizeModelSlug } from "@t3tools/contracts";
|
||||
|
||||
import { useAppSettings } from "../appSettings";
|
||||
import { MAX_CUSTOM_MODEL_LENGTH, useAppSettings } from "../appSettings";
|
||||
import { isElectron } from "../env";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||
@@ -52,9 +53,12 @@ function SettingsRouteView() {
|
||||
const serverConfigQuery = useQuery(serverConfigQueryOptions());
|
||||
const [isOpeningKeybindings, setIsOpeningKeybindings] = useState(false);
|
||||
const [openKeybindingsError, setOpenKeybindingsError] = useState<string | null>(null);
|
||||
const [customModelInput, setCustomModelInput] = useState("");
|
||||
const [customModelError, setCustomModelError] = useState<string | null>(null);
|
||||
|
||||
const codexBinaryPath = settings.codexBinaryPath;
|
||||
const codexHomePath = settings.codexHomePath;
|
||||
const customCodexModels = settings.customCodexModels;
|
||||
const keybindingsConfigPath = serverConfigQuery.data?.keybindingsConfigPath ?? null;
|
||||
|
||||
const openKeybindingsFile = useCallback(() => {
|
||||
@@ -74,6 +78,42 @@ function SettingsRouteView() {
|
||||
});
|
||||
}, [keybindingsConfigPath]);
|
||||
|
||||
const addCustomModel = useCallback(() => {
|
||||
const normalized = normalizeModelSlug(customModelInput);
|
||||
if (!normalized) {
|
||||
setCustomModelError("Enter a model slug.");
|
||||
return;
|
||||
}
|
||||
if (MODEL_OPTIONS.some((option) => option.slug === normalized)) {
|
||||
setCustomModelError("That model is already built in.");
|
||||
return;
|
||||
}
|
||||
if (normalized.length > MAX_CUSTOM_MODEL_LENGTH) {
|
||||
setCustomModelError(`Model slugs must be ${MAX_CUSTOM_MODEL_LENGTH} characters or less.`);
|
||||
return;
|
||||
}
|
||||
if (customCodexModels.includes(normalized)) {
|
||||
setCustomModelError("That custom model is already saved.");
|
||||
return;
|
||||
}
|
||||
|
||||
updateSettings({
|
||||
customCodexModels: [...customCodexModels, normalized],
|
||||
});
|
||||
setCustomModelInput("");
|
||||
setCustomModelError(null);
|
||||
}, [customCodexModels, customModelInput, updateSettings]);
|
||||
|
||||
const removeCustomModel = useCallback(
|
||||
(slug: string) => {
|
||||
updateSettings({
|
||||
customCodexModels: customCodexModels.filter((model) => model !== slug),
|
||||
});
|
||||
setCustomModelError(null);
|
||||
},
|
||||
[customCodexModels, updateSettings],
|
||||
);
|
||||
|
||||
return (
|
||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">
|
||||
@@ -193,6 +233,96 @@ function SettingsRouteView() {
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="rounded-2xl border border-border bg-card p-5">
|
||||
<div className="mb-4">
|
||||
<h2 className="text-sm font-medium text-foreground">Models</h2>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Save additional Codex model slugs so they appear in the chat model picker.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<form
|
||||
className="flex flex-col gap-3 sm:flex-row sm:items-start"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
addCustomModel();
|
||||
}}
|
||||
>
|
||||
<label className="block flex-1 space-y-1">
|
||||
<span className="text-xs font-medium text-foreground">Custom model slug</span>
|
||||
<Input
|
||||
value={customModelInput}
|
||||
onChange={(event) => {
|
||||
setCustomModelInput(event.target.value);
|
||||
if (customModelError) {
|
||||
setCustomModelError(null);
|
||||
}
|
||||
}}
|
||||
placeholder="your-model-slug"
|
||||
spellCheck={false}
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Example: <code>gpt-6.7-codex-ultra-preview</code>
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<Button className="sm:mt-6" type="submit">
|
||||
Add model
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{customModelError ? (
|
||||
<p className="text-xs text-destructive">{customModelError}</p>
|
||||
) : null}
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">
|
||||
<p>Saved custom models: {customCodexModels.length}</p>
|
||||
{customCodexModels.length > 0 ? (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
customCodexModels: defaults.customCodexModels,
|
||||
})
|
||||
}
|
||||
>
|
||||
Reset custom models
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{customCodexModels.length > 0 ? (
|
||||
<div className="space-y-2">
|
||||
{customCodexModels.map((slug) => (
|
||||
<div
|
||||
key={slug}
|
||||
className="flex items-center justify-between gap-3 rounded-lg border border-border bg-background px-3 py-2"
|
||||
>
|
||||
<code className="min-w-0 flex-1 truncate text-xs text-foreground">
|
||||
{slug}
|
||||
</code>
|
||||
<Button
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
onClick={() => removeCustomModel(slug)}
|
||||
>
|
||||
Remove
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-lg border border-dashed border-border bg-background px-3 py-4 text-xs text-muted-foreground">
|
||||
No custom models saved yet.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="rounded-2xl border border-border bg-card p-5">
|
||||
<div className="mb-4">
|
||||
<h2 className="text-sm font-medium text-foreground">Runtime Mode</h2>
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -18,6 +18,8 @@ export const GitPrStepStatus = Schema.Literals([
|
||||
"opened_existing",
|
||||
"skipped_not_requested",
|
||||
]);
|
||||
export const GitStatusPrState = Schema.Literals(["open", "closed", "merged"]);
|
||||
export type GitStatusPrState = typeof GitStatusPrState.Type;
|
||||
|
||||
export const GitBranch = Schema.Struct({
|
||||
name: TrimmedNonEmptyStringSchema,
|
||||
@@ -91,6 +93,16 @@ export type GitInitInput = typeof GitInitInput.Type;
|
||||
|
||||
// RPC Results
|
||||
|
||||
export const GitStatusPr = Schema.Struct({
|
||||
number: PositiveInt,
|
||||
title: TrimmedNonEmptyStringSchema,
|
||||
url: Schema.String,
|
||||
baseBranch: TrimmedNonEmptyStringSchema,
|
||||
headBranch: TrimmedNonEmptyStringSchema,
|
||||
state: GitStatusPrState,
|
||||
});
|
||||
export type GitStatusPr = typeof GitStatusPr.Type;
|
||||
|
||||
export const GitStatusResult = Schema.Struct({
|
||||
branch: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr),
|
||||
hasWorkingTreeChanges: Schema.Boolean,
|
||||
@@ -108,15 +120,7 @@ export const GitStatusResult = Schema.Struct({
|
||||
hasUpstream: Schema.Boolean,
|
||||
aheadCount: NonNegativeInt,
|
||||
behindCount: NonNegativeInt,
|
||||
openPr: Schema.NullOr(
|
||||
Schema.Struct({
|
||||
number: PositiveInt,
|
||||
title: TrimmedNonEmptyStringSchema,
|
||||
url: Schema.String,
|
||||
baseBranch: TrimmedNonEmptyStringSchema,
|
||||
headBranch: TrimmedNonEmptyStringSchema,
|
||||
}),
|
||||
),
|
||||
pr: Schema.NullOr(GitStatusPr),
|
||||
});
|
||||
export type GitStatusResult = typeof GitStatusResult.Type;
|
||||
|
||||
|
||||
@@ -22,9 +22,14 @@ describe("normalizeModelSlug", () => {
|
||||
});
|
||||
|
||||
describe("resolveModelSlug", () => {
|
||||
it("returns default for missing and unknown models", () => {
|
||||
it("returns default only when the model is missing", () => {
|
||||
expect(resolveModelSlug(undefined)).toBe(DEFAULT_MODEL);
|
||||
expect(resolveModelSlug("gpt-4.1")).toBe(DEFAULT_MODEL);
|
||||
expect(resolveModelSlug(null)).toBe(DEFAULT_MODEL);
|
||||
});
|
||||
|
||||
it("preserves unknown custom models", () => {
|
||||
expect(resolveModelSlug("gpt-4.1")).toBe("gpt-4.1");
|
||||
expect(resolveModelSlug("custom/internal-model")).toBe("custom/internal-model");
|
||||
});
|
||||
|
||||
it("resolves only supported model options", () => {
|
||||
|
||||
@@ -5,11 +5,12 @@ export const MODEL_OPTIONS = [
|
||||
{ slug: "gpt-5.2", name: "GPT-5.2" },
|
||||
] as const;
|
||||
|
||||
export type ModelSlug = (typeof MODEL_OPTIONS)[number]["slug"];
|
||||
export type BuiltInModelSlug = (typeof MODEL_OPTIONS)[number]["slug"];
|
||||
export type ModelSlug = string;
|
||||
|
||||
export const DEFAULT_MODEL = "gpt-5.3-codex";
|
||||
|
||||
export const MODEL_SLUG_ALIASES: Record<string, ModelSlug> = {
|
||||
export const MODEL_SLUG_ALIASES: Record<string, BuiltInModelSlug> = {
|
||||
"5.3": "gpt-5.3-codex",
|
||||
"gpt-5.3": "gpt-5.3-codex",
|
||||
"5.3-spark": "gpt-5.3-codex-spark",
|
||||
@@ -26,16 +27,12 @@ export function normalizeModelSlug(model: string | null | undefined): ModelSlug
|
||||
return null;
|
||||
}
|
||||
|
||||
return MODEL_SLUG_ALIASES[trimmed] ?? (trimmed as ModelSlug);
|
||||
return MODEL_SLUG_ALIASES[trimmed] ?? trimmed;
|
||||
}
|
||||
|
||||
export function resolveModelSlug(model: string | null | undefined): ModelSlug {
|
||||
const normalized = normalizeModelSlug(model);
|
||||
if (!normalized) {
|
||||
return DEFAULT_MODEL;
|
||||
}
|
||||
|
||||
return MODEL_OPTIONS.some((option) => option.slug === normalized) ? normalized : DEFAULT_MODEL;
|
||||
return normalized ?? DEFAULT_MODEL;
|
||||
}
|
||||
|
||||
export const REASONING_OPTIONS = ["xhigh", "high", "medium", "low"] as const;
|
||||
|
||||
@@ -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)) {
|
||||
|
||||