From eb91d466572658ad05dd67771755b0ef47c98eb6 Mon Sep 17 00:00:00 2001 From: James Babcock Date: Tue, 13 Oct 2026 00:46:54 -0700 Subject: [PATCH] Add thread options to t3 client --- CHANGELOG | 12 + app/apps/t3code/t3-client.ts | 11 +- app/apps/t3code/t3-launch.ts | 516 +++++++++++++++++++++++ app/apps/t3code/t3-model.ts | 92 +--- app/apps/t3code/t3code-app.worker.ts | 605 ++++++++++++++++++++++++--- app/ui/window-menu.ts | 9 +- tests/t3code-launch.test.cjs | 174 ++++++++ tests/t3code-model.test.cjs | 16 - tests/tsconfig.json | 3 +- 9 files changed, 1275 insertions(+), 163 deletions(-) create mode 100644 app/apps/t3code/t3-launch.ts create mode 100644 tests/t3code-launch.test.cjs diff --git a/CHANGELOG b/CHANGELOG index 432f1053..8ac7642b 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,17 @@ # Changelog +## 0.8.4 - Future + +### Features + +* Bottom-bar app switcher switches two a multi-row layout when it runs out of space +* T3 Code client: Add options (worktree, host, etc) when creating threads + +### Bug fixes + +* Phone preview is centered on the phone screen when apps are not maximized +* iOS: Add missing EvenHub icons on the phone home screen + ## 0.8.3 - 2026-10-10 * Fix several issues that would cause disconnection and disconnect-looping diff --git a/app/apps/t3code/t3-client.ts b/app/apps/t3code/t3-client.ts index 776475ed..b977a038 100644 --- a/app/apps/t3code/t3-client.ts +++ b/app/apps/t3code/t3-client.ts @@ -15,7 +15,8 @@ import { webSocketUrl, type T3Fetch, } from "./t3-auth"; -import { ShellModel, ThreadDetailModel, type T3ServerProvider } from "./t3-model"; +import type { T3ServerProvider } from "./t3-launch"; +import { ShellModel, ThreadDetailModel } from "./t3-model"; import { T3RpcConnection, T3RpcError, type RpcSocketFactory, type T3Subscription } from "./t3-rpc"; /** A paired environment as stored on the phone. */ @@ -79,6 +80,8 @@ export class T3EnvironmentClient { readonly shell = new ShellModel(); providers: T3ServerProvider[] = []; settings: Record | null = null; + /** The folder of threads without a project (its project is the "Scratch" one). */ + scratchWorkspaceRoot: string | null = null; private phaseValue: EnvironmentPhase = "idle"; private statusValue = ""; private connection: T3RpcConnection | null = null; @@ -200,6 +203,11 @@ export class T3EnvironmentClient { return String(result?.threadId ?? payload.threadId); } + /** Any other unary RPC (vcs.listRefs, projects.readFile, ...). */ + call(method: string, payload: Record): Promise { + return this.requireConnection().call(method, payload); + } + private requireConnection(): T3RpcConnection { if (this.phaseValue !== "connected" || !this.connection) { throw new T3RpcError("disconnected", `Not connected to ${this.config.label || "the server"}.`); @@ -265,6 +273,7 @@ export class T3EnvironmentClient { } this.providers = Array.isArray(config.providers) ? config.providers : []; this.settings = config.settings ?? null; + this.scratchWorkspaceRoot = typeof config.scratchWorkspaceRoot === "string" ? config.scratchWorkspaceRoot : null; if (typeof config.environment?.label === "string" && config.environment.label && config.environment.label !== this.config.label) { this.config = { ...this.config, label: config.environment.label }; } diff --git a/app/apps/t3code/t3-launch.ts b/app/apps/t3code/t3-launch.ts new file mode 100644 index 00000000..49de6783 --- /dev/null +++ b/app/apps/t3code/t3-launch.ts @@ -0,0 +1,516 @@ +/** + * New-thread options for orchestration.launchThread, resolved the way T3 + * Code's own new-task flow does it (apps/mobile/src/features/threads/ + * new-task-flow-provider.tsx, lib/modelOptions.ts, thread-settings-options.ts, + * new-task-context-presentation.ts; packages/shared/src/projectSettings.ts + * and model.ts): which models, model options, access modes, workspaces and + * branches to offer, their defaults, and the launch payload. + * + * Defaults follow T3's project-settings chain: the project's override, then + * the environment's setting, then (for the workspace mode) the repository's + * checked-in t3.json, then the built-in value. The user's explicit picks live + * in a LaunchDraft; resolveLaunch() layers them over those defaults. + * + * Pure (no I/O), so it runs under the Node tests; the worker owns the draft, + * the branch list and t3.json reads. + */ +import type { T3ModelOptionSelection, T3ModelSelection, T3ProjectShell } from "./t3-model"; +import { uuidv4 } from "./t3-model"; + +// --------------------------------------------------------------------------- +// Wire shapes (subset) + +export type T3OptionChoice = { id: string; label: string; description?: string; isDefault?: boolean }; + +/** One per-model option a provider offers (reasoning effort, fast mode, ...). */ +export type T3OptionDescriptor = + | { + id: string; + label: string; + description?: string; + type: "select"; + options: T3OptionChoice[]; + currentValue?: string; + /** Values applied by rewriting the prompt (Claude's "ultrathink"), not offered as picks. */ + promptInjectedValues?: string[]; + } + | { id: string; label: string; description?: string; type: "boolean"; currentValue?: boolean }; + +export type T3ProviderModel = { + slug: string; + name?: string; + isDefault?: boolean; + isLegacy?: boolean; + capabilities?: { optionDescriptors?: T3OptionDescriptor[] } | null; +}; + +export type T3ServerProvider = { + instanceId: string; + displayName?: string; + driver?: string; + enabled?: boolean; + installed?: boolean; + availability?: string; + auth?: { status?: string }; + supportedRuntimeModes?: string[]; + models?: T3ProviderModel[]; +}; + +/** A branch from vcs.listRefs. */ +export type T3VcsRef = { + name: string; + isRemote?: boolean; + remoteName?: string; + current: boolean; + isDefault: boolean; + /** Set when the branch is checked out in a worktree (the project root counts). */ + worktreePath: string | null; +}; + +export type T3RefList = { + refs: T3VcsRef[]; + isRepo: boolean; + hasPrimaryRemote: boolean; + nextCursor?: number | null; + totalCount?: number; +}; + +/** The settings a repository's t3.json can supply. */ +export type T3ProjectFileDefaults = { defaultThreadEnvMode?: WorkspaceMode }; + +export const T3_PROJECT_FILE_NAME = "t3.json"; + +export function parseProjectFile(contents: string): T3ProjectFileDefaults | null { + try { + const parsed = JSON.parse(contents); + if (!parsed || typeof parsed !== "object") return null; + const mode = parsed.defaultThreadEnvMode; + return mode === "local" || mode === "worktree" ? { defaultThreadEnvMode: mode } : {}; + } catch { + return null; + } +} + +// --------------------------------------------------------------------------- +// Project-scoped settings + +type Settings = Record | null | undefined; + +/** + * The project's overrides. Until the server has folded them into + * settings.projectSettingsOverrides, the project's own legacy model and + * workspace fields count as overrides too. + */ +function projectOverrides(settings: Settings, project: T3ProjectShell): Record { + const stored = (settings?.projectSettingsOverrides?.[project.id] ?? {}) as Record; + if (settings?.projectSettingsFolded) return stored; + return { + ...(project.defaultModelSelection != null ? { defaultModelSelection: project.defaultModelSelection } : {}), + ...(project.defaultThreadEnvMode != null ? { defaultThreadEnvMode: project.defaultThreadEnvMode } : {}), + ...stored, + }; +} + +/** A project-scoped setting: the project's override (even null), else the environment's. */ +function projectSetting(settings: Settings, project: T3ProjectShell, key: string): unknown { + const override = projectOverrides(settings, project)[key]; + return override !== undefined ? override : settings?.[key]; +} + +/** The project that is the environment's Scratch folder (threads without a project). */ +export function isScratchProject(project: T3ProjectShell, scratchWorkspaceRoot: string | null | undefined): boolean { + if (!scratchWorkspaceRoot || !project.workspaceRoot) return false; + const normalize = (path: string) => path.replace(/[\\/]+$/, ""); + return normalize(project.workspaceRoot) === normalize(scratchWorkspaceRoot); +} + +/** + * The same repository among another environment's projects (moving a new + * thread to another computer): repository identity, else the checkout's + * folder name, else the title. + */ +export function matchingProject(projects: Iterable, target: T3ProjectShell): T3ProjectShell | null { + const list = [...projects]; + const key = target.repositoryIdentity?.canonicalKey ?? null; + if (key) { + const match = list.find((project) => project.repositoryIdentity?.canonicalKey === key); + if (match) return match; + } + const folder = baseName(target.workspaceRoot); + return ( + (folder ? list.find((project) => baseName(project.workspaceRoot) === folder) : undefined) ?? + list.find((project) => project.title === target.title) ?? + null + ); +} + +function baseName(path: string | undefined): string { + return (path ?? "").replace(/[\\/]+$/, "").split(/[\\/]/).pop() ?? ""; +} + +// --------------------------------------------------------------------------- +// Providers and models + +function providerUsable(provider: T3ServerProvider): boolean { + return ( + provider.enabled !== false && + provider.installed !== false && + provider.auth?.status !== "unauthenticated" && + provider.availability !== "unavailable" + ); +} + +function findProvider(providers: readonly T3ServerProvider[], instanceId: string | null | undefined): T3ServerProvider | undefined { + return instanceId ? providers.find((provider) => provider.instanceId === instanceId) : undefined; +} + +function findModel(providers: readonly T3ServerProvider[], selection: T3ModelSelection | null | undefined): T3ProviderModel | undefined { + return findProvider(providers, selection?.instanceId)?.models?.find((model) => model.slug === selection?.model); +} + +const DRIVER_NAMES: Record = { codex: "Codex", claudeAgent: "Claude", pi: "Pi" }; + +/** "Claude", "Codex", or the provider's configured name. */ +export function providerDisplayName(providers: readonly T3ServerProvider[], instanceId: string | null | undefined): string { + if (!instanceId) return ""; + const provider = findProvider(providers, instanceId); + const driver = provider?.driver ?? ""; + return provider?.displayName || DRIVER_NAMES[driver] || driver || instanceId; +} + +/** The model's display name ("Claude Opus 5"), else its slug. */ +export function modelDisplayName(providers: readonly T3ServerProvider[], selection: T3ModelSelection | null | undefined): string { + if (!selection) return ""; + return findModel(providers, selection)?.name || selection.model; +} + +export type ModelChoiceGroup = { + instanceId: string; + label: string; + /** Current models first, then legacy ones. */ + models: Array<{ selection: T3ModelSelection; label: string; isLegacy: boolean }>; +}; + +/** Every model on a usable provider, grouped by provider. */ +export function modelChoices(providers: readonly T3ServerProvider[]): ModelChoiceGroup[] { + const groups: ModelChoiceGroup[] = []; + for (const provider of providers) { + if (!providerUsable(provider)) continue; + const models = (provider.models ?? []) + .map((model) => ({ + selection: { instanceId: provider.instanceId, model: model.slug }, + label: model.name || model.slug, + isLegacy: model.isLegacy === true, + })) + .sort((a, b) => Number(a.isLegacy) - Number(b.isLegacy)); + if (models.length) groups.push({ instanceId: provider.instanceId, label: providerDisplayName(providers, provider.instanceId), models }); + } + return groups; +} + +/** + * Model for a new thread, the way T3's mobile app defaults it: the project's + * default (project override, then environment), then the first usable + * provider's default model, then any current model. Legacy models are never + * picked implicitly. + */ +export function defaultModelSelection( + settings: Settings, + providers: readonly T3ServerProvider[], + project: T3ProjectShell, +): T3ModelSelection | null { + const usable = (selection: unknown): selection is T3ModelSelection => { + const candidate = selection as T3ModelSelection | null | undefined; + if (!candidate?.instanceId || !candidate.model) return false; + const provider = findProvider(providers, candidate.instanceId); + if (!provider) return providers.length === 0; + return providerUsable(provider) && findModel(providers, candidate)?.isLegacy !== true; + }; + const override = projectOverrides(settings, project).defaultModelSelection; + for (const candidate of [override, settings?.defaultModelSelection]) if (usable(candidate)) return candidate; + for (const pickDefault of [true, false]) { + for (const provider of providers) { + if (!providerUsable(provider)) continue; + const model = (provider.models ?? []).find((entry) => !entry.isLegacy && (!pickDefault || entry.isDefault)); + if (model) return { instanceId: provider.instanceId, model: model.slug }; + } + } + return null; +} + +// --------------------------------------------------------------------------- +// Per-model options (effort, fast mode, ...) + +/** Effort values T3 mobile leaves out of its picker (a workflow trigger, not a reasoning level). */ +const HIDDEN_CHOICE_IDS = new Set(["ultracode"]); + +export function modelOptionDescriptors(providers: readonly T3ServerProvider[], selection: T3ModelSelection | null | undefined): T3OptionDescriptor[] { + return findModel(providers, selection)?.capabilities?.optionDescriptors ?? []; +} + +function selectionOptions(selection: T3ModelSelection | null | undefined): T3ModelOptionSelection[] { + return Array.isArray(selection?.options) ? selection!.options! : []; +} + +function validChoice(descriptor: Extract, value: unknown): string | undefined { + if (typeof value !== "string" || !value) return undefined; + if (!descriptor.options.length) return value; + if (descriptor.promptInjectedValues?.includes(value)) return undefined; + return descriptor.options.some((option) => option.id === value) ? value : undefined; +} + +/** The option's effective value: the selection's pick, else the provider's current value, else its default. */ +export function optionValue(descriptor: T3OptionDescriptor, selection: T3ModelSelection | null | undefined): string | boolean | undefined { + const picked = selectionOptions(selection).find((option) => option.id === descriptor.id)?.value; + if (descriptor.type === "boolean") { + if (typeof picked === "boolean") return picked; + return descriptor.currentValue; + } + return ( + validChoice(descriptor, picked) ?? + validChoice(descriptor, descriptor.currentValue) ?? + descriptor.options.find((option) => option.isDefault)?.id + ); +} + +export function optionValueLabel(descriptor: T3OptionDescriptor, value: string | boolean | undefined): string { + if (descriptor.type === "boolean") return value ? "On" : "Off"; + return descriptor.options.find((option) => option.id === value)?.label ?? (typeof value === "string" ? value : "Default"); +} + +/** The choices to offer for a select option. */ +export function selectableChoices(descriptor: Extract): T3OptionChoice[] { + const injected = new Set(descriptor.promptInjectedValues ?? []); + return descriptor.options.filter((option) => !injected.has(option.id) && !HIDDEN_CHOICE_IDS.has(option.id)); +} + +/** The selection with one option picked. */ +export function withModelOption(selection: T3ModelSelection, id: string, value: string | boolean): T3ModelSelection { + return { ...selection, options: [...selectionOptions(selection).filter((option) => option.id !== id), { id, value }] }; +} + +/** + * The selection as sent: only explicitly picked options whose values the + * model still accepts (T3's normalizeSelectionOptions); none at all leaves + * the provider's defaults in charge. + */ +export function dispatchModelSelection(providers: readonly T3ServerProvider[], selection: T3ModelSelection): T3ModelSelection { + const bare = { instanceId: selection.instanceId, model: selection.model }; + const picked = selectionOptions(selection); + if (!picked.length) return bare; + const model = findModel(providers, selection); + if (!model?.capabilities) return { ...bare, options: picked }; + const options: T3ModelOptionSelection[] = []; + for (const descriptor of model.capabilities.optionDescriptors ?? []) { + if (!picked.some((option) => option.id === descriptor.id)) continue; + const value = optionValue(descriptor, selection); + if (typeof value === "string" || typeof value === "boolean") options.push({ id: descriptor.id, value }); + } + return options.length ? { ...bare, options } : bare; +} + +// --------------------------------------------------------------------------- +// Access (runtime mode) + +export const RUNTIME_MODE_CHOICES: ReadonlyArray<{ mode: string; label: string; description: string }> = [ + { mode: "approval-required", label: "Supervised", description: "Ask before commands and file changes." }, + { mode: "auto-accept-edits", label: "Auto-accept edits", description: "Auto-approve edits, ask before other actions." }, + { mode: "auto", label: "Auto", description: "Supported providers approve routine actions; others still ask." }, + { mode: "full-access", label: "Full access", description: "Allow commands and edits without prompts." }, +]; + +const DEFAULT_RUNTIME_MODE = "full-access"; + +/** The access modes the provider supports (all of them when it doesn't say). */ +export function runtimeModeChoices(provider: T3ServerProvider | null | undefined): typeof RUNTIME_MODE_CHOICES { + const supported = provider?.supportedRuntimeModes; + if (!supported?.length) return RUNTIME_MODE_CHOICES; + const filtered = RUNTIME_MODE_CHOICES.filter((choice) => supported.includes(choice.mode)); + return filtered.length ? filtered : RUNTIME_MODE_CHOICES; +} + +export function runtimeModeLabel(mode: string): string { + return RUNTIME_MODE_CHOICES.find((choice) => choice.mode === mode)?.label ?? mode; +} + +// --------------------------------------------------------------------------- +// Workspace and branch + +export type WorkspaceMode = "local" | "worktree"; + +/** Project override, then environment setting, then the repo's t3.json, then "local". */ +export function defaultWorkspaceMode(settings: Settings, project: T3ProjectShell, projectFile: T3ProjectFileDefaults | null | undefined): WorkspaceMode { + const value = projectSetting(settings, project, "defaultThreadEnvMode"); + if (value === "local" || value === "worktree") return value; + return projectFile?.defaultThreadEnvMode ?? "local"; +} + +function defaultStartFromOrigin(settings: Settings, project: T3ProjectShell): boolean { + const value = projectSetting(settings, project, "newWorktreesStartFromOrigin"); + return typeof value === "boolean" ? value : true; +} + +/** The checked-out branch's worktree, when it isn't the project checkout itself. */ +function separateWorktree(ref: T3VcsRef, project: T3ProjectShell): string | null { + return ref.worktreePath && ref.worktreePath !== project.workspaceRoot ? ref.worktreePath : null; +} + +/** A short tag for a branch in the picker. */ +export function refBadge(ref: T3VcsRef, project: T3ProjectShell): string { + if (ref.current) return "current"; + if (separateWorktree(ref, project)) return "worktree"; + if (ref.isRemote) return "remote"; + if (ref.isDefault) return "default"; + return ""; +} + +/** + * Picking this branch for a thread in the project checkout means switching + * that checkout to it first (vcs.switchRef), as T3 mobile does. Branches + * already checked out somewhere run where they are. + */ +export function needsCheckout(ref: T3VcsRef, mode: WorkspaceMode): boolean { + return mode === "local" && !ref.current && !ref.worktreePath; +} + +// --------------------------------------------------------------------------- +// Draft → launch + +/** The user's explicit picks; null fields take the resolved default. */ +export type LaunchDraft = { + model: T3ModelSelection | null; + runtimeMode: string | null; + workspaceMode: WorkspaceMode | null; + /** Local: the branch the thread runs on; worktree: the base branch. */ + branch: string | null; + /** Local: run in this existing worktree (the picked branch is checked out there). */ + worktreePath: string | null; + startFromOrigin: boolean | null; +}; + +export function emptyLaunchDraft(): LaunchDraft { + return { model: null, runtimeMode: null, workspaceMode: null, branch: null, worktreePath: null, startFromOrigin: null }; +} + +export type LaunchContext = { + settings: Settings; + providers: readonly T3ServerProvider[]; + project: T3ProjectShell; + scratchWorkspaceRoot?: string | null; + /** The repo's t3.json defaults: undefined while unread, null when absent. */ + projectFile?: T3ProjectFileDefaults | null; + /** vcs.listRefs for the project, or null until loaded. */ + refs: T3RefList | null; +}; + +export type ResolvedLaunch = { + model: T3ModelSelection | null; + runtimeMode: string; + /** False for the Scratch project and for folders that aren't repositories. */ + canChooseWorkspace: boolean; + workspaceMode: WorkspaceMode; + branch: string | null; + worktreePath: string | null; + startFromOrigin: boolean; + /** Why the thread can't start yet (nothing to run it with, no base branch). */ + blocker: string | null; +}; + +export function resolveLaunch(draft: LaunchDraft, context: LaunchContext): ResolvedLaunch { + const { settings, providers, project, refs } = context; + const model = draft.model ?? defaultModelSelection(settings, providers, project); + const choices = runtimeModeChoices(findProvider(providers, model?.instanceId)); + const wantedMode = draft.runtimeMode ?? (projectSetting(settings, project, "defaultRuntimeMode") as string | null | undefined) ?? DEFAULT_RUNTIME_MODE; + const runtimeMode = choices.some((choice) => choice.mode === wantedMode) ? wantedMode : choices[0]!.mode; + const canChooseWorkspace = !isScratchProject(project, context.scratchWorkspaceRoot) && refs?.isRepo !== false; + const workspaceMode: WorkspaceMode = canChooseWorkspace ? (draft.workspaceMode ?? defaultWorkspaceMode(settings, project, context.projectFile)) : "local"; + const startFromOrigin = draft.startFromOrigin ?? defaultStartFromOrigin(settings, project); + const localRefs = (refs?.refs ?? []).filter((ref) => !ref.isRemote); + let branch: string | null; + let worktreePath: string | null = null; + if (workspaceMode === "worktree") { + // The default branch may only exist as origin/, so search every ref for it. + branch = draft.branch ?? refs?.refs.find((ref) => ref.isDefault)?.name ?? localRefs.find((ref) => ref.current)?.name ?? null; + } else if (draft.branch) { + branch = draft.branch; + worktreePath = draft.worktreePath; + } else { + const current = localRefs.find((ref) => ref.current); + branch = current?.name ?? null; + worktreePath = current ? separateWorktree(current, project) : null; + } + let blocker: string | null = null; + if (!model) blocker = "No usable agent on that computer: sign in to Claude Code, Codex or another provider in T3 Code first."; + else if (workspaceMode === "worktree" && !branch) blocker = refs ? "Choose a base branch for the worktree." : "Still loading branches."; + return { model, runtimeMode, canChooseWorkspace, workspaceMode, branch, worktreePath, startFromOrigin, blocker }; +} + +/** "Current checkout", "Existing worktree" or "New worktree". */ +export function workspaceLabel(resolved: Pick): string { + if (resolved.workspaceMode === "worktree") return "New worktree"; + return resolved.worktreePath ? "Existing worktree" : "Current checkout"; +} + +/** The branch row: "main", or a worktree's base "From origin/main". */ +export function branchLabel(resolved: Pick, hasPrimaryRemote: boolean): string { + if (!resolved.branch) return resolved.workspaceMode === "worktree" ? "Choose branch" : "Unknown"; + if (resolved.workspaceMode === "local") return resolved.branch; + const fromOrigin = resolved.startFromOrigin && hasPrimaryRemote && !resolved.branch.startsWith("origin/"); + return `From ${fromOrigin ? `origin/${resolved.branch}` : resolved.branch}`; +} + +/** The draft after picking a branch (or worktree base) in the given mode. */ +export function pickBranch(draft: LaunchDraft, ref: T3VcsRef, mode: WorkspaceMode, project: T3ProjectShell): LaunchDraft { + return { ...draft, branch: ref.name, worktreePath: mode === "local" ? separateWorktree(ref, project) : null }; +} + +/** + * The draft after switching workspace mode. A new worktree keeps an explicitly + * picked base; the project checkout goes back to whatever is checked out. + */ +export function pickWorkspaceMode(draft: LaunchDraft, mode: WorkspaceMode): LaunchDraft { + return mode === "local" + ? { ...draft, workspaceMode: mode, branch: null, worktreePath: null } + : { ...draft, workspaceMode: mode, worktreePath: null }; +} + +/** Where the server runs the thread (OrchestrationV2 workspaceStrategy). */ +export function workspaceStrategy(resolved: ResolvedLaunch): Record { + if (resolved.workspaceMode === "worktree") { + return { type: "worktree", baseRef: resolved.branch, ...(resolved.startFromOrigin ? { startFromOrigin: true } : {}) }; + } + if (resolved.worktreePath) { + return { type: "existing_worktree", worktreePath: resolved.worktreePath, ...(resolved.branch ? { branch: resolved.branch } : {}) }; + } + return { type: "root", ...(resolved.branch ? { branch: resolved.branch } : {}) }; +} + +/** First line of a prompt as a provisional title (the server generates a better one). */ +export function provisionalTitle(text: string): string { + const collapsed = text.replace(/\s+/g, " ").trim(); + if (!collapsed) return "New thread"; + return collapsed.length > 72 ? `${collapsed.slice(0, 71).trimEnd()}…` : collapsed; +} + +/** The orchestration.launchThread payload. Throws when resolveLaunch reported a blocker. */ +export function launchThreadPayload( + project: T3ProjectShell, + text: string, + resolved: ResolvedLaunch, + providers: readonly T3ServerProvider[], +): Record { + if (resolved.blocker || !resolved.model) throw new Error(resolved.blocker ?? "No model selected."); + return { + commandId: uuidv4(), + creationSource: "mobile", + threadId: uuidv4(), + projectId: project.id, + title: provisionalTitle(text), + generateTitle: true, + modelSelection: dispatchModelSelection(providers, resolved.model), + runtimeMode: resolved.runtimeMode, + interactionMode: "default", + workspaceStrategy: workspaceStrategy(resolved), + initialMessage: { messageId: uuidv4(), text, attachments: [] }, + }; +} diff --git a/app/apps/t3code/t3-model.ts b/app/apps/t3code/t3-model.ts index 63ecab1e..9d356797 100644 --- a/app/apps/t3code/t3-model.ts +++ b/app/apps/t3code/t3-model.ts @@ -3,6 +3,7 @@ * transport and rendering: the shell (projects + thread list) reducer, the * per-thread detail reducer, thread status / ordering for the glasses list, * one-line summaries of timeline items, and the dispatch-command builders. + * (New-thread options and the launch payload are in t3-launch.ts.) * * Mirrors T3's own client runtime (packages/client-runtime/src/state/ * shellReducer.ts, orchestrationV2Projection.ts, models.ts; apps/mobile's @@ -18,10 +19,16 @@ export type T3ProjectShell = { id: string; title: string; workspaceRoot?: string; + repositoryIdentity?: { canonicalKey?: string | null } | null; + /** Legacy per-project defaults (superseded by settings.projectSettingsOverrides once folded). */ defaultModelSelection?: T3ModelSelection | null; + defaultThreadEnvMode?: string | null; }; -export type T3ModelSelection = { instanceId: string; model: string; options?: unknown[] }; +/** A provider model option picked for a run ("effort" = "high", "fastMode" = true). */ +export type T3ModelOptionSelection = { id: string; value: string | boolean }; + +export type T3ModelSelection = { instanceId: string; model: string; options?: T3ModelOptionSelection[] }; export type T3ThreadShell = { id: string; @@ -839,86 +846,3 @@ export function approvalOptions(item: T3TurnItem): T3ApprovalOption[] { export function optionAnswer(option: { label: string; value?: string }): string { return option.value ?? option.label; } - -// --------------------------------------------------------------------------- -// New threads - -export type T3ServerProvider = { - instanceId: string; - displayName?: string; - driver?: string; - enabled?: boolean; - installed?: boolean; - auth?: { status?: string }; - models?: Array<{ slug: string; name?: string; isDefault?: boolean; isLegacy?: boolean }>; -}; - -function providerUsable(provider: T3ServerProvider): boolean { - return provider.enabled !== false && provider.installed !== false && provider.auth?.status !== "unauthenticated"; -} - -export function providerDisplayName(providers: readonly T3ServerProvider[], instanceId: string | null | undefined): string { - if (!instanceId) return ""; - const provider = providers.find((candidate) => candidate.instanceId === instanceId); - return provider?.displayName || provider?.driver || instanceId; -} - -/** - * Model for a new thread, the way T3's mobile app defaults it: project - * override, environment default, the project's legacy default, then the - * first usable provider's default model, then any usable model. - */ -export function defaultModelSelection( - settings: Record | null, - providers: readonly T3ServerProvider[], - project: T3ProjectShell, -): T3ModelSelection | null { - const usable = (selection: T3ModelSelection | null | undefined): selection is T3ModelSelection => { - if (!selection?.instanceId || !selection.model) return false; - const provider = providers.find((candidate) => candidate.instanceId === selection.instanceId); - return provider ? providerUsable(provider) : providers.length === 0; - }; - const candidates = [ - settings?.projectSettingsOverrides?.[project.id]?.defaultModelSelection, - settings?.defaultModelSelection, - project.defaultModelSelection, - ]; - for (const candidate of candidates) if (usable(candidate)) return candidate; - for (const pickDefault of [true, false]) { - for (const provider of providers) { - if (!providerUsable(provider)) continue; - const model = (provider.models ?? []).find((entry) => !entry.isLegacy && (!pickDefault || entry.isDefault)); - if (model) return { instanceId: provider.instanceId, model: model.slug }; - } - } - return null; -} - -/** First line of a prompt as a provisional title (the server generates a better one). */ -export function provisionalTitle(text: string): string { - const collapsed = oneLine(text); - if (!collapsed) return "New thread"; - return collapsed.length > 72 ? `${collapsed.slice(0, 71).trimEnd()}…` : collapsed; -} - -export function launchThreadPayload( - project: T3ProjectShell, - text: string, - modelSelection: T3ModelSelection, - settings: Record | null, -): Record { - const runtimeMode = settings?.projectSettingsOverrides?.[project.id]?.defaultRuntimeMode ?? settings?.defaultRuntimeMode ?? "full-access"; - return { - commandId: uuidv4(), - creationSource: "mobile", - threadId: uuidv4(), - projectId: project.id, - title: provisionalTitle(text), - generateTitle: true, - modelSelection, - runtimeMode, - interactionMode: "default", - workspaceStrategy: { type: "root" }, - initialMessage: { messageId: uuidv4(), text, attachments: [] }, - }; -} diff --git a/app/apps/t3code/t3code-app.worker.ts b/app/apps/t3code/t3code-app.worker.ts index b4db75f4..ec2697fc 100644 --- a/app/apps/t3code/t3code-app.worker.ts +++ b/app/apps/t3code/t3code-app.worker.ts @@ -15,7 +15,9 @@ * chosen from the menu). Tap-then-hold has Stop, Settle, etc. * - environments / pair: manage paired servers; pairing takes the link from * `t3 pair`, typed into the phone app's text editor. - * - compose: the first message of a new thread in a chosen project. + * - compose: a new thread's options (host, project, model and its options, + * access mode, workspace/worktree, branch), then its first message by + * voice or phone keyboard. * Double-click backs out a level, and from the list yields focus. * * Connections (one T3EnvironmentClient per paired environment) live while the @@ -39,7 +41,7 @@ import { openSocket } from "../../native/socket"; import { fetchWithUserAgent } from "../../util/http"; import { drawSubmenuIndicator, submenuItem, type MenuItem } from "../../ui/menu"; import { Menu, type MenuDrawArgs } from "../../ui/menu-core"; -import { lineStep, listRowHeight } from "../../ui/metrics"; +import { LIST_ROW_TEXT_INSET, lineStep, listRowHeight } from "../../ui/metrics"; import { WindowMenu, WindowMenuLayer } from "../../ui/window-menu"; import type { WorkerAppMessage, WorkerAppReply } from "../../ui/shell/worker-window"; import type { ToolResult, ToolSpec } from "../../assistant/tool-registry"; @@ -57,17 +59,14 @@ import { buildGlanceSnapshot, glanceSummary, T3_GLANCE_STATE_KEY } from "./t3-gl import { approvalOptions, approvalResponseCommand, - defaultModelSelection, describeRequest, formatAge, interruptCommand, isThreadSettled, isThreadUnread, - launchThreadPayload, messageDispatchCommand, optionAnswer, plainMarkdown, - providerDisplayName, questionAnswerCommand, sectionThreads, settleCommand, @@ -78,10 +77,43 @@ import { timelineEntries, visitCommand, type PendingRequest, + type T3ModelSelection, type T3ProjectShell, type T3ThreadShell, type T3ThreadStatus, } from "./t3-model"; +import { + branchLabel, + emptyLaunchDraft, + isScratchProject, + launchThreadPayload, + matchingProject, + modelChoices, + modelDisplayName, + modelOptionDescriptors, + needsCheckout, + optionValue, + optionValueLabel, + parseProjectFile, + pickBranch, + pickWorkspaceMode, + providerDisplayName, + refBadge, + resolveLaunch, + runtimeModeChoices, + runtimeModeLabel, + selectableChoices, + T3_PROJECT_FILE_NAME, + withModelOption, + workspaceLabel, + type LaunchDraft, + type ResolvedLaunch, + type T3OptionDescriptor, + type T3ProjectFileDefaults, + type T3RefList, + type T3VcsRef, + type WorkspaceMode, +} from "./t3-launch"; import { parsePairingInput, baseUrlLabel } from "./t3-pairing"; import type { RpcSocketFactory } from "./t3-rpc"; import { TranscriptLayout } from "./t3-transcript"; @@ -118,7 +150,7 @@ type Screen = | { kind: "thread"; envId: string; threadId: string } | { kind: "environments" } | { kind: "pair"; repairId: string | null } - | { kind: "compose"; envId: string; projectId: string }; + | { kind: "compose" }; type AppWindow = { windowId: string; @@ -157,9 +189,10 @@ type ThreadView = { type ListItem = { key: string; - kind: "heading" | "thread" | "action"; + /** "field": a new-thread option, its name in a column and `right` as its value. */ + kind: "heading" | "thread" | "action" | "field"; label: string; - /** Dim text at the right edge (project, age, status). */ + /** Dim text at the right edge (project, age, status); a field's value. */ right?: string; /** Status marker drawn left of a thread title. */ marker?: string; @@ -184,6 +217,25 @@ let noticeTimer: ReturnType | null = null; let busyText = ""; let screenError = ""; +/** The new thread being set up on the compose screen. */ +type ComposeState = { + envId: string; + projectId: string; + draft: LaunchDraft; + /** vcs.listRefs for the project: null while loading, or when it failed (refsError). */ + refs: T3RefList | null; + refsError: string; + /** The repo's t3.json defaults: undefined while reading, null when it has none. */ + projectFile: T3ProjectFileDefaults | null | undefined; + /** Settles when the branch list and t3.json reads in flight finish. */ + loading: Promise; +}; + +let compose: ComposeState | null = null; +let composeSelectionKey: string | null = null; +/** Where field values start on the compose screen (set per paint from the field names). */ +let composeValueColumn = 0; + const clients = new Map(); const clientUnsubscribers = new Map void>(); /** The label last saved for each environment. */ @@ -276,7 +328,8 @@ const T3_TOOLS: ToolSpec[] = [ }, { name: "start_thread", - description: "Start a new T3 Code thread in a project (found by matching its name) with a first message for the agent.", + description: + "Start a new T3 Code thread in a project (found by matching its name) with a first message for the agent. Uses the project's defaults for model, access mode and workspace.", inputSchema: { type: "object", properties: { @@ -339,6 +392,7 @@ global.onmessage = (event: { data: WorkerAppMessage }) => { if (window.renderTimer) clearTimeout(window.renderTimer); window = null; closeThreadView(); + compose = null; screen = { kind: "list" }; // The Glanceboard widget may still want the connections. if (!hasT3BackgroundWork()) stopAllClients(); @@ -582,10 +636,11 @@ function noteAttention(client: T3EnvironmentClient): void { function setScreen(next: Screen): void { leaveScreenSideEffects(); if (next.kind !== "thread") closeThreadView(); + if (next.kind !== "compose") compose = null; screen = next; busyText = ""; screenError = ""; - if (next.kind === "list" || next.kind === "environments") listMenu?.select(0); + if (next.kind === "list" || next.kind === "environments" || next.kind === "compose") listMenu?.select(0); if (window) post({ type: "set-title", windowId: window.windowId, title: next.kind === "thread" ? threadTitle() : APP_TITLE }); updateListRefreshTimer(); } @@ -689,10 +744,10 @@ function showNotice(text: string): void { * From inside another menu's item the old menu is still closing (WindowMenu * ignores open() until its input handling finishes), so wait a tick. */ -function openWindowMenu(items: MenuItem[], title: string): void { +function openWindowMenu(items: MenuItem[], title: string, selectedIndex?: number): void { const open = () => { if (!window) return; - windowMenu(window).open(items, title); + windowMenu(window).open(items, title, selectedIndex); renderNow(); }; if (window?.menu?.isOpen()) setTimeout(open, 0); @@ -732,6 +787,7 @@ function handleInput(win: AppWindow, event: InputEvent, frameId: number): void { switch (screen.kind) { case "list": case "environments": + case "compose": handleListInput(event, frameId); return; case "thread": @@ -744,13 +800,6 @@ function handleInput(win: AppWindow, event: InputEvent, frameId: number): void { return; } break; - case "compose": - if (event.type === "click" && !busyText) { - post({ type: "start-voice-input", windowId: win.windowId }); - frameTimings.finishFrame(frameId, "discarded: t3code opened voice input"); - return; - } - break; } frameTimings.finishFrame(frameId, "discarded: t3code ignored input"); } @@ -761,14 +810,26 @@ function handleListInput(event: InputEvent, frameId: number): void { return; } const menu = list(); - const items = screen.kind === "environments" ? environmentItems() : listItems(); + const items = currentListItems(); menu.setItems(items, selectionIndex(items)); // Item actions are synchronous, so the move or action has applied when this returns. menu.handleInput(event).catch((error) => console.error("t3code list action failed", error)); - if (event.type !== "click") listSelectionKey = menu.selectedItem?.key ?? null; + if (event.type !== "click") setSelectedKey(menu.selectedItem?.key ?? null); renderNow(frameId); } +/** The rows of whichever list-shaped screen is showing. */ +function currentListItems(): ListItem[] { + switch (screen.kind) { + case "environments": + return environmentItems(); + case "compose": + return composeItems(); + default: + return listItems(); + } +} + function handleThreadInput(event: InputEvent, frameId: number): void { const view = threadView; if (!view) { @@ -825,7 +886,7 @@ function handleTextInput(text: string): void { render(); return; case "compose": - void launchNewThread(screen.envId, screen.projectId, text); + void launchNewThread(text); return; case "thread": { const view = threadView; @@ -1081,8 +1142,7 @@ function projectMenuItems(): MenuItem[] { label: multiEnv ? `${project.title} · ${environmentName(client)}` : project.title, onSelect: (ctx) => { ctx.stack.clearToBase(); - setScreen({ kind: "compose", envId: client.config.id, projectId: project.id }); - if (window) post({ type: "start-voice-input", windowId: window.windowId }); + beginCompose(client, project); }, })); } @@ -1156,37 +1216,432 @@ async function pairFromDraft(): Promise { // --------------------------------------------------------------------------- // New threads -function composeTarget(): { client: T3EnvironmentClient; project: T3ProjectShell } | null { - if (screen.kind !== "compose") return null; - const client = clients.get(screen.envId); - const project = client?.shell.projects.get(screen.projectId); - return client && project ? { client, project } : null; +/** Most branches a picker lists (vcs.listRefs pages past this aren't fetched). */ +const BRANCH_LIST_LIMIT = 100; + +type ComposeTarget = { client: T3EnvironmentClient; project: T3ProjectShell; state: ComposeState }; + +function composeTarget(): ComposeTarget | null { + if (screen.kind !== "compose" || !compose) return null; + const client = clients.get(compose.envId); + const project = client?.shell.projects.get(compose.projectId); + return client && project ? { client, project, state: compose } : null; } -async function launchNewThread(envId: string, projectId: string, text: string): Promise { - const client = clients.get(envId); - const project = client?.shell.projects.get(projectId); - if (!client || !project) return; - const selection = defaultModelSelection(client.settings, client.providers, project); - if (!selection) { - screenError = "No usable agent on that computer: sign in to Claude Code, Codex or another provider in T3 Code first."; +/** Show the new-thread options for a project, keeping whatever `draft` picks still apply there. */ +function beginCompose(client: T3EnvironmentClient, project: T3ProjectShell, draft: LaunchDraft = emptyLaunchDraft()): void { + const state: ComposeState = { + envId: client.config.id, + projectId: project.id, + draft, + refs: null, + refsError: "", + projectFile: undefined, + loading: Promise.resolve(), + }; + if (screen.kind === "compose") { + // Another host or project: keep the selection on the row that changed it. + compose = state; + screenError = ""; + } else { + compose = state; + composeSelectionKey = null; + setScreen({ kind: "compose" }); + } + loadComposeContext(state); + render(); +} + +/** Read the project's branches and t3.json (defaults and the branch picker). */ +function loadComposeContext(state: ComposeState): void { + const client = clients.get(state.envId); + const project = client?.shell.projects.get(state.projectId); + if (!client || !project?.workspaceRoot || isScratchProject(project, client.scratchWorkspaceRoot)) { + state.projectFile = null; + return; + } + state.refsError = ""; + const refs = fetchRefs(client, project, true).then( + (refList) => { + if (compose !== state) return; + state.refs = refList; + render(); + }, + (error) => { + if (compose !== state) return; + state.refsError = errorMessage(error); + render(); + }, + ); + const projectFile = + state.projectFile !== undefined + ? Promise.resolve() + : readProjectFile(client, project).then((file) => { + if (compose !== state) return; + state.projectFile = file; + render(); + }); + state.loading = Promise.all([refs, projectFile]).then(() => {}); +} + +function fetchRefs(client: T3EnvironmentClient, project: T3ProjectShell, refresh: boolean): Promise { + // refresh: the cached list's "current" flag can lag a checkout made outside T3 by minutes. + return client.call("vcs.listRefs", { cwd: project.workspaceRoot, limit: BRANCH_LIST_LIMIT, ...(refresh ? { refresh: true } : {}) }); +} + +/** The repo's t3.json defaults; null when it has none or it can't be read. */ +async function readProjectFile(client: T3EnvironmentClient, project: T3ProjectShell): Promise { + try { + const result = await client.call<{ contents?: unknown; truncated?: boolean }>("projects.readFile", { + cwd: project.workspaceRoot, + relativePath: T3_PROJECT_FILE_NAME, + }); + return typeof result?.contents === "string" && !result.truncated ? parseProjectFile(result.contents) : null; + } catch { + return null; + } +} + +function composeResolved({ client, project, state }: ComposeTarget): ResolvedLaunch { + return resolveLaunch(state.draft, { + settings: client.settings, + providers: client.providers, + project, + scratchWorkspaceRoot: client.scratchWorkspaceRoot, + projectFile: state.projectFile, + refs: state.refs, + }); +} + +/** A new-thread option row; `action` opens its picker (or toggles it). */ +function field(key: string, label: string, value: string, action?: () => void, submenu = true): ListItem { + return { + key: `field:${key}`, + kind: "field", + label, + right: value, + submenu: Boolean(action) && submenu, + onSelect: action + ? () => { + if (!busyText) action(); + } + : undefined, + }; +} + +function composeItems(): ListItem[] { + const target = composeTarget(); + if (!target) return []; + const { client, project, state } = target; + const resolved = composeResolved(target); + const model = resolved.model; + const items: ListItem[] = [ + { + key: "start", + kind: "action", + label: "Say what to do…", + right: "or type it on the phone", + onSelect: () => { + if (!busyText && window) post({ type: "start-voice-input", windowId: window.windowId }); + }, + }, + field("host", "Host", environmentName(client), readyClients().length > 1 ? () => openHostPicker(target) : undefined), + field("project", "Project", project.title, () => openProjectPicker(target)), + field( + "model", + "Model", + model ? modelRowValue(client, model) : "None available", + modelChoices(client.providers).length ? () => openModelPicker(target, resolved) : undefined, + ), + ]; + if (model) { + for (const descriptor of modelOptionDescriptors(client.providers, model)) { + const value = optionValue(descriptor, model); + const shown = optionValueLabel(descriptor, value); + if (descriptor.type === "boolean") { + items.push(field(`option:${descriptor.id}`, descriptor.label, shown, () => setModelOption(target, resolved, descriptor.id, !value), false)); + } else if (selectableChoices(descriptor).length) { + items.push(field(`option:${descriptor.id}`, descriptor.label, shown, () => openOptionPicker(target, resolved, descriptor))); + } + } + } + const accessChoices = runtimeModeChoices(client.providers.find((provider) => provider.instanceId === model?.instanceId)); + items.push(field("access", "Access", runtimeModeLabel(resolved.runtimeMode), accessChoices.length > 1 ? () => openAccessPicker(target, resolved) : undefined)); + if (!resolved.canChooseWorkspace) { + const why = isScratchProject(project, client.scratchWorkspaceRoot) ? "Own folder (no project)" : "Project folder (not a git repo)"; + items.push(field("workspace", "Workspace", why)); + return items; + } + items.push(field("workspace", "Workspace", workspaceLabel(resolved), () => openWorkspacePicker(target, resolved))); + const branchName = resolved.workspaceMode === "worktree" ? "Base" : "Branch"; + if (state.refsError) { + items.push(field("branch", branchName, "Couldn't load; retry", () => { + loadComposeContext(state); + render(); + }, false)); + } else if (!state.refs && !resolved.branch) { + items.push(field("branch", branchName, "Loading…")); + } else { + items.push(field("branch", branchName, branchLabel(resolved, Boolean(state.refs?.hasPrimaryRemote)), state.refs ? () => openBranchPicker(target, resolved) : undefined)); + } + if (resolved.workspaceMode === "worktree" && state.refs?.hasPrimaryRemote) { + items.push(field("origin", "From origin", resolved.startFromOrigin ? "On" : "Off", () => { + state.draft = { ...state.draft, startFromOrigin: !resolved.startFromOrigin }; + }, false)); + } + return items; +} + +/** "Claude Opus 5", or "Codex · GPT-5.4" when the model's name doesn't say whose it is. */ +function modelRowValue(client: T3EnvironmentClient, model: T3ModelSelection): string { + const provider = providerDisplayName(client.providers, model.instanceId); + const name = modelDisplayName(client.providers, model); + return name.toLowerCase().startsWith(provider.toLowerCase()) ? name : `${provider} · ${name}`; +} + +/** A picker row, " *" marking the current value, with an optional dim tag at the right. */ +function choiceItem(label: string, onSelect: MenuItem["onSelect"], options: { current?: boolean; right?: string } = {}): MenuItem { + const text = options.current ? `${label} *` : label; + const right = options.right; + return { + label: text, + onSelect, + render: right + ? ({ image, x, y, width, selected, disabled }) => { + const f = font(); + const rightWidth = f.measureText(right); + image.drawText(f, x, y + LIST_ROW_TEXT_INSET, truncateText(f, text, width - rightWidth - 12), disabled ? 70 : selected ? 255 : 200); + image.drawText(f, x + width - rightWidth - 2, y + LIST_ROW_TEXT_INSET, right, selected ? 200 : 120); + } + : undefined, + }; +} + +/** Open a picker on its current row. */ +function openChoices(items: MenuItem[], title: string, currentIndex: number): void { + openWindowMenu(items, title, currentIndex >= 0 ? currentIndex : undefined); +} + +function openHostPicker({ client, project }: ComposeTarget): void { + const hosts = readyClients(); + const items = hosts.map((host) => + choiceItem( + environmentName(host), + (ctx) => { + ctx.stack.pop(); + if (host === client) return; + // The same repository there if it has it, else its most recently used project. + const target = matchingProject(host.shell.projects.values(), project) ?? projectChoices().find((choice) => choice.client === host)?.project; + if (!target) { + showNotice(`${environmentName(host)} has no projects.`); + return; + } + beginCompose(host, target); + }, + { current: host === client }, + ), + ); + openChoices(items, "Host", hosts.indexOf(client)); +} + +function openProjectPicker({ client, project, state }: ComposeTarget): void { + const projects = projectChoices() + .filter((choice) => choice.client === client) + .map((choice) => choice.project); + const items = projects.map((candidate) => + choiceItem( + candidate.title, + (ctx) => { + ctx.stack.pop(); + if (candidate.id === project.id) return; + // The model and access picks carry over; workspace and branch belong to the old repo. + beginCompose(client, candidate, { ...emptyLaunchDraft(), model: state.draft.model, runtimeMode: state.draft.runtimeMode }); + }, + { current: candidate.id === project.id }, + ), + ); + openChoices(items, "Project", projects.findIndex((candidate) => candidate.id === project.id)); +} + +function openModelPicker({ client, state }: ComposeTarget, resolved: ResolvedLaunch): void { + const current = resolved.model; + const isCurrent = (instanceId: string, model: string) => current?.instanceId === instanceId && current.model === model; + const groups = modelChoices(client.providers); + const modelItems = (group: (typeof groups)[number]) => + group.models.map((choice) => + choiceItem( + choice.label, + (ctx) => { + ctx.stack.clearToBase(); + // A different model starts from its own option defaults. + if (!isCurrent(choice.selection.instanceId, choice.selection.model)) state.draft = { ...state.draft, model: choice.selection }; + }, + { current: isCurrent(choice.selection.instanceId, choice.selection.model), right: choice.isLegacy ? "legacy" : undefined }, + ), + ); + const currentModelIndex = (group: (typeof groups)[number]) => group.models.findIndex((choice) => isCurrent(choice.selection.instanceId, choice.selection.model)); + if (groups.length === 1) { + openChoices(modelItems(groups[0]!), `${groups[0]!.label} model`, currentModelIndex(groups[0]!)); + return; + } + const items = groups.map((group) => + submenuItem(group.instanceId === current?.instanceId ? `${group.label} *` : group.label, (ctx) => + ctx.stack.push(new WindowMenuLayer(`${group.label} model`, modelItems(group)).selectItem(Math.max(0, currentModelIndex(group)))), + ), + ); + openChoices(items, "Model", groups.findIndex((group) => group.instanceId === current?.instanceId)); +} + +function setModelOption({ state }: ComposeTarget, resolved: ResolvedLaunch, id: string, value: string | boolean): void { + if (!resolved.model) return; + state.draft = { ...state.draft, model: withModelOption(resolved.model, id, value) }; +} + +function openOptionPicker(target: ComposeTarget, resolved: ResolvedLaunch, descriptor: Extract): void { + const value = optionValue(descriptor, resolved.model); + const choices = selectableChoices(descriptor); + const items = choices.map((choice) => + choiceItem( + choice.label, + (ctx) => { + ctx.stack.pop(); + setModelOption(target, resolved, descriptor.id, choice.id); + }, + { current: choice.id === value }, + ), + ); + openChoices(items, descriptor.label, choices.findIndex((choice) => choice.id === value)); +} + +function openAccessPicker({ client, state }: ComposeTarget, resolved: ResolvedLaunch): void { + const choices = runtimeModeChoices(client.providers.find((provider) => provider.instanceId === resolved.model?.instanceId)); + const items = choices.map((choice) => + choiceItem( + choice.label, + (ctx) => { + ctx.stack.pop(); + state.draft = { ...state.draft, runtimeMode: choice.mode }; + }, + { current: choice.mode === resolved.runtimeMode }, + ), + ); + openChoices(items, "Access", choices.findIndex((choice) => choice.mode === resolved.runtimeMode)); +} + +function openWorkspacePicker({ state }: ComposeTarget, resolved: ResolvedLaunch): void { + const modes: Array<{ mode: WorkspaceMode; label: string }> = [ + { mode: "local", label: "Current checkout" }, + { mode: "worktree", label: "New worktree" }, + ]; + const items = modes.map(({ mode, label }) => + choiceItem( + label, + (ctx) => { + ctx.stack.pop(); + if (mode !== resolved.workspaceMode || state.draft.worktreePath) state.draft = pickWorkspaceMode(state.draft, mode); + }, + { current: mode === resolved.workspaceMode && !resolved.worktreePath }, + ), + ); + openChoices(items, "Workspace", modes.findIndex(({ mode }) => mode === resolved.workspaceMode)); +} + +function openBranchPicker(target: ComposeTarget, resolved: ResolvedLaunch): void { + const { project, state } = target; + const mode = resolved.workspaceMode; + // A thread in the checkout runs on a local branch; a worktree can start from a remote one too. + const refs = (state.refs?.refs ?? []).filter((ref) => mode === "worktree" || !ref.isRemote); + const items: MenuItem[] = refs.map((ref) => + choiceItem( + ref.name, + (ctx) => { + ctx.stack.pop(); + void selectBranch(target, ref, mode); + }, + { current: ref.name === resolved.branch, right: needsCheckout(ref, mode) ? "check out" : refBadge(ref, project) || undefined }, + ), + ); + const hidden = (state.refs?.totalCount ?? 0) - (state.refs?.refs.length ?? 0); + if (state.refs?.nextCursor != null && hidden > 0) items.push({ label: `(${hidden} more not listed)`, disabled: true, onSelect: () => {} }); + if (!items.length) items.push({ label: "No branches", disabled: true, onSelect: () => {} }); + openChoices(items, mode === "worktree" ? "New worktree from" : "Run on branch", refs.findIndex((ref) => ref.name === resolved.branch)); +} + +/** + * Use a branch. In the project checkout, a branch that isn't checked out + * anywhere is checked out first (vcs.switchRef), as T3's own app does; + * one checked out in another worktree runs there. + */ +async function selectBranch({ client, project, state }: ComposeTarget, ref: T3VcsRef, mode: WorkspaceMode): Promise { + if (!needsCheckout(ref, mode)) { + state.draft = pickBranch(state.draft, ref, mode, project); render(); return; } + busyText = `Checking out ${ref.name}…`; + screenError = ""; + render(); + try { + const result = await client.call<{ refName?: string | null }>("vcs.switchRef", { cwd: project.workspaceRoot, refName: ref.name }); + if (compose !== state) return; + state.draft = pickBranch(state.draft, { ...ref, name: result?.refName || ref.name, current: true }, mode, project); + busyText = ""; + showNotice(`Checked out ${result?.refName || ref.name}`); + loadComposeContext(state); + } catch (error) { + if (compose !== state) return; + busyText = ""; + screenError = `Couldn't check out ${ref.name}: ${errorMessage(error)}`; + render(); + } +} + +async function launchNewThread(text: string): Promise { + const target = composeTarget(); + if (!target) return; + if (busyText) { + showNotice(`Not started: still ${busyText.replace(/…$/, "").toLowerCase()}.`); + return; + } + const { client, project, state } = target; busyText = "Starting thread…"; screenError = ""; render(); try { - const threadId = await client.launchThread(launchThreadPayload(project, text, selection, client.settings)); - if (screen.kind === "compose") openThread(envId, threadId); + // Defaults can depend on the branch list and t3.json. + await state.loading; + if (compose !== state) return; + const resolved = composeResolved(target); + if (resolved.blocker) throw new Error(resolved.blocker); + const threadId = await client.launchThread(launchThreadPayload(project, text, resolved, client.providers)); + if (compose === state) openThread(client.config.id, threadId); render(); } catch (error) { + if (compose !== state) return; busyText = ""; screenError = errorMessage(error); render(); } } +/** The project's own defaults for a new thread (the assistant tool has no screen to pick on). */ +async function defaultLaunch(client: T3EnvironmentClient, project: T3ProjectShell): Promise { + const scratch = isScratchProject(project, client.scratchWorkspaceRoot); + const usesRepo = Boolean(project.workspaceRoot) && !scratch; + const [projectFile, refs] = await Promise.all([ + usesRepo ? readProjectFile(client, project) : Promise.resolve(null), + usesRepo ? fetchRefs(client, project, false).catch(() => null) : Promise.resolve(null), + ]); + return resolveLaunch(emptyLaunchDraft(), { + settings: client.settings, + providers: client.providers, + project, + scratchWorkspaceRoot: client.scratchWorkspaceRoot, + projectFile, + refs, + }); +} + // --------------------------------------------------------------------------- // List items @@ -1208,11 +1663,17 @@ function list(): Menu { /** The selection index for the remembered key (selection follows its thread as the list reorders). */ function selectionIndex(items: readonly ListItem[]): number | undefined { - if (!listSelectionKey) return undefined; - const index = items.findIndex((item) => item.key === listSelectionKey); + const key = screen.kind === "compose" ? composeSelectionKey : listSelectionKey; + if (!key) return undefined; + const index = items.findIndex((item) => item.key === key); return index >= 0 ? index : undefined; } +function setSelectedKey(key: string | null): void { + if (screen.kind === "compose") composeSelectionKey = key; + else listSelectionKey = key; +} + function threadItem(client: T3EnvironmentClient, thread: T3ThreadShell, multiEnv: boolean, nowMs: number): ListItem { const { marker, value } = threadMarker(threadStatus(thread), { settled: isThreadSettled(thread), unread: isThreadUnread(thread) }); const project = client.shell.projects.get(thread.projectId)?.title ?? ""; @@ -1365,6 +1826,15 @@ function drawListRow({ image, item, x, y, width, height, selected }: MenuDrawArg image.drawText(f, x + 4, textY, truncateText(f, item.label, width - 8), selected ? 255 : 140); return; } + if (item.kind === "field") { + const submenuWidth = item.submenu ? 16 : 0; + const valueX = x + 6 + composeValueColumn; + image.drawText(f, x + 6, textY, truncateText(f, item.label, composeValueColumn - 8), selected ? 230 : 140); + const valueValue = selected ? 255 : item.onSelect ? 210 : 150; + image.drawText(f, valueX, textY, truncateText(f, item.right ?? "", Math.max(10, x + width - valueX - submenuWidth - 6)), valueValue); + if (item.submenu) drawSubmenuIndicator(image, f, x, y, width, height, selected ? 255 : 200); + return; + } const value = selected ? 255 : 200; const markerWidth = item.kind === "thread" ? 18 : 0; if (item.marker) image.drawText(f, x + 6, textY, item.marker, selected ? 255 : (item.markerValue ?? value)); @@ -1580,20 +2050,33 @@ function paintPair(win: AppWindow): GrayImage { function paintCompose(win: AppWindow): GrayImage { const target = composeTarget(); if (!target) return paintMessageScreen(win, "New thread", [{ text: "That project is no longer available.", value: 170 }], ""); - const { client, project } = target; - const selection = defaultModelSelection(client.settings, client.providers, project); - const agent = selection ? `${providerDisplayName(client.providers, selection.instanceId)} · ${selection.model}` : "No usable agent"; - return paintMessageScreen( - win, - `New thread: ${project.title}`, - [ - { text: `Agent: ${agent}`, value: 150 }, - { text: "Say or type what the agent should do.", value: 200 }, - { text: busyText, value: 200 }, - { text: screenError, value: 230 }, - ], - busyText ? "" : `${GESTURE_CLICK} speak ${GESTURE_DOUBLE_CLICK} cancel`, - ); + const image = new GrayImage(win.viewportWidth, win.viewportHeight, 0); + const f = font(); + const step = lineStep(f); + const title = "New thread"; + image.drawText(f, TITLE_X, TITLE_Y, title, 220); + const status = busyText || notice?.text || ""; + if (status) { + const statusX = TITLE_X + f.measureText(title) + 16; + image.drawText(f, statusX, TITLE_Y, truncateText(f, status, win.viewportWidth - statusX - 14), 150); + } + // Below the list: an error, or why nothing can start here. + const resolved = composeResolved(target); + const problem = screenError || (resolved.model ? "" : (resolved.blocker ?? "")); + const problemLines = problem ? wrapText(f, problem, win.viewportWidth - TITLE_X * 2).slice(0, 3) : []; + const listTop = TITLE_Y + step + 8; + const listWidth = win.viewportWidth - LIST_LEFT - LIST_RIGHT; + const listHeight = win.viewportHeight - 6 - listTop - (problemLines.length ? problemLines.length * step + 6 : 0); + const items = composeItems(); + const widest = Math.max(0, ...items.filter((item) => item.kind === "field").map((item) => f.measureText(item.label))); + composeValueColumn = Math.min(widest + 16, Math.floor(listWidth * 0.4)); + const menu = list(); + menu.setItems(items, selectionIndex(items)); + composeSelectionKey = menu.selectedItem?.key ?? composeSelectionKey; + menu.paint(image, { x: LIST_LEFT, y: listTop - 2, width: listWidth, height: listHeight }, win.focused); + menu.drawScrollbar(image, win.viewportWidth - 10, listTop, listHeight - 4); + problemLines.forEach((line, index) => image.drawText(f, TITLE_X, listTop + listHeight + 4 + index * step, line, 230)); + return image; } // --------------------------------------------------------------------------- @@ -1735,10 +2218,16 @@ async function handleTool(name: string, args: any): Promise { if (!choice) { return { ok: false, error: `No project matches "${args?.project}". Projects: ${projectChoices().map(({ project }) => project.title).join(", ")}` }; } - const selection = defaultModelSelection(choice.client.settings, choice.client.providers, choice.project); - if (!selection) return { ok: false, error: "No usable agent provider on that computer." }; - const threadId = await choice.client.launchThread(launchThreadPayload(choice.project, text, selection, choice.client.settings)); - return { ok: true, content: `Started a thread in ${choice.project.title} (id ${threadId}).` }; + const { client, project } = choice; + const resolved = await defaultLaunch(client, project); + if (resolved.blocker) return { ok: false, error: resolved.blocker }; + const threadId = await client.launchThread(launchThreadPayload(project, text, resolved, client.providers)); + const how = [ + modelDisplayName(client.providers, resolved.model), + runtimeModeLabel(resolved.runtimeMode).toLowerCase(), + resolved.workspaceMode === "worktree" ? `new worktree from ${resolved.branch}` : resolved.branch ? `on ${resolved.branch}` : "", + ].filter(Boolean); + return { ok: true, content: `Started a thread in ${project.title} (${how.join(", ")}; id ${threadId}).` }; } default: return { ok: false, error: `Unknown T3 Code tool: ${name}` }; diff --git a/app/ui/window-menu.ts b/app/ui/window-menu.ts index cb71474f..e8b4e757 100644 --- a/app/ui/window-menu.ts +++ b/app/ui/window-menu.ts @@ -99,9 +99,10 @@ export class WindowMenu { /** * Open the menu, or the shell's system menu when this window has no * entries. `items` (and optionally `title`) override the window's own for - * an app that reuses this host for another list (a per-row action menu). + * an app that reuses this host for another list (a per-row action menu), + * and `selectedIndex` starts a picker on its current value. */ - open(items: MenuItem[] = this.options.items(), title: string = this.options.title()): void { + open(items: MenuItem[] = this.options.items(), title: string = this.options.title(), selectedIndex?: number): void { if (this.stack) return; if (!items.length) { this.options.post({ type: "open-system-menu", windowId: this.options.windowId }); @@ -112,7 +113,9 @@ export class WindowMenu { handleInput: () => {}, }; const stack = new LayerStack(base, this.layerActions(), this.options.size, this.options.isFocused); - stack.push(new WindowMenuLayer(title, items)); + const layer = new WindowMenuLayer(title, items); + if (selectedIndex !== undefined) layer.selectItem(selectedIndex); + stack.push(layer); this.stack = stack; } diff --git a/tests/t3code-launch.test.cjs b/tests/t3code-launch.test.cjs new file mode 100644 index 00000000..14ff3102 --- /dev/null +++ b/tests/t3code-launch.test.cjs @@ -0,0 +1,174 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const launch = require('../.test-build/app/apps/t3code/t3-launch.js'); + +const EFFORT = { + id: 'effort', label: 'Effort', type: 'select', promptInjectedValues: ['ultrathink'], + options: [{ id: 'low', label: 'Low' }, { id: 'high', label: 'High', isDefault: true }, { id: 'ultrathink', label: 'Ultrathink' }, { id: 'ultracode', label: 'Ultracode' }], +}; +const FAST = { id: 'fastMode', label: 'Fast mode', type: 'boolean' }; + +const providers = [ + { instanceId: 'codex', driver: 'codex', enabled: true, installed: true, auth: { status: 'unauthenticated' }, models: [{ slug: 'gpt-5', isDefault: true }] }, + { + instanceId: 'claudeAgent', driver: 'claudeAgent', enabled: true, installed: true, auth: { status: 'authenticated' }, + supportedRuntimeModes: ['approval-required', 'full-access'], + models: [ + { slug: 'old', name: 'Old', isLegacy: true, isDefault: true }, + { slug: 'claude-sonnet-5', name: 'Claude Sonnet 5' }, + { slug: 'claude-opus-5', name: 'Claude Opus 5', isDefault: true, capabilities: { optionDescriptors: [EFFORT, FAST] } }, + ], + }, + { instanceId: 'pi', driver: 'pi', enabled: true, installed: true, auth: { status: 'authenticated' }, models: [{ slug: 'pi-1' }] }, +]; +const project = { id: 'p1', title: 'faceclaw', workspaceRoot: '/src/faceclaw' }; +const refs = { + isRepo: true, hasPrimaryRemote: true, nextCursor: null, totalCount: 4, + refs: [ + { name: 'feature', current: true, isDefault: false, worktreePath: '/src/faceclaw' }, + { name: 'main', current: false, isDefault: true, worktreePath: null }, + { name: 'spike', current: false, isDefault: false, worktreePath: '/src/faceclaw-spike' }, + { name: 'origin/main', isRemote: true, remoteName: 'origin', current: false, isDefault: false, worktreePath: null }, + ], +}; +const context = (overrides = {}) => ({ settings: null, providers, project, scratchWorkspaceRoot: '/home/scratch', projectFile: null, refs, ...overrides }); + +test('default model selection mirrors mobile', () => { + assert.deepEqual(launch.defaultModelSelection(null, providers, project), { instanceId: 'claudeAgent', model: 'claude-opus-5' }); + const settings = { defaultModelSelection: { instanceId: 'codex', model: 'gpt-5' }, projectSettingsOverrides: { p1: { defaultModelSelection: { instanceId: 'claudeAgent', model: 'claude-sonnet-5' } } } }; + assert.deepEqual(launch.defaultModelSelection(settings, providers, project), { instanceId: 'claudeAgent', model: 'claude-sonnet-5' }); + assert.equal(launch.defaultModelSelection({ defaultModelSelection: { instanceId: 'codex', model: 'gpt-5' } }, providers.slice(0, 1), project), null, 'unauthenticated providers are skipped'); + // The project's legacy field acts as an override until the server folds it. + const legacyProject = { ...project, defaultModelSelection: { instanceId: 'pi', model: 'pi-1' } }; + assert.deepEqual(launch.defaultModelSelection({ defaultModelSelection: { instanceId: 'claudeAgent', model: 'claude-sonnet-5' } }, providers, legacyProject), { instanceId: 'pi', model: 'pi-1' }); + assert.deepEqual( + launch.defaultModelSelection({ projectSettingsFolded: true, defaultModelSelection: { instanceId: 'claudeAgent', model: 'claude-sonnet-5' } }, providers, legacyProject), + { instanceId: 'claudeAgent', model: 'claude-sonnet-5' }, + ); +}); + +test('model choices group usable providers, legacy last', () => { + const groups = launch.modelChoices(providers); + assert.deepEqual(groups.map((group) => group.label), ['Claude', 'Pi']); + assert.deepEqual(groups[0].models.map((model) => model.label), ['Claude Sonnet 5', 'Claude Opus 5', 'Old']); + assert.equal(groups[0].models[2].isLegacy, true); + assert.equal(launch.modelDisplayName(providers, { instanceId: 'claudeAgent', model: 'claude-opus-5' }), 'Claude Opus 5'); +}); + +test('model options: defaults, picks, hidden choices, dispatch normalization', () => { + const opus = { instanceId: 'claudeAgent', model: 'claude-opus-5' }; + const [effort, fast] = launch.modelOptionDescriptors(providers, opus); + assert.equal(launch.optionValue(effort, opus), 'high', 'isDefault choice'); + assert.equal(launch.optionValueLabel(fast, launch.optionValue(fast, opus)), 'Off'); + assert.deepEqual(launch.selectableChoices(effort).map((choice) => choice.id), ['low', 'high'], 'prompt-injected and ultracode are not offered'); + const picked = launch.withModelOption(launch.withModelOption(opus, 'effort', 'low'), 'fastMode', true); + assert.equal(launch.optionValue(effort, picked), 'low'); + assert.equal(launch.optionValue(fast, picked), true); + assert.deepEqual(launch.withModelOption(picked, 'effort', 'high').options, [{ id: 'fastMode', value: true }, { id: 'effort', value: 'high' }]); + assert.deepEqual(launch.dispatchModelSelection(providers, opus), opus, 'no picks: provider defaults'); + const stale = { ...opus, options: [{ id: 'effort', value: 'ultrathink' }, { id: 'gone', value: 'x' }] }; + assert.deepEqual(launch.dispatchModelSelection(providers, stale), { ...opus, options: [{ id: 'effort', value: 'high' }] }, 'invalid values fall back; unknown ids drop'); +}); + +test('access modes follow the provider and project defaults', () => { + assert.deepEqual(launch.runtimeModeChoices(providers[1]).map((choice) => choice.mode), ['approval-required', 'full-access']); + assert.equal(launch.runtimeModeChoices(providers[2]).length, 4, 'unspecified: every mode'); + const draft = launch.emptyLaunchDraft(); + assert.equal(launch.resolveLaunch(draft, context()).runtimeMode, 'full-access'); + const settings = { defaultRuntimeMode: 'auto', projectSettingsOverrides: { p1: { defaultRuntimeMode: 'approval-required' } } }; + assert.equal(launch.resolveLaunch(draft, context({ settings })).runtimeMode, 'approval-required'); + // "auto" isn't one of Claude's here, so it falls back to the first supported mode. + assert.equal(launch.resolveLaunch({ ...draft, runtimeMode: 'auto' }, context()).runtimeMode, 'approval-required'); +}); + +test('workspace: defaults chain, current checkout, existing and new worktrees', () => { + let draft = launch.emptyLaunchDraft(); + let resolved = launch.resolveLaunch(draft, context()); + assert.equal(resolved.workspaceMode, 'local'); + assert.equal(resolved.branch, 'feature'); + assert.equal(launch.workspaceLabel(resolved), 'Current checkout'); + assert.deepEqual(launch.workspaceStrategy(resolved), { type: 'root', branch: 'feature' }); + + assert.equal(launch.resolveLaunch(draft, context({ projectFile: { defaultThreadEnvMode: 'worktree' } })).workspaceMode, 'worktree', 't3.json'); + assert.equal( + launch.resolveLaunch(draft, context({ settings: { defaultThreadEnvMode: 'local' }, projectFile: { defaultThreadEnvMode: 'worktree' } })).workspaceMode, + 'local', + 'the environment setting outranks t3.json', + ); + assert.equal( + launch.resolveLaunch(draft, context({ project: { ...project, defaultThreadEnvMode: 'worktree' }, settings: { defaultThreadEnvMode: 'local' } })).workspaceMode, + 'worktree', + 'a project override outranks the environment', + ); + + // A branch checked out in another worktree runs there. + draft = launch.pickBranch(draft, refs.refs[2], 'local', project); + resolved = launch.resolveLaunch(draft, context()); + assert.equal(launch.workspaceLabel(resolved), 'Existing worktree'); + assert.deepEqual(launch.workspaceStrategy(resolved), { type: 'existing_worktree', worktreePath: '/src/faceclaw-spike', branch: 'spike' }); + assert.equal(launch.needsCheckout(refs.refs[1], 'local'), true); + assert.equal(launch.needsCheckout(refs.refs[2], 'local'), false); + assert.equal(launch.needsCheckout(refs.refs[1], 'worktree'), false); + assert.equal(launch.refBadge(refs.refs[0], project), 'current'); + assert.equal(launch.refBadge(refs.refs[2], project), 'worktree'); + + // New worktree: from the default branch, origin by default. + draft = launch.pickWorkspaceMode(launch.emptyLaunchDraft(), 'worktree'); + resolved = launch.resolveLaunch(draft, context()); + assert.equal(resolved.branch, 'main'); + assert.equal(launch.branchLabel(resolved, true), 'From origin/main'); + assert.deepEqual(launch.workspaceStrategy(resolved), { type: 'worktree', baseRef: 'main', startFromOrigin: true }); + resolved = launch.resolveLaunch({ ...draft, startFromOrigin: false }, context()); + assert.equal(launch.branchLabel(resolved, true), 'From main'); + assert.deepEqual(launch.workspaceStrategy(resolved), { type: 'worktree', baseRef: 'main' }); + assert.equal(launch.resolveLaunch(draft, context({ settings: { newWorktreesStartFromOrigin: false } })).startFromOrigin, false); + // An explicit base survives switching back and forth; the checkout returns to what's checked out. + draft = launch.pickBranch(draft, refs.refs[0], 'worktree', project); + assert.equal(launch.resolveLaunch(draft, context()).branch, 'feature'); + assert.equal(launch.resolveLaunch(launch.pickWorkspaceMode(draft, 'local'), context()).worktreePath, null); + assert.equal(launch.resolveLaunch(launch.pickWorkspaceMode(draft, 'worktree'), context()).branch, 'feature'); + + // Still loading branches: worktree mode can't start yet. + assert.match(launch.resolveLaunch(launch.pickWorkspaceMode(launch.emptyLaunchDraft(), 'worktree'), context({ refs: null })).blocker, /loading/); +}); + +test('scratch projects and non-repos run in their folder', () => { + const scratch = { id: 'p2', title: 'Scratch', workspaceRoot: '/home/scratch/' }; + let resolved = launch.resolveLaunch({ ...launch.emptyLaunchDraft(), workspaceMode: 'worktree' }, context({ project: scratch, refs: null })); + assert.equal(resolved.canChooseWorkspace, false); + assert.deepEqual(launch.workspaceStrategy(resolved), { type: 'root' }); + resolved = launch.resolveLaunch(launch.emptyLaunchDraft(), context({ refs: { refs: [], isRepo: false, hasPrimaryRemote: false } })); + assert.equal(resolved.canChooseWorkspace, false); +}); + +test('launch payload carries every option', () => { + const draft = { ...launch.pickWorkspaceMode(launch.emptyLaunchDraft(), 'worktree'), model: { instanceId: 'claudeAgent', model: 'claude-opus-5', options: [{ id: 'effort', value: 'low' }] }, runtimeMode: 'approval-required' }; + const resolved = launch.resolveLaunch(draft, context()); + const payload = launch.launchThreadPayload(project, ' Fix the login test ', resolved, providers); + assert.equal(payload.title, 'Fix the login test'); + assert.equal(payload.projectId, 'p1'); + assert.deepEqual(payload.modelSelection, { instanceId: 'claudeAgent', model: 'claude-opus-5', options: [{ id: 'effort', value: 'low' }] }); + assert.equal(payload.runtimeMode, 'approval-required'); + assert.equal(payload.interactionMode, 'default'); + assert.deepEqual(payload.workspaceStrategy, { type: 'worktree', baseRef: 'main', startFromOrigin: true }); + assert.equal(payload.initialMessage.text, ' Fix the login test '); + assert.throws(() => launch.launchThreadPayload(project, 'x', launch.resolveLaunch(launch.emptyLaunchDraft(), context({ providers: [] })), []), /No usable agent/); +}); + +test('matching project on another host', () => { + const projects = [ + { id: 'a', title: 'Other', workspaceRoot: '/w/other' }, + { id: 'b', title: 'faceclaw-fork', workspaceRoot: '/w/faceclaw' }, + { id: 'c', title: 'renamed', workspaceRoot: '/w/x', repositoryIdentity: { canonicalKey: 'github.com/jimrandomh/faceclaw' } }, + ]; + assert.equal(launch.matchingProject(projects, { ...project, repositoryIdentity: { canonicalKey: 'github.com/jimrandomh/faceclaw' } }).id, 'c'); + assert.equal(launch.matchingProject(projects, project).id, 'b', 'folder name'); + assert.equal(launch.matchingProject(projects, { id: 'z', title: 'Other', workspaceRoot: '/elsewhere/q' }).id, 'a', 'title'); + assert.equal(launch.matchingProject(projects, { id: 'z', title: 'none', workspaceRoot: '/q/none' }), null); +}); + +test('t3.json parsing', () => { + assert.deepEqual(launch.parseProjectFile('{"defaultThreadEnvMode":"worktree","scripts":[]}'), { defaultThreadEnvMode: 'worktree' }); + assert.deepEqual(launch.parseProjectFile('{"defaultThreadEnvMode":"bogus"}'), {}); + assert.equal(launch.parseProjectFile('not json'), null); +}); diff --git a/tests/t3code-model.test.cjs b/tests/t3code-model.test.cjs index a510830f..65f33248 100644 --- a/tests/t3code-model.test.cjs +++ b/tests/t3code-model.test.cjs @@ -198,22 +198,6 @@ test('plainMarkdown cleans up for the glasses', () => { ); }); -test('default model selection mirrors mobile', () => { - const providers = [ - { instanceId: 'codex', enabled: true, installed: true, auth: { status: 'unauthenticated' }, models: [{ slug: 'gpt-5', isDefault: true }] }, - { instanceId: 'claudeAgent', enabled: true, installed: true, auth: { status: 'authenticated' }, models: [{ slug: 'old', isLegacy: true, isDefault: true }, { slug: 'claude-sonnet-5' }, { slug: 'claude-opus-5', isDefault: true }] }, - ]; - const project = { id: 'p1', title: 'faceclaw' }; - assert.deepEqual(model.defaultModelSelection(null, providers, project), { instanceId: 'claudeAgent', model: 'claude-opus-5' }); - const settings = { defaultModelSelection: { instanceId: 'codex', model: 'gpt-5' }, projectSettingsOverrides: { p1: { defaultModelSelection: { instanceId: 'claudeAgent', model: 'claude-sonnet-5' } } } }; - assert.deepEqual(model.defaultModelSelection(settings, providers, project), { instanceId: 'claudeAgent', model: 'claude-sonnet-5' }); - assert.equal(model.defaultModelSelection({ defaultModelSelection: { instanceId: 'codex', model: 'gpt-5' } }, providers.slice(0, 1), project), null, 'unauthenticated providers are skipped'); - const payload = model.launchThreadPayload(project, ' Fix the login test ', { instanceId: 'claudeAgent', model: 'claude-opus-5' }, null); - assert.equal(payload.title, 'Fix the login test'); - assert.equal(payload.runtimeMode, 'full-access'); - assert.deepEqual(payload.workspaceStrategy, { type: 'root' }); -}); - test('formatAge', () => { assert.equal(model.formatAge(NOW - 20_000, NOW), 'now'); assert.equal(model.formatAge(NOW - 5 * 60_000, NOW), '5m'); diff --git a/tests/tsconfig.json b/tests/tsconfig.json index a1c2e944..671426a9 100644 --- a/tests/tsconfig.json +++ b/tests/tsconfig.json @@ -61,6 +61,7 @@ "../app/apps/t3code/t3-auth.ts", "../app/apps/t3code/t3-client.ts", "../app/apps/t3code/t3-transcript.ts", - "../app/apps/t3code/t3-glance.ts" + "../app/apps/t3code/t3-glance.ts", + "../app/apps/t3code/t3-launch.ts" ] }