diff --git a/apps/mobile/src/features/threads/ComposerCommandPopover.tsx b/apps/mobile/src/features/threads/ComposerCommandPopover.tsx new file mode 100644 index 0000000000..08746eb74e --- /dev/null +++ b/apps/mobile/src/features/threads/ComposerCommandPopover.tsx @@ -0,0 +1,211 @@ +import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass"; +import type { ComposerTriggerKind } from "@t3tools/shared/composerTrigger"; +import type { ServerProviderSkill, ServerProviderSlashCommand } from "@t3tools/contracts"; +import { SymbolView } from "expo-symbols"; +import { memo } from "react"; +import { Pressable, ScrollView, useColorScheme, View, type ViewStyle } from "react-native"; + +import { AppText as Text } from "../../components/AppText"; + +export type ComposerCommandItem = + | { + readonly id: string; + readonly type: "path"; + readonly path: string; + readonly kind: "file" | "directory"; + readonly label: string; + readonly description: string; + } + | { + readonly id: string; + readonly type: "slash-command"; + readonly command: string; + readonly label: string; + readonly description: string; + } + | { + readonly id: string; + readonly type: "provider-slash-command"; + readonly command: ServerProviderSlashCommand; + readonly label: string; + readonly description: string; + } + | { + readonly id: string; + readonly type: "skill"; + readonly skill: ServerProviderSkill; + readonly label: string; + readonly description: string; + }; + +interface ComposerCommandPopoverProps { + readonly items: ReadonlyArray; + readonly triggerKind: ComposerTriggerKind | null; + readonly isLoading: boolean; + readonly onSelect: (item: ComposerCommandItem) => void; +} + +function PopoverSurface(props: { + readonly children: React.ReactNode; + readonly isDarkMode: boolean; + readonly style?: ViewStyle; +}) { + const baseStyle: ViewStyle = { + borderRadius: 16, + overflow: "hidden", + ...props.style, + }; + + if (isLiquidGlassSupported) { + return ( + + {props.children} + + ); + } + + return ( + + {props.children} + + ); +} + +function itemIcon(item: ComposerCommandItem) { + switch (item.type) { + case "path": + return item.kind === "directory" ? ("folder" as const) : ("doc" as const); + case "slash-command": + case "provider-slash-command": + return "terminal" as const; + case "skill": + return "cube" as const; + } +} + +function groupLabel(triggerKind: ComposerTriggerKind | null): string | null { + switch (triggerKind) { + case "slash-command": + return "Commands"; + case "skill": + return "Skills"; + case "path": + return "Files"; + default: + return null; + } +} + +function emptyText(triggerKind: ComposerTriggerKind | null, isLoading: boolean): string { + if (isLoading) { + return triggerKind === "path" ? "Searching files…" : "Loading…"; + } + switch (triggerKind) { + case "path": + return "No matching files or folders."; + case "skill": + return "No skills found."; + case "slash-command": + return "No matching commands."; + default: + return "No results."; + } +} + +const CommandRow = memo(function CommandRow(props: { + readonly item: ComposerCommandItem; + readonly onPress: () => void; + readonly isLast: boolean; +}) { + const iconName = itemIcon(props.item); + const iconColor = "#a1a1aa"; + + return ( + ({ + flexDirection: "row", + alignItems: "center", + paddingHorizontal: 14, + paddingVertical: 10, + gap: 10, + opacity: pressed ? 0.6 : 1, + borderBottomWidth: props.isLast ? 0 : 0.5, + borderBottomColor: "rgba(255,255,255,0.1)", + })} + > + + + {props.item.label} + + {props.item.description ? ( + + {props.item.description} + + ) : null} + + ); +}); + +export const ComposerCommandPopover = memo(function ComposerCommandPopover( + props: ComposerCommandPopoverProps, +) { + const isDarkMode = useColorScheme() === "dark"; + const label = groupLabel(props.triggerKind); + + return ( + + {label ? ( + + + {label} + + + ) : null} + {props.items.length > 0 ? ( + + {props.items.map((item, index) => ( + props.onSelect(item)} + isLast={index === props.items.length - 1} + /> + ))} + + ) : ( + + + {emptyText(props.triggerKind, props.isLoading)} + + + )} + + ); +}); diff --git a/apps/mobile/src/features/threads/GitActionProgressOverlay.tsx b/apps/mobile/src/features/threads/GitActionProgressOverlay.tsx new file mode 100644 index 0000000000..30c1531a29 --- /dev/null +++ b/apps/mobile/src/features/threads/GitActionProgressOverlay.tsx @@ -0,0 +1,121 @@ +import * as Haptics from "expo-haptics"; +import { SymbolView } from "expo-symbols"; +import { useCallback, useEffect, useRef } from "react"; +import { ActivityIndicator, Linking, Pressable, View } from "react-native"; +import Animated, { FadeIn, FadeOut } from "react-native-reanimated"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; + +import { AppText as Text } from "../../components/AppText"; +import { useThemeColor } from "../../lib/useThemeColor"; +import type { GitActionProgress } from "../../state/use-git-action-state"; + +export function GitActionProgressOverlay(props: { + readonly progress: GitActionProgress; + readonly onDismiss: () => void; +}) { + const { progress, onDismiss } = props; + const insets = useSafeAreaInsets(); + const prevPhaseRef = useRef(progress.phase); + + useEffect(() => { + const prev = prevPhaseRef.current; + prevPhaseRef.current = progress.phase; + + if (prev === "running" && progress.phase === "success") { + Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success); + } else if (prev === "running" && progress.phase === "error") { + Haptics.notificationAsync(Haptics.NotificationFeedbackType.Error); + } + }, [progress.phase]); + + const handlePress = useCallback(() => { + if (progress.prUrl) { + void Linking.openURL(progress.prUrl); + return; + } + if (progress.phase === "success" || progress.phase === "error") { + onDismiss(); + } + }, [onDismiss, progress.phase, progress.prUrl]); + + if (progress.phase === "idle") { + return null; + } + + return ( + + + + + + ); +} + +function OverlayContent(props: { readonly progress: GitActionProgress }) { + const { progress } = props; + const iconColor = useThemeColor("--color-icon"); + + const bgClass = + progress.phase === "error" + ? "bg-red-50 dark:bg-red-950/80 border-red-200 dark:border-red-800" + : "bg-card border-border"; + + return ( + + + + + {progress.label ? ( + + {progress.label} + + ) : null} + {progress.description ? ( + + {progress.description} + + ) : null} + + + {progress.prUrl ? ( + + ) : null} + + ); +} + +function OverlayIcon(props: { + readonly phase: GitActionProgress["phase"]; + readonly iconColor: ReturnType; +}) { + switch (props.phase) { + case "running": + return ; + case "success": + return ( + + + + ); + case "error": + return ( + + + + ); + default: + return null; + } +} diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index e043db9dcc..32c10bcfd7 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -8,6 +8,11 @@ import type { ServerConfig as T3ServerConfig, } from "@t3tools/contracts"; import { CLAUDE_CODE_EFFORT_OPTIONS } from "@t3tools/contracts"; +import { + detectComposerTrigger, + replaceTextRange, + type ComposerTrigger, +} from "@t3tools/shared/composerTrigger"; import { TextInputWrapper } from "expo-paste-input"; import type { ReactNode } from "react"; import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react"; @@ -17,6 +22,8 @@ import { TextInput as RNTextInput, useColorScheme, View, + type NativeSyntheticEvent, + type TextInputSelectionChangeEventData, type ViewStyle, } from "react-native"; import ImageViewing from "react-native-image-viewing"; @@ -30,6 +37,13 @@ import type { DraftComposerImageAttachment } from "../../lib/composerImages"; import { buildModelOptions, groupByProvider } from "../../lib/modelOptions"; import type { RemoteClientConnectionState } from "../../lib/connection"; import { useNativePaste } from "../../hooks/useNativePaste"; +import { + insertRankedSearchResult, + normalizeSearchQuery, + scoreQueryMatch, +} from "@t3tools/shared/searchRanking"; +import { getEnvironmentClient } from "../../state/use-remote-environment-registry"; +import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover"; /** * Height of the collapsed composer (pill + vertical padding, excluding safe-area inset). @@ -53,6 +67,8 @@ export interface ThreadComposerProps { readonly serverConfig: T3ServerConfig | null; readonly queueCount: number; readonly activeThreadBusy: boolean; + readonly environmentId: string; + readonly projectCwd: string | null; readonly onChangeDraftMessage: (value: string) => void; readonly onPickDraftImages: () => Promise; readonly onNativePasteImages: (uris: ReadonlyArray) => Promise; @@ -167,6 +183,281 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer void props.onNativePasteImages(uris); }); + // ── Trigger detection ──────────────────────────────────── + const [cursorPosition, setCursorPosition] = useState(0); + const [composerTrigger, setComposerTrigger] = useState(null); + const [pathSearchResults, setPathSearchResults] = useState< + ReadonlyArray<{ path: string; kind: "file" | "directory" }> + >([]); + const [pathSearchLoading, setPathSearchLoading] = useState(false); + const pathSearchTimerRef = useRef | null>(null); + + const handleSelectionChange = useCallback( + (event: NativeSyntheticEvent) => { + const { start } = event.nativeEvent.selection; + setCursorPosition(start); + }, + [], + ); + + useEffect(() => { + const trigger = detectComposerTrigger(props.draftMessage, cursorPosition); + setComposerTrigger(trigger); + }, [props.draftMessage, cursorPosition]); + + // ── File search (debounced) ────────────────────────────── + useEffect(() => { + if (pathSearchTimerRef.current) { + clearTimeout(pathSearchTimerRef.current); + pathSearchTimerRef.current = null; + } + + if (composerTrigger?.kind !== "path" || !composerTrigger.query || !props.projectCwd) { + setPathSearchResults([]); + setPathSearchLoading(false); + return; + } + + setPathSearchLoading(true); + const query = composerTrigger.query; + const cwd = props.projectCwd; + const envId = props.environmentId; + + pathSearchTimerRef.current = setTimeout(() => { + const client = getEnvironmentClient(envId); + if (!client) { + setPathSearchLoading(false); + return; + } + + void client.projects + .searchEntries({ cwd, query, limit: 20 }) + .then((result) => { + setPathSearchResults( + result.entries.map((entry) => ({ + path: entry.path, + kind: entry.kind === "directory" ? ("directory" as const) : ("file" as const), + })), + ); + }) + .catch(() => { + setPathSearchResults([]); + }) + .finally(() => { + setPathSearchLoading(false); + }); + }, 200); + + return () => { + if (pathSearchTimerRef.current) { + clearTimeout(pathSearchTimerRef.current); + } + }; + }, [composerTrigger?.kind, composerTrigger?.query, props.projectCwd, props.environmentId]); + + // ── Build menu items ───────────────────────────────────── + const selectedProviderStatus = useMemo(() => { + if (!props.serverConfig) return null; + return ( + props.serverConfig.providers.find( + (p) => p.provider === props.selectedThread.modelSelection.provider, + ) ?? null + ); + }, [props.serverConfig, props.selectedThread.modelSelection.provider]); + + const composerMenuItems: ComposerCommandItem[] = useMemo(() => { + if (!composerTrigger) return []; + + if (composerTrigger.kind === "slash-command") { + const q = composerTrigger.query.toLowerCase(); + const allBuiltIn = [ + { + id: "cmd:model", + type: "slash-command" as const, + command: "model", + label: "/model", + description: "Switch model", + }, + { + id: "cmd:plan", + type: "slash-command" as const, + command: "plan", + label: "/plan", + description: "Switch to plan mode", + }, + { + id: "cmd:default", + type: "slash-command" as const, + command: "default", + label: "/default", + description: "Switch to default mode", + }, + ]; + const builtIn = allBuiltIn.filter((item) => item.command.includes(q)); + + const providerCommands: ComposerCommandItem[] = (selectedProviderStatus?.slashCommands ?? []) + .filter((cmd) => cmd.name.toLowerCase().includes(q)) + .map((cmd) => ({ + id: `pcmd:${cmd.name}`, + type: "provider-slash-command" as const, + command: cmd, + label: `/${cmd.name}`, + description: cmd.description ?? "", + })); + + return [...builtIn, ...providerCommands]; + } + + if (composerTrigger.kind === "skill") { + const enabledSkills = (selectedProviderStatus?.skills ?? []).filter((s) => s.enabled); + const normalizedQuery = normalizeSearchQuery(composerTrigger.query, { + trimLeadingPattern: /^\$+/, + }); + + if (!normalizedQuery) { + return enabledSkills.slice(0, 20).map((skill) => ({ + id: `skill:${skill.name}`, + type: "skill" as const, + skill, + label: skill.displayName ?? skill.name, + description: skill.shortDescription ?? skill.description ?? "", + })); + } + + const ranked: Array<{ + item: (typeof enabledSkills)[number]; + score: number; + tieBreaker: string; + }> = []; + for (const skill of enabledSkills) { + const displayLabel = (skill.displayName ?? skill.name).toLowerCase(); + const scores = [ + scoreQueryMatch({ + value: skill.name.toLowerCase(), + query: normalizedQuery, + exactBase: 0, + prefixBase: 2, + boundaryBase: 4, + includesBase: 6, + fuzzyBase: 100, + boundaryMarkers: ["-", "_", "/"], + }), + scoreQueryMatch({ + value: displayLabel, + query: normalizedQuery, + exactBase: 1, + prefixBase: 3, + boundaryBase: 5, + includesBase: 7, + fuzzyBase: 110, + }), + scoreQueryMatch({ + value: skill.shortDescription?.toLowerCase() ?? "", + query: normalizedQuery, + exactBase: 20, + prefixBase: 22, + boundaryBase: 24, + includesBase: 26, + }), + scoreQueryMatch({ + value: skill.description?.toLowerCase() ?? "", + query: normalizedQuery, + exactBase: 30, + prefixBase: 32, + boundaryBase: 34, + includesBase: 36, + }), + ].filter((s): s is number => s !== null); + + if (scores.length > 0) { + insertRankedSearchResult( + ranked, + { + item: skill, + score: Math.min(...scores), + tieBreaker: `${displayLabel}\u0000${skill.name}`, + }, + 20, + ); + } + } + + return ranked.map(({ item: skill }) => ({ + id: `skill:${skill.name}`, + type: "skill" as const, + skill, + label: skill.displayName ?? skill.name, + description: skill.shortDescription ?? skill.description ?? "", + })); + } + + if (composerTrigger.kind === "path") { + return pathSearchResults.map((entry) => { + const parts = entry.path.split("/"); + return { + id: `path:${entry.path}`, + type: "path" as const, + path: entry.path, + kind: entry.kind, + label: parts[parts.length - 1] ?? entry.path, + description: parts.length > 1 ? parts.slice(0, -1).join("/") : "", + }; + }); + } + + return []; + }, [composerTrigger, selectedProviderStatus, pathSearchResults]); + + // ── Handle command selection ────────────────────────────── + const { onChangeDraftMessage, onUpdateInteractionMode, draftMessage, onSendMessage } = props; + + const handleSend = useCallback(() => { + onSendMessage(); + inputRef.current?.blur(); + }, [onSendMessage]); + const handleCommandSelect = useCallback( + (item: ComposerCommandItem) => { + if (!composerTrigger) return; + + if ( + item.type === "slash-command" && + (item.command === "plan" || item.command === "default") + ) { + const result = replaceTextRange( + draftMessage, + composerTrigger.rangeStart, + composerTrigger.rangeEnd, + "", + ); + setCursorPosition(result.cursor); + onChangeDraftMessage(result.text); + void onUpdateInteractionMode(item.command); + return; + } + + let replacement = ""; + if (item.type === "path") { + replacement = `@${item.path} `; + } else if (item.type === "skill") { + replacement = `$${item.skill.name} `; + } else if (item.type === "slash-command") { + replacement = `/${item.command} `; + } else if (item.type === "provider-slash-command") { + replacement = `/${item.command.name} `; + } + + const result = replaceTextRange( + draftMessage, + composerTrigger.rangeStart, + composerTrigger.rangeEnd, + replacement, + ); + setCursorPosition(result.cursor); + onChangeDraftMessage(result.text); + }, + [composerTrigger, draftMessage, onChangeDraftMessage, onUpdateInteractionMode], + ); + // ── Model menu ─────────────────────────────────────────── const providerGroups = useMemo(() => { const options = buildModelOptions(props.serverConfig, currentModelSelection); @@ -346,8 +637,27 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer : "linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.85) 40%, rgba(255,255,255,0.95) 100%)", }} > - - {/* Input surface — the pill/card IS the glass element */} + + {composerTrigger && composerMenuItems.length > 0 ? ( + + + + ) : null} + ) ) : null} @@ -508,7 +819,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer label={sendLabel} variant="primary" disabled={!canSend} - onPress={props.onSendMessage} + onPress={handleSend} /> ) : null} diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 0a179e8bb5..94e8074c3e 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -53,6 +53,7 @@ export interface ThreadDetailScreenProps { readonly draftAttachments: ReadonlyArray; readonly connectionStateLabel: "ready" | "connecting" | "reconnecting" | "disconnected" | "idle"; readonly activeThreadBusy: boolean; + readonly environmentId: string; readonly projectWorkspaceRoot: string | null; readonly selectedThreadQueueCount: number; readonly serverConfig: T3ServerConfig | null; @@ -313,6 +314,8 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread serverConfig={props.serverConfig} queueCount={props.selectedThreadQueueCount} activeThreadBusy={props.activeThreadBusy} + environmentId={props.environmentId} + projectCwd={props.projectWorkspaceRoot} bottomInset={composerBottomInset} onChangeDraftMessage={props.onChangeDraftMessage} onPickDraftImages={props.onPickDraftImages} diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index fba2a05d71..05c1b73d13 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -1,11 +1,12 @@ import { Stack, useLocalSearchParams, useRouter } from "expo-router"; -import { useCallback, useState } from "react"; +import { useCallback, useMemo, useState } from "react"; import * as Arr from "effect/Array"; import * as Option from "effect/Option"; import { pipe } from "effect/Function"; import { Pressable, ScrollView, Text as RNText, View, useColorScheme } from "react-native"; import { useThemeColor } from "../../lib/useThemeColor"; import { useGitStatus, gitStatusManager } from "../../state/use-git-status"; +import { dismissGitActionResult, useGitActionProgress } from "../../state/use-git-action-state"; import { EmptyState } from "../../components/EmptyState"; import { LoadingScreen } from "../../components/LoadingScreen"; @@ -20,10 +21,10 @@ import { } from "../../state/use-remote-environment-registry"; import { useSelectedThreadDetail } from "../../state/use-thread-detail"; import { useThreadSelection } from "../../state/use-thread-selection"; +import { GitActionProgressOverlay } from "./GitActionProgressOverlay"; import { ThreadDetailScreen } from "./ThreadDetailScreen"; import { ThreadGitControls } from "./ThreadGitControls"; import { ThreadNavigationDrawer } from "./ThreadNavigationDrawer"; -import { screenTitle } from "./threadPresentation"; import { useSelectedThreadCommands } from "./use-selected-thread-commands"; import { useSelectedThreadGitActions } from "./use-selected-thread-git-actions"; import { useSelectedThreadGitState } from "./use-selected-thread-git-state"; @@ -82,6 +83,20 @@ export function ThreadRouteScreen() { cwd: selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null, }); + /* ─── Git action progress (for overlay banner) ──────────────────── */ + const gitActionProgressTarget = useMemo( + () => ({ + environmentId: selectedThread?.environmentId ?? null, + cwd: selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null, + }), + [ + selectedThread?.environmentId, + selectedThread?.worktreePath, + selectedThreadProject?.workspaceRoot, + ], + ); + const gitActionProgress = useGitActionProgress(gitActionProgressTarget); + const handleRefreshGitStatus = useCallback(async () => { if (!selectedThread) return; await gitStatusManager.refresh({ @@ -152,7 +167,7 @@ export function ThreadRouteScreen() { ); const headerSubtitle = [ - screenTitle(serverConfig, null), + selectedThreadProject?.title ?? null, selectedEnvironmentConnection?.environmentLabel ?? null, ] .filter(Boolean) @@ -212,6 +227,8 @@ export function ThreadRouteScreen() { onRunAction={gitActions.onRunSelectedThreadGitAction} /> + + {currentWorktreePath ? : null} - - {gitOperationLabel ? ( - - - - ) : null} ); diff --git a/apps/mobile/src/features/threads/threadPresentation.ts b/apps/mobile/src/features/threads/threadPresentation.ts index 01b6415df8..4253cedbc7 100644 --- a/apps/mobile/src/features/threads/threadPresentation.ts +++ b/apps/mobile/src/features/threads/threadPresentation.ts @@ -1,4 +1,3 @@ -import type { ServerConfig as T3ServerConfig } from "@t3tools/contracts"; import type { StatusTone } from "../../components/StatusPill"; import { EnvironmentScopedThreadShell } from "@t3tools/client-runtime"; @@ -52,12 +51,3 @@ export function messageImageUrl(httpBaseUrl: string | null, attachmentId: string const url = new URL(`/attachments/${encodeURIComponent(attachmentId)}`, httpBaseUrl); return url.toString(); } - -export function screenTitle(config: T3ServerConfig | null, serverUrl: string | null): string { - if (config) { - const segments = config.cwd.split(/[/\\]/).filter(Boolean); - const candidate = segments.at(-1) ?? config.cwd; - return /^t3[-_\s]?code$/i.test(candidate) ? "T3 Code" : candidate; - } - return serverUrl ?? "T3 Code"; -} diff --git a/apps/mobile/src/features/threads/use-project-actions.ts b/apps/mobile/src/features/threads/use-project-actions.ts index 8be7826d08..5abc13acf6 100644 --- a/apps/mobile/src/features/threads/use-project-actions.ts +++ b/apps/mobile/src/features/threads/use-project-actions.ts @@ -96,77 +96,53 @@ export function useProjectActions() { const initialMessageText = input.initialMessageText.trim(); const nextTitle = deriveThreadTitleFromPrompt(input.initialMessageText); - if (input.envMode === "worktree") { - if (!input.branch || initialMessageText.length === 0) { - return null; - } + if (initialMessageText.length === 0) { + return null; + } + if (input.envMode === "worktree" && !input.branch) { + return null; + } - await client.orchestration.dispatchCommand({ - type: "thread.turn.start", - commandId: CommandId.make(uuidv4()), - threadId, - message: { - messageId: MessageId.make(uuidv4()), - role: "user", - text: initialMessageText, - attachments: input.initialAttachments, - }, - modelSelection: input.modelSelection, - titleSeed: nextTitle, - runtimeMode: input.runtimeMode, - interactionMode: input.interactionMode, - bootstrap: { - createThread: { - projectId: input.project.id, - title: nextTitle, - modelSelection: input.modelSelection, - runtimeMode: input.runtimeMode, - interactionMode: input.interactionMode, - branch: input.branch, - worktreePath: null, - createdAt, - }, - prepareWorktree: { - projectCwd: input.project.workspaceRoot, - baseBranch: input.branch, - branch: buildTemporaryWorktreeBranchName(), - }, - runSetupScript: true, - }, - createdAt: new Date().toISOString(), - }); - } else { - await client.orchestration.dispatchCommand({ - type: "thread.create", - commandId: CommandId.make(uuidv4()), - threadId, - projectId: input.project.id, - title: nextTitle, - modelSelection: input.modelSelection, - runtimeMode: input.runtimeMode, - interactionMode: input.interactionMode, - branch: input.branch, - worktreePath: input.worktreePath, - createdAt, - }); + const isWorktree = input.envMode === "worktree"; - if (initialMessageText.length > 0 || input.initialAttachments.length > 0) { - await client.orchestration.dispatchCommand({ - type: "thread.turn.start", - commandId: CommandId.make(uuidv4()), - threadId, - message: { - messageId: MessageId.make(uuidv4()), - role: "user", - text: initialMessageText, - attachments: input.initialAttachments, - }, + await client.orchestration.dispatchCommand({ + type: "thread.turn.start", + commandId: CommandId.make(uuidv4()), + threadId, + message: { + messageId: MessageId.make(uuidv4()), + role: "user", + text: initialMessageText, + attachments: input.initialAttachments, + }, + modelSelection: input.modelSelection, + titleSeed: nextTitle, + runtimeMode: input.runtimeMode, + interactionMode: input.interactionMode, + bootstrap: { + createThread: { + projectId: input.project.id, + title: nextTitle, + modelSelection: input.modelSelection, runtimeMode: input.runtimeMode, interactionMode: input.interactionMode, - createdAt: new Date().toISOString(), - }); - } - } + branch: input.branch, + worktreePath: isWorktree ? null : input.worktreePath, + createdAt, + }, + ...(isWorktree + ? { + prepareWorktree: { + projectCwd: input.project.workspaceRoot, + baseBranch: input.branch!, + branch: buildTemporaryWorktreeBranchName(), + }, + runSetupScript: true, + } + : {}), + }, + createdAt: new Date().toISOString(), + }); await refreshRemoteData([input.project.environmentId]); return { diff --git a/apps/mobile/src/features/threads/use-selected-thread-git-actions.ts b/apps/mobile/src/features/threads/use-selected-thread-git-actions.ts index 6892f381aa..283c530554 100644 --- a/apps/mobile/src/features/threads/use-selected-thread-git-actions.ts +++ b/apps/mobile/src/features/threads/use-selected-thread-git-actions.ts @@ -21,7 +21,7 @@ import { getEnvironmentClient, setPendingConnectionError, } from "../../state/use-remote-environment-registry"; -import { gitActionManager } from "../../state/use-git-action-state"; +import { gitActionManager, showGitActionResult } from "../../state/use-git-action-state"; import { gitBranchManager } from "../../state/use-git-branches"; import { gitStatusManager } from "../../state/use-git-status"; import { useThreadSelection } from "../../state/use-thread-selection"; @@ -122,7 +122,9 @@ export function useSelectedThreadGitActions() { cwd, }); } catch (error) { - setPendingConnectionError(error instanceof Error ? error.message : "Git action failed."); + const message = error instanceof Error ? error.message : "Git action failed."; + setPendingConnectionError(message); + showGitActionResult({ type: "error", title: "Git action failed", description: message }); return null; } }, @@ -264,8 +266,17 @@ export function useSelectedThreadGitActions() { const onPullSelectedThreadBranch = useCallback(async () => { await runSelectedThreadGitMutation(async ({ thread, cwd }) => { - await gitActionManager.pull({ environmentId: thread.environmentId, cwd }); + const result = await gitActionManager.pull({ environmentId: thread.environmentId, cwd }); await refreshSelectedThreadGitStatus({ quiet: true, cwd }); + if (result) { + showGitActionResult({ + type: "success", + title: + result.status === "skipped_up_to_date" + ? "Already up to date" + : `Pulled latest on ${result.branch}`, + }); + } }); }, [refreshSelectedThreadGitStatus, runSelectedThreadGitMutation]); @@ -292,6 +303,13 @@ export function useSelectedThreadGitActions() { return null; } + showGitActionResult({ + type: "success", + title: result.toast.title, + description: result.toast.description, + prUrl: result.toast.cta.kind === "open_pr" ? result.toast.cta.url : undefined, + }); + if (result.branch.status === "created" && result.branch.name) { await syncSelectedThreadBranchState({ thread, diff --git a/apps/mobile/src/state/use-git-action-state.ts b/apps/mobile/src/state/use-git-action-state.ts index 8eb2d8ea66..479d396320 100644 --- a/apps/mobile/src/state/use-git-action-state.ts +++ b/apps/mobile/src/state/use-git-action-state.ts @@ -8,6 +8,7 @@ import { getGitActionTargetKey, gitActionStateAtom, } from "@t3tools/client-runtime"; +import { useCallback, useEffect, useRef, useState } from "react"; import { uuidv4 } from "../lib/uuid"; import { appAtomRegistry } from "./atom-registry"; @@ -29,3 +30,133 @@ export function useGitActionState(target: GitActionTarget): GitActionState { ); return targetKey === null ? EMPTY_GIT_ACTION_STATE : state; } + +// --------------------------------------------------------------------------- +// Git action result notification +// --------------------------------------------------------------------------- + +export interface GitActionResultNotification { + readonly type: "success" | "error"; + readonly title: string; + readonly description?: string; + readonly prUrl?: string; +} + +const RESULT_DISMISS_MS = 5_000; + +type ResultListener = (result: GitActionResultNotification | null) => void; +const resultListeners = new Set(); +let currentResult: GitActionResultNotification | null = null; +let dismissTimer: ReturnType | null = null; + +function broadcast(result: GitActionResultNotification | null): void { + currentResult = result; + for (const listener of resultListeners) { + listener(result); + } +} + +export function showGitActionResult(result: GitActionResultNotification): void { + if (dismissTimer) clearTimeout(dismissTimer); + broadcast(result); + dismissTimer = setTimeout(() => broadcast(null), RESULT_DISMISS_MS); +} + +export function dismissGitActionResult(): void { + if (dismissTimer) clearTimeout(dismissTimer); + broadcast(null); +} + +export function useGitActionResultNotification(): { + readonly result: GitActionResultNotification | null; + readonly dismiss: () => void; +} { + const [result, setResult] = useState(currentResult); + + useEffect(() => { + resultListeners.add(setResult); + setResult(currentResult); + return () => { + resultListeners.delete(setResult); + }; + }, []); + + return { result, dismiss: dismissGitActionResult }; +} + +// --------------------------------------------------------------------------- +// Unified git action progress (combines running state + result notification) +// --------------------------------------------------------------------------- + +export type GitActionProgressPhase = "idle" | "running" | "success" | "error"; + +export interface GitActionProgress { + readonly phase: GitActionProgressPhase; + readonly label: string | null; + readonly description: string | null; + readonly prUrl?: string; +} + +const EMPTY_PROGRESS: GitActionProgress = { + phase: "idle", + label: null, + description: null, +}; + +function formatElapsedSeconds(ms: number | null): string | null { + if (ms === null) return null; + const elapsed = Math.max(0, Math.floor((Date.now() - ms) / 1000)); + if (elapsed < 2) return null; + return `Running for ${elapsed}s`; +} + +export function useGitActionProgress(target: GitActionTarget): GitActionProgress { + const actionState = useGitActionState(target); + const { result } = useGitActionResultNotification(); + + const [, forceUpdate] = useState(0); + const intervalRef = useRef | null>(null); + + const startElapsedTimer = useCallback(() => { + if (intervalRef.current) return; + intervalRef.current = setInterval(() => forceUpdate((n) => n + 1), 1000); + }, []); + + const stopElapsedTimer = useCallback(() => { + if (intervalRef.current) { + clearInterval(intervalRef.current); + intervalRef.current = null; + } + }, []); + + useEffect(() => { + if (actionState.isRunning) { + startElapsedTimer(); + } else { + stopElapsedTimer(); + } + return stopElapsedTimer; + }, [actionState.isRunning, startElapsedTimer, stopElapsedTimer]); + + if (actionState.isRunning) { + const description = + actionState.lastOutputLine ?? + formatElapsedSeconds(actionState.hookStartedAtMs ?? actionState.phaseStartedAtMs); + return { + phase: "running", + label: actionState.currentLabel, + description, + }; + } + + if (result) { + return { + phase: result.type, + label: result.title, + description: result.description ?? null, + prUrl: result.prUrl, + }; + } + + return EMPTY_PROGRESS; +} diff --git a/apps/web/src/composer-logic.ts b/apps/web/src/composer-logic.ts index a5b26b0e2d..0fc0759309 100644 --- a/apps/web/src/composer-logic.ts +++ b/apps/web/src/composer-logic.ts @@ -1,16 +1,18 @@ +import { + detectComposerTrigger as detectComposerTriggerBase, + type ComposerTrigger, + type ComposerTriggerKind, + type ComposerSlashCommand, +} from "@t3tools/shared/composerTrigger"; +export { + replaceTextRange, + parseStandaloneComposerSlashCommand, +} from "@t3tools/shared/composerTrigger"; +export type { ComposerTrigger, ComposerTriggerKind, ComposerSlashCommand }; + import { splitPromptIntoComposerSegments } from "./composer-editor-mentions"; import { INLINE_TERMINAL_CONTEXT_PLACEHOLDER } from "./lib/terminalContext"; -export type ComposerTriggerKind = "path" | "slash-command" | "slash-model" | "skill"; -export type ComposerSlashCommand = "model" | "plan" | "default"; - -export interface ComposerTrigger { - kind: ComposerTriggerKind; - query: string; - rangeStart: number; - rangeEnd: number; -} - const isInlineTokenSegment = ( segment: | { type: "text"; text: string } @@ -216,83 +218,5 @@ export function isCollapsedCursorAdjacentToInlineToken( export const isCollapsedCursorAdjacentToMention = isCollapsedCursorAdjacentToInlineToken; export function detectComposerTrigger(text: string, cursorInput: number): ComposerTrigger | null { - const cursor = clampCursor(text, cursorInput); - const lineStart = text.lastIndexOf("\n", Math.max(0, cursor - 1)) + 1; - const linePrefix = text.slice(lineStart, cursor); - - if (linePrefix.startsWith("/")) { - const commandMatch = /^\/(\S*)$/.exec(linePrefix); - if (commandMatch) { - const commandQuery = commandMatch[1] ?? ""; - if (commandQuery.toLowerCase() === "model") { - return { - kind: "slash-model", - query: "", - rangeStart: lineStart, - rangeEnd: cursor, - }; - } - return { - kind: "slash-command", - query: commandQuery, - rangeStart: lineStart, - rangeEnd: cursor, - }; - } - - const modelMatch = /^\/model(?:\s+(.*))?$/.exec(linePrefix); - if (modelMatch) { - return { - kind: "slash-model", - query: (modelMatch[1] ?? "").trim(), - rangeStart: lineStart, - rangeEnd: cursor, - }; - } - } - - const tokenStart = tokenStartForCursor(text, cursor); - const token = text.slice(tokenStart, cursor); - if (token.startsWith("$")) { - return { - kind: "skill", - query: token.slice(1), - rangeStart: tokenStart, - rangeEnd: cursor, - }; - } - if (!token.startsWith("@")) { - return null; - } - - return { - kind: "path", - query: token.slice(1), - rangeStart: tokenStart, - rangeEnd: cursor, - }; -} - -export function parseStandaloneComposerSlashCommand( - text: string, -): Exclude | null { - const match = /^\/(plan|default)\s*$/i.exec(text.trim()); - if (!match) { - return null; - } - const command = match[1]?.toLowerCase(); - if (command === "plan") return "plan"; - return "default"; -} - -export function replaceTextRange( - text: string, - rangeStart: number, - rangeEnd: number, - replacement: string, -): { text: string; cursor: number } { - const safeStart = Math.max(0, Math.min(text.length, rangeStart)); - const safeEnd = Math.max(safeStart, Math.min(text.length, rangeEnd)); - const nextText = `${text.slice(0, safeStart)}${replacement}${text.slice(safeEnd)}`; - return { text: nextText, cursor: safeStart + replacement.length }; + return detectComposerTriggerBase(text, cursorInput, isWhitespace); } diff --git a/packages/shared/package.json b/packages/shared/package.json index 533399ee79..b449537f40 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -67,6 +67,10 @@ "./qrCode": { "types": "./src/qrCode.ts", "import": "./src/qrCode.ts" + }, + "./composerTrigger": { + "types": "./src/composerTrigger.ts", + "import": "./src/composerTrigger.ts" } }, "scripts": { diff --git a/packages/shared/src/composerTrigger.ts b/packages/shared/src/composerTrigger.ts new file mode 100644 index 0000000000..8d12f954f6 --- /dev/null +++ b/packages/shared/src/composerTrigger.ts @@ -0,0 +1,117 @@ +export type ComposerTriggerKind = "path" | "slash-command" | "slash-model" | "skill"; +export type ComposerSlashCommand = "model" | "plan" | "default"; + +export interface ComposerTrigger { + kind: ComposerTriggerKind; + query: string; + rangeStart: number; + rangeEnd: number; +} + +function clampCursor(text: string, cursor: number): number { + if (!Number.isFinite(cursor)) return text.length; + return Math.max(0, Math.min(text.length, Math.floor(cursor))); +} + +function isWhitespace(char: string): boolean { + return char === " " || char === "\n" || char === "\t" || char === "\r"; +} + +/** + * Detect an active trigger (@path, $skill, /command) at the cursor position. + * + * Accepts an optional `isWhitespaceChar` override so callers with inline + * placeholder characters (e.g. terminal context chips on web) can treat + * those as token boundaries. + */ +export function detectComposerTrigger( + text: string, + cursorInput: number, + isWhitespaceChar?: (char: string) => boolean, +): ComposerTrigger | null { + const cursor = clampCursor(text, cursorInput); + const lineStart = text.lastIndexOf("\n", Math.max(0, cursor - 1)) + 1; + const linePrefix = text.slice(lineStart, cursor); + + if (linePrefix.startsWith("/")) { + const commandMatch = /^\/(\S*)$/.exec(linePrefix); + if (commandMatch) { + const commandQuery = commandMatch[1] ?? ""; + if (commandQuery.toLowerCase() === "model") { + return { + kind: "slash-model", + query: "", + rangeStart: lineStart, + rangeEnd: cursor, + }; + } + return { + kind: "slash-command", + query: commandQuery, + rangeStart: lineStart, + rangeEnd: cursor, + }; + } + + const modelMatch = /^\/model(?:\s+(.*))?$/.exec(linePrefix); + if (modelMatch) { + return { + kind: "slash-model", + query: (modelMatch[1] ?? "").trim(), + rangeStart: lineStart, + rangeEnd: cursor, + }; + } + } + + const wsCheck = isWhitespaceChar ?? isWhitespace; + let tokenIdx = cursor - 1; + while (tokenIdx >= 0 && !wsCheck(text[tokenIdx] ?? "")) { + tokenIdx -= 1; + } + const tokenStart = tokenIdx + 1; + + const token = text.slice(tokenStart, cursor); + if (token.startsWith("$")) { + return { + kind: "skill", + query: token.slice(1), + rangeStart: tokenStart, + rangeEnd: cursor, + }; + } + if (!token.startsWith("@")) { + return null; + } + + return { + kind: "path", + query: token.slice(1), + rangeStart: tokenStart, + rangeEnd: cursor, + }; +} + +export function parseStandaloneComposerSlashCommand( + text: string, +): Exclude | null { + const match = /^\/(plan|default)\s*$/i.exec(text.trim()); + if (!match) { + return null; + } + const command = match[1]?.toLowerCase(); + if (command === "plan") return "plan"; + return "default"; +} + +export function replaceTextRange( + text: string, + rangeStart: number, + rangeEnd: number, + replacement: string, +): { text: string; cursor: number } { + const safeStart = Math.max(0, Math.min(text.length, rangeStart)); + const safeEnd = Math.max(safeStart, Math.min(text.length, rangeEnd)); + const nextText = `${text.slice(0, safeStart)}${replacement}${text.slice(safeEnd)}`; + return { text: nextText, cursor: safeStart + replacement.length }; +}