Add composer suggestions and git action overlay
- Suggest files, skills, and commands from composer triggers - Show git action progress, success, and error feedback
This commit is contained in:
1 parent
99190d7742
commit
fbcf04a2a3
13 files changed
+1000
-188
No files matched your search
@@ -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<ComposerCommandItem>;
|
||||
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 (
|
||||
<LiquidGlassView
|
||||
effect="clear"
|
||||
interactive={false}
|
||||
tintColor={props.isDarkMode ? "rgba(30,30,32,0.95)" : "rgba(255,255,255,0.92)"}
|
||||
colorScheme={props.isDarkMode ? "dark" : "light"}
|
||||
style={baseStyle}
|
||||
>
|
||||
{props.children}
|
||||
</LiquidGlassView>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View
|
||||
style={[
|
||||
baseStyle,
|
||||
{
|
||||
backgroundColor: props.isDarkMode ? "rgba(44,44,46,0.96)" : "rgba(255,255,255,0.96)",
|
||||
borderWidth: 1,
|
||||
borderColor: props.isDarkMode ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.06)",
|
||||
},
|
||||
]}
|
||||
>
|
||||
{props.children}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<Pressable
|
||||
onPress={props.onPress}
|
||||
style={({ pressed }) => ({
|
||||
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)",
|
||||
})}
|
||||
>
|
||||
<SymbolView name={iconName} size={14} tintColor={iconColor} type="monochrome" />
|
||||
<Text
|
||||
className="text-[14px] font-t3-medium text-foreground"
|
||||
numberOfLines={1}
|
||||
style={{ flexShrink: 0 }}
|
||||
>
|
||||
{props.item.label}
|
||||
</Text>
|
||||
{props.item.description ? (
|
||||
<Text numberOfLines={1} style={{ flex: 1, minWidth: 0, fontSize: 12, color: "#a1a1aa" }}>
|
||||
{props.item.description}
|
||||
</Text>
|
||||
) : null}
|
||||
</Pressable>
|
||||
);
|
||||
});
|
||||
|
||||
export const ComposerCommandPopover = memo(function ComposerCommandPopover(
|
||||
props: ComposerCommandPopoverProps,
|
||||
) {
|
||||
const isDarkMode = useColorScheme() === "dark";
|
||||
const label = groupLabel(props.triggerKind);
|
||||
|
||||
return (
|
||||
<PopoverSurface isDarkMode={isDarkMode}>
|
||||
{label ? (
|
||||
<View style={{ paddingHorizontal: 14, paddingTop: 10, paddingBottom: 4 }}>
|
||||
<Text
|
||||
className="text-[10px] font-t3-bold text-foreground-muted"
|
||||
style={{ letterSpacing: 0.8, textTransform: "uppercase" }}
|
||||
>
|
||||
{label}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
{props.items.length > 0 ? (
|
||||
<ScrollView
|
||||
style={{ maxHeight: 180 }}
|
||||
keyboardShouldPersistTaps="always"
|
||||
showsVerticalScrollIndicator={false}
|
||||
>
|
||||
{props.items.map((item, index) => (
|
||||
<CommandRow
|
||||
key={item.id}
|
||||
item={item}
|
||||
onPress={() => props.onSelect(item)}
|
||||
isLast={index === props.items.length - 1}
|
||||
/>
|
||||
))}
|
||||
</ScrollView>
|
||||
) : (
|
||||
<View style={{ paddingHorizontal: 14, paddingVertical: 10 }}>
|
||||
<Text className="text-[12px] text-foreground-tertiary">
|
||||
{emptyText(props.triggerKind, props.isLoading)}
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
</PopoverSurface>
|
||||
);
|
||||
});
|
||||
@@ -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 (
|
||||
<Animated.View
|
||||
entering={FadeIn.duration(200)}
|
||||
exiting={FadeOut.duration(150)}
|
||||
style={{ top: insets.top + 48, left: 12, right: 12, position: "absolute", zIndex: 100 }}
|
||||
pointerEvents="box-none"
|
||||
>
|
||||
<Pressable onPress={handlePress}>
|
||||
<OverlayContent progress={progress} />
|
||||
</Pressable>
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<View
|
||||
className={`flex-row items-center gap-2.5 rounded-2xl border px-3.5 py-3 shadow-lg shadow-black/10 ${bgClass}`}
|
||||
>
|
||||
<OverlayIcon phase={progress.phase} iconColor={iconColor} />
|
||||
|
||||
<View className="flex-1 gap-0.5">
|
||||
{progress.label ? (
|
||||
<Text className="text-[13px] font-t3-bold text-foreground" numberOfLines={1}>
|
||||
{progress.label}
|
||||
</Text>
|
||||
) : null}
|
||||
{progress.description ? (
|
||||
<Text className="text-[11px] text-foreground-muted" numberOfLines={1}>
|
||||
{progress.description}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
{progress.prUrl ? (
|
||||
<SymbolView name="arrow.up.right" size={13} tintColor={iconColor} type="monochrome" />
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function OverlayIcon(props: {
|
||||
readonly phase: GitActionProgress["phase"];
|
||||
readonly iconColor: ReturnType<typeof useThemeColor>;
|
||||
}) {
|
||||
switch (props.phase) {
|
||||
case "running":
|
||||
return <ActivityIndicator size="small" />;
|
||||
case "success":
|
||||
return (
|
||||
<View className="h-6 w-6 items-center justify-center rounded-full bg-green-500">
|
||||
<SymbolView name="checkmark" size={12} tintColor="white" type="monochrome" />
|
||||
</View>
|
||||
);
|
||||
case "error":
|
||||
return (
|
||||
<View className="h-6 w-6 items-center justify-center rounded-full bg-red-500">
|
||||
<SymbolView
|
||||
name="exclamationmark.triangle"
|
||||
size={12}
|
||||
tintColor="white"
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -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<void>;
|
||||
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
|
||||
@@ -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<ComposerTrigger | null>(null);
|
||||
const [pathSearchResults, setPathSearchResults] = useState<
|
||||
ReadonlyArray<{ path: string; kind: "file" | "directory" }>
|
||||
>([]);
|
||||
const [pathSearchLoading, setPathSearchLoading] = useState(false);
|
||||
const pathSearchTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
const handleSelectionChange = useCallback(
|
||||
(event: NativeSyntheticEvent<TextInputSelectionChangeEventData>) => {
|
||||
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%)",
|
||||
}}
|
||||
>
|
||||
<View className="w-full">
|
||||
{/* Input surface — the pill/card IS the glass element */}
|
||||
<View className="w-full" style={{ position: "relative" }}>
|
||||
{composerTrigger && composerMenuItems.length > 0 ? (
|
||||
<View
|
||||
style={{
|
||||
position: "absolute",
|
||||
bottom: "100%",
|
||||
left: 0,
|
||||
right: 0,
|
||||
marginBottom: 8,
|
||||
zIndex: 10,
|
||||
}}
|
||||
>
|
||||
<ComposerCommandPopover
|
||||
items={composerMenuItems}
|
||||
triggerKind={composerTrigger.kind}
|
||||
isLoading={pathSearchLoading}
|
||||
onSelect={handleCommandSelect}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
<ComposerSurface
|
||||
isDarkMode={isDarkMode}
|
||||
style={
|
||||
@@ -387,6 +697,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
multiline
|
||||
value={props.draftMessage}
|
||||
onChangeText={props.onChangeDraftMessage}
|
||||
onSelectionChange={handleSelectionChange}
|
||||
placeholder={props.placeholder}
|
||||
placeholderTextColor={placeholderColor}
|
||||
editable={props.connectionState === "ready"}
|
||||
@@ -463,7 +774,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
icon="arrow.up"
|
||||
variant="primary"
|
||||
disabled={!canSend}
|
||||
onPress={props.onSendMessage}
|
||||
onPress={handleSend}
|
||||
/>
|
||||
)
|
||||
) : null}
|
||||
@@ -508,7 +819,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
label={sendLabel}
|
||||
variant="primary"
|
||||
disabled={!canSend}
|
||||
onPress={props.onSendMessage}
|
||||
onPress={handleSend}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
@@ -53,6 +53,7 @@ export interface ThreadDetailScreenProps {
|
||||
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
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}
|
||||
|
||||
@@ -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}
|
||||
/>
|
||||
|
||||
<GitActionProgressOverlay progress={gitActionProgress} onDismiss={dismissGitActionResult} />
|
||||
|
||||
<View className="flex-1 bg-screen">
|
||||
<ThreadDetailScreen
|
||||
selectedThread={selectedThreadDetail}
|
||||
@@ -231,6 +248,7 @@ export function ThreadRouteScreen() {
|
||||
draftAttachments={composer.draftAttachments}
|
||||
connectionStateLabel={routeConnectionState}
|
||||
activeThreadBusy={composer.activeThreadBusy}
|
||||
environmentId={selectedThread.environmentId}
|
||||
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
|
||||
selectedThreadQueueCount={composer.selectedThreadQueueCount}
|
||||
onOpenDrawer={handleOpenDrawer}
|
||||
|
||||
@@ -12,7 +12,6 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../../lib/useThemeColor";
|
||||
|
||||
import { AppText as Text } from "../../../components/AppText";
|
||||
import { StatusPill } from "../../../components/StatusPill";
|
||||
import { useGitStatus } from "../../../state/use-git-status";
|
||||
import { useThreadSelection } from "../../../state/use-thread-selection";
|
||||
import { useSelectedThreadGitActions } from "../use-selected-thread-git-actions";
|
||||
@@ -231,17 +230,6 @@ export function GitOverviewSheet() {
|
||||
</View>
|
||||
|
||||
{currentWorktreePath ? <MetaCard label="Worktree" value={currentWorktreePath} /> : null}
|
||||
|
||||
{gitOperationLabel ? (
|
||||
<View className="self-start">
|
||||
<StatusPill
|
||||
label={gitOperationLabel}
|
||||
pillClassName="bg-neutral-900/8"
|
||||
textClassName="text-neutral-700"
|
||||
size="compact"
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -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";
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<ResultListener>();
|
||||
let currentResult: GitActionResultNotification | null = null;
|
||||
let dismissTimer: ReturnType<typeof setTimeout> | 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<GitActionResultNotification | null>(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<ReturnType<typeof setInterval> | 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;
|
||||
}
|
||||
@@ -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<ComposerSlashCommand, "model"> | 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);
|
||||
}
|
||||
@@ -67,6 +67,10 @@
|
||||
"./qrCode": {
|
||||
"types": "./src/qrCode.ts",
|
||||
"import": "./src/qrCode.ts"
|
||||
},
|
||||
"./composerTrigger": {
|
||||
"types": "./src/composerTrigger.ts",
|
||||
"import": "./src/composerTrigger.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
@@ -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<ComposerSlashCommand, "model"> | 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 };
|
||||
}
|
||||
Reference in new issue
Block a user