Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6be48eb238 | ||
|
|
2218b91213 | ||
|
|
6cf940c8dc | ||
|
|
53086fef3d | ||
|
|
bead1e4eaf | ||
|
|
bae3c9470f | ||
|
|
ac8f559445 | ||
|
|
9a0a07167f | ||
|
|
9fe4832a3f | ||
|
|
376c149eac | ||
|
|
7e2bb47504 | ||
|
|
18fa89c4ad | ||
|
|
f74eb62661 | ||
|
|
e5fba263e6 | ||
|
|
18b468871e | ||
|
|
020179c19a | ||
|
|
571a8b44bd | ||
|
|
b6e1b39335 | ||
|
|
c7b21ff172 | ||
|
|
4e09cddb40 | ||
|
|
783692afc1 | ||
|
|
aa5ec80364 | ||
|
|
282ecb3178 | ||
|
|
32c6012dab | ||
|
|
6f34ad3e87 | ||
|
|
62cf461759 | ||
|
|
23c18fda7a | ||
|
|
c0bb237345 |
No files matched your search
@@ -1,3 +1,9 @@
|
||||
for (const stream of [process.stdout, process.stderr]) {
|
||||
stream.on("error", (err: NodeJS.ErrnoException) => {
|
||||
if (err.code !== "EPIPE") throw err;
|
||||
});
|
||||
}
|
||||
|
||||
import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
@@ -20,6 +20,7 @@ const clientSettings: ClientSettings = {
|
||||
diffIgnoreWhitespace: true,
|
||||
favorites: [],
|
||||
providerModelPreferences: {},
|
||||
sidebarAutoSettleAfterDays: 3,
|
||||
sidebarProjectGroupingMode: "repository_path",
|
||||
sidebarProjectGroupingOverrides: {
|
||||
"environment-1:/tmp/project-a": "separate",
|
||||
@@ -27,6 +28,7 @@ const clientSettings: ClientSettings = {
|
||||
sidebarProjectSortOrder: "manual",
|
||||
sidebarThreadSortOrder: "created_at",
|
||||
sidebarThreadPreviewCount: 6,
|
||||
sidebarV2Enabled: false,
|
||||
timestampFormat: "24-hour",
|
||||
wordWrap: true,
|
||||
};
|
||||
|
||||
@@ -41,6 +41,8 @@ function makeThread(
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -28,7 +28,8 @@ export function HomeRouteScreen() {
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
const navigation = useNavigation();
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const { archiveThread, confirmDeleteThread } = useThreadListActions();
|
||||
const { archiveThread, confirmDeleteThread, settleThread, unsettleThread } =
|
||||
useThreadListActions();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
|
||||
const environments = useMemo(
|
||||
@@ -111,6 +112,8 @@ export function HomeRouteScreen() {
|
||||
}
|
||||
onArchiveThread={archiveThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
onSettleThread={settleThread}
|
||||
onUnsettleThread={unsettleThread}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onOpenEnvironments={() =>
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
|
||||
@@ -120,6 +123,8 @@ export function HomeRouteScreen() {
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
onSelectThread={(thread) => {
|
||||
// Settled threads are live shells: opening one is plain
|
||||
// navigation, and sending a message un-settles server-side.
|
||||
navigation.navigate("Thread", {
|
||||
environmentId: thread.environmentId,
|
||||
threadId: thread.id,
|
||||
|
||||
@@ -14,18 +14,22 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import { useAtomSet, useAtomValue } from "@effect/atom-react";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import { ActivityIndicator, Platform, View } from "react-native";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { ActivityIndicator, FlatList, Platform, Pressable, ScrollView, View } from "react-native";
|
||||
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { EmptyState } from "../../components/EmptyState";
|
||||
import { ProjectFavicon } from "../../components/ProjectFavicon";
|
||||
import type { WorkspaceState } from "../../state/workspaceModel";
|
||||
import type { SavedRemoteConnection } from "../../lib/connection";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
|
||||
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
|
||||
import { environmentServerConfigsAtom } from "../../state/server";
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import {
|
||||
PendingTaskListRow,
|
||||
@@ -33,6 +37,8 @@ import {
|
||||
ThreadListRow,
|
||||
ThreadListShowMoreRow,
|
||||
} from "../threads/thread-list-items";
|
||||
import { ThreadListV2Row } from "../threads/thread-list-v2-items";
|
||||
import { buildThreadListV2Items, type ThreadListV2Item } from "../threads/threadListV2";
|
||||
import type { HomeListFilterMenuEnvironment } from "./home-list-filter-menu";
|
||||
import {
|
||||
buildHomeListLayout,
|
||||
@@ -74,6 +80,9 @@ interface HomeScreenProps {
|
||||
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
/** Resolves true iff the settle was dispatched and succeeded. */
|
||||
readonly onSettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
|
||||
@@ -82,6 +91,10 @@ interface HomeScreenProps {
|
||||
/* ─── Layout constants ───────────────────────────────────────────────── */
|
||||
|
||||
const ESTIMATED_THREAD_ROW_HEIGHT = 72;
|
||||
// v2 settled-tail paging: recent history is the common lookup; the deep
|
||||
// tail stays behind an explicit Show more.
|
||||
const THREAD_LIST_V2_SETTLED_INITIAL_COUNT = 10;
|
||||
const THREAD_LIST_V2_SETTLED_PAGE_COUNT = 25;
|
||||
/**
|
||||
* Top spacing between the list and the Android custom header. The Android
|
||||
* header (AndroidHomeHeader) is rendered in-flow above this screen and
|
||||
@@ -156,6 +169,80 @@ function HomeTopContentSpacer() {
|
||||
return <View className="h-4" />;
|
||||
}
|
||||
|
||||
function ThreadListV2ProjectScope(props: {
|
||||
readonly projects: ReadonlyArray<EnvironmentProject>;
|
||||
readonly selectedKey: string | null;
|
||||
readonly onChange: (key: string | null) => void;
|
||||
}) {
|
||||
if (props.projects.length === 0) return null;
|
||||
|
||||
return (
|
||||
<ScrollView
|
||||
horizontal
|
||||
contentContainerStyle={{
|
||||
gap: 8,
|
||||
paddingHorizontal: 16,
|
||||
paddingBottom: 8,
|
||||
paddingTop: Platform.OS === "ios" ? 12 : 4,
|
||||
}}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
showsHorizontalScrollIndicator={false}
|
||||
>
|
||||
{props.projects.length > 1 ? (
|
||||
<Pressable
|
||||
accessibilityLabel="Show all threads"
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected: props.selectedKey === null }}
|
||||
hitSlop={4}
|
||||
onPress={() => props.onChange(null)}
|
||||
className={cn(
|
||||
"min-h-8 items-center justify-center rounded-lg border px-3",
|
||||
props.selectedKey === null
|
||||
? "border-border bg-subtle-strong"
|
||||
: "border-black/15 dark:border-white/15",
|
||||
)}
|
||||
>
|
||||
<Text className="text-sm font-t3-medium text-foreground">All</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
{props.projects.map((project) => {
|
||||
const key = scopedProjectKey(project.environmentId, project.id);
|
||||
const selected = props.selectedKey === key;
|
||||
return (
|
||||
<Pressable
|
||||
key={key}
|
||||
accessibilityLabel={`Show ${project.title} threads`}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected }}
|
||||
hitSlop={4}
|
||||
onPress={() => props.onChange(selected ? null : key)}
|
||||
className={cn(
|
||||
"min-h-8 flex-row items-center gap-1.5 rounded-lg border py-1 pl-2 pr-3",
|
||||
selected ? "border-border bg-subtle-strong" : "border-black/15 dark:border-white/15",
|
||||
)}
|
||||
>
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
projectTitle={project.title}
|
||||
size={15}
|
||||
workspaceRoot={project.workspaceRoot}
|
||||
/>
|
||||
<Text
|
||||
className={cn(
|
||||
"max-w-36 text-sm font-t3-medium",
|
||||
selected ? "text-foreground" : "text-foreground-muted",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{project.title}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
|
||||
/* ─── Main screen ────────────────────────────────────────────────────── */
|
||||
|
||||
export function HomeScreen(props: HomeScreenProps) {
|
||||
@@ -163,6 +250,9 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
ReadonlyMap<string, HomeGroupDisplayState>
|
||||
>(() => new Map());
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const threadListV2Enabled =
|
||||
AsyncResult.isSuccess(preferencesResult) &&
|
||||
preferencesResult.value.threadListV2Enabled === true;
|
||||
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
|
||||
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const listRef = useRef<LegendListRef | null>(null);
|
||||
@@ -267,6 +357,193 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
return map;
|
||||
}, [props.projects]);
|
||||
|
||||
const projectByKey = useMemo(() => {
|
||||
const map = new Map<string, EnvironmentProject>();
|
||||
for (const project of props.projects) {
|
||||
map.set(scopedProjectKey(project.environmentId, project.id), project);
|
||||
}
|
||||
return map;
|
||||
}, [props.projects]);
|
||||
|
||||
const [v2ProjectScopeKey, setV2ProjectScopeKey] = useState<string | null>(null);
|
||||
const v2ScopeProjects = useMemo(
|
||||
() =>
|
||||
props.selectedEnvironmentId === null
|
||||
? props.projects
|
||||
: props.projects.filter((project) => project.environmentId === props.selectedEnvironmentId),
|
||||
[props.projects, props.selectedEnvironmentId],
|
||||
);
|
||||
const v2ScopedProject = useMemo(
|
||||
() =>
|
||||
v2ProjectScopeKey === null
|
||||
? null
|
||||
: (v2ScopeProjects.find(
|
||||
(project) => scopedProjectKey(project.environmentId, project.id) === v2ProjectScopeKey,
|
||||
) ?? null),
|
||||
[v2ProjectScopeKey, v2ScopeProjects],
|
||||
);
|
||||
useEffect(() => {
|
||||
if (v2ProjectScopeKey !== null && v2ScopedProject === null) {
|
||||
setV2ProjectScopeKey(null);
|
||||
}
|
||||
}, [v2ProjectScopeKey, v2ScopedProject]);
|
||||
|
||||
// Thread List v2 (beta): one flat list in creation order, no grouping.
|
||||
// Settled threads collapse into a recency tail below the card block.
|
||||
// Settled threads stay in the live shell stream (settled ≠ archived), so
|
||||
// the partition works directly off live shells — no snapshot merging or
|
||||
// optimistic holds.
|
||||
// PR states stream in per-row (rows own the VCS subscriptions); a merged or
|
||||
// closed PR auto-settles its thread on the next partition (mirrors web).
|
||||
const [changeRequestStateByKey, setChangeRequestStateByKey] = useState<
|
||||
ReadonlyMap<string, "open" | "closed" | "merged">
|
||||
>(() => new Map());
|
||||
const handleChangeRequestState = useCallback(
|
||||
(threadKey: string, state: "open" | "closed" | "merged" | null) => {
|
||||
setChangeRequestStateByKey((current) => {
|
||||
if ((current.get(threadKey) ?? null) === state) return current;
|
||||
const next = new Map(current);
|
||||
if (state === null) {
|
||||
next.delete(threadKey);
|
||||
} else {
|
||||
next.set(threadKey, state);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
const handleSettleThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
void props.onSettleThread(thread);
|
||||
},
|
||||
[props.onSettleThread],
|
||||
);
|
||||
const handleDeleteThread = props.onDeleteThread;
|
||||
const handleUnsettleThread = props.onUnsettleThread;
|
||||
// The settled tail renders in pages; expansion resets when the filter
|
||||
// context changes so environment/search flips never inherit a deep page.
|
||||
const [settledVisibleCount, setSettledVisibleCount] = useState(
|
||||
THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
|
||||
);
|
||||
const settledResetKey = `${props.selectedEnvironmentId ?? "all"}:${v2ProjectScopeKey ?? "all"}:${props.searchQuery.trim()}`;
|
||||
const lastSettledResetKeyRef = useRef(settledResetKey);
|
||||
if (lastSettledResetKeyRef.current !== settledResetKey) {
|
||||
lastSettledResetKeyRef.current = settledResetKey;
|
||||
setSettledVisibleCount(THREAD_LIST_V2_SETTLED_INITIAL_COUNT);
|
||||
}
|
||||
const showMoreSettled = useCallback(
|
||||
() => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
|
||||
[],
|
||||
);
|
||||
// now is quantized to the minute and ticks so the inactivity auto-settle
|
||||
// boundary is actually crossed while the app stays open (mirrors web);
|
||||
// without a clock dependency the partition memoizes a frozen "now".
|
||||
const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
|
||||
useEffect(() => {
|
||||
if (!threadListV2Enabled) return;
|
||||
const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000);
|
||||
return () => clearInterval(id);
|
||||
}, [threadListV2Enabled]);
|
||||
// Threads on servers without the settlement capability never classify as
|
||||
// settled (the user could neither un-settle nor pin them).
|
||||
const serverConfigs = useAtomValue(environmentServerConfigsAtom);
|
||||
const settlementEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadSettlement === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled) return { items: [], hiddenSettledCount: 0 };
|
||||
// Settled threads are live shells; archived threads keep their original
|
||||
// "hidden from lists" meaning.
|
||||
return buildThreadListV2Items({
|
||||
threads: props.threads.filter((thread) => thread.archivedAt === null),
|
||||
environmentId: props.selectedEnvironmentId,
|
||||
projectRef:
|
||||
v2ScopedProject === null
|
||||
? null
|
||||
: {
|
||||
environmentId: v2ScopedProject.environmentId,
|
||||
projectId: v2ScopedProject.id,
|
||||
},
|
||||
searchQuery: props.searchQuery,
|
||||
changeRequestStateByKey,
|
||||
settlementEnvironmentIds,
|
||||
settledLimit: settledVisibleCount,
|
||||
now: `${nowMinute}:00.000Z`,
|
||||
});
|
||||
}, [
|
||||
changeRequestStateByKey,
|
||||
nowMinute,
|
||||
settledVisibleCount,
|
||||
settlementEnvironmentIds,
|
||||
props.searchQuery,
|
||||
props.selectedEnvironmentId,
|
||||
props.threads,
|
||||
threadListV2Enabled,
|
||||
v2ScopedProject,
|
||||
]);
|
||||
const threadListV2Items = threadListV2Layout.items;
|
||||
|
||||
const renderV2Item = useCallback(
|
||||
({ item }: { readonly item: ThreadListV2Item }) => (
|
||||
<ThreadListV2Row
|
||||
thread={item.thread}
|
||||
variant={item.variant}
|
||||
showSettledDivider={item.showSettledDivider}
|
||||
project={
|
||||
projectByKey.get(scopedProjectKey(item.thread.environmentId, item.thread.projectId)) ??
|
||||
null
|
||||
}
|
||||
providerDriver={
|
||||
serverConfigs
|
||||
.get(item.thread.environmentId)
|
||||
?.providers.find(
|
||||
(provider) =>
|
||||
provider.instanceId ===
|
||||
(item.thread.session?.providerInstanceId ?? item.thread.modelSelection.instanceId),
|
||||
)?.driver ?? null
|
||||
}
|
||||
onSelectThread={props.onSelectThread}
|
||||
onDeleteThread={handleDeleteThread}
|
||||
onArchiveThread={props.onArchiveThread}
|
||||
settlementSupported={settlementEnvironmentIds.has(item.thread.environmentId)}
|
||||
onSettleThread={handleSettleThread}
|
||||
onUnsettleThread={handleUnsettleThread}
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
projectCwd={
|
||||
projectCwdByKey.get(scopedProjectKey(item.thread.environmentId, item.thread.projectId)) ??
|
||||
null
|
||||
}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
/>
|
||||
),
|
||||
[
|
||||
handleChangeRequestState,
|
||||
handleDeleteThread,
|
||||
handleSettleThread,
|
||||
handleSwipeableClose,
|
||||
handleSwipeableWillOpen,
|
||||
handleUnsettleThread,
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
props.onArchiveThread,
|
||||
props.onSelectThread,
|
||||
serverConfigs,
|
||||
settlementEnvironmentIds,
|
||||
],
|
||||
);
|
||||
const v2KeyExtractor = useCallback(
|
||||
(item: ThreadListV2Item) => `${item.thread.environmentId}:${item.thread.id}`,
|
||||
[],
|
||||
);
|
||||
|
||||
const extraData = useMemo(
|
||||
() => ({ savedConnectionsById: props.savedConnectionsById, projectCwdByKey }),
|
||||
[props.savedConnectionsById, projectCwdByKey],
|
||||
@@ -360,6 +637,10 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
const keyExtractor = useCallback((item: HomeListItem) => item.key, []);
|
||||
|
||||
/* Empty states */
|
||||
// The signal must ignore the search/environment filters: an active query
|
||||
// that matches nothing needs the in-list "No results" state, not the
|
||||
// full-page "No threads yet". Settled threads are unarchived live shells,
|
||||
// so the v1 check already covers v2.
|
||||
const hasAnyThreads =
|
||||
props.threads.some((thread) => thread.archivedAt === null) || props.pendingTasks.length > 0;
|
||||
const hasResults = projectGroups.length > 0;
|
||||
@@ -436,6 +717,44 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
</>
|
||||
);
|
||||
|
||||
// v2 renders queued offline tasks above the thread cards — they are not
|
||||
// thread shells, so the v2 item builder never sees them, but they must
|
||||
// stay visible and deletable while their environment is offline. They
|
||||
// respect the same environment scope and search filter as the list.
|
||||
const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
|
||||
const v2PendingTasks = props.pendingTasks.filter(
|
||||
(pendingTask) =>
|
||||
(props.selectedEnvironmentId === null ||
|
||||
pendingTask.message.environmentId === props.selectedEnvironmentId) &&
|
||||
(v2ScopedProject === null ||
|
||||
(pendingTask.message.environmentId === v2ScopedProject.environmentId &&
|
||||
pendingTask.creation.projectId === v2ScopedProject.id)) &&
|
||||
(v2SearchQuery.length === 0 || pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
|
||||
);
|
||||
const v2ListHeader = (
|
||||
<>
|
||||
{listHeader}
|
||||
<ThreadListV2ProjectScope
|
||||
projects={v2ScopeProjects}
|
||||
selectedKey={v2ProjectScopeKey}
|
||||
onChange={setV2ProjectScopeKey}
|
||||
/>
|
||||
{v2PendingTasks.map((pendingTask, index) => (
|
||||
<PendingTaskListRow
|
||||
key={pendingTask.message.messageId}
|
||||
variant="compact"
|
||||
pendingTask={pendingTask}
|
||||
environmentLabel={
|
||||
props.savedConnectionsById[pendingTask.message.environmentId]?.environmentLabel ?? null
|
||||
}
|
||||
isLast={index === v2PendingTasks.length - 1}
|
||||
onSelectPendingTask={props.onSelectPendingTask}
|
||||
onDeletePendingTask={props.onDeletePendingTask}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
|
||||
const listEmpty = !hasResults ? (
|
||||
hasSearchQuery ? (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
@@ -448,6 +767,69 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
<EmptyState title="No threads yet" detail="Create a task to start a new coding session." />
|
||||
)
|
||||
) : null;
|
||||
// Self-contained: v1's listEmpty keys off projectGroups, which ignores the
|
||||
// v2 project scope, so it can be null (results elsewhere) while this list
|
||||
// is empty. Search outranks the scope — "No results" names the actionable
|
||||
// fact when a query is active. Pending tasks render in the header, so the
|
||||
// list showing them isn't empty in the user's eyes.
|
||||
const v2ListEmpty =
|
||||
v2PendingTasks.length > 0 ? null : hasSearchQuery ? (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
) : v2ScopedProject !== null ? (
|
||||
<EmptyState
|
||||
title={`No threads in ${v2ScopedProject.title}`}
|
||||
detail="Choose another project or create a new task."
|
||||
/>
|
||||
) : (
|
||||
listEmpty
|
||||
);
|
||||
|
||||
if (threadListV2Enabled) {
|
||||
return (
|
||||
<View className="flex-1 bg-screen">
|
||||
<SwipeableScrollGateProvider enabled={swipeEnabled}>
|
||||
<FlatList
|
||||
data={threadListV2Items}
|
||||
renderItem={renderV2Item}
|
||||
keyExtractor={v2KeyExtractor}
|
||||
extraData={{ projectByKey, serverConfigs }}
|
||||
ListHeaderComponent={v2ListHeader}
|
||||
ListFooterComponent={
|
||||
threadListV2Layout.hiddenSettledCount > 0 ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`Show ${Math.min(threadListV2Layout.hiddenSettledCount, THREAD_LIST_V2_SETTLED_PAGE_COUNT)} more settled threads`}
|
||||
onPress={showMoreSettled}
|
||||
className="mx-4 mt-2 items-center rounded-lg border border-dashed border-border py-2.5"
|
||||
style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
|
||||
>
|
||||
<Text className="text-xs font-t3-medium text-foreground-muted">
|
||||
Show more ({threadListV2Layout.hiddenSettledCount} settled hidden)
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null
|
||||
}
|
||||
ListEmptyComponent={v2ListEmpty}
|
||||
style={{ flex: 1 }}
|
||||
automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
|
||||
contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
|
||||
showsVerticalScrollIndicator={false}
|
||||
keyboardDismissMode="on-drag"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
{...scrollGateHandlers}
|
||||
scrollEventThrottle={16}
|
||||
contentContainerStyle={{
|
||||
paddingBottom:
|
||||
Platform.OS === "ios"
|
||||
? Math.max(insets.bottom, 24) + 96
|
||||
: Math.max(insets.bottom, 16) + 88,
|
||||
}}
|
||||
/>
|
||||
</SwipeableScrollGateProvider>
|
||||
{connectionStatus}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-screen">
|
||||
|
||||
@@ -47,6 +47,8 @@ function makeThread(id: string, projectId: ProjectId): EnvironmentThreadShell {
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
|
||||
@@ -41,6 +41,8 @@ function makeThread(
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -167,6 +167,13 @@ export function ThreadSwipeable(props: {
|
||||
/** Disables NEW swipe activations (e.g. while the list scrolls). */
|
||||
readonly enabled?: boolean;
|
||||
readonly enableTrackpadSwipe?: boolean;
|
||||
/**
|
||||
* What a full swipe commits: "delete" (default, v1 behavior — the Delete
|
||||
* button stretches) or "primary" — the advertised primary action fires and
|
||||
* its button stretches instead. A full swipe must always match the action
|
||||
* the stretching button advertises.
|
||||
*/
|
||||
readonly fullSwipeAction?: "delete" | "primary";
|
||||
readonly fullSwipeWidth: number;
|
||||
readonly onDelete: () => void;
|
||||
readonly onSwipeableClose?: (methods: SwipeableMethods) => void;
|
||||
@@ -239,7 +246,11 @@ export function ThreadSwipeable(props: {
|
||||
if (fullSwipeArmedRef.current) {
|
||||
fullSwipeArmedRef.current = false;
|
||||
methods.close();
|
||||
props.onDelete();
|
||||
if (props.fullSwipeAction === "primary") {
|
||||
props.primaryAction.onPress();
|
||||
} else {
|
||||
props.onDelete();
|
||||
}
|
||||
}
|
||||
}}
|
||||
overshootFriction={1}
|
||||
@@ -247,6 +258,7 @@ export function ThreadSwipeable(props: {
|
||||
renderRightActions={(_progress, translation, methods) => (
|
||||
<ThreadSwipeActions
|
||||
backgroundColor={props.backgroundColor}
|
||||
fullSwipeAction={props.fullSwipeAction ?? "delete"}
|
||||
fullSwipeThreshold={fullSwipeThreshold}
|
||||
onDelete={props.onDelete}
|
||||
onFullSwipeArmedChange={handleFullSwipeArmedChange}
|
||||
@@ -422,6 +434,7 @@ function SwipeActionButton(props: {
|
||||
|
||||
export function ThreadSwipeActions(props: {
|
||||
readonly backgroundColor: ColorValue;
|
||||
readonly fullSwipeAction?: "delete" | "primary";
|
||||
readonly fullSwipeThreshold: number;
|
||||
readonly onDelete: () => void;
|
||||
readonly onFullSwipeArmedChange: (armed: boolean) => void;
|
||||
@@ -430,6 +443,7 @@ export function ThreadSwipeActions(props: {
|
||||
readonly threadTitle: string;
|
||||
readonly translation: SharedValue<number>;
|
||||
}) {
|
||||
const fullSwipeIsPrimary = props.fullSwipeAction === "primary";
|
||||
useAnimatedReaction(
|
||||
() => -props.translation.value >= props.fullSwipeThreshold,
|
||||
(armed, previous) => {
|
||||
@@ -457,7 +471,7 @@ export function ThreadSwipeActions(props: {
|
||||
icon={props.primaryAction.icon}
|
||||
label={props.primaryAction.label}
|
||||
onPress={props.primaryAction.onPress}
|
||||
stretchesOnFullSwipe={false}
|
||||
stretchesOnFullSwipe={fullSwipeIsPrimary}
|
||||
translation={props.translation}
|
||||
/>
|
||||
<SwipeActionButton
|
||||
@@ -471,7 +485,7 @@ export function ThreadSwipeActions(props: {
|
||||
props.swipeableMethods.close();
|
||||
props.onDelete();
|
||||
}}
|
||||
stretchesOnFullSwipe
|
||||
stretchesOnFullSwipe={!fullSwipeIsPrimary}
|
||||
translation={props.translation}
|
||||
/>
|
||||
</View>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { canSettle } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { useCallback, useRef } from "react";
|
||||
@@ -6,19 +7,37 @@ import { Alert } from "react-native";
|
||||
|
||||
import { showConfirmDialog } from "../../components/ConfirmDialogHost";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { refreshArchivedThreadsForEnvironment } from "../archive/useArchivedThreadSnapshots";
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { environmentServerConfigsAtom } from "../../state/server";
|
||||
import { threadEnvironment } from "../../state/threads";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
|
||||
type ThreadListAction = "archive" | "unarchive" | "delete";
|
||||
/** Version skew: never send settle/unsettle to a server that predates them
|
||||
(capability defaults false on decode for older servers). */
|
||||
function environmentSupportsSettlement(environmentId: EnvironmentThreadShell["environmentId"]) {
|
||||
return (
|
||||
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
|
||||
.threadSettlement === true
|
||||
);
|
||||
}
|
||||
|
||||
type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";
|
||||
|
||||
const ACTION_VERBS: Record<ThreadListAction, string> = {
|
||||
archive: "archived",
|
||||
unarchive: "unarchived",
|
||||
delete: "deleted",
|
||||
settle: "settled",
|
||||
unsettle: "un-settled",
|
||||
};
|
||||
|
||||
function actionFailureMessage(action: ThreadListAction, cause: Cause.Cause<unknown>): string {
|
||||
const error = Cause.squash(cause);
|
||||
if (error instanceof Error && error.message.trim().length > 0) {
|
||||
return error.message;
|
||||
}
|
||||
const verb =
|
||||
action === "archive" ? "archived" : action === "unarchive" ? "unarchived" : "deleted";
|
||||
return `The thread could not be ${verb}.`;
|
||||
return `The thread could not be ${ACTION_VERBS[action]}.`;
|
||||
}
|
||||
|
||||
function selectionHaptic(): void {
|
||||
@@ -28,54 +47,115 @@ function selectionHaptic(): void {
|
||||
function actionFailureTitle(action: ThreadListAction): string {
|
||||
if (action === "archive") return "Could not archive thread";
|
||||
if (action === "unarchive") return "Could not unarchive thread";
|
||||
if (action === "settle") return "Could not settle thread";
|
||||
if (action === "unsettle") return "Could not un-settle thread";
|
||||
return "Could not delete thread";
|
||||
}
|
||||
|
||||
/** Resolves to true iff the action was dispatched and succeeded. */
|
||||
function useThreadActionExecutor(
|
||||
onCompleted?: (action: ThreadListAction, thread: EnvironmentThreadShell) => void,
|
||||
) {
|
||||
const archiveMutation = useAtomCommand(threadEnvironment.archive, { reportFailure: false });
|
||||
const unarchiveMutation = useAtomCommand(threadEnvironment.unarchive, { reportFailure: false });
|
||||
const deleteMutation = useAtomCommand(threadEnvironment.delete, { reportFailure: false });
|
||||
const settleMutation = useAtomCommand(threadEnvironment.settle, { reportFailure: false });
|
||||
const unsettleMutation = useAtomCommand(threadEnvironment.unsettle, { reportFailure: false });
|
||||
const inFlightThreadKeys = useRef(new Set<string>());
|
||||
|
||||
const executeAction = useCallback(
|
||||
async (action: ThreadListAction, thread: EnvironmentThreadShell) => {
|
||||
const key = scopedThreadKey(thread.environmentId, thread.id);
|
||||
if (inFlightThreadKeys.current.has(key)) {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
inFlightThreadKeys.current.add(key);
|
||||
selectionHaptic();
|
||||
try {
|
||||
const mutation =
|
||||
action === "archive"
|
||||
? archiveMutation
|
||||
: action === "unarchive"
|
||||
? unarchiveMutation
|
||||
: deleteMutation;
|
||||
const result = await mutation({
|
||||
environmentId: thread.environmentId,
|
||||
input: { threadId: thread.id },
|
||||
});
|
||||
if (
|
||||
(action === "settle" || action === "unsettle") &&
|
||||
!environmentSupportsSettlement(thread.environmentId)
|
||||
) {
|
||||
Alert.alert(
|
||||
actionFailureTitle(action),
|
||||
"This environment's server does not support settling yet. Update the server to use Settle.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
// Settle may only target what effectiveSettled could classify as
|
||||
// settled: not starting/running sessions, not threads waiting on
|
||||
// approvals or user input. Anything else would hide live work.
|
||||
if (action === "settle" && !canSettle(thread, { now: new Date().toISOString() })) {
|
||||
Alert.alert(
|
||||
actionFailureTitle(action),
|
||||
"This thread still needs attention. Resolve or interrupt it first, then try again.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
// Archive keeps its original, narrower guard: never interrupt a
|
||||
// thread mid-turn.
|
||||
if (
|
||||
action === "archive" &&
|
||||
thread.session?.status === "running" &&
|
||||
thread.session.activeTurnId != null
|
||||
) {
|
||||
Alert.alert(
|
||||
actionFailureTitle(action),
|
||||
"This thread is working. Interrupt it first, then try again.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
const result =
|
||||
action === "unsettle"
|
||||
? // reason "user" pins the thread active: auto-settle stays
|
||||
// suppressed until real activity clears the pin server-side.
|
||||
await unsettleMutation({
|
||||
environmentId: thread.environmentId,
|
||||
input: { threadId: thread.id, reason: "user" },
|
||||
})
|
||||
: await (
|
||||
action === "settle"
|
||||
? settleMutation
|
||||
: action === "archive"
|
||||
? archiveMutation
|
||||
: action === "unarchive"
|
||||
? unarchiveMutation
|
||||
: deleteMutation
|
||||
)({
|
||||
environmentId: thread.environmentId,
|
||||
input: { threadId: thread.id },
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
Alert.alert(actionFailureTitle(action), actionFailureMessage(action, result.cause));
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
// Settled threads stay in the live shell stream; only the archive
|
||||
// lifecycle still feeds the archived-snapshot surface.
|
||||
if (action === "archive" || action === "unarchive" || action === "delete") {
|
||||
refreshArchivedThreadsForEnvironment(thread.environmentId);
|
||||
}
|
||||
onCompleted?.(action, thread);
|
||||
return true;
|
||||
} finally {
|
||||
inFlightThreadKeys.current.delete(key);
|
||||
}
|
||||
},
|
||||
[archiveMutation, deleteMutation, onCompleted, unarchiveMutation],
|
||||
[
|
||||
archiveMutation,
|
||||
deleteMutation,
|
||||
onCompleted,
|
||||
settleMutation,
|
||||
unarchiveMutation,
|
||||
unsettleMutation,
|
||||
],
|
||||
);
|
||||
|
||||
return executeAction;
|
||||
}
|
||||
|
||||
function useConfirmDeleteThread(
|
||||
executeAction: (action: ThreadListAction, thread: EnvironmentThreadShell) => Promise<void>,
|
||||
executeAction: (action: ThreadListAction, thread: EnvironmentThreadShell) => Promise<boolean>,
|
||||
) {
|
||||
return useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
@@ -111,6 +191,8 @@ function useConfirmDeleteThread(
|
||||
export function useThreadListActions(): {
|
||||
readonly archiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly confirmDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly settleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly unsettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
} {
|
||||
const executeAction = useThreadActionExecutor();
|
||||
|
||||
@@ -120,10 +202,18 @@ export function useThreadListActions(): {
|
||||
},
|
||||
[executeAction],
|
||||
);
|
||||
const settleThread = useCallback(
|
||||
async (thread: EnvironmentThreadShell) => (await executeAction("settle", thread)) === true,
|
||||
[executeAction],
|
||||
);
|
||||
const unsettleThread = useCallback(
|
||||
async (thread: EnvironmentThreadShell) => (await executeAction("unsettle", thread)) === true,
|
||||
[executeAction],
|
||||
);
|
||||
|
||||
const confirmDeleteThread = useConfirmDeleteThread(executeAction);
|
||||
|
||||
return { archiveThread, confirmDeleteThread };
|
||||
return { archiveThread, confirmDeleteThread, settleThread, unsettleThread };
|
||||
}
|
||||
|
||||
export function useArchivedThreadListActions(
|
||||
|
||||
@@ -123,6 +123,8 @@ function LocalSettingsRouteScreen() {
|
||||
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
|
||||
</SettingsSection>
|
||||
|
||||
<BetaSettingsSection />
|
||||
|
||||
<ArchivedThreadsSettingsSection />
|
||||
|
||||
<AppSettingsSection />
|
||||
@@ -506,6 +508,8 @@ function ConfiguredSettingsRouteScreen() {
|
||||
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
|
||||
</SettingsSection>
|
||||
|
||||
<BetaSettingsSection />
|
||||
|
||||
<ArchivedThreadsSettingsSection />
|
||||
|
||||
<AppSettingsSection />
|
||||
@@ -514,6 +518,35 @@ function ConfiguredSettingsRouteScreen() {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Device-local beta toggles. Mobile has no client-settings sync, so this is
|
||||
* the counterpart of web's Settings → Beta backed by mobile preferences.
|
||||
*/
|
||||
function BetaSettingsSection() {
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
|
||||
const threadListV2Enabled = AsyncResult.isSuccess(preferencesResult)
|
||||
? preferencesResult.value.threadListV2Enabled === true
|
||||
: false;
|
||||
|
||||
return (
|
||||
<View className="gap-3">
|
||||
<SettingsSection title="Beta">
|
||||
<SettingsSwitchRow
|
||||
icon="sidebar.left"
|
||||
label="Thread List v2"
|
||||
value={threadListV2Enabled}
|
||||
onValueChange={(value) => savePreferences({ threadListV2Enabled: value })}
|
||||
/>
|
||||
</SettingsSection>
|
||||
<Text className="px-2 text-sm text-foreground-muted">
|
||||
One flat thread list in creation order. Active work renders as cards; settled threads
|
||||
collapse to compact rows. Switch back any time.
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function AppSettingsSection() {
|
||||
const icon = useThemeColor("--color-icon");
|
||||
|
||||
|
||||
@@ -26,7 +26,13 @@ import {
|
||||
type ViewStyle,
|
||||
} from "react-native";
|
||||
import ImageViewing from "react-native-image-viewing";
|
||||
import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated";
|
||||
import Animated, {
|
||||
FadeIn,
|
||||
FadeInDown,
|
||||
FadeOut,
|
||||
FadeOutDown,
|
||||
LinearTransition,
|
||||
} from "react-native-reanimated";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
@@ -232,7 +238,12 @@ const ComposerConnectionStatusPill = memo(function ComposerConnectionStatusPill(
|
||||
const isReconnecting = props.status.kind !== "unavailable";
|
||||
|
||||
return (
|
||||
<View className="items-center pb-2">
|
||||
<Animated.View
|
||||
className="absolute inset-x-0 bottom-full items-center pb-2"
|
||||
entering={FadeInDown.duration(180)}
|
||||
exiting={FadeOutDown.duration(140)}
|
||||
pointerEvents="box-none"
|
||||
>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
onPress={props.onPress}
|
||||
@@ -250,7 +261,7 @@ const ComposerConnectionStatusPill = memo(function ComposerConnectionStatusPill(
|
||||
{props.status.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</Animated.View>
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -14,21 +14,18 @@ import type {
|
||||
ServerConfig as T3ServerConfig,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { Platform, View, type GestureResponderEvent } from "react-native";
|
||||
import { KeyboardController, KeyboardStickyView } from "react-native-keyboard-controller";
|
||||
import Animated, { FadeInDown, FadeOut, LinearTransition } from "react-native-reanimated";
|
||||
import Animated, { FadeInDown, FadeOut } from "react-native-reanimated";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import type { ComposerEditorHandle } from "../../components/ComposerEditor";
|
||||
import type { StatusTone } from "../../components/StatusPill";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import { CHAT_CONTENT_MAX_WIDTH, type LayoutVariant } from "../../lib/layout";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
|
||||
import type {
|
||||
PendingApproval,
|
||||
PendingUserInput,
|
||||
@@ -172,54 +169,6 @@ function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray<ThreadFeedE
|
||||
}, [threadId, feed]);
|
||||
}
|
||||
|
||||
// Pre-measurement estimate for the working pill's slot (the real height is
|
||||
// measured via onComposerLayout since the pill lives inside the composer
|
||||
// overlay). Matches the rendered pill: pt-2 + pb-2 (16) wrapping a bordered
|
||||
// px-3/py-2 row (~36), so ~52 — keep it in sync with WorkingDurationPill.
|
||||
const WORKING_INDICATOR_HEIGHT = 52;
|
||||
|
||||
const WorkingDurationPill = memo(function WorkingDurationPill(props: {
|
||||
readonly startedAt: string;
|
||||
}) {
|
||||
const [nowMs, setNowMs] = useState(() => Date.now());
|
||||
|
||||
useEffect(() => {
|
||||
const intervalId = setInterval(() => {
|
||||
setNowMs(Date.now());
|
||||
}, 1_000);
|
||||
return () => clearInterval(intervalId);
|
||||
}, [props.startedAt]);
|
||||
|
||||
const durationLabel = formatElapsed(props.startedAt, new Date(nowMs).toISOString()) ?? "0s";
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
className="shrink-0 px-4 pb-2 pt-2"
|
||||
entering={FadeInDown.duration(200)}
|
||||
exiting={FadeOut.duration(140)}
|
||||
>
|
||||
<View
|
||||
className={
|
||||
Platform.OS === "ios" && !NATIVE_LIQUID_GLASS_SUPPORTED
|
||||
? "self-start rounded-full border border-border bg-card px-3 py-2"
|
||||
: "self-start rounded-full border border-neutral-200/80 bg-neutral-50/90 px-3 py-2 dark:border-white/[0.08] dark:bg-white/[0.04]"
|
||||
}
|
||||
>
|
||||
<View className="flex-row items-center gap-2">
|
||||
<View className="flex-row items-center gap-1">
|
||||
<View className="h-1.5 w-1.5 rounded-full bg-neutral-400 dark:bg-neutral-500" />
|
||||
<View className="h-1.5 w-1.5 rounded-full bg-neutral-400/80 dark:bg-neutral-500/80" />
|
||||
<View className="h-1.5 w-1.5 rounded-full bg-neutral-400/60 dark:bg-neutral-500/60" />
|
||||
</View>
|
||||
<Text className="font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
|
||||
Working for {durationLabel}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
</Animated.View>
|
||||
);
|
||||
});
|
||||
|
||||
export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
|
||||
@@ -253,8 +202,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
const selectedThreadFeed = props.selectedThreadFeed;
|
||||
const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
|
||||
const composerOverlapHeight = composerChrome + composerBottomInset;
|
||||
const activeWorkIndicatorHeight = props.activeWorkStartedAt ? WORKING_INDICATOR_HEIGHT : 0;
|
||||
const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight;
|
||||
const estimatedOverlayHeight = composerOverlapHeight;
|
||||
// The overlay's measured height includes the home-indicator inset (the
|
||||
// composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
|
||||
// UIKit add the safe-area bottom to the content inset AGAIN — leaving a
|
||||
@@ -411,6 +359,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
contentPresentation={props.contentPresentation}
|
||||
agentLabel={agentLabel}
|
||||
latestTurn={props.selectedThread.latestTurn}
|
||||
activeWorkStartedAt={props.activeWorkStartedAt}
|
||||
listRef={listRef}
|
||||
freeze={freeze}
|
||||
anchorMessageId={anchorMessageId}
|
||||
@@ -438,15 +387,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
list's bottom inset, so any padding above the pill/composer
|
||||
pushes the resting content floor up by the same amount. */}
|
||||
<View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
|
||||
<Animated.View
|
||||
className="w-full self-center"
|
||||
layout={LinearTransition.duration(220)}
|
||||
style={{ maxWidth: contentMaxWidth }}
|
||||
>
|
||||
{props.activeWorkStartedAt ? (
|
||||
<WorkingDurationPill startedAt={props.activeWorkStartedAt} />
|
||||
) : null}
|
||||
|
||||
<View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
|
||||
{props.activePendingApproval || props.activePendingUserInput ? (
|
||||
<Animated.View
|
||||
className="shrink-0 gap-3 px-4 pb-3"
|
||||
@@ -473,7 +414,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
) : null}
|
||||
</Animated.View>
|
||||
) : null}
|
||||
</Animated.View>
|
||||
</View>
|
||||
|
||||
<ThreadComposer
|
||||
editorRef={composerEditorRef}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
|
||||
import { type LegendListRef } from "@legendapp/list/react-native";
|
||||
import type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
|
||||
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { HeaderHeightContext } from "@react-navigation/elements";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
@@ -128,6 +129,7 @@ export interface ThreadFeedProps {
|
||||
readonly contentPresentation: ThreadContentPresentation;
|
||||
readonly agentLabel: string;
|
||||
readonly latestTurn: ThreadFeedLatestTurn | null;
|
||||
readonly activeWorkStartedAt: string | null;
|
||||
readonly listRef: RefObject<LegendListRef | null>;
|
||||
readonly freeze: SharedValue<boolean>;
|
||||
readonly anchorMessageId: MessageId | null;
|
||||
@@ -816,6 +818,10 @@ function renderFeedEntry(
|
||||
const entry = info.item;
|
||||
const { markdownStyles, iconSubtleColor, userBubbleColor } = props;
|
||||
|
||||
if (entry.type === "working") {
|
||||
return <WorkingTimelineRow startedAt={entry.createdAt} />;
|
||||
}
|
||||
|
||||
if (entry.type === "turn-fold") {
|
||||
return (
|
||||
<Pressable
|
||||
@@ -993,6 +999,32 @@ function renderFeedEntry(
|
||||
);
|
||||
}
|
||||
|
||||
const WorkingTimelineRow = memo(function WorkingTimelineRow(props: { readonly startedAt: string }) {
|
||||
const [nowMs, setNowMs] = useState(() => Date.now());
|
||||
|
||||
useEffect(() => {
|
||||
const intervalId = setInterval(() => {
|
||||
setNowMs(Date.now());
|
||||
}, 1_000);
|
||||
return () => clearInterval(intervalId);
|
||||
}, [props.startedAt]);
|
||||
|
||||
const durationLabel = formatElapsed(props.startedAt, new Date(nowMs).toISOString()) ?? "0s";
|
||||
|
||||
return (
|
||||
<View className="mb-4 flex-row items-center gap-2 px-1.5 py-1">
|
||||
<View className="flex-row items-center gap-1">
|
||||
<View className="h-1 w-1 rounded-full bg-neutral-400 dark:bg-neutral-500" />
|
||||
<View className="h-1 w-1 rounded-full bg-neutral-400/80 dark:bg-neutral-500/80" />
|
||||
<View className="h-1 w-1 rounded-full bg-neutral-400/60 dark:bg-neutral-500/60" />
|
||||
</View>
|
||||
<Text className="font-t3-medium text-xs tabular-nums text-neutral-600 dark:text-neutral-400">
|
||||
Working for {durationLabel}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
function UserMessageContent(props: {
|
||||
readonly text: string;
|
||||
readonly markdownStyles: MarkdownStyleSet;
|
||||
@@ -1415,8 +1447,15 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
props.latestTurn,
|
||||
expandedTurnIds,
|
||||
expandedWorkGroupIds,
|
||||
props.activeWorkStartedAt,
|
||||
),
|
||||
[expandedTurnIds, expandedWorkGroupIds, props.feed, props.latestTurn],
|
||||
[
|
||||
expandedTurnIds,
|
||||
expandedWorkGroupIds,
|
||||
props.activeWorkStartedAt,
|
||||
props.feed,
|
||||
props.latestTurn,
|
||||
],
|
||||
);
|
||||
|
||||
// The empty↔filled key below remounts the list, which resets its imperative
|
||||
@@ -1761,7 +1800,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
{props.feed.length === 0 && props.contentPresentation.kind === "ready" ? (
|
||||
{props.feed.length === 0 &&
|
||||
props.activeWorkStartedAt === null &&
|
||||
props.contentPresentation.kind === "ready" ? (
|
||||
<View pointerEvents="none" style={StyleSheet.absoluteFill}>
|
||||
<ThreadFeedPlaceholder
|
||||
title="No conversation yet"
|
||||
|
||||
@@ -58,6 +58,8 @@ import { type VcsRef } from "@t3tools/client-runtime/state/vcs";
|
||||
|
||||
type WorkspaceMode = "local" | "worktree";
|
||||
|
||||
const EMPTY_BRANCH_REFS: ReadonlyArray<VcsRef> = [];
|
||||
|
||||
function pendingTaskDraftKey(messageId: string): string {
|
||||
return `pending-task:${messageId}`;
|
||||
}
|
||||
@@ -348,7 +350,14 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? "local";
|
||||
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
|
||||
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
|
||||
const startFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin ?? false;
|
||||
// Keep the user's explicit choice separate from the resolved display value:
|
||||
// only the explicit flag is ever written back to the draft, so the resolved
|
||||
// value keeps tracking the server setting when the config loads late.
|
||||
const draftStartFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin;
|
||||
const startFromOrigin =
|
||||
draftStartFromOrigin ??
|
||||
selectedEnvironmentServerConfig?.settings.newWorktreesStartFromOrigin ??
|
||||
true;
|
||||
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
|
||||
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
|
||||
|
||||
@@ -368,6 +377,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
const selectedModel =
|
||||
selectedProjectDraft.modelSelection ??
|
||||
selectedProject?.defaultModelSelection ??
|
||||
modelOptions.find((option) => option.isDefault)?.selection ??
|
||||
modelOptions[0]?.selection ??
|
||||
null;
|
||||
const selectedModelKey = selectedModel
|
||||
@@ -475,13 +485,14 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
);
|
||||
const branchState = useBranches(branchTarget);
|
||||
const branchesLoading = branchState.isPending;
|
||||
const allBranchRefs = branchState.data?.refs ?? EMPTY_BRANCH_REFS;
|
||||
const availableBranches = useMemo(
|
||||
() =>
|
||||
pipe(
|
||||
branchState.data?.refs ?? [],
|
||||
allBranchRefs,
|
||||
Arr.filter((branch) => !branch.isRemote),
|
||||
),
|
||||
[branchState.data?.refs],
|
||||
[allBranchRefs],
|
||||
);
|
||||
|
||||
const filteredBranches = useMemo(() => {
|
||||
@@ -543,11 +554,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
mode,
|
||||
branch: selectedBranchName,
|
||||
worktreePath: selectedWorktreePath,
|
||||
startFromOrigin,
|
||||
...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedBranchName, selectedProjectDraftKey, selectedWorktreePath, startFromOrigin],
|
||||
[draftStartFromOrigin, selectedBranchName, selectedProjectDraftKey, selectedWorktreePath],
|
||||
);
|
||||
|
||||
const selectBranch = useCallback(
|
||||
@@ -560,11 +571,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
mode: workspaceMode,
|
||||
branch: branch.name,
|
||||
worktreePath: normalizeSelectedWorktreePath(selectedProject, branch),
|
||||
startFromOrigin,
|
||||
...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedProject, selectedProjectDraftKey, startFromOrigin, workspaceMode],
|
||||
[draftStartFromOrigin, selectedProject, selectedProjectDraftKey, workspaceMode],
|
||||
);
|
||||
|
||||
const setStartFromOrigin = useCallback(
|
||||
@@ -597,14 +608,16 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
if (workspaceMode !== "worktree" || selectedBranchName !== null) {
|
||||
return;
|
||||
}
|
||||
// The default may only exist as origin/<default> (isRemote), which
|
||||
// availableBranches filters out — search the unfiltered refs for it.
|
||||
const preferredBranch =
|
||||
allBranchRefs.find((branch) => branch.isDefault) ??
|
||||
availableBranches.find((branch) => branch.current) ??
|
||||
availableBranches.find((branch) => branch.isDefault) ??
|
||||
null;
|
||||
if (preferredBranch) {
|
||||
selectBranch(preferredBranch);
|
||||
}
|
||||
}, [availableBranches, selectBranch, selectedBranchName, workspaceMode]);
|
||||
}, [allBranchRefs, availableBranches, selectBranch, selectedBranchName, workspaceMode]);
|
||||
|
||||
const setRuntimeMode = useCallback(
|
||||
(value: RuntimeMode) => {
|
||||
@@ -696,7 +709,12 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
workspaceMode: mode,
|
||||
branch: workspaceSelection?.branch ?? null,
|
||||
worktreePath: mode === "worktree" ? null : (workspaceSelection?.worktreePath ?? null),
|
||||
...(workspaceSelection?.startFromOrigin ? { startFromOrigin: true } : {}),
|
||||
// The draft only carries the flag when the user touched it; fall
|
||||
// back to the resolved default (server settings) so queued tasks
|
||||
// drain with the same origin mode the composer displayed.
|
||||
...((workspaceSelection?.startFromOrigin ?? startFromOrigin)
|
||||
? { startFromOrigin: true }
|
||||
: {}),
|
||||
},
|
||||
createdAt: metadata.createdAt,
|
||||
};
|
||||
@@ -707,6 +725,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
selectedModel,
|
||||
selectedProject,
|
||||
selectedProjectDraftKey,
|
||||
startFromOrigin,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,329 @@
|
||||
import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import { memo, useCallback, useEffect, useMemo, type ComponentProps } from "react";
|
||||
import { Platform, Pressable, useWindowDimensions, View } from "react-native";
|
||||
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { ProjectFavicon } from "../../components/ProjectFavicon";
|
||||
import { ProviderIcon } from "../../components/ProviderIcon";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { relativeTime } from "../../lib/time";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useThreadPr } from "../../state/use-thread-pr";
|
||||
import { ThreadSwipeable } from "../home/thread-swipe-actions";
|
||||
import { resolveThreadListV2Status, type ThreadListV2Status } from "./threadListV2";
|
||||
|
||||
/**
|
||||
* Thread List v2 rows mirror the web sidebar's compact tonal cards and
|
||||
* receded settled tail while retaining native swipe and long-press actions.
|
||||
*/
|
||||
|
||||
const MONO_FONT = Platform.select({
|
||||
ios: "Menlo",
|
||||
android: "monospace",
|
||||
default: "monospace",
|
||||
});
|
||||
|
||||
const STATUS_LABEL_BY_STATUS: Partial<
|
||||
Record<ThreadListV2Status, { label: string; className: string }>
|
||||
> = {
|
||||
approval: { label: "Approval", className: "text-amber-700 dark:text-amber-300" },
|
||||
input: { label: "Input", className: "text-amber-700 dark:text-amber-300" },
|
||||
working: { label: "Working", className: "text-blue-600 dark:text-blue-400" },
|
||||
failed: { label: "Failed", className: "text-red-700 dark:text-red-300" },
|
||||
};
|
||||
|
||||
function threadTimeLabel(thread: EnvironmentThreadShell): string {
|
||||
return relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt);
|
||||
}
|
||||
|
||||
// Menus stay lifecycle-focused: settle/un-settle plus delete. Archive keeps
|
||||
// its own surface (thread screen / settings) rather than crowding the row.
|
||||
const CARD_MENU_ACTIONS: MenuAction[] = [
|
||||
{ id: "settle", title: "Settle", image: "checkmark" },
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
];
|
||||
|
||||
const SLIM_MENU_ACTIONS: MenuAction[] = [
|
||||
{ id: "unsettle", title: "Un-settle", image: "arrow.uturn.backward" },
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
];
|
||||
|
||||
// Pre-settlement servers: no lifecycle items, archive fills the gap.
|
||||
const LEGACY_MENU_ACTIONS: MenuAction[] = [
|
||||
{ id: "archive", title: "Archive", image: "archivebox" },
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
];
|
||||
|
||||
export const ThreadListV2SettledDivider = memo(function ThreadListV2SettledDivider() {
|
||||
const borderColor = useThemeColor("--color-border");
|
||||
return (
|
||||
<View className="mb-1.5 mt-4 flex-row items-center gap-2.5 px-5">
|
||||
<Text className="text-xs font-t3-medium text-foreground-tertiary">Settled</Text>
|
||||
<View className="h-px flex-1" style={{ backgroundColor: borderColor }} />
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly thread: EnvironmentThreadShell;
|
||||
readonly variant: "card" | "slim";
|
||||
readonly showSettledDivider: boolean;
|
||||
readonly project: EnvironmentProject | null;
|
||||
readonly providerDriver: string | null;
|
||||
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onSettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
/** False on environments whose server predates thread.settle/unsettle:
|
||||
swipe + menu fall back to Archive instead of failing on use. */
|
||||
readonly settlementSupported: boolean;
|
||||
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
|
||||
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
|
||||
/** Reports this row's live PR state up so the partition can auto-settle
|
||||
merged/closed work (mirrors web's onChangeRequestState). */
|
||||
readonly onChangeRequestState?: (
|
||||
threadKey: string,
|
||||
state: "open" | "closed" | "merged" | null,
|
||||
) => void;
|
||||
readonly projectCwd?: string | null;
|
||||
readonly simultaneousSwipeGesture?: ComponentProps<
|
||||
typeof ThreadSwipeable
|
||||
>["simultaneousWithExternalGesture"];
|
||||
}) {
|
||||
const { width: windowWidth } = useWindowDimensions();
|
||||
const {
|
||||
thread,
|
||||
variant,
|
||||
onSelectThread,
|
||||
onDeleteThread,
|
||||
onSettleThread,
|
||||
onUnsettleThread,
|
||||
onArchiveThread,
|
||||
onChangeRequestState,
|
||||
} = props;
|
||||
|
||||
const pr = useThreadPr(thread, props.projectCwd ?? props.project?.workspaceRoot ?? null);
|
||||
const prState = pr?.state ?? null;
|
||||
const threadKey = `${thread.environmentId}:${thread.id}`;
|
||||
useEffect(() => {
|
||||
onChangeRequestState?.(threadKey, prState);
|
||||
}, [onChangeRequestState, prState, threadKey]);
|
||||
|
||||
const screenColor = useThemeColor("--color-screen");
|
||||
|
||||
const status = resolveThreadListV2Status(thread);
|
||||
const statusLabel = STATUS_LABEL_BY_STATUS[status];
|
||||
const timeLabel = threadTimeLabel(thread);
|
||||
|
||||
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
|
||||
const handleSettle = useCallback(() => onSettleThread(thread), [onSettleThread, thread]);
|
||||
const handleUnsettle = useCallback(() => onUnsettleThread(thread), [onUnsettleThread, thread]);
|
||||
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
|
||||
const handleMenuAction = useCallback(
|
||||
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
|
||||
if (nativeEvent.event === "settle") handleSettle();
|
||||
if (nativeEvent.event === "unsettle") handleUnsettle();
|
||||
if (nativeEvent.event === "archive") handleArchive();
|
||||
if (nativeEvent.event === "delete") handleDelete();
|
||||
},
|
||||
[handleArchive, handleDelete, handleSettle, handleUnsettle],
|
||||
);
|
||||
|
||||
// Swipe: the v2 primary action is the lifecycle transition. Every settled
|
||||
// row can un-settle — explicit settles clear the override, auto-settled
|
||||
// rows get pinned active until real activity clears the pin.
|
||||
const canUnsettle = variant === "slim";
|
||||
const primaryAction = useMemo(() => {
|
||||
// Pre-settlement server: archive is the swipe action, as in v1. (Slim
|
||||
// rows cannot occur here — unsupported environments never classify as
|
||||
// settled.)
|
||||
if (!props.settlementSupported) {
|
||||
return {
|
||||
accessibilityLabel: `Archive ${thread.title}`,
|
||||
icon: "archivebox" as const,
|
||||
label: "Archive",
|
||||
onPress: handleArchive,
|
||||
};
|
||||
}
|
||||
return canUnsettle
|
||||
? {
|
||||
accessibilityLabel: `Un-settle ${thread.title}`,
|
||||
icon: "arrow.uturn.backward" as const,
|
||||
label: "Un-settle",
|
||||
onPress: handleUnsettle,
|
||||
}
|
||||
: {
|
||||
accessibilityLabel: `Settle ${thread.title}`,
|
||||
icon: "checkmark" as const,
|
||||
label: "Settle",
|
||||
onPress: handleSettle,
|
||||
};
|
||||
}, [
|
||||
canUnsettle,
|
||||
handleArchive,
|
||||
handleSettle,
|
||||
handleUnsettle,
|
||||
props.settlementSupported,
|
||||
thread.title,
|
||||
]);
|
||||
|
||||
const rowContent = (close: () => void) =>
|
||||
variant === "card" ? (
|
||||
<Pressable
|
||||
accessibilityHint={`Opens the thread. Swipe left to ${primaryAction.label.toLowerCase()}.`}
|
||||
accessibilityLabel={thread.title}
|
||||
accessibilityRole="button"
|
||||
onPress={() => {
|
||||
close();
|
||||
onSelectThread(thread);
|
||||
}}
|
||||
style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}
|
||||
>
|
||||
<View className="bg-screen px-4 py-1">
|
||||
<View
|
||||
className={cn(
|
||||
"overflow-hidden",
|
||||
status === "ready"
|
||||
? "bg-black/[0.025] dark:bg-white/[0.025]"
|
||||
: "bg-black/[0.04] dark:bg-white/[0.04]",
|
||||
)}
|
||||
style={{ borderRadius: 12, borderCurve: "continuous", minHeight: 84 }}
|
||||
>
|
||||
<View className="px-3 py-2.5">
|
||||
<View className="flex-row items-center gap-1.5">
|
||||
{props.project ? (
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
size={15}
|
||||
projectTitle={props.project.title}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
/>
|
||||
) : null}
|
||||
<Text
|
||||
className="flex-1 text-sm font-t3-medium text-foreground-muted"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.project?.title ?? ""}
|
||||
</Text>
|
||||
<Text
|
||||
className={cn(
|
||||
"text-xs tabular-nums",
|
||||
statusLabel?.className ?? "text-foreground-tertiary",
|
||||
)}
|
||||
>
|
||||
{statusLabel?.label ?? timeLabel}
|
||||
</Text>
|
||||
</View>
|
||||
<Text className="mt-1 text-base font-t3-medium text-foreground" numberOfLines={2}>
|
||||
{thread.title}
|
||||
</Text>
|
||||
<View className="mt-1 flex-row items-center gap-2">
|
||||
{status === "failed" && thread.session?.lastError ? (
|
||||
<Text
|
||||
className="flex-1 text-xs text-red-600/80 dark:text-red-400/80"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{thread.session.lastError}
|
||||
</Text>
|
||||
) : thread.branch ? (
|
||||
<Text
|
||||
className="flex-1 text-xs text-foreground-muted"
|
||||
numberOfLines={1}
|
||||
style={{ fontFamily: MONO_FONT }}
|
||||
>
|
||||
{thread.branch}
|
||||
</Text>
|
||||
) : (
|
||||
<View className="flex-1" />
|
||||
)}
|
||||
{props.providerDriver ? (
|
||||
<View className="opacity-60">
|
||||
<ProviderIcon provider={props.providerDriver} size={14} />
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
</Pressable>
|
||||
) : (
|
||||
<Pressable
|
||||
accessibilityHint={`Opens the thread. Swipe left to ${primaryAction.label.toLowerCase()}.`}
|
||||
accessibilityLabel={thread.title}
|
||||
accessibilityRole="button"
|
||||
className="bg-screen"
|
||||
onPress={() => {
|
||||
close();
|
||||
onSelectThread(thread);
|
||||
}}
|
||||
style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}
|
||||
>
|
||||
{/* Settled history recedes: dimmed favicon + muted title. */}
|
||||
<View className="min-h-[44px] flex-row items-center gap-2.5 px-5 py-2">
|
||||
{props.project ? (
|
||||
<View className="opacity-40">
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
size={15}
|
||||
projectTitle={props.project.title}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
<Text className="flex-1 text-base text-foreground-muted" numberOfLines={1}>
|
||||
{thread.title}
|
||||
</Text>
|
||||
<Text
|
||||
className="text-sm tabular-nums text-foreground-tertiary"
|
||||
style={{ fontFamily: MONO_FONT }}
|
||||
>
|
||||
{relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt)}
|
||||
</Text>
|
||||
</View>
|
||||
</Pressable>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{props.showSettledDivider ? <ThreadListV2SettledDivider /> : null}
|
||||
<ThreadSwipeable
|
||||
backgroundColor={screenColor}
|
||||
enableTrackpadSwipe
|
||||
// Full swipe commits the advertised lifecycle action (Settle /
|
||||
// Un-settle), never the destructive delete.
|
||||
fullSwipeAction="primary"
|
||||
fullSwipeWidth={windowWidth - 32}
|
||||
onDelete={handleDelete}
|
||||
onSwipeableClose={props.onSwipeableClose}
|
||||
onSwipeableWillOpen={props.onSwipeableWillOpen}
|
||||
primaryAction={primaryAction}
|
||||
resetKey={`${thread.environmentId}:${thread.id}`}
|
||||
simultaneousWithExternalGesture={props.simultaneousSwipeGesture}
|
||||
threadTitle={thread.title}
|
||||
>
|
||||
{(close) => (
|
||||
<ControlPillMenu
|
||||
actions={
|
||||
!props.settlementSupported
|
||||
? LEGACY_MENU_ACTIONS
|
||||
: canUnsettle
|
||||
? SLIM_MENU_ACTIONS
|
||||
: CARD_MENU_ACTIONS
|
||||
}
|
||||
onPressAction={handleMenuAction}
|
||||
shouldOpenOnLongPress
|
||||
>
|
||||
{rowContent(close)}
|
||||
</ControlPillMenu>
|
||||
)}
|
||||
</ThreadSwipeable>
|
||||
</>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,220 @@
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
buildThreadListV2Items,
|
||||
resolveThreadListV2Status,
|
||||
sortThreadsForListV2,
|
||||
} from "./threadListV2";
|
||||
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
|
||||
function makeThread(
|
||||
input: Partial<EnvironmentThreadShell> & Pick<EnvironmentThreadShell, "id" | "title">,
|
||||
): EnvironmentThreadShell {
|
||||
return {
|
||||
environmentId,
|
||||
projectId: ProjectId.make("project-1"),
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
};
|
||||
}
|
||||
|
||||
const NOW = "2026-06-02T00:00:00.000Z";
|
||||
|
||||
describe("resolveThreadListV2Status", () => {
|
||||
it("prioritizes approval over a running session", () => {
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("t"),
|
||||
title: "t",
|
||||
hasPendingApprovals: true,
|
||||
session: {
|
||||
threadId: ThreadId.make("t"),
|
||||
status: "running",
|
||||
providerName: "Codex",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: NOW,
|
||||
},
|
||||
});
|
||||
expect(resolveThreadListV2Status(thread)).toBe("approval");
|
||||
});
|
||||
|
||||
it("resolves ready for quiescent threads", () => {
|
||||
expect(resolveThreadListV2Status(makeThread({ id: ThreadId.make("t"), title: "t" }))).toBe(
|
||||
"ready",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sortThreadsForListV2", () => {
|
||||
it("orders by creation time, newest first, ignoring activity", () => {
|
||||
const sorted = sortThreadsForListV2([
|
||||
{ id: "oldest", createdAt: "2026-06-01T08:00:00.000Z" },
|
||||
{ id: "newest", createdAt: "2026-06-01T12:00:00.000Z" },
|
||||
{ id: "middle", createdAt: "2026-06-01T10:00:00.000Z" },
|
||||
]);
|
||||
expect(sorted.map((thread) => thread.id)).toEqual(["newest", "middle", "oldest"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildThreadListV2Items", () => {
|
||||
it("partitions settled threads into a slim tail with one divider", () => {
|
||||
const { items } = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("active"), title: "Active" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("settled"),
|
||||
title: "Settled",
|
||||
settledOverride: "settled",
|
||||
settledAt: NOW,
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("settled-2"),
|
||||
title: "Settled 2",
|
||||
settledOverride: "settled",
|
||||
settledAt: NOW,
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(items.map((item) => [item.thread.id, item.variant])).toEqual([
|
||||
["active", "card"],
|
||||
["settled", "slim"],
|
||||
["settled-2", "slim"],
|
||||
]);
|
||||
expect(items.map((item) => item.showSettledDivider)).toEqual([false, true, false]);
|
||||
expect(items.map((item) => item.isLast)).toEqual([false, false, true]);
|
||||
});
|
||||
|
||||
it("keeps cards in creation order while settled sorts by recency", () => {
|
||||
const { items } = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("older-created"),
|
||||
title: "Older",
|
||||
createdAt: "2026-06-01T08:00:00.000Z",
|
||||
updatedAt: NOW, // recent activity must NOT promote it
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("newer-created"),
|
||||
title: "Newer",
|
||||
createdAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.thread.id)).toEqual(["newer-created", "older-created"]);
|
||||
});
|
||||
|
||||
it("keeps settled threads in the tail and filters by search query", () => {
|
||||
const { items } = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("match"), title: "Fix login bug" }),
|
||||
makeThread({ id: ThreadId.make("miss"), title: "Greeting" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("settled"),
|
||||
title: "Fix login again",
|
||||
settledOverride: "settled",
|
||||
settledAt: NOW,
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "login",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(items.map((item) => [item.thread.id, item.variant])).toEqual([
|
||||
["match", "card"],
|
||||
["settled", "slim"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("scopes the flat list to one project", () => {
|
||||
const otherProjectId = ProjectId.make("project-2");
|
||||
const { items } = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("included"), title: "Included" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("excluded"),
|
||||
projectId: otherProjectId,
|
||||
title: "Excluded",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
projectRef: { environmentId, projectId: ProjectId.make("project-1") },
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.thread.id)).toEqual(["included"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildThreadListV2Items settled paging", () => {
|
||||
it("caps the settled tail at settledLimit and reports the hidden count", () => {
|
||||
const threads = [
|
||||
makeThread({ id: ThreadId.make("active"), title: "Active" }),
|
||||
...Array.from({ length: 4 }, (_, index) =>
|
||||
makeThread({
|
||||
id: ThreadId.make(`settled-${index}`),
|
||||
title: `Settled ${index}`,
|
||||
settledOverride: "settled",
|
||||
settledAt: NOW,
|
||||
latestUserMessageAt: `2026-06-01T0${index}:00:00.000Z`,
|
||||
// A turn adopted the message (same requestedAt): without it the
|
||||
// thread reads as a queued turn start, which never settles.
|
||||
latestTurn: {
|
||||
turnId: TurnId.make(`turn-${index}`),
|
||||
state: "completed",
|
||||
requestedAt: `2026-06-01T0${index}:00:00.000Z`,
|
||||
startedAt: `2026-06-01T0${index}:00:00.000Z`,
|
||||
completedAt: `2026-06-01T0${index}:10:00.000Z`,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
}),
|
||||
),
|
||||
];
|
||||
|
||||
const layout = buildThreadListV2Items({
|
||||
threads,
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
settledLimit: 2,
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(layout.hiddenSettledCount).toBe(2);
|
||||
expect(layout.items.filter((item) => item.variant === "slim")).toHaveLength(2);
|
||||
// Most recent settled first — the hidden ones are the oldest.
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual([
|
||||
"active",
|
||||
"settled-3",
|
||||
"settled-2",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,167 @@
|
||||
import { effectiveSettled } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
|
||||
/**
|
||||
* Thread List v2 model, ported from the web sidebar v2
|
||||
* (apps/web/src/components/Sidebar.logic.ts + SidebarV2.tsx).
|
||||
*
|
||||
* Four visual states, three colors: color is reserved for "act now"
|
||||
* (approval), "in motion" (working), and "broken" (failed). Ready is the
|
||||
* unlabeled resting state.
|
||||
*/
|
||||
export type ThreadListV2Status = "approval" | "input" | "working" | "failed" | "ready";
|
||||
|
||||
export function resolveThreadListV2Status(
|
||||
thread: Pick<EnvironmentThreadShell, "hasPendingApprovals" | "hasPendingUserInput" | "session">,
|
||||
): ThreadListV2Status {
|
||||
if (thread.hasPendingApprovals) {
|
||||
return "approval";
|
||||
}
|
||||
if (thread.hasPendingUserInput) {
|
||||
return "input";
|
||||
}
|
||||
if (thread.session?.status === "running" || thread.session?.status === "starting") {
|
||||
return "working";
|
||||
}
|
||||
if (thread.session?.status === "error") {
|
||||
return "failed";
|
||||
}
|
||||
return "ready";
|
||||
}
|
||||
|
||||
/** NaN-safe Date.parse for sort comparators: a malformed timestamp must not
|
||||
poison the whole ordering, so it sinks to the epoch instead. */
|
||||
function parseTimestampMs(isoDate: string): number {
|
||||
const parsed = Date.parse(isoDate);
|
||||
return Number.isNaN(parsed) ? 0 : parsed;
|
||||
}
|
||||
|
||||
/** First VALID timestamp wins: a present-yet-malformed string falls through
|
||||
to the next candidate rather than sinking the row to the epoch. */
|
||||
function firstValidTimestampMs(...candidates: ReadonlyArray<string | null | undefined>): number {
|
||||
for (const candidate of candidates) {
|
||||
if (candidate == null) continue;
|
||||
const parsed = Date.parse(candidate);
|
||||
if (!Number.isNaN(parsed)) return parsed;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* v2 sort: static creation order, newest thread on top. Activity NEVER
|
||||
* reorders the list — a row holds its position from open until settled, so
|
||||
* the screen only moves at lifecycle transitions. Mirrors web's
|
||||
* sortThreadsForSidebarV2.
|
||||
*/
|
||||
export function sortThreadsForListV2<T extends { readonly id: string; readonly createdAt: string }>(
|
||||
threads: readonly T[],
|
||||
): T[] {
|
||||
// .sort() on a copy, not .toSorted(): Hermes doesn't ship the ES2023
|
||||
// change-by-copy array methods.
|
||||
return [...threads].sort(
|
||||
(left, right) =>
|
||||
parseTimestampMs(right.createdAt) - parseTimestampMs(left.createdAt) ||
|
||||
left.id.localeCompare(right.id),
|
||||
);
|
||||
}
|
||||
|
||||
export interface ThreadListV2Item {
|
||||
readonly thread: EnvironmentThreadShell;
|
||||
readonly variant: "card" | "slim";
|
||||
/** First settled row after the card block draws the SETTLED divider. */
|
||||
readonly showSettledDivider: boolean;
|
||||
readonly isLast: boolean;
|
||||
}
|
||||
|
||||
export interface ThreadListV2Layout {
|
||||
readonly items: ThreadListV2Item[];
|
||||
/** Settled threads beyond the render limit (behind "Show more"). */
|
||||
readonly hiddenSettledCount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Partitions visible threads into the active card block (creation order) and
|
||||
* the settled recency tail, matching the web v2 list. `autoSettleAfterDays`
|
||||
* mirrors the web default of 3 — mobile has no client-settings sync yet, so
|
||||
* the default is fixed here rather than user-configurable.
|
||||
*/
|
||||
export function buildThreadListV2Items(input: {
|
||||
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly projectRef?: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly projectId: ProjectId;
|
||||
} | null;
|
||||
readonly searchQuery: string;
|
||||
/** Per-row PR state reported up by visible rows ("env:threadId" keys). */
|
||||
readonly changeRequestStateByKey?: ReadonlyMap<string, "open" | "closed" | "merged">;
|
||||
/** Environments whose server supports thread.settle/unsettle. Threads on
|
||||
other environments never classify as settled — the user could neither
|
||||
un-settle nor pin them. Absent = no gating (tests). */
|
||||
readonly settlementEnvironmentIds?: ReadonlySet<EnvironmentId>;
|
||||
readonly autoSettleAfterDays?: number;
|
||||
/** Max settled rows to render; the rest are counted, not built. */
|
||||
readonly settledLimit?: number;
|
||||
/** Injectable for tests; defaults to now. */
|
||||
readonly now?: string;
|
||||
}): ThreadListV2Layout {
|
||||
const now = input.now ?? new Date().toISOString();
|
||||
const autoSettleAfterDays = input.autoSettleAfterDays ?? 3;
|
||||
const query = input.searchQuery.trim().toLocaleLowerCase();
|
||||
|
||||
const active: EnvironmentThreadShell[] = [];
|
||||
const settled: EnvironmentThreadShell[] = [];
|
||||
for (const thread of input.threads) {
|
||||
// Callers pass live (unarchived) shells; settled threads are among them
|
||||
// and partition into the tail via effectiveSettled.
|
||||
if (input.environmentId !== null && thread.environmentId !== input.environmentId) continue;
|
||||
if (
|
||||
input.projectRef != null &&
|
||||
(thread.environmentId !== input.projectRef.environmentId ||
|
||||
thread.projectId !== input.projectRef.projectId)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if (query.length > 0 && !thread.title.toLocaleLowerCase().includes(query)) continue;
|
||||
const supportsSettlement = input.settlementEnvironmentIds?.has(thread.environmentId) ?? true;
|
||||
const changeRequestState =
|
||||
input.changeRequestStateByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null;
|
||||
if (
|
||||
supportsSettlement &&
|
||||
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
|
||||
) {
|
||||
settled.push(thread);
|
||||
} else {
|
||||
active.push(thread);
|
||||
}
|
||||
}
|
||||
|
||||
const orderedActive = sortThreadsForListV2(active);
|
||||
const orderedSettled = [...settled].sort(
|
||||
(left, right) =>
|
||||
firstValidTimestampMs(right.latestUserMessageAt, right.updatedAt) -
|
||||
firstValidTimestampMs(left.latestUserMessageAt, left.updatedAt),
|
||||
);
|
||||
const settledLimit = input.settledLimit ?? Number.POSITIVE_INFINITY;
|
||||
const visibleSettled =
|
||||
orderedSettled.length > settledLimit ? orderedSettled.slice(0, settledLimit) : orderedSettled;
|
||||
|
||||
const items: ThreadListV2Item[] = [];
|
||||
for (const thread of orderedActive) {
|
||||
items.push({ thread, variant: "card", showSettledDivider: false, isLast: false });
|
||||
}
|
||||
for (const [index, thread] of visibleSettled.entries()) {
|
||||
items.push({
|
||||
thread,
|
||||
variant: "slim",
|
||||
showSettledDivider: index === 0,
|
||||
isLast: false,
|
||||
});
|
||||
}
|
||||
const last = items.at(-1);
|
||||
if (last) {
|
||||
items[items.length - 1] = { ...last, isLast: true };
|
||||
}
|
||||
return { items, hiddenSettledCount: orderedSettled.length - visibleSettled.length };
|
||||
}
|
||||
@@ -15,6 +15,7 @@ export type ModelOption = {
|
||||
readonly providerKey: string;
|
||||
readonly providerLabel: string;
|
||||
readonly providerDriver: string;
|
||||
readonly isDefault: boolean;
|
||||
readonly capabilities: ModelCapabilities | null;
|
||||
readonly selection: ModelSelection;
|
||||
};
|
||||
@@ -78,6 +79,7 @@ export function buildModelOptions(
|
||||
providerKey: provider.instanceId,
|
||||
providerLabel,
|
||||
providerDriver: provider.driver,
|
||||
isDefault: model.isDefault === true,
|
||||
capabilities: model.capabilities,
|
||||
selection: normalizeSelectionOptions(
|
||||
{
|
||||
@@ -107,6 +109,7 @@ export function buildModelOptions(
|
||||
providerKey: fallbackModelSelection.instanceId,
|
||||
providerLabel,
|
||||
providerDriver: fallbackModelSelection.instanceId,
|
||||
isDefault: false,
|
||||
capabilities: null,
|
||||
selection: fallbackModelSelection,
|
||||
});
|
||||
|
||||
@@ -38,6 +38,8 @@ function makeThread(
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -45,11 +45,15 @@ function makeThread(
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
queuedMessages: [],
|
||||
pendingTurnStart: null,
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -412,6 +416,20 @@ describe("buildThreadFeed", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("appends active work as a normal timeline row", () => {
|
||||
const startedAt = "2026-04-01T00:00:01.000Z";
|
||||
const presented = deriveThreadFeedPresentation([], null, new Set(), new Set(), startedAt);
|
||||
|
||||
expect(presented).toEqual([
|
||||
{
|
||||
type: "working",
|
||||
id: "working-indicator-row",
|
||||
createdAt: startedAt,
|
||||
},
|
||||
]);
|
||||
expect(deriveThreadFeedPresentation(presented, null, new Set())).toEqual([]);
|
||||
});
|
||||
|
||||
it("models work-log overflow as list rows", () => {
|
||||
const activity = (
|
||||
id: string,
|
||||
|
||||
@@ -98,6 +98,11 @@ type RawThreadFeedEntry =
|
||||
|
||||
export type ThreadFeedEntry =
|
||||
| Extract<RawThreadFeedEntry, { type: "message" }>
|
||||
| {
|
||||
readonly type: "working";
|
||||
readonly id: string;
|
||||
readonly createdAt: string;
|
||||
}
|
||||
| {
|
||||
readonly type: "activity-group";
|
||||
readonly id: string;
|
||||
@@ -1105,9 +1110,11 @@ export function deriveThreadFeedPresentation(
|
||||
latestTurn: ThreadFeedLatestTurn | null,
|
||||
expandedTurnIds: ReadonlySet<TurnId>,
|
||||
expandedWorkGroupIds: ReadonlySet<string> = new Set(),
|
||||
activeWorkStartedAt: string | null = null,
|
||||
): ThreadFeedEntry[] {
|
||||
const sourceFeed = feed.filter(
|
||||
(entry) => entry.type !== "turn-fold" && entry.type !== "work-toggle",
|
||||
(entry) =>
|
||||
entry.type !== "turn-fold" && entry.type !== "work-toggle" && entry.type !== "working",
|
||||
);
|
||||
const foldsByAnchorId = deriveThreadFeedTurnFolds(sourceFeed, latestTurn);
|
||||
const collapsedEntryIds = new Set<string>();
|
||||
@@ -1136,12 +1143,19 @@ export function deriveThreadFeedPresentation(
|
||||
appendPresentedFeedEntry(result, entry, expandedWorkGroupIds);
|
||||
}
|
||||
}
|
||||
if (activeWorkStartedAt !== null) {
|
||||
result.push({
|
||||
type: "working",
|
||||
id: "working-indicator-row",
|
||||
createdAt: activeWorkStartedAt,
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function appendPresentedFeedEntry(
|
||||
result: ThreadFeedEntry[],
|
||||
entry: Exclude<ThreadFeedEntry, { readonly type: "turn-fold" | "work-toggle" }>,
|
||||
entry: Exclude<ThreadFeedEntry, { readonly type: "turn-fold" | "work-toggle" | "working" }>,
|
||||
expandedWorkGroupIds: ReadonlySet<string>,
|
||||
): void {
|
||||
if (entry.type !== "activity-group") {
|
||||
|
||||
@@ -22,6 +22,12 @@ export interface Preferences {
|
||||
readonly codeWordBreak?: boolean;
|
||||
readonly connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
|
||||
readonly collapsedProjectGroups?: readonly string[];
|
||||
/**
|
||||
* Device-local mirror of the web beta's `sidebarV2Enabled`. Mobile has no
|
||||
* client-settings sync, so the flat v2 thread list is opted into per
|
||||
* device.
|
||||
*/
|
||||
readonly threadListV2Enabled?: boolean;
|
||||
}
|
||||
|
||||
export class MobilePreferencesLoadError extends Schema.TaggedErrorClass<MobilePreferencesLoadError>()(
|
||||
@@ -71,6 +77,7 @@ function sanitizePreferences(parsed: Preferences): Preferences {
|
||||
codeWordBreak?: boolean;
|
||||
connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
|
||||
collapsedProjectGroups?: readonly string[];
|
||||
threadListV2Enabled?: boolean;
|
||||
} = {};
|
||||
|
||||
if (typeof parsed.liveActivitiesEnabled === "boolean") {
|
||||
@@ -97,6 +104,9 @@ function sanitizePreferences(parsed: Preferences): Preferences {
|
||||
(key): key is string => typeof key === "string",
|
||||
);
|
||||
}
|
||||
if (typeof parsed.threadListV2Enabled === "boolean") {
|
||||
preferences.threadListV2Enabled = parsed.threadListV2Enabled;
|
||||
}
|
||||
return preferences;
|
||||
}
|
||||
|
||||
|
||||
@@ -58,6 +58,8 @@ function threadDetailToShell(
|
||||
createdAt: thread.createdAt,
|
||||
updatedAt: thread.updatedAt,
|
||||
archivedAt: thread.archivedAt,
|
||||
settledOverride: thread.settledOverride,
|
||||
settledAt: thread.settledAt,
|
||||
session: thread.session,
|
||||
latestUserMessageAt: latestUserMessageAt(thread),
|
||||
hasPendingApprovals: false,
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { buildAssetResponseHeaders } from "./assetResponseHeaders.ts";
|
||||
|
||||
describe("buildAssetResponseHeaders", () => {
|
||||
it("forces non-image assets to download without overriding the client filename", () => {
|
||||
expect(buildAssetResponseHeaders({ download: true })).toEqual({
|
||||
"Cache-Control": "private, max-age=3600",
|
||||
"Content-Disposition": "attachment",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not force image assets to download", () => {
|
||||
expect(buildAssetResponseHeaders({ download: false })).toEqual({
|
||||
"Cache-Control": "private, max-age=3600",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,7 +0,0 @@
|
||||
export function buildAssetResponseHeaders(input: { readonly download?: boolean }) {
|
||||
return {
|
||||
"Cache-Control": "private, max-age=3600",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
...(input.download ? { "Content-Disposition": "attachment" } : {}),
|
||||
};
|
||||
}
|
||||
@@ -198,32 +198,6 @@ describe("AssetAccess", () => {
|
||||
expect(yield* resolveAsset(token, "ignored.png")).toEqual({
|
||||
kind: "file",
|
||||
path: attachmentPath,
|
||||
download: false,
|
||||
});
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("marks non-image attachment capabilities for download", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const attachmentId = "thread-1-00000000-0000-4000-8000-000000000002";
|
||||
const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.pdf`);
|
||||
yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
|
||||
yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
|
||||
|
||||
const result = yield* issueAssetUrl({
|
||||
resource: { _tag: "attachment", attachmentId },
|
||||
});
|
||||
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
||||
const separatorIndex = suffix.indexOf("/");
|
||||
const token = suffix.slice(0, separatorIndex);
|
||||
|
||||
expect(yield* resolveAsset(token, "ignored.pdf")).toEqual({
|
||||
kind: "file",
|
||||
path: attachmentPath,
|
||||
download: true,
|
||||
});
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
@@ -36,7 +36,6 @@ import {
|
||||
} from "../auth/utils.ts";
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import { resolveAttachmentPathById } from "../attachmentStore.ts";
|
||||
import { SAFE_IMAGE_FILE_EXTENSIONS } from "../imageMime.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
|
||||
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
|
||||
@@ -92,11 +91,7 @@ const AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema);
|
||||
const decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson);
|
||||
const encodeAssetClaims = Schema.encodeSync(AssetClaimsJson);
|
||||
|
||||
export type ResolvedAsset = {
|
||||
readonly kind: "file";
|
||||
readonly path: string;
|
||||
readonly download?: boolean;
|
||||
};
|
||||
export type ResolvedAsset = { readonly kind: "file"; readonly path: string };
|
||||
|
||||
function decodeClaims(encodedPayload: string): AssetClaims | null {
|
||||
try {
|
||||
@@ -388,17 +383,9 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
|
||||
),
|
||||
Effect.orElseSucceed(() => Option.none()),
|
||||
);
|
||||
if (!Option.isSome(info) || info.value.type !== "File") {
|
||||
return null;
|
||||
}
|
||||
// Non-image attachments are downloaded rather than rendered inline so the
|
||||
// same-origin asset route never interprets uploaded content (e.g. HTML/XML).
|
||||
const extension = attachmentPath.slice(attachmentPath.lastIndexOf(".")).toLowerCase();
|
||||
return {
|
||||
kind: "file",
|
||||
path: attachmentPath,
|
||||
download: !SAFE_IMAGE_FILE_EXTENSIONS.has(extension),
|
||||
} satisfies ResolvedAsset;
|
||||
return Option.isSome(info) && info.value.type === "File"
|
||||
? ({ kind: "file", path: attachmentPath } satisfies ResolvedAsset)
|
||||
: null;
|
||||
}
|
||||
|
||||
if (claims.kind === "project-favicon") {
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as NodePath from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { appendFileAttachmentPromptText } from "./attachmentPrompt.ts";
|
||||
|
||||
const attachmentsDir = NodePath.join(NodePath.sep, "tmp", "t3-attachment-prompt");
|
||||
|
||||
describe("attachmentPrompt", () => {
|
||||
it("appends a prompt line for file attachments", () => {
|
||||
const result = appendFileAttachmentPromptText({
|
||||
text: "hello",
|
||||
attachmentsDir,
|
||||
attachments: [
|
||||
{
|
||||
type: "file",
|
||||
id: "thread-1-00000000-0000-4000-8000-000000000001",
|
||||
name: "notes.txt",
|
||||
mimeType: "text/plain",
|
||||
sizeBytes: 2048,
|
||||
},
|
||||
],
|
||||
});
|
||||
const attachmentPath = NodePath.join(
|
||||
attachmentsDir,
|
||||
"thread-1-00000000-0000-4000-8000-000000000001.txt",
|
||||
);
|
||||
expect(result).toBe(
|
||||
`hello\n\n[Attached file: ${attachmentPath} (notes.txt, text/plain, 2.0 KB). Read it from disk when needed.]`,
|
||||
);
|
||||
});
|
||||
|
||||
it("returns text unchanged when only image attachments are present", () => {
|
||||
expect(
|
||||
appendFileAttachmentPromptText({
|
||||
text: "hello",
|
||||
attachmentsDir,
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "thread-1-00000000-0000-4000-8000-000000000002",
|
||||
name: "screen.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 4,
|
||||
},
|
||||
],
|
||||
}),
|
||||
).toBe("hello");
|
||||
});
|
||||
|
||||
it("returns only the prompt lines when the text is empty", () => {
|
||||
const result = appendFileAttachmentPromptText({
|
||||
text: "",
|
||||
attachmentsDir,
|
||||
attachments: [
|
||||
{
|
||||
type: "file",
|
||||
id: "thread-1-00000000-0000-4000-8000-000000000003",
|
||||
name: "data.csv",
|
||||
mimeType: "text/csv",
|
||||
sizeBytes: 12,
|
||||
},
|
||||
],
|
||||
});
|
||||
const attachmentPath = NodePath.join(
|
||||
attachmentsDir,
|
||||
"thread-1-00000000-0000-4000-8000-000000000003.csv",
|
||||
);
|
||||
expect(result).toBe(
|
||||
`[Attached file: ${attachmentPath} (data.csv, text/csv, 12 B). Read it from disk when needed.]`,
|
||||
);
|
||||
});
|
||||
|
||||
it("strips control characters, brackets, and parentheses from attachment names", () => {
|
||||
const result = appendFileAttachmentPromptText({
|
||||
text: "hello",
|
||||
attachmentsDir,
|
||||
attachments: [
|
||||
{
|
||||
type: "file",
|
||||
id: "thread-1-00000000-0000-4000-8000-000000000004",
|
||||
name: "a(b)\u0001[c].txt",
|
||||
mimeType: "text/plain",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
});
|
||||
const attachmentPath = NodePath.join(
|
||||
attachmentsDir,
|
||||
"thread-1-00000000-0000-4000-8000-000000000004.txt",
|
||||
);
|
||||
expect(result).toBe(
|
||||
`hello\n\n[Attached file: ${attachmentPath} (a b c .txt, text/plain, 5 B). Read it from disk when needed.]`,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,55 +0,0 @@
|
||||
import type { ChatAttachment } from "@t3tools/contracts";
|
||||
|
||||
import { resolveAttachmentPath } from "./attachmentStore.ts";
|
||||
|
||||
const SIZE_LABEL_UNITS = ["B", "KB", "MB"] as const;
|
||||
|
||||
function formatSizeLabel(sizeBytes: number): string {
|
||||
let value = sizeBytes;
|
||||
let unitIndex = 0;
|
||||
while (value >= 1024 && unitIndex < SIZE_LABEL_UNITS.length - 1) {
|
||||
value /= 1024;
|
||||
unitIndex += 1;
|
||||
}
|
||||
const rounded = unitIndex === 0 ? String(value) : value.toFixed(1);
|
||||
return `${rounded} ${SIZE_LABEL_UNITS[unitIndex]}`;
|
||||
}
|
||||
|
||||
function sanitizePromptFileName(name: string): string {
|
||||
// eslint-disable-next-line no-control-regex
|
||||
return name.replace(/[\u0000-\u001f\u007f()[\]]+/gu, " ").trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Non-image attachments are delivered by reference: the file already lives on
|
||||
* the server's disk, so the provider agent reads it with its own tools. Images
|
||||
* keep their native content-block path and are not mentioned here.
|
||||
*/
|
||||
export function appendFileAttachmentPromptText(input: {
|
||||
readonly text: string;
|
||||
readonly attachmentsDir: string;
|
||||
readonly attachments: ReadonlyArray<ChatAttachment>;
|
||||
}): string {
|
||||
const lines: Array<string> = [];
|
||||
for (const attachment of input.attachments) {
|
||||
if (attachment.type !== "file") {
|
||||
continue;
|
||||
}
|
||||
const attachmentPath = resolveAttachmentPath({
|
||||
attachmentsDir: input.attachmentsDir,
|
||||
attachment,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
continue;
|
||||
}
|
||||
const name = sanitizePromptFileName(attachment.name);
|
||||
lines.push(
|
||||
`[Attached file: ${attachmentPath} (${name}, ${attachment.mimeType}, ${formatSizeLabel(attachment.sizeBytes)}). Read it from disk when needed.]`,
|
||||
);
|
||||
}
|
||||
if (lines.length === 0) {
|
||||
return input.text;
|
||||
}
|
||||
const joined = lines.join("\n");
|
||||
return input.text.trim().length > 0 ? `${input.text}\n\n${joined}` : joined;
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import * as NodePath from "node:path";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
attachmentRelativePath,
|
||||
createAttachmentId,
|
||||
parseThreadSegmentFromAttachmentId,
|
||||
resolveAttachmentPathById,
|
||||
@@ -45,37 +44,6 @@ describe("attachmentStore", () => {
|
||||
expect(parseThreadSegmentFromAttachmentId(attachmentId)).toBe("thread-foo");
|
||||
});
|
||||
|
||||
it("builds file attachment relative paths with the inferred file extension", () => {
|
||||
expect(
|
||||
attachmentRelativePath({
|
||||
type: "file",
|
||||
id: "thread-1-00000000-0000-4000-8000-000000000001",
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 5,
|
||||
}),
|
||||
).toBe("thread-1-00000000-0000-4000-8000-000000000001.pdf");
|
||||
});
|
||||
|
||||
it("resolves attachment path by id for a written file attachment extension", () => {
|
||||
const attachmentsDir = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"),
|
||||
);
|
||||
try {
|
||||
const attachmentId = "thread-1-attachment";
|
||||
const pdfPath = NodePath.join(attachmentsDir, `${attachmentId}.pdf`);
|
||||
NodeFS.writeFileSync(pdfPath, Buffer.from("hello"));
|
||||
|
||||
const resolved = resolveAttachmentPathById({
|
||||
attachmentsDir,
|
||||
attachmentId,
|
||||
});
|
||||
expect(resolved).toBe(pdfPath);
|
||||
} finally {
|
||||
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("resolves attachment path by id using the extension that exists on disk", () => {
|
||||
const attachmentsDir = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"),
|
||||
|
||||
@@ -8,16 +8,9 @@ import {
|
||||
normalizeAttachmentRelativePath,
|
||||
resolveAttachmentRelativePath,
|
||||
} from "./attachmentPaths.ts";
|
||||
import {
|
||||
inferFileExtension,
|
||||
inferImageExtension,
|
||||
SAFE_FILE_EXTENSIONS,
|
||||
SAFE_IMAGE_FILE_EXTENSIONS,
|
||||
} from "./imageMime.ts";
|
||||
import { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts";
|
||||
|
||||
const ATTACHMENT_FILENAME_EXTENSIONS = [
|
||||
...new Set([...SAFE_IMAGE_FILE_EXTENSIONS, ...SAFE_FILE_EXTENSIONS, ".bin"]),
|
||||
];
|
||||
const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"];
|
||||
const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;
|
||||
const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*";
|
||||
const ATTACHMENT_ID_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
|
||||
@@ -70,13 +63,6 @@ export function attachmentRelativePath(attachment: ChatAttachment): string {
|
||||
});
|
||||
return `${attachment.id}${extension}`;
|
||||
}
|
||||
case "file": {
|
||||
const extension = inferFileExtension({
|
||||
mimeType: attachment.mimeType,
|
||||
fileName: attachment.name,
|
||||
});
|
||||
return `${attachment.id}${extension}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -136,6 +136,7 @@ export const make = Effect.gen(function* () {
|
||||
capabilities: {
|
||||
repositoryIdentity: true,
|
||||
connectionProbe: true,
|
||||
threadSettlement: true,
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -50,6 +50,8 @@ interface FakeGhScenario {
|
||||
};
|
||||
repositoryCloneUrls?: Record<string, { url: string; sshUrl: string }>;
|
||||
failWith?: GitHubCli.GitHubCliError;
|
||||
/** Let this many gh calls succeed before failWith kicks in (default 0 = fail immediately). */
|
||||
failAfterCalls?: number;
|
||||
}
|
||||
|
||||
function fakeGhOutput(stdout: string): VcsProcess.VcsProcessOutput {
|
||||
@@ -382,7 +384,7 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
const args = [...input.args];
|
||||
ghCalls.push(args.join(" "));
|
||||
|
||||
if (scenario.failWith) {
|
||||
if (scenario.failWith && ghCalls.length > (scenario.failAfterCalls ?? 0)) {
|
||||
return Effect.fail(scenario.failWith);
|
||||
}
|
||||
|
||||
@@ -1336,6 +1338,230 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status keeps the last known PR when a later lookup fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-sticky"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-sticky"]);
|
||||
|
||||
const existingPr = {
|
||||
number: 214,
|
||||
title: "Sticky PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/214",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-sticky",
|
||||
};
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
prListSequence: [JSON.stringify([existingPr])],
|
||||
failWith: new GitHubCli.GitHubCliUnavailableError({
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
cause: new Error("rate limited"),
|
||||
}),
|
||||
failAfterCalls: 1,
|
||||
},
|
||||
});
|
||||
|
||||
const first = yield* manager.status({ cwd: repoDir });
|
||||
expect(first.pr?.number).toBe(214);
|
||||
|
||||
// An explicit invalidation (user refresh, git action) bypasses the PR
|
||||
// cache and forces a live lookup — which now fails. The badge must keep
|
||||
// the last known PR instead of blanking out.
|
||||
yield* manager.invalidateStatus(repoDir);
|
||||
const second = yield* manager.status({ cwd: repoDir });
|
||||
expect(second.pr?.number).toBe(214);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"status does not reuse a stale PR after the branch is retargeted to a different upstream",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-retarget"]);
|
||||
|
||||
const originRemote = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", originRemote]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-retarget"]);
|
||||
|
||||
const existingPr = {
|
||||
number: 214,
|
||||
title: "Sticky PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/214",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-retarget",
|
||||
};
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
prListSequence: [JSON.stringify([existingPr])],
|
||||
failWith: new GitHubCli.GitHubCliUnavailableError({
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
cause: new Error("rate limited"),
|
||||
}),
|
||||
failAfterCalls: 1,
|
||||
},
|
||||
});
|
||||
|
||||
const first = yield* manager.status({ cwd: repoDir });
|
||||
expect(first.pr?.number).toBe(214);
|
||||
|
||||
// Retarget the branch to a different remote/upstream (e.g. the PR was
|
||||
// reopened against a fork). The previously cached PR belonged to the
|
||||
// old upstream and must not be shown against the new one.
|
||||
const forkRemote = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "fork", forkRemote]);
|
||||
yield* runGit(repoDir, ["push", "fork", "feature/pr-retarget"]);
|
||||
yield* runGit(repoDir, [
|
||||
"branch",
|
||||
"--set-upstream-to=fork/feature/pr-retarget",
|
||||
"feature/pr-retarget",
|
||||
]);
|
||||
|
||||
yield* manager.invalidateStatus(repoDir);
|
||||
const second = yield* manager.status({ cwd: repoDir });
|
||||
expect(second.pr).toBeNull();
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status keeps the last known PR when the branch gains its first upstream", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-sticky-first-push"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
|
||||
const existingPr = {
|
||||
number: 215,
|
||||
title: "Sticky first-push PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/215",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-sticky-first-push",
|
||||
};
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
prListSequence: [JSON.stringify([existingPr])],
|
||||
failWith: new GitHubCli.GitHubCliUnavailableError({
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
cause: new Error("rate limited"),
|
||||
}),
|
||||
failAfterCalls: 1,
|
||||
},
|
||||
});
|
||||
|
||||
const first = yield* manager.status({ cwd: repoDir });
|
||||
expect(first.pr?.number).toBe(215);
|
||||
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-sticky-first-push"]);
|
||||
yield* manager.invalidateStatus(repoDir);
|
||||
|
||||
const second = yield* manager.status({ cwd: repoDir });
|
||||
expect(second.pr?.number).toBe(215);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status drops the last known PR when the tracked remote is repointed", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-repointed"]);
|
||||
const originalRemoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", originalRemoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-repointed"]);
|
||||
|
||||
const existingPr = {
|
||||
number: 216,
|
||||
title: "Old remote PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/216",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-repointed",
|
||||
};
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
prListSequence: [JSON.stringify([existingPr])],
|
||||
failWith: new GitHubCli.GitHubCliUnavailableError({
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
cause: new Error("rate limited"),
|
||||
}),
|
||||
failAfterCalls: 1,
|
||||
},
|
||||
});
|
||||
|
||||
const first = yield* manager.status({ cwd: repoDir });
|
||||
expect(first.pr?.number).toBe(216);
|
||||
|
||||
const replacementRemoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "replacement", replacementRemoteDir]);
|
||||
yield* runGit(repoDir, ["push", "replacement", "feature/pr-repointed"]);
|
||||
yield* runGit(repoDir, ["remote", "set-url", "origin", replacementRemoteDir]);
|
||||
yield* manager.invalidateStatus(repoDir);
|
||||
|
||||
const second = yield* manager.status({ cwd: repoDir });
|
||||
expect(second.pr).toBeNull();
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status keeps the last known PR when the current remote URL can't be resolved", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-config-hiccup"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-config-hiccup"]);
|
||||
|
||||
const existingPr = {
|
||||
number: 217,
|
||||
title: "Config hiccup PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/217",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-config-hiccup",
|
||||
};
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
prListSequence: [JSON.stringify([existingPr])],
|
||||
failWith: new GitHubCli.GitHubCliUnavailableError({
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
cause: new Error("rate limited"),
|
||||
}),
|
||||
failAfterCalls: 1,
|
||||
},
|
||||
});
|
||||
|
||||
const first = yield* manager.status({ cwd: repoDir });
|
||||
expect(first.pr?.number).toBe(217);
|
||||
|
||||
// `remote.origin.url` reads go through readConfigValueNullable, which
|
||||
// maps ANY failed read (a real "no remote configured" state or a
|
||||
// transient git-config hiccup) to null the same way. Unsetting the
|
||||
// key here reproduces that ambiguity without touching branch
|
||||
// tracking (refs/remotes/origin/* and branch.<b>.remote are
|
||||
// untouched) — the remote identity has not actually changed, so the
|
||||
// sticky PR must survive even though the current lookup can no
|
||||
// longer resolve a remote URL to compare against.
|
||||
yield* runGit(repoDir, ["config", "--unset", "remote.origin.url"]);
|
||||
yield* manager.invalidateStatus(repoDir);
|
||||
|
||||
const second = yield* manager.status({ cwd: repoDir });
|
||||
expect(second.pr?.number).toBe(217);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates a commit when working tree is dirty", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
import {
|
||||
detectSourceControlProviderFromGitRemoteUrl,
|
||||
mergeGitStatusParts,
|
||||
normalizeGitRemoteUrl,
|
||||
resolveAutoFeatureBranchName,
|
||||
sanitizeBranchFragment,
|
||||
sanitizeFeatureBranchName,
|
||||
@@ -95,6 +96,9 @@ const SHORT_SHA_LENGTH = 7;
|
||||
const TOAST_DESCRIPTION_MAX = 72;
|
||||
const STATUS_RESULT_CACHE_TTL = Duration.seconds(1);
|
||||
const STATUS_RESULT_CACHE_CAPACITY = 2_048;
|
||||
const PR_LOOKUP_CACHE_TTL = Duration.minutes(2);
|
||||
const PR_LOOKUP_FAILURE_TTL = Duration.seconds(20);
|
||||
const PR_LOOKUP_CACHE_CAPACITY = 2_048;
|
||||
type StripProgressContext<T> = T extends any ? Omit<T, "actionId" | "cwd" | "action"> : never;
|
||||
type GitActionProgressPayload = StripProgressContext<GitActionProgressEvent>;
|
||||
type GitActionProgressEmitter = (event: GitActionProgressPayload) => Effect.Effect<void, never>;
|
||||
@@ -142,6 +146,7 @@ interface BranchHeadContext {
|
||||
headSelectors: ReadonlyArray<string>;
|
||||
preferredHeadSelector: string;
|
||||
remoteName: string | null;
|
||||
headRemoteUrlKey: string | null;
|
||||
headRepositoryNameWithOwner: string | null;
|
||||
headRepositoryOwnerLogin: string | null;
|
||||
isCrossRepository: boolean;
|
||||
@@ -768,6 +773,154 @@ export const make = Effect.gen(function* () {
|
||||
normalizeStatusCacheKey(cwd).pipe(
|
||||
Effect.flatMap((cacheKey) => Cache.invalidate(localStatusResultCache, cacheKey)),
|
||||
);
|
||||
// PR lookups hit the hosting provider's API (gh/glab/...), so they refresh
|
||||
// on their own, slower cadence: ahead/behind counts stay fresh on every
|
||||
// status poll while the PR association is re-fetched at most once per
|
||||
// PR_LOOKUP_CACHE_TTL per branch. Git actions and user-driven refreshes bump
|
||||
// the epoch (invalidateStatus) to bypass the cache immediately.
|
||||
const prLookupEpochByCwd = new Map<string, number>();
|
||||
const prLookupEpoch = (cwd: string) => prLookupEpochByCwd.get(cwd) ?? 0;
|
||||
const bumpPrLookupEpoch = (cwd: string) =>
|
||||
normalizeStatusCacheKey(cwd).pipe(
|
||||
Effect.map((cacheKey) => {
|
||||
prLookupEpochByCwd.set(cacheKey, prLookupEpoch(cacheKey) + 1);
|
||||
}),
|
||||
);
|
||||
// Cache keys are NUL-joined [cwd, branch, upstreamRef, epoch] — none of the
|
||||
// segments can contain a NUL byte, and refs are never empty, so "" decodes
|
||||
// back to a null upstreamRef.
|
||||
const prLookupCacheKey = (cwd: string, details: { branch: string; upstreamRef: string | null }) =>
|
||||
[cwd, details.branch, details.upstreamRef ?? "", String(prLookupEpoch(cwd))].join("\u0000");
|
||||
const prLookupCache = yield* Cache.makeWith(
|
||||
(key: string) => {
|
||||
const [cwd = "", branch = "", upstreamRef = ""] = key.split("\u0000");
|
||||
const details = {
|
||||
branch,
|
||||
upstreamRef: upstreamRef.length > 0 ? upstreamRef : null,
|
||||
};
|
||||
return resolveBranchHeadContext(cwd, details).pipe(
|
||||
Effect.flatMap((headContext) =>
|
||||
findLatestPrForHeadContext(cwd, headContext).pipe(
|
||||
Effect.map((latest) => ({ latest, headContext })),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
{
|
||||
capacity: PR_LOOKUP_CACHE_CAPACITY,
|
||||
timeToLive: (exit) => (Exit.isSuccess(exit) ? PR_LOOKUP_CACHE_TTL : PR_LOOKUP_FAILURE_TTL),
|
||||
},
|
||||
);
|
||||
// A transient lookup failure (rate limit, network blip) must not clear an
|
||||
// already-known PR badge, so the last successful answer per branch sticks
|
||||
// around as the fallback. Keep the resolved head context with it so a
|
||||
// branch retargeted to another remote/fork cannot inherit the old badge.
|
||||
interface LastKnownPr {
|
||||
readonly pr: ReturnType<typeof toStatusPr> | null;
|
||||
readonly upstreamRef: string | null;
|
||||
readonly headBranch: string;
|
||||
readonly remoteName: string | null;
|
||||
readonly headRemoteUrlKey: string | null;
|
||||
}
|
||||
const lastKnownPrByBranchKey = new Map<string, LastKnownPr>();
|
||||
const rememberLastKnownPr = (branchKey: string, entry: LastKnownPr) => {
|
||||
if (
|
||||
!lastKnownPrByBranchKey.has(branchKey) &&
|
||||
lastKnownPrByBranchKey.size >= PR_LOOKUP_CACHE_CAPACITY
|
||||
) {
|
||||
const oldestKey = lastKnownPrByBranchKey.keys().next().value;
|
||||
if (oldestKey !== undefined) {
|
||||
lastKnownPrByBranchKey.delete(oldestKey);
|
||||
}
|
||||
}
|
||||
lastKnownPrByBranchKey.set(branchKey, entry);
|
||||
};
|
||||
const resolveLastKnownPr = (
|
||||
branchKey: string,
|
||||
current: Pick<LastKnownPr, "upstreamRef" | "headBranch" | "remoteName" | "headRemoteUrlKey">,
|
||||
): ReturnType<typeof toStatusPr> | null => {
|
||||
const lastKnown = lastKnownPrByBranchKey.get(branchKey);
|
||||
if (!lastKnown) return null;
|
||||
if (lastKnown.headBranch !== current.headBranch) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// The normalized URL catches both remote-alias changes and an existing
|
||||
// alias being repointed. Both sides must be resolved before treating a
|
||||
// mismatch as real: `readConfigValueNullable` swallows any git-config
|
||||
// read failure into `null`, so a transient failure to resolve the
|
||||
// *current* remote URL must read as "unknown", not as "no remote" — the
|
||||
// latter would otherwise drop an already-known PR badge on every hiccup.
|
||||
if (lastKnown.headRemoteUrlKey !== null && current.headRemoteUrlKey !== null) {
|
||||
return lastKnown.headRemoteUrlKey === current.headRemoteUrlKey ? lastKnown.pr : null;
|
||||
}
|
||||
|
||||
// If the remote URL can't be compared, fall back to the remote identity
|
||||
// encoded by tracked branches — same "both sides known" requirement, for
|
||||
// the same reason. A null-to-non-null transition (upstream/remoteName)
|
||||
// is allowed because that is the expected first-push case.
|
||||
if (
|
||||
lastKnown.upstreamRef !== null &&
|
||||
current.upstreamRef !== null &&
|
||||
lastKnown.remoteName !== null &&
|
||||
current.remoteName !== null
|
||||
) {
|
||||
return lastKnown.remoteName === current.remoteName ? lastKnown.pr : null;
|
||||
}
|
||||
return lastKnown.pr;
|
||||
};
|
||||
const lookupStatusPr = Effect.fn("lookupStatusPr")(function* (
|
||||
cwd: string,
|
||||
details: { branch: string; upstreamRef: string | null; isDefaultBranch: boolean },
|
||||
) {
|
||||
// Keyed by (cwd, branch) only: the upstream ref changing (e.g. a first
|
||||
// `push -u`) must not orphan the fallback value for the same branch.
|
||||
const branchKey = `${cwd}\u0000${details.branch}`;
|
||||
return yield* Cache.get(prLookupCache, prLookupCacheKey(cwd, details)).pipe(
|
||||
Effect.map(({ latest, headContext }) => {
|
||||
if (!latest) return { pr: null, headContext };
|
||||
// On the default branch, only surface open PRs.
|
||||
// Merged/closed matches are usually reverse-merge history, not the thread's PR context.
|
||||
if (details.isDefaultBranch && latest.state !== "open") {
|
||||
return { pr: null, headContext };
|
||||
}
|
||||
return { pr: toStatusPr(latest), headContext };
|
||||
}),
|
||||
Effect.tap(({ pr, headContext }) =>
|
||||
Effect.sync(() =>
|
||||
rememberLastKnownPr(branchKey, {
|
||||
pr,
|
||||
upstreamRef: details.upstreamRef,
|
||||
headBranch: headContext.headBranch,
|
||||
remoteName: headContext.remoteName,
|
||||
headRemoteUrlKey: headContext.headRemoteUrlKey,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.map(({ pr }) => pr),
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("PR lookup failed; keeping last known PR state.").pipe(
|
||||
Effect.annotateLogs({
|
||||
operation: "lookupStatusPr",
|
||||
branch: details.branch,
|
||||
errorTag:
|
||||
typeof error === "object" && error !== null && "_tag" in error
|
||||
? String(error._tag)
|
||||
: typeof error,
|
||||
}),
|
||||
Effect.andThen(resolveBranchHeadContext(cwd, details)),
|
||||
Effect.map((headContext) =>
|
||||
resolveLastKnownPr(branchKey, {
|
||||
upstreamRef: details.upstreamRef,
|
||||
headBranch: headContext.headBranch,
|
||||
remoteName: headContext.remoteName,
|
||||
headRemoteUrlKey: headContext.headRemoteUrlKey,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
const readRemoteStatus = Effect.fn("readRemoteStatus")(function* (
|
||||
cwd: string,
|
||||
options?: GitVcsDriver.GitRemoteStatusOptions,
|
||||
@@ -781,19 +934,11 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const pr =
|
||||
details.branch !== null
|
||||
? yield* findLatestPr(cwd, {
|
||||
? yield* lookupStatusPr(cwd, {
|
||||
branch: details.branch,
|
||||
upstreamRef: details.upstreamRef,
|
||||
}).pipe(
|
||||
Effect.map((latest) => {
|
||||
if (!latest) return null;
|
||||
// On the default branch, only surface open PRs.
|
||||
// Merged/closed matches are usually reverse-merge history, not the thread's PR context.
|
||||
if (details.isDefaultBranch && latest.state !== "open") return null;
|
||||
return toStatusPr(latest);
|
||||
}),
|
||||
Effect.orElseSucceed(() => null),
|
||||
)
|
||||
isDefaultBranch: details.isDefaultBranch,
|
||||
})
|
||||
: null;
|
||||
|
||||
return {
|
||||
@@ -837,6 +982,7 @@ export const make = Effect.gen(function* () {
|
||||
) {
|
||||
if (!remoteName) {
|
||||
return {
|
||||
remoteUrlKey: null,
|
||||
repositoryNameWithOwner: null,
|
||||
ownerLogin: null,
|
||||
};
|
||||
@@ -845,6 +991,7 @@ export const make = Effect.gen(function* () {
|
||||
const remoteUrl = yield* readConfigValueNullable(cwd, `remote.${remoteName}.url`);
|
||||
const repositoryNameWithOwner = parseGitHubRepositoryNameWithOwnerFromRemoteUrl(remoteUrl);
|
||||
return {
|
||||
remoteUrlKey: remoteUrl ? normalizeGitRemoteUrl(remoteUrl) : null,
|
||||
repositoryNameWithOwner,
|
||||
ownerLogin: parseRepositoryOwnerLogin(repositoryNameWithOwner),
|
||||
};
|
||||
@@ -915,6 +1062,9 @@ export const make = Effect.gen(function* () {
|
||||
preferredHeadSelector:
|
||||
ownerHeadSelector && isCrossRepository ? ownerHeadSelector : headBranch,
|
||||
remoteName,
|
||||
headRemoteUrlKey:
|
||||
remoteRepository.remoteUrlKey ??
|
||||
(remoteName === null ? originRepository.remoteUrlKey : null),
|
||||
headRepositoryNameWithOwner: remoteRepository.repositoryNameWithOwner,
|
||||
headRepositoryOwnerLogin: remoteRepository.ownerLogin,
|
||||
isCrossRepository,
|
||||
@@ -960,11 +1110,10 @@ export const make = Effect.gen(function* () {
|
||||
return null;
|
||||
});
|
||||
|
||||
const findLatestPr = Effect.fn("findLatestPr")(function* (
|
||||
const findLatestPrForHeadContext = Effect.fn("findLatestPrForHeadContext")(function* (
|
||||
cwd: string,
|
||||
details: { branch: string; upstreamRef: string | null },
|
||||
headContext: BranchHeadContext,
|
||||
) {
|
||||
const headContext = yield* resolveBranchHeadContext(cwd, details);
|
||||
const parsedByNumber = new Map<number, PullRequestInfo>();
|
||||
|
||||
for (const headSelector of headContext.headSelectors) {
|
||||
@@ -991,7 +1140,6 @@ export const make = Effect.gen(function* () {
|
||||
}
|
||||
return parsed[0] ?? null;
|
||||
});
|
||||
|
||||
const buildCompletionToast = Effect.fn("buildCompletionToast")(function* (
|
||||
cwd: string,
|
||||
result: Pick<GitRunStackedActionResult, "action" | "branch" | "commit" | "push" | "pr">,
|
||||
@@ -1442,6 +1590,10 @@ export const make = Effect.gen(function* () {
|
||||
function* (cwd) {
|
||||
yield* invalidateLocalStatusResultCache(cwd);
|
||||
yield* invalidateRemoteStatusResultCache(cwd);
|
||||
// Full invalidation is the explicit-freshness path (git actions, user
|
||||
// refresh); it also bypasses the slow PR-lookup cache. The periodic
|
||||
// status poll only invalidates local/remote and keeps the PR cache warm.
|
||||
yield* bumpPrLookupEpoch(cwd);
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -25,7 +25,6 @@ import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
|
||||
import { OtlpTracer } from "effect/unstable/observability";
|
||||
|
||||
import * as ServerConfig from "./config.ts";
|
||||
import { buildAssetResponseHeaders } from "./assetResponseHeaders.ts";
|
||||
import { ASSET_ROUTE_PREFIX, resolveAsset } from "./assets/AssetAccess.ts";
|
||||
import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
|
||||
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
|
||||
@@ -195,7 +194,10 @@ export const assetRouteLayer = HttpRouter.add(
|
||||
}
|
||||
return yield* HttpServerResponse.file(asset.path, {
|
||||
status: 200,
|
||||
headers: buildAssetResponseHeaders(asset),
|
||||
headers: {
|
||||
"Cache-Control": "private, max-age=3600",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
},
|
||||
}).pipe(
|
||||
Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
|
||||
);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { inferFileExtension, inferImageExtension, parseBase64DataUrl } from "./imageMime.ts";
|
||||
import { inferImageExtension, parseBase64DataUrl } from "./imageMime.ts";
|
||||
|
||||
describe("imageMime", () => {
|
||||
it("parses base64 data URL with mime type", () => {
|
||||
@@ -92,39 +92,4 @@ describe("imageMime", () => {
|
||||
it("does not read inherited keys from mime extension map", () => {
|
||||
expect(inferImageExtension({ mimeType: "constructor" })).toBe(".bin");
|
||||
});
|
||||
|
||||
it("infers file extension from an allowlisted file name extension", () => {
|
||||
expect(
|
||||
inferFileExtension({ mimeType: "application/octet-stream", fileName: "report.PDF" }),
|
||||
).toBe(".pdf");
|
||||
});
|
||||
|
||||
it("infers file extension from the last segment of a multi-dot file name", () => {
|
||||
expect(inferFileExtension({ mimeType: "application/octet-stream", fileName: "a.b.csv" })).toBe(
|
||||
".csv",
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to an allowlisted mime extension when the file name extension is unsafe", () => {
|
||||
expect(inferFileExtension({ mimeType: "application/pdf", fileName: "notes.exe" })).toBe(".pdf");
|
||||
});
|
||||
|
||||
it("falls back to an allowlisted mime extension when the file name has no extension", () => {
|
||||
expect(inferFileExtension({ mimeType: "text/plain", fileName: "notes" })).toBe(".txt");
|
||||
});
|
||||
|
||||
it("defaults file extension to .bin when neither file name nor mime is allowlisted", () => {
|
||||
expect(inferFileExtension({ mimeType: "application/x-unknown", fileName: "payload.exe" })).toBe(
|
||||
".bin",
|
||||
);
|
||||
expect(inferFileExtension({ mimeType: "application/x-unknown", fileName: "notes" })).toBe(
|
||||
".bin",
|
||||
);
|
||||
});
|
||||
|
||||
it("defaults dotfile names without an allowlisted mime to .bin", () => {
|
||||
expect(inferFileExtension({ mimeType: "application/x-unknown", fileName: ".env" })).toBe(
|
||||
".bin",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -112,48 +112,6 @@ export function parseBase64DataUrl(
|
||||
return { mimeType, base64 };
|
||||
}
|
||||
|
||||
export const SAFE_FILE_EXTENSIONS = new Set([
|
||||
".csv",
|
||||
".diff",
|
||||
".docx",
|
||||
".gz",
|
||||
".json",
|
||||
".jsonl",
|
||||
".log",
|
||||
".md",
|
||||
".patch",
|
||||
".pdf",
|
||||
".pptx",
|
||||
".tar",
|
||||
".toml",
|
||||
".tsv",
|
||||
".txt",
|
||||
".xlsx",
|
||||
".xml",
|
||||
".yaml",
|
||||
".yml",
|
||||
".zip",
|
||||
]);
|
||||
|
||||
export function inferFileExtension(input: { mimeType: string; fileName?: string }): string {
|
||||
const fileName = input.fileName?.trim() ?? "";
|
||||
const extensionMatch = /\.([a-z0-9]{1,8})$/i.exec(fileName);
|
||||
const fileNameExtension = extensionMatch ? `.${extensionMatch[1]!.toLowerCase()}` : "";
|
||||
if (SAFE_FILE_EXTENSIONS.has(fileNameExtension)) {
|
||||
return fileNameExtension;
|
||||
}
|
||||
|
||||
// Mime.getExtension returns dot-less extensions ("pdf"), the sets hold
|
||||
// dotted ones (".pdf").
|
||||
const fromMimeExtension = Mime.getExtension(input.mimeType);
|
||||
const dottedMimeExtension = fromMimeExtension ? `.${fromMimeExtension}` : null;
|
||||
if (dottedMimeExtension && SAFE_FILE_EXTENSIONS.has(dottedMimeExtension)) {
|
||||
return dottedMimeExtension;
|
||||
}
|
||||
|
||||
return ".bin";
|
||||
}
|
||||
|
||||
export function inferImageExtension(input: { mimeType: string; fileName?: string }): string {
|
||||
const key = input.mimeType.toLowerCase();
|
||||
const fromMime = Object.hasOwn(IMAGE_EXTENSION_BY_MIME_TYPE, key)
|
||||
|
||||
@@ -146,8 +146,12 @@ describe("OrchestrationEngine", () => {
|
||||
createdAt: "2026-03-03T00:00:02.000Z",
|
||||
updatedAt: "2026-03-03T00:00:03.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
queuedMessages: [],
|
||||
pendingTurnStart: null,
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
@@ -160,6 +164,8 @@ describe("OrchestrationEngine", () => {
|
||||
threads: projectionSnapshot.threads.map((thread) => ({
|
||||
...thread,
|
||||
messages: [],
|
||||
queuedMessages: [],
|
||||
pendingTurnStart: null,
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
|
||||
@@ -171,6 +171,70 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
for (const row of stateRows) {
|
||||
assert.equal(row.lastAppliedSequence, 3);
|
||||
}
|
||||
|
||||
// Settled lifecycle through the DB pipeline: thread.settled writes the
|
||||
// override + timestamp, thread.unsettled(user) flips to the active pin.
|
||||
yield* eventStore.append({
|
||||
type: "thread.settled",
|
||||
eventId: EventId.make("evt-settle-1"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-1"),
|
||||
occurredAt: "2026-01-01T00:00:01.000Z",
|
||||
commandId: CommandId.make("cmd-settle-1"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("cmd-settle-1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
settledAt: "2026-01-01T00:00:01.000Z",
|
||||
updatedAt: "2026-01-01T00:00:01.000Z",
|
||||
},
|
||||
});
|
||||
yield* projectionPipeline.bootstrap;
|
||||
|
||||
const settledRows = yield* sql<{
|
||||
readonly settledOverride: string | null;
|
||||
readonly settledAt: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = 'thread-1'
|
||||
`;
|
||||
assert.deepEqual(settledRows, [
|
||||
{ settledOverride: "settled", settledAt: "2026-01-01T00:00:01.000Z" },
|
||||
]);
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "thread.unsettled",
|
||||
eventId: EventId.make("evt-unsettle-1"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-1"),
|
||||
occurredAt: "2026-01-01T00:00:02.000Z",
|
||||
commandId: CommandId.make("cmd-unsettle-1"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("cmd-unsettle-1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
reason: "user",
|
||||
updatedAt: "2026-01-01T00:00:02.000Z",
|
||||
},
|
||||
});
|
||||
yield* projectionPipeline.bootstrap;
|
||||
|
||||
const unsettledRows = yield* sql<{
|
||||
readonly settledOverride: string | null;
|
||||
readonly settledAt: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = 'thread-1'
|
||||
`;
|
||||
assert.deepEqual(unsettledRows, [{ settledOverride: "active", settledAt: null }]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -928,214 +992,6 @@ it.layer(
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(
|
||||
Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-attachments-file-gc-")),
|
||||
)("OrchestrationProjectionPipeline", (it) => {
|
||||
it.effect("keeps referenced file attachments and prunes orphans when a thread is reverted", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const { attachmentsDir } = yield* ServerConfig;
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const threadId = ThreadId.make("Thread Revert.Docs");
|
||||
const keepAttachmentId = "thread-revert-docs-00000000-0000-4000-8000-000000000001";
|
||||
const removeAttachmentId = "thread-revert-docs-00000000-0000-4000-8000-000000000002";
|
||||
const orphanAttachmentId = "thread-revert-docs-00000000-0000-4000-8000-000000000003";
|
||||
|
||||
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
|
||||
eventStore
|
||||
.append(event)
|
||||
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "project.created",
|
||||
eventId: EventId.make("evt-revert-docs-1"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: ProjectId.make("project-revert-docs"),
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-revert-docs-1"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-revert-docs-1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: ProjectId.make("project-revert-docs"),
|
||||
title: "Project Revert Docs",
|
||||
workspaceRoot: "/tmp/project-revert-docs",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.created",
|
||||
eventId: EventId.make("evt-revert-docs-2"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-revert-docs-2"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-revert-docs-2"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
projectId: ProjectId.make("project-revert-docs"),
|
||||
title: "Thread Revert Docs",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.turn-diff-completed",
|
||||
eventId: EventId.make("evt-revert-docs-3"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-revert-docs-3"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-revert-docs-3"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
turnId: TurnId.make("turn-keep"),
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-revert-docs/turn/1"),
|
||||
status: "ready",
|
||||
files: [],
|
||||
assistantMessageId: MessageId.make("message-keep"),
|
||||
completedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.message-sent",
|
||||
eventId: EventId.make("evt-revert-docs-4"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-revert-docs-4"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-revert-docs-4"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
messageId: MessageId.make("message-keep"),
|
||||
role: "assistant",
|
||||
text: "Keep",
|
||||
attachments: [
|
||||
{
|
||||
type: "file",
|
||||
id: keepAttachmentId,
|
||||
name: "keep.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
turnId: TurnId.make("turn-keep"),
|
||||
streaming: false,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.turn-diff-completed",
|
||||
eventId: EventId.make("evt-revert-docs-5"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-revert-docs-5"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-revert-docs-5"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
turnId: TurnId.make("turn-remove"),
|
||||
checkpointTurnCount: 2,
|
||||
checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-revert-docs/turn/2"),
|
||||
status: "ready",
|
||||
files: [],
|
||||
assistantMessageId: MessageId.make("message-remove"),
|
||||
completedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.message-sent",
|
||||
eventId: EventId.make("evt-revert-docs-6"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-revert-docs-6"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-revert-docs-6"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
messageId: MessageId.make("message-remove"),
|
||||
role: "assistant",
|
||||
text: "Remove",
|
||||
attachments: [
|
||||
{
|
||||
type: "file",
|
||||
id: removeAttachmentId,
|
||||
name: "remove.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
turnId: TurnId.make("turn-remove"),
|
||||
streaming: false,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
const keepPath = path.join(attachmentsDir, `${keepAttachmentId}.pdf`);
|
||||
const removePath = path.join(attachmentsDir, `${removeAttachmentId}.pdf`);
|
||||
const orphanPath = path.join(attachmentsDir, `${orphanAttachmentId}.pdf`);
|
||||
yield* fileSystem.makeDirectory(attachmentsDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(keepPath, "keep");
|
||||
yield* fileSystem.writeFileString(removePath, "remove");
|
||||
yield* fileSystem.writeFileString(orphanPath, "orphan");
|
||||
assert.isTrue(yield* exists(keepPath));
|
||||
assert.isTrue(yield* exists(removePath));
|
||||
assert.isTrue(yield* exists(orphanPath));
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.reverted",
|
||||
eventId: EventId.make("evt-revert-docs-7"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-revert-docs-7"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-revert-docs-7"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
turnCount: 1,
|
||||
},
|
||||
});
|
||||
|
||||
assert.isTrue(yield* exists(keepPath));
|
||||
assert.isFalse(yield* exists(removePath));
|
||||
assert.isFalse(yield* exists(orphanPath));
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-attachments-revert-")))(
|
||||
"OrchestrationProjectionPipeline",
|
||||
(it) => {
|
||||
@@ -2608,6 +2464,74 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(makeProjectionPipelinePrefixedTestLayer("t3-pending-turn-terminal-test-"))(
|
||||
"OrchestrationProjectionPipeline pending turn cleanup",
|
||||
(it) => {
|
||||
it.effect("clears pending turn starts when startup reaches a terminal session state", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
for (const [index, status] of (["error", "interrupted", "stopped"] as const).entries()) {
|
||||
const threadId = ThreadId.make(`thread-terminal-${status}`);
|
||||
const requestedAt = `2026-02-26T14:00:0${index}.000Z`;
|
||||
yield* eventStore.append({
|
||||
type: "thread.turn-start-requested",
|
||||
eventId: EventId.make(`evt-terminal-pending-${status}`),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: requestedAt,
|
||||
commandId: CommandId.make(`cmd-terminal-pending-${status}`),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make(`cmd-terminal-pending-${status}`),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
messageId: MessageId.make(`message-terminal-${status}`),
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: requestedAt,
|
||||
},
|
||||
});
|
||||
yield* eventStore.append({
|
||||
type: "thread.session-set",
|
||||
eventId: EventId.make(`evt-terminal-session-${status}`),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: requestedAt,
|
||||
commandId: CommandId.make(`cmd-terminal-session-${status}`),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make(`cmd-terminal-session-${status}`),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status,
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: status === "error" ? "startup failed" : null,
|
||||
updatedAt: requestedAt,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
yield* projectionPipeline.bootstrap;
|
||||
|
||||
const pendingRows = yield* sql<{ readonly threadId: string }>`
|
||||
SELECT thread_id AS "threadId"
|
||||
FROM projection_turns
|
||||
WHERE turn_id IS NULL
|
||||
AND state = 'pending'
|
||||
`;
|
||||
assert.deepEqual(pendingRows, []);
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.effect("restores pending turn-start metadata across projection pipeline restart", () =>
|
||||
Effect.gen(function* () {
|
||||
const { dbPath } = yield* ServerConfig;
|
||||
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
type ProjectionThreadProposedPlan,
|
||||
ProjectionThreadProposedPlanRepository,
|
||||
} from "../../persistence/Services/ProjectionThreadProposedPlans.ts";
|
||||
import { ProjectionQueuedMessageRepository } from "../../persistence/Services/ProjectionQueuedMessages.ts";
|
||||
import { ProjectionThreadSessionRepository } from "../../persistence/Services/ProjectionThreadSessions.ts";
|
||||
import {
|
||||
type ProjectionTurn,
|
||||
@@ -40,6 +41,7 @@ import { ProjectionStateRepositoryLive } from "../../persistence/Layers/Projecti
|
||||
import { ProjectionThreadActivityRepositoryLive } from "../../persistence/Layers/ProjectionThreadActivities.ts";
|
||||
import { ProjectionThreadMessageRepositoryLive } from "../../persistence/Layers/ProjectionThreadMessages.ts";
|
||||
import { ProjectionThreadProposedPlanRepositoryLive } from "../../persistence/Layers/ProjectionThreadProposedPlans.ts";
|
||||
import { ProjectionQueuedMessageRepositoryLive } from "../../persistence/Layers/ProjectionQueuedMessages.ts";
|
||||
import { ProjectionThreadSessionRepositoryLive } from "../../persistence/Layers/ProjectionThreadSessions.ts";
|
||||
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
|
||||
import { ProjectionThreadRepositoryLive } from "../../persistence/Layers/ProjectionThreads.ts";
|
||||
@@ -59,6 +61,7 @@ export const ORCHESTRATION_PROJECTOR_NAMES = {
|
||||
projects: "projection.projects",
|
||||
threads: "projection.threads",
|
||||
threadMessages: "projection.thread-messages",
|
||||
queuedMessages: "projection.queued-messages",
|
||||
threadProposedPlans: "projection.thread-proposed-plans",
|
||||
threadActivities: "projection.thread-activities",
|
||||
threadSessions: "projection.thread-sessions",
|
||||
@@ -329,7 +332,7 @@ function retainProjectionProposedPlansAfterRevert(
|
||||
|
||||
function collectThreadAttachmentRelativePaths(
|
||||
threadId: string,
|
||||
messages: ReadonlyArray<ProjectionThreadMessage>,
|
||||
messages: ReadonlyArray<Pick<ProjectionThreadMessage, "attachments">>,
|
||||
): Set<string> {
|
||||
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||
if (!threadSegment) {
|
||||
@@ -338,6 +341,9 @@ function collectThreadAttachmentRelativePaths(
|
||||
const relativePaths = new Set<string>();
|
||||
for (const message of messages) {
|
||||
for (const attachment of message.attachments ?? []) {
|
||||
if (attachment.type !== "image") {
|
||||
continue;
|
||||
}
|
||||
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachment.id);
|
||||
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
|
||||
continue;
|
||||
@@ -473,6 +479,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
const projectionThreadRepository = yield* ProjectionThreadRepository;
|
||||
const projectionThreadMessageRepository = yield* ProjectionThreadMessageRepository;
|
||||
const projectionThreadProposedPlanRepository = yield* ProjectionThreadProposedPlanRepository;
|
||||
const projectionQueuedMessageRepository = yield* ProjectionQueuedMessageRepository;
|
||||
const projectionThreadActivityRepository = yield* ProjectionThreadActivityRepository;
|
||||
const projectionThreadSessionRepository = yield* ProjectionThreadSessionRepository;
|
||||
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
||||
@@ -604,6 +611,8 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
createdAt: event.payload.createdAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
@@ -642,6 +651,38 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.settled": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
settledOverride: "settled",
|
||||
settledAt: event.payload.settledAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.unsettled": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
settledOverride: event.payload.reason === "user" ? "active" : null,
|
||||
settledAt: null,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.meta-updated": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
@@ -711,6 +752,8 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
}
|
||||
|
||||
case "thread.message-sent":
|
||||
case "thread.message-queued":
|
||||
case "thread.queued-message-removed":
|
||||
case "thread.proposed-plan-upserted":
|
||||
case "thread.activity-appended":
|
||||
case "thread.approval-response-requested":
|
||||
@@ -871,9 +914,17 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
yield* Effect.forEach(keptRows, projectionThreadMessageRepository.upsert, {
|
||||
concurrency: 1,
|
||||
}).pipe(Effect.asVoid);
|
||||
// Queued messages survive a revert (they are not part of the
|
||||
// timeline), so their attachment files must survive pruning too.
|
||||
const queuedRows = yield* projectionQueuedMessageRepository.listByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
attachmentSideEffects.prunedThreadRelativePaths.set(
|
||||
event.payload.threadId,
|
||||
collectThreadAttachmentRelativePaths(event.payload.threadId, keptRows),
|
||||
collectThreadAttachmentRelativePaths(event.payload.threadId, [
|
||||
...keptRows,
|
||||
...queuedRows,
|
||||
]),
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -883,6 +934,67 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
}
|
||||
});
|
||||
|
||||
const applyQueuedMessagesProjection: ProjectorDefinition["apply"] = Effect.fn(
|
||||
"applyQueuedMessagesProjection",
|
||||
)(function* (event, attachmentSideEffects) {
|
||||
switch (event.type) {
|
||||
case "thread.message-queued":
|
||||
yield* projectionQueuedMessageRepository.upsert({
|
||||
messageId: event.payload.messageId,
|
||||
threadId: event.payload.threadId,
|
||||
text: event.payload.text,
|
||||
attachments: event.payload.attachments,
|
||||
modelSelection: event.payload.modelSelection ?? null,
|
||||
sourceProposedPlanThreadId: event.payload.sourceProposedPlan?.threadId ?? null,
|
||||
sourceProposedPlanId: event.payload.sourceProposedPlan?.planId ?? null,
|
||||
queuedAt: event.payload.queuedAt,
|
||||
});
|
||||
return;
|
||||
|
||||
case "thread.queued-message-removed": {
|
||||
// A user removal orphans the removed message's attachment files —
|
||||
// prune to what the timeline and remaining queue still reference.
|
||||
// Dispatch removals keep everything: the same attachments re-enter
|
||||
// the timeline via the paired thread.message-sent.
|
||||
const removedQueuedMessage =
|
||||
event.payload.reason === "user"
|
||||
? (yield* projectionQueuedMessageRepository.listByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
})).find((entry) => entry.messageId === event.payload.messageId)
|
||||
: undefined;
|
||||
yield* projectionQueuedMessageRepository.deleteByMessageId({
|
||||
threadId: event.payload.threadId,
|
||||
messageId: event.payload.messageId,
|
||||
});
|
||||
if (removedQueuedMessage && (removedQueuedMessage.attachments?.length ?? 0) > 0) {
|
||||
const retainedMessageRows = yield* projectionThreadMessageRepository.listByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
const retainedQueuedRows = yield* projectionQueuedMessageRepository.listByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
attachmentSideEffects.prunedThreadRelativePaths.set(
|
||||
event.payload.threadId,
|
||||
collectThreadAttachmentRelativePaths(event.payload.threadId, [
|
||||
...retainedMessageRows,
|
||||
...retainedQueuedRows,
|
||||
]),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.deleted":
|
||||
yield* projectionQueuedMessageRepository.deleteByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
return;
|
||||
|
||||
default:
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadProposedPlansProjection: ProjectorDefinition["apply"] = Effect.fn(
|
||||
"applyThreadProposedPlansProjection",
|
||||
)(function* (event, _attachmentSideEffects) {
|
||||
@@ -1026,6 +1138,18 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
// settle still-running turns so their duration reflects the whole
|
||||
// turn rather than the last assistant message.
|
||||
const settledTurnState = settledTurnStateForSessionStatus(event.payload.session.status);
|
||||
// Any settled status abandons an unadopted pending turn start —
|
||||
// including "ready": a mid-turn steer re-arms the pending row
|
||||
// without a fresh adoption, and a stale row would block queue
|
||||
// drains (and re-arm the read model's pendingTurnStart flag on
|
||||
// restart hydration). Ready-with-genuinely-pending starts never
|
||||
// reach this projection: ingestion maps that shape to
|
||||
// "starting" before dispatching the session set.
|
||||
if (settledTurnState !== null) {
|
||||
yield* projectionTurnRepository.deletePendingTurnStartByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
}
|
||||
if (settledTurnState === null) {
|
||||
return;
|
||||
}
|
||||
@@ -1461,6 +1585,14 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.projects,
|
||||
apply: applyProjectsProjection,
|
||||
},
|
||||
// queuedMessages must bootstrap before threadMessages: the revert
|
||||
// handler in threadMessages reads the queued-message projection to
|
||||
// retain queued attachments, so on replay that table has to be
|
||||
// populated first or the prune deletes files still referenced.
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.queuedMessages,
|
||||
apply: applyQueuedMessagesProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadMessages,
|
||||
apply: applyThreadMessagesProjection,
|
||||
@@ -1591,6 +1723,7 @@ export const OrchestrationProjectionPipelineLive = Layer.effect(
|
||||
Layer.provideMerge(ProjectionThreadRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadMessageRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadProposedPlanRepositoryLive),
|
||||
Layer.provideMerge(ProjectionQueuedMessageRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadActivityRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadSessionRepositoryLive),
|
||||
Layer.provideMerge(ProjectionTurnRepositoryLive),
|
||||
|
||||
@@ -308,6 +308,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
createdAt: "2026-02-24T00:00:02.000Z",
|
||||
updatedAt: "2026-02-24T00:00:03.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
messages: [
|
||||
{
|
||||
@@ -320,6 +322,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
updatedAt: "2026-02-24T00:00:05.000Z",
|
||||
},
|
||||
],
|
||||
queuedMessages: [],
|
||||
pendingTurnStart: null,
|
||||
proposedPlans: [
|
||||
{
|
||||
id: "plan-1",
|
||||
@@ -418,6 +422,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
createdAt: "2026-02-24T00:00:02.000Z",
|
||||
updatedAt: "2026-02-24T00:00:03.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "running",
|
||||
@@ -562,6 +568,115 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps settled threads in the shell snapshot with non-null settlement fields", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`DELETE FROM projection_projects`;
|
||||
yield* sql`DELETE FROM projection_threads`;
|
||||
yield* sql`DELETE FROM projection_state`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_projects (
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model_selection_json,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'project-settled-test',
|
||||
'Settled Test',
|
||||
'/tmp/settled-test',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'[]',
|
||||
'2026-04-06T00:00:00.000Z',
|
||||
'2026-04-06T00:00:01.000Z',
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_threads (
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
has_actionable_proposed_plan,
|
||||
created_at,
|
||||
updated_at,
|
||||
archived_at,
|
||||
settled_override,
|
||||
settled_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'thread-settled',
|
||||
'project-settled-test',
|
||||
'Settled Thread',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'full-access',
|
||||
'default',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
'2026-04-06T00:00:02.000Z',
|
||||
'2026-04-06T00:00:05.000Z',
|
||||
NULL,
|
||||
'settled',
|
||||
'2026-04-06T00:00:04.000Z',
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_state (projector, last_applied_sequence, updated_at)
|
||||
VALUES
|
||||
(${ORCHESTRATION_PROJECTOR_NAMES.projects}, 4, '2026-04-06T00:00:07.000Z'),
|
||||
(${ORCHESTRATION_PROJECTOR_NAMES.threads}, 4, '2026-04-06T00:00:07.000Z'),
|
||||
(${ORCHESTRATION_PROJECTOR_NAMES.threadMessages}, 4, '2026-04-06T00:00:07.000Z'),
|
||||
(${ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans}, 4, '2026-04-06T00:00:07.000Z'),
|
||||
(${ORCHESTRATION_PROJECTOR_NAMES.threadActivities}, 4, '2026-04-06T00:00:07.000Z'),
|
||||
(${ORCHESTRATION_PROJECTOR_NAMES.threadSessions}, 4, '2026-04-06T00:00:07.000Z'),
|
||||
(${ORCHESTRATION_PROJECTOR_NAMES.checkpoints}, 4, '2026-04-06T00:00:07.000Z')
|
||||
`;
|
||||
|
||||
// Settled ≠ archived: the thread must appear in the LIVE shell
|
||||
// snapshot, carrying its settlement fields through the row aliases.
|
||||
const shellSnapshot = yield* snapshotQuery.getShellSnapshot();
|
||||
assert.deepEqual(
|
||||
shellSnapshot.threads.map((thread) => thread.id),
|
||||
[ThreadId.make("thread-settled")],
|
||||
);
|
||||
assert.equal(shellSnapshot.threads[0]?.settledOverride, "settled");
|
||||
assert.equal(shellSnapshot.threads[0]?.settledAt, "2026-04-06T00:00:04.000Z");
|
||||
|
||||
// And the full command read model carries them too.
|
||||
const readModel = yield* snapshotQuery.getCommandReadModel();
|
||||
const thread = readModel.threads.find(
|
||||
(candidate) => candidate.id === ThreadId.make("thread-settled"),
|
||||
);
|
||||
assert.equal(thread?.settledOverride, "settled");
|
||||
assert.equal(thread?.settledAt, "2026-04-06T00:00:04.000Z");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"reads targeted project, thread, and count queries without hydrating the full snapshot",
|
||||
() =>
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
type OrchestrationMessage,
|
||||
type OrchestrationProjectShell,
|
||||
type OrchestrationProposedPlan,
|
||||
type OrchestrationQueuedMessage,
|
||||
type OrchestrationProject,
|
||||
type OrchestrationSession,
|
||||
type OrchestrationThreadActivity,
|
||||
@@ -47,6 +48,7 @@ import { ProjectionState } from "../../persistence/Services/ProjectionState.ts";
|
||||
import { ProjectionThreadActivity } from "../../persistence/Services/ProjectionThreadActivities.ts";
|
||||
import { ProjectionThreadMessage } from "../../persistence/Services/ProjectionThreadMessages.ts";
|
||||
import { ProjectionThreadProposedPlan } from "../../persistence/Services/ProjectionThreadProposedPlans.ts";
|
||||
import { ProjectionQueuedMessage } from "../../persistence/Services/ProjectionQueuedMessages.ts";
|
||||
import { ProjectionThreadSession } from "../../persistence/Services/ProjectionThreadSessions.ts";
|
||||
import { ProjectionThread } from "../../persistence/Services/ProjectionThreads.ts";
|
||||
import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResolver.ts";
|
||||
@@ -75,6 +77,12 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadProposedPlanDbRowSchema = ProjectionThreadProposedPlan;
|
||||
const ProjectionQueuedMessageDbRowSchema = ProjectionQueuedMessage.mapFields(
|
||||
Struct.assign({
|
||||
attachments: Schema.fromJsonString(Schema.Array(ChatAttachment)),
|
||||
modelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadDbRowSchema = ProjectionThread.mapFields(
|
||||
Struct.assign({
|
||||
modelSelection: Schema.fromJsonString(ModelSelection),
|
||||
@@ -254,6 +262,26 @@ function mapProposedPlanRow(
|
||||
};
|
||||
}
|
||||
|
||||
function mapQueuedMessageRow(
|
||||
row: Schema.Schema.Type<typeof ProjectionQueuedMessageDbRowSchema>,
|
||||
): OrchestrationQueuedMessage {
|
||||
return {
|
||||
messageId: row.messageId,
|
||||
text: row.text,
|
||||
attachments: row.attachments,
|
||||
...(row.modelSelection !== null ? { modelSelection: row.modelSelection } : {}),
|
||||
...(row.sourceProposedPlanThreadId !== null && row.sourceProposedPlanId !== null
|
||||
? {
|
||||
sourceProposedPlan: {
|
||||
threadId: row.sourceProposedPlanThreadId,
|
||||
planId: row.sourceProposedPlanId,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
queuedAt: row.queuedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
|
||||
return (cause: unknown): ProjectionRepositoryError =>
|
||||
Schema.isSchemaError(cause)
|
||||
@@ -334,6 +362,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -362,6 +392,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -392,6 +424,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -443,6 +477,45 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const listQueuedMessageRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProjectionQueuedMessageDbRowSchema,
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT
|
||||
message_id AS "messageId",
|
||||
thread_id AS "threadId",
|
||||
text,
|
||||
attachments_json AS "attachments",
|
||||
model_selection_json AS "modelSelection",
|
||||
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
|
||||
source_proposed_plan_id AS "sourceProposedPlanId",
|
||||
queued_at AS "queuedAt"
|
||||
FROM projection_queued_messages
|
||||
ORDER BY thread_id ASC, rowid ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const listQueuedMessageRowsByThread = SqlSchema.findAll({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionQueuedMessageDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
message_id AS "messageId",
|
||||
thread_id AS "threadId",
|
||||
text,
|
||||
attachments_json AS "attachments",
|
||||
model_selection_json AS "modelSelection",
|
||||
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
|
||||
source_proposed_plan_id AS "sourceProposedPlanId",
|
||||
queued_at AS "queuedAt"
|
||||
FROM projection_queued_messages
|
||||
WHERE thread_id = ${threadId}
|
||||
ORDER BY rowid ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadActivityRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProjectionThreadActivityDbRowSchema,
|
||||
@@ -582,6 +655,50 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const PendingTurnStartDbRowSchema = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
messageId: MessageId,
|
||||
requestedAt: IsoDateTime,
|
||||
});
|
||||
|
||||
const getPendingTurnStartRowByThread = SqlSchema.findOneOption({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: PendingTurnStartDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
pending_message_id AS "messageId",
|
||||
requested_at AS "requestedAt"
|
||||
FROM projection_turns
|
||||
WHERE thread_id = ${threadId}
|
||||
AND turn_id IS NULL
|
||||
AND state = 'pending'
|
||||
AND pending_message_id IS NOT NULL
|
||||
AND checkpoint_turn_count IS NULL
|
||||
ORDER BY requested_at DESC
|
||||
LIMIT 1
|
||||
`,
|
||||
});
|
||||
|
||||
const listPendingTurnStartRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: PendingTurnStartDbRowSchema,
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
pending_message_id AS "messageId",
|
||||
requested_at AS "requestedAt"
|
||||
FROM projection_turns
|
||||
WHERE turn_id IS NULL
|
||||
AND state = 'pending'
|
||||
AND pending_message_id IS NOT NULL
|
||||
AND checkpoint_turn_count IS NULL
|
||||
ORDER BY thread_id ASC, requested_at DESC
|
||||
`,
|
||||
});
|
||||
|
||||
const listActiveLatestTurnRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProjectionLatestTurnDbRowSchema,
|
||||
@@ -754,6 +871,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -967,6 +1086,22 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
),
|
||||
),
|
||||
),
|
||||
listQueuedMessageRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getSnapshot:listQueuedMessages:query",
|
||||
"ProjectionSnapshotQuery.getSnapshot:listQueuedMessages:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listPendingTurnStartRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getSnapshot:listPendingTurnStarts:query",
|
||||
"ProjectionSnapshotQuery.getSnapshot:listPendingTurnStarts:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadActivityRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
@@ -1016,6 +1151,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
threadRows,
|
||||
messageRows,
|
||||
proposedPlanRows,
|
||||
queuedMessageRows,
|
||||
pendingTurnStartRows,
|
||||
activityRows,
|
||||
sessionRows,
|
||||
checkpointRows,
|
||||
@@ -1024,6 +1161,20 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
]) =>
|
||||
Effect.gen(function* () {
|
||||
const messagesByThread = new Map<string, Array<OrchestrationMessage>>();
|
||||
const queuedMessagesByThread = new Map<string, Array<OrchestrationQueuedMessage>>();
|
||||
// Rows are ordered requested_at DESC per thread; first wins.
|
||||
const pendingTurnStartByThread = new Map<
|
||||
string,
|
||||
{ messageId: MessageId; requestedAt: string }
|
||||
>();
|
||||
for (const row of pendingTurnStartRows) {
|
||||
if (!pendingTurnStartByThread.has(row.threadId)) {
|
||||
pendingTurnStartByThread.set(row.threadId, {
|
||||
messageId: row.messageId,
|
||||
requestedAt: row.requestedAt,
|
||||
});
|
||||
}
|
||||
}
|
||||
const proposedPlansByThread = new Map<string, Array<OrchestrationProposedPlan>>();
|
||||
const activitiesByThread = new Map<string, Array<OrchestrationThreadActivity>>();
|
||||
const checkpointsByThread = new Map<string, Array<OrchestrationCheckpointSummary>>();
|
||||
@@ -1073,6 +1224,13 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
proposedPlansByThread.set(row.threadId, threadProposedPlans);
|
||||
}
|
||||
|
||||
for (const row of queuedMessageRows) {
|
||||
updatedAt = maxIso(updatedAt, row.queuedAt);
|
||||
const threadQueuedMessages = queuedMessagesByThread.get(row.threadId) ?? [];
|
||||
threadQueuedMessages.push(mapQueuedMessageRow(row));
|
||||
queuedMessagesByThread.set(row.threadId, threadQueuedMessages);
|
||||
}
|
||||
|
||||
for (const row of activityRows) {
|
||||
updatedAt = maxIso(updatedAt, row.createdAt);
|
||||
const threadActivities = activitiesByThread.get(row.threadId) ?? [];
|
||||
@@ -1186,8 +1344,12 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
deletedAt: row.deletedAt,
|
||||
messages: messagesByThread.get(row.threadId) ?? [],
|
||||
queuedMessages: queuedMessagesByThread.get(row.threadId) ?? [],
|
||||
pendingTurnStart: pendingTurnStartByThread.get(row.threadId) ?? null,
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
activities: activitiesByThread.get(row.threadId) ?? [],
|
||||
checkpoints: checkpointsByThread.get(row.threadId) ?? [],
|
||||
@@ -1244,6 +1406,22 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
),
|
||||
),
|
||||
),
|
||||
listQueuedMessageRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getCommandReadModel:listQueuedMessages:query",
|
||||
"ProjectionSnapshotQuery.getCommandReadModel:listQueuedMessages:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listPendingTurnStartRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getCommandReadModel:listPendingTurnStarts:query",
|
||||
"ProjectionSnapshotQuery.getCommandReadModel:listPendingTurnStarts:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadSessionRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
@@ -1272,7 +1450,16 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
)
|
||||
.pipe(
|
||||
Effect.flatMap(
|
||||
([projectRows, threadRows, proposedPlanRows, sessionRows, latestTurnRows, stateRows]) =>
|
||||
([
|
||||
projectRows,
|
||||
threadRows,
|
||||
proposedPlanRows,
|
||||
queuedMessageRows,
|
||||
pendingTurnStartRows,
|
||||
sessionRows,
|
||||
latestTurnRows,
|
||||
stateRows,
|
||||
]) =>
|
||||
Effect.sync(() => {
|
||||
let updatedAt: string | null = null;
|
||||
const projects: OrchestrationProject[] = [];
|
||||
@@ -1346,8 +1533,33 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
latestTurnByThread.set(row.threadId, mapLatestTurn(row));
|
||||
}
|
||||
const proposedPlansByThread = new Map<string, Array<OrchestrationProposedPlan>>();
|
||||
const queuedMessagesByThread = new Map<string, Array<OrchestrationQueuedMessage>>();
|
||||
// Rows are ordered requested_at DESC per thread; first wins.
|
||||
const pendingTurnStartByThread = new Map<
|
||||
string,
|
||||
{ messageId: MessageId; requestedAt: string }
|
||||
>();
|
||||
for (const row of pendingTurnStartRows) {
|
||||
if (!pendingTurnStartByThread.has(row.threadId)) {
|
||||
pendingTurnStartByThread.set(row.threadId, {
|
||||
messageId: row.messageId,
|
||||
requestedAt: row.requestedAt,
|
||||
});
|
||||
}
|
||||
}
|
||||
const sessionByThread = new Map<string, OrchestrationSession>();
|
||||
|
||||
for (let index = 0; index < queuedMessageRows.length; index += 1) {
|
||||
const row = queuedMessageRows[index];
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
updatedAt = maxIso(updatedAt, row.queuedAt);
|
||||
const threadQueuedMessages = queuedMessagesByThread.get(row.threadId) ?? [];
|
||||
threadQueuedMessages.push(mapQueuedMessageRow(row));
|
||||
queuedMessagesByThread.set(row.threadId, threadQueuedMessages);
|
||||
}
|
||||
|
||||
for (let index = 0; index < sessionRows.length; index += 1) {
|
||||
const row = sessionRows[index];
|
||||
if (!row) {
|
||||
@@ -1384,8 +1596,12 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
deletedAt: row.deletedAt,
|
||||
messages: [],
|
||||
queuedMessages: queuedMessagesByThread.get(row.threadId) ?? [],
|
||||
pendingTurnStart: pendingTurnStartByThread.get(row.threadId) ?? null,
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
@@ -1513,6 +1729,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
session: sessionByThread.get(row.threadId) ?? null,
|
||||
latestUserMessageAt: row.latestUserMessageAt,
|
||||
hasPendingApprovals: row.pendingApprovalCount > 0,
|
||||
@@ -1647,6 +1865,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
session: sessionByThread.get(row.threadId) ?? null,
|
||||
latestUserMessageAt: row.latestUserMessageAt,
|
||||
hasPendingApprovals: row.pendingApprovalCount > 0,
|
||||
@@ -1887,6 +2107,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
createdAt: threadRow.value.createdAt,
|
||||
updatedAt: threadRow.value.updatedAt,
|
||||
archivedAt: threadRow.value.archivedAt,
|
||||
settledOverride: threadRow.value.settledOverride,
|
||||
settledAt: threadRow.value.settledAt,
|
||||
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
|
||||
latestUserMessageAt: threadRow.value.latestUserMessageAt,
|
||||
hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,
|
||||
@@ -1901,6 +2123,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
threadRow,
|
||||
messageRows,
|
||||
proposedPlanRows,
|
||||
queuedMessageRows,
|
||||
pendingTurnStartRow,
|
||||
activityRows,
|
||||
checkpointRows,
|
||||
latestTurnRow,
|
||||
@@ -1930,6 +2154,22 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
),
|
||||
),
|
||||
),
|
||||
listQueuedMessageRowsByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listQueuedMessages:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listQueuedMessages:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
getPendingTurnStartRowByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:getPendingTurnStart:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:getPendingTurnStart:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadActivityRowsByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
@@ -1981,6 +2221,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
createdAt: threadRow.value.createdAt,
|
||||
updatedAt: threadRow.value.updatedAt,
|
||||
archivedAt: threadRow.value.archivedAt,
|
||||
settledOverride: threadRow.value.settledOverride,
|
||||
settledAt: threadRow.value.settledAt,
|
||||
deletedAt: null,
|
||||
messages: messageRows.map((row) => {
|
||||
const message = {
|
||||
@@ -1997,6 +2239,13 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
}
|
||||
return message;
|
||||
}),
|
||||
queuedMessages: queuedMessageRows.map(mapQueuedMessageRow),
|
||||
pendingTurnStart: Option.isSome(pendingTurnStartRow)
|
||||
? {
|
||||
messageId: pendingTurnStartRow.value.messageId,
|
||||
requestedAt: pendingTurnStartRow.value.requestedAt,
|
||||
}
|
||||
: null,
|
||||
proposedPlans: proposedPlanRows.map(mapProposedPlanRow),
|
||||
activities: activityRows.map((row) => {
|
||||
const activity = {
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as ManagedRuntime from "effect/ManagedRuntime";
|
||||
@@ -145,6 +146,9 @@ describe("ProviderCommandReactor", () => {
|
||||
readonly threadModelSelection?: ModelSelection;
|
||||
readonly sessionModelSwitch?: "unsupported" | "in-session";
|
||||
readonly requiresNewThreadForModelChange?: boolean;
|
||||
readonly startSessionEffect?: (
|
||||
session: ProviderSession,
|
||||
) => Effect.Effect<ProviderSession, ProviderAdapterRequestError>;
|
||||
}) {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const baseDir =
|
||||
@@ -159,6 +163,7 @@ describe("ProviderCommandReactor", () => {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
};
|
||||
const startSessionEffect = input?.startSessionEffect;
|
||||
const startSession = vi.fn((_: unknown, input: unknown) => {
|
||||
const sessionIndex = nextSessionIndex++;
|
||||
const resumeCursor =
|
||||
@@ -212,8 +217,13 @@ describe("ProviderCommandReactor", () => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
runtimeSessions.push(session);
|
||||
return Effect.succeed(session);
|
||||
return (startSessionEffect?.(session) ?? Effect.succeed(session)).pipe(
|
||||
Effect.tap((startedSession) =>
|
||||
Effect.sync(() => {
|
||||
runtimeSessions.push(startedSession);
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
const sendTurn = vi.fn((_: unknown) =>
|
||||
Effect.succeed({
|
||||
@@ -408,9 +418,59 @@ describe("ProviderCommandReactor", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
// Queue-by-default holds turn.start commands while the session is
|
||||
// starting/running. The mock provider never emits runtime events, so
|
||||
// tests that send a follow-up on an idle thread must settle the session
|
||||
// back to ready first — in production, turn completion does this. The
|
||||
// projected session is preserved apart from status/activeTurnId so
|
||||
// provider identity fields survive the settle.
|
||||
const harnessRuntime = runtime;
|
||||
let settleIndex = 0;
|
||||
const settleSession = async (threadId: ThreadId = ThreadId.make("thread-1")) => {
|
||||
settleIndex += 1;
|
||||
const readModel = await harnessRuntime.runPromise(snapshotQuery.getSnapshot());
|
||||
const session = readModel.threads.find((entry) => entry.id === threadId)?.session;
|
||||
if (!session) {
|
||||
return;
|
||||
}
|
||||
// Mirror the real lifecycle: report the turn running (stamping
|
||||
// latestTurn so the decider's pending-turn-start guard clears), then
|
||||
// settle back to ready. A lone ready-set would leave latestTurn null
|
||||
// and the just-sent message would read as a still-pending start.
|
||||
await harnessRuntime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make(`cmd-session-run-${settleIndex}`),
|
||||
threadId,
|
||||
session: {
|
||||
...session,
|
||||
status: "running",
|
||||
activeTurnId: asTurnId(`turn-settle-${settleIndex}`),
|
||||
updatedAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
await harnessRuntime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make(`cmd-session-settle-${settleIndex}`),
|
||||
threadId,
|
||||
session: {
|
||||
...session,
|
||||
status: "ready",
|
||||
activeTurnId: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
return {
|
||||
engine,
|
||||
readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()),
|
||||
settleSession,
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
@@ -463,59 +523,118 @@ describe("ProviderCommandReactor", () => {
|
||||
const readModel = await harness.readModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.status).toBe("starting");
|
||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||
});
|
||||
|
||||
effectIt.effect(
|
||||
"sends only image attachments to the provider and appends file attachment prompt text",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* Effect.promise(() => createHarness());
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const imageAttachment = {
|
||||
type: "image" as const,
|
||||
id: "thread-1-00000000-0000-4000-8000-000000000001",
|
||||
name: "screen.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 4,
|
||||
};
|
||||
const fileAttachment = {
|
||||
type: "file" as const,
|
||||
id: "thread-1-00000000-0000-4000-8000-000000000002",
|
||||
name: "notes.txt",
|
||||
mimeType: "text/plain",
|
||||
sizeBytes: 5,
|
||||
};
|
||||
const attachmentsDir = NodePath.join(harness.stateDir, "attachments");
|
||||
const fileAttachmentPath = NodePath.join(attachmentsDir, `${fileAttachment.id}.txt`);
|
||||
NodeFS.mkdirSync(attachmentsDir, { recursive: true });
|
||||
NodeFS.writeFileSync(fileAttachmentPath, "notes");
|
||||
effectIt.effect("projects starting before a slow provider session finishes", () =>
|
||||
Effect.gen(function* () {
|
||||
const releaseStart = yield* Deferred.make<void>();
|
||||
const harness = yield* Effect.promise(() =>
|
||||
createHarness({
|
||||
startSessionEffect: (session) => Deferred.await(releaseStart).pipe(Effect.as(session)),
|
||||
}),
|
||||
);
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-file-attachments"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-file-attachments"),
|
||||
role: "user",
|
||||
text: "hello with attachments",
|
||||
attachments: [imageAttachment, fileAttachment],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
});
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-slow-provider"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-slow-provider"),
|
||||
role: "user",
|
||||
text: "start slowly",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
});
|
||||
|
||||
yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 1));
|
||||
const request = harness.sendTurn.mock.calls[0]?.[0] as {
|
||||
readonly input?: string;
|
||||
readonly attachments?: ReadonlyArray<unknown>;
|
||||
};
|
||||
expect(request.attachments).toEqual([imageAttachment]);
|
||||
expect(request.input).toBe(
|
||||
`hello with attachments\n\n[Attached file: ${fileAttachmentPath} (notes.txt, text/plain, 5 B). Read it from disk when needed.]`,
|
||||
);
|
||||
}),
|
||||
yield* Effect.promise(() => waitFor(() => harness.startSession.mock.calls.length === 1));
|
||||
const duringStartup = yield* Effect.promise(() => harness.readModel());
|
||||
expect(
|
||||
duringStartup.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.session
|
||||
?.status,
|
||||
).toBe("starting");
|
||||
expect(harness.sendTurn).not.toHaveBeenCalled();
|
||||
|
||||
yield* Deferred.succeed(releaseStart, undefined);
|
||||
yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 1));
|
||||
}),
|
||||
);
|
||||
|
||||
effectIt.effect("settles a failed provider startup and allows a clean retry", () =>
|
||||
Effect.gen(function* () {
|
||||
let failStartup = true;
|
||||
const harness = yield* Effect.promise(() =>
|
||||
createHarness({
|
||||
startSessionEffect: (session) =>
|
||||
failStartup
|
||||
? Effect.fail(
|
||||
new ProviderAdapterRequestError({
|
||||
provider: "codex",
|
||||
method: "thread.start",
|
||||
detail: "deterministic startup failure",
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(session),
|
||||
}),
|
||||
);
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-provider-failure"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-provider-failure"),
|
||||
role: "user",
|
||||
text: "fail once",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
});
|
||||
|
||||
yield* Effect.promise(() =>
|
||||
waitFor(async () => {
|
||||
const readModel = await harness.readModel();
|
||||
return (
|
||||
readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.session
|
||||
?.status === "error"
|
||||
);
|
||||
}),
|
||||
);
|
||||
let readModel = yield* Effect.promise(() => harness.readModel());
|
||||
let thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session?.lastError).toContain("deterministic startup failure");
|
||||
expect(harness.sendTurn).not.toHaveBeenCalled();
|
||||
|
||||
failStartup = false;
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-provider-retry"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-provider-retry"),
|
||||
role: "user",
|
||||
text: "retry",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
});
|
||||
|
||||
yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 1));
|
||||
readModel = yield* Effect.promise(() => harness.readModel());
|
||||
thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session?.status).toBe("starting");
|
||||
expect(thread?.session?.lastError).toBeNull();
|
||||
}),
|
||||
);
|
||||
|
||||
it("generates a thread title on the first turn", async () => {
|
||||
@@ -916,6 +1035,7 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
await harness.settleSession();
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
@@ -970,6 +1090,7 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 1));
|
||||
|
||||
yield* Effect.promise(() => harness.settleSession());
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-restricted-2"),
|
||||
@@ -1090,6 +1211,7 @@ describe("ProviderCommandReactor", () => {
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
await harness.settleSession();
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
@@ -1139,6 +1261,7 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
await harness.settleSession();
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
@@ -1215,6 +1338,7 @@ describe("ProviderCommandReactor", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
await harness.settleSession();
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
@@ -1281,6 +1405,7 @@ describe("ProviderCommandReactor", () => {
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
await harness.settleSession();
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
@@ -1365,6 +1490,7 @@ describe("ProviderCommandReactor", () => {
|
||||
return thread?.runtimeMode === "approval-required";
|
||||
});
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 2);
|
||||
await harness.settleSession();
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
@@ -1537,6 +1663,7 @@ describe("ProviderCommandReactor", () => {
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
await harness.settleSession();
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
|
||||
@@ -25,9 +25,7 @@ import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
|
||||
import { appendFileAttachmentPromptText } from "../../attachmentPrompt.ts";
|
||||
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts";
|
||||
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
|
||||
import type { ProviderServiceError } from "../../provider/Errors.ts";
|
||||
@@ -198,7 +196,6 @@ const make = Effect.gen(function* () {
|
||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
|
||||
const textGeneration = yield* TextGeneration;
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const serverCommandId = (tag: string) =>
|
||||
crypto.randomUUIDv4.pipe(Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`)));
|
||||
const serverEventId = () => crypto.randomUUIDv4.pipe(Effect.map(EventId.make));
|
||||
@@ -291,15 +288,20 @@ const make = Effect.gen(function* () {
|
||||
readonly createdAt: string;
|
||||
}) {
|
||||
const thread = yield* resolveThread(input.threadId);
|
||||
const session = thread?.session;
|
||||
if (!session) {
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
const session = thread.session;
|
||||
yield* setThreadSession({
|
||||
threadId: input.threadId,
|
||||
session: {
|
||||
...session,
|
||||
status: session.status === "stopped" ? "stopped" : "ready",
|
||||
...(session ?? {
|
||||
threadId: input.threadId,
|
||||
providerName: null,
|
||||
providerInstanceId: thread.modelSelection.instanceId,
|
||||
runtimeMode: thread.runtimeMode,
|
||||
}),
|
||||
status: session?.status === "stopped" ? "stopped" : "error",
|
||||
activeTurnId: null,
|
||||
lastError: input.detail,
|
||||
updatedAt: input.createdAt,
|
||||
@@ -357,6 +359,7 @@ const make = Effect.gen(function* () {
|
||||
createdAt: string,
|
||||
options?: {
|
||||
readonly modelSelection?: ModelSelection;
|
||||
readonly pendingTurnStart?: boolean;
|
||||
},
|
||||
) {
|
||||
const thread = yield* resolveThread(threadId);
|
||||
@@ -431,6 +434,22 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
const preferredProvider: ProviderDriverKind = desiredDriverKind;
|
||||
if (options?.pendingTurnStart === true && thread.session?.status !== "running") {
|
||||
yield* setThreadSession({
|
||||
threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: "starting",
|
||||
providerName: activeSession?.provider ?? preferredProvider,
|
||||
providerInstanceId: activeSession?.providerInstanceId ?? desiredInstanceId,
|
||||
runtimeMode: desiredRuntimeMode,
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
createdAt,
|
||||
});
|
||||
}
|
||||
if (thread.session !== null) {
|
||||
yield* rejectStartedThreadModelChangeIfRequired({
|
||||
threadId,
|
||||
@@ -501,7 +520,10 @@ const make = Effect.gen(function* () {
|
||||
threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: mapProviderSessionStatusToOrchestrationStatus(session.status),
|
||||
status:
|
||||
options?.pendingTurnStart === true && session.status === "ready"
|
||||
? "starting"
|
||||
: mapProviderSessionStatusToOrchestrationStatus(session.status),
|
||||
providerName: session.provider,
|
||||
providerInstanceId: session.providerInstanceId,
|
||||
runtimeMode: desiredRuntimeMode,
|
||||
@@ -600,26 +622,15 @@ const make = Effect.gen(function* () {
|
||||
new Error(`Thread '${input.threadId}' was not found in read model.`),
|
||||
);
|
||||
}
|
||||
yield* ensureSessionForThread(
|
||||
input.threadId,
|
||||
input.createdAt,
|
||||
input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {},
|
||||
);
|
||||
yield* ensureSessionForThread(input.threadId, input.createdAt, {
|
||||
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
|
||||
pendingTurnStart: true,
|
||||
});
|
||||
if (input.modelSelection !== undefined) {
|
||||
threadModelSelections.set(input.threadId, input.modelSelection);
|
||||
}
|
||||
const normalizedInput = toNonEmptyProviderInput(
|
||||
appendFileAttachmentPromptText({
|
||||
text: input.messageText,
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachments: input.attachments ?? [],
|
||||
}),
|
||||
);
|
||||
// Only image attachments go to the provider as content blocks; file
|
||||
// attachments are delivered by path in the prompt text above.
|
||||
const normalizedAttachments = (input.attachments ?? []).filter(
|
||||
(attachment) => attachment.type === "image",
|
||||
);
|
||||
const normalizedInput = toNonEmptyProviderInput(input.messageText);
|
||||
const normalizedAttachments = input.attachments ?? [];
|
||||
const activeSession = yield* providerService
|
||||
.listSessions()
|
||||
.pipe(
|
||||
|
||||
@@ -30,6 +30,7 @@ import * as ManagedRuntime from "effect/ManagedRuntime";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { it as effectIt } from "@effect/vitest";
|
||||
import { afterEach, describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
|
||||
@@ -493,6 +494,185 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
expect(thread.session?.lastError).toBeNull();
|
||||
});
|
||||
|
||||
effectIt.effect(
|
||||
"keeps a reconnecting pending turn starting while ready clears stale active state",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* Effect.promise(() => createHarness());
|
||||
const threadId = asThreadId("thread-1");
|
||||
const staleTurnId = asTurnId("turn-stale-before-reconnect");
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-pending-reconnect"),
|
||||
threadId,
|
||||
message: {
|
||||
messageId: MessageId.make("message-pending-reconnect"),
|
||||
role: "user",
|
||||
text: "resume after reconnect",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
});
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("cmd-session-starting-pending-reconnect"),
|
||||
threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: "starting",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: staleTurnId,
|
||||
lastError: null,
|
||||
updatedAt: "2026-01-01T00:00:01.000Z",
|
||||
},
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
});
|
||||
|
||||
harness.emit({
|
||||
type: "session.state.changed",
|
||||
eventId: asEventId("evt-session-ready-pending-reconnect"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId,
|
||||
createdAt: "2026-01-01T00:00:02.000Z",
|
||||
payload: { state: "ready" },
|
||||
});
|
||||
|
||||
let thread = yield* Effect.promise(() =>
|
||||
waitForThread(
|
||||
harness.readModel,
|
||||
(entry) => entry.session?.status === "starting" && entry.session.activeTurnId === null,
|
||||
),
|
||||
);
|
||||
expect(thread.session?.status).toBe("starting");
|
||||
expect(thread.session?.activeTurnId).toBeNull();
|
||||
|
||||
harness.emit({
|
||||
type: "session.started",
|
||||
eventId: asEventId("evt-session-started-pending-reconnect"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId,
|
||||
createdAt: "2026-01-01T00:00:03.000Z",
|
||||
});
|
||||
yield* Effect.promise(() => harness.drain());
|
||||
thread = (yield* Effect.promise(() => harness.readModel())).threads.find(
|
||||
(entry) => entry.id === threadId,
|
||||
)!;
|
||||
expect(thread.session?.status).toBe("starting");
|
||||
expect(thread.session?.activeTurnId).toBeNull();
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-pending-reconnect"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId,
|
||||
turnId: asTurnId("turn-after-reconnect"),
|
||||
createdAt: "2026-01-01T00:00:04.000Z",
|
||||
});
|
||||
thread = yield* Effect.promise(() =>
|
||||
waitForThread(
|
||||
harness.readModel,
|
||||
(entry) =>
|
||||
entry.session?.status === "running" &&
|
||||
entry.session.activeTurnId === asTurnId("turn-after-reconnect"),
|
||||
),
|
||||
);
|
||||
expect(thread.session?.status).toBe("running");
|
||||
|
||||
harness.emit({
|
||||
type: "session.started",
|
||||
eventId: asEventId("evt-session-started-duplicate-midturn"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId,
|
||||
createdAt: "2026-01-01T00:00:05.000Z",
|
||||
});
|
||||
yield* Effect.promise(() => harness.drain());
|
||||
thread = (yield* Effect.promise(() => harness.readModel())).threads.find(
|
||||
(entry) => entry.id === threadId,
|
||||
)!;
|
||||
expect(thread.session?.status).toBe("running");
|
||||
expect(thread.session?.activeTurnId).toBe(asTurnId("turn-after-reconnect"));
|
||||
}),
|
||||
);
|
||||
|
||||
effectIt.effect("keeps an aborted pending start stopped across duplicate exit events", () =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* Effect.promise(() => createHarness());
|
||||
const threadId = asThreadId("thread-1");
|
||||
const stoppedAt = "2026-01-01T00:00:02.000Z";
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-before-stop"),
|
||||
threadId,
|
||||
message: {
|
||||
messageId: MessageId.make("message-before-stop"),
|
||||
role: "user",
|
||||
text: "stop this startup",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
});
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("cmd-session-starting-before-stop"),
|
||||
threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: "starting",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: "2026-01-01T00:00:01.000Z",
|
||||
},
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
});
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("cmd-session-stop-pending-start"),
|
||||
threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: "stopped",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: stoppedAt,
|
||||
},
|
||||
createdAt: stoppedAt,
|
||||
});
|
||||
|
||||
harness.emit({
|
||||
type: "session.exited",
|
||||
eventId: asEventId("evt-session-exited-after-stop"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId,
|
||||
createdAt: "2026-01-01T00:00:03.000Z",
|
||||
});
|
||||
harness.emit({
|
||||
type: "session.exited",
|
||||
eventId: asEventId("evt-duplicate-session-exited-after-stop"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId,
|
||||
createdAt: "2026-01-01T00:00:04.000Z",
|
||||
});
|
||||
|
||||
yield* Effect.promise(() => harness.drain());
|
||||
const thread = (yield* Effect.promise(() => harness.readModel())).threads.find(
|
||||
(entry) => entry.id === threadId,
|
||||
);
|
||||
expect(thread?.session?.status).toBe("stopped");
|
||||
expect(thread?.session?.activeTurnId).toBeNull();
|
||||
}),
|
||||
);
|
||||
|
||||
it("does not clear active turn when session/thread started arrives mid-turn", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
@@ -1343,22 +1523,35 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
threadId,
|
||||
);
|
||||
|
||||
// The steer: a user-requested turn start while the old turn still runs.
|
||||
// The steer: a follow-up sent mid-turn queues by default, then the
|
||||
// explicit queue.steer command dispatches it into the running turn.
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-steer"),
|
||||
threadId,
|
||||
message: {
|
||||
messageId: asMessageId("msg-steer"),
|
||||
role: "user",
|
||||
text: "actually, do 15 instead",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt,
|
||||
}),
|
||||
harness.engine
|
||||
.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-steer"),
|
||||
threadId,
|
||||
message: {
|
||||
messageId: asMessageId("msg-steer"),
|
||||
role: "user",
|
||||
text: "actually, do 15 instead",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt,
|
||||
})
|
||||
.pipe(
|
||||
Effect.andThen(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.queue.steer",
|
||||
commandId: CommandId.make("cmd-queue-steer"),
|
||||
threadId,
|
||||
messageId: asMessageId("msg-steer"),
|
||||
createdAt,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
// The provider session tracks the new turn before emitting turn.started
|
||||
|
||||
@@ -30,6 +30,8 @@ import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
|
||||
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
|
||||
import { ProjectionQueuedMessageRepository } from "../../persistence/Services/ProjectionQueuedMessages.ts";
|
||||
import { ProjectionQueuedMessageRepositoryLive } from "../../persistence/Layers/ProjectionQueuedMessages.ts";
|
||||
import { isGitRepository } from "../../git/Utils.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
@@ -692,6 +694,7 @@ const make = Effect.gen(function* () {
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const providerService = yield* ProviderService;
|
||||
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
||||
const projectionQueuedMessageRepository = yield* ProjectionQueuedMessageRepository;
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
const providerCommandId = (event: ProviderRuntimeEvent, tag: string) =>
|
||||
crypto.randomUUIDv4.pipe(
|
||||
@@ -746,6 +749,29 @@ const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const dispatchQueueDrain = Effect.fn("dispatchQueueDrain")(function* (
|
||||
threadId: ThreadId,
|
||||
event: ProviderRuntimeEvent,
|
||||
now: string,
|
||||
) {
|
||||
const queuedMessages = yield* projectionQueuedMessageRepository.listByThreadId({ threadId });
|
||||
if (queuedMessages.length === 0) {
|
||||
return;
|
||||
}
|
||||
yield* orchestrationEngine
|
||||
.dispatch({
|
||||
type: "thread.queue.drain",
|
||||
commandId: yield* providerCommandId(event, "queue-drain"),
|
||||
threadId,
|
||||
createdAt: now,
|
||||
})
|
||||
.pipe(
|
||||
// A drain losing the race to a fresh user turn (or an already-empty
|
||||
// queue) is expected; the next natural completion re-attempts.
|
||||
Effect.catchTag("OrchestrationCommandInvariantError", () => Effect.void),
|
||||
);
|
||||
});
|
||||
|
||||
const resolveThreadDetail = Effect.fn("resolveThreadDetail")(function* (threadId: ThreadId) {
|
||||
return yield* projectionSnapshotQuery
|
||||
.getThreadDetailById(threadId)
|
||||
@@ -1308,6 +1334,12 @@ const make = Effect.gen(function* () {
|
||||
const now = event.createdAt;
|
||||
const eventTurnId = toTurnId(event.turnId);
|
||||
const activeTurnId = thread.session?.activeTurnId ?? null;
|
||||
const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({
|
||||
threadId: thread.id,
|
||||
});
|
||||
const hasPendingTurnStart =
|
||||
Option.isSome(pendingTurnStart) && thread.session?.status === "starting";
|
||||
let drainQueueAfterTurnFinalize = false;
|
||||
|
||||
const conflictsWithActiveTurn =
|
||||
activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId);
|
||||
@@ -1322,11 +1354,7 @@ const make = Effect.gen(function* () {
|
||||
const conflictingTurnStartIsPendingTurnStart =
|
||||
event.type === "turn.started" && conflictsWithActiveTurn
|
||||
? sameId(yield* getExpectedProviderTurnIdForThread(thread.id), eventTurnId) &&
|
||||
Option.isSome(
|
||||
yield* projectionTurnRepository.getPendingTurnStartByThreadId({
|
||||
threadId: thread.id,
|
||||
}),
|
||||
)
|
||||
Option.isSome(pendingTurnStart)
|
||||
: false;
|
||||
|
||||
const shouldApplyThreadLifecycle = (() => {
|
||||
@@ -1370,8 +1398,10 @@ const make = Effect.gen(function* () {
|
||||
) {
|
||||
const status = (() => {
|
||||
switch (event.type) {
|
||||
case "session.state.changed":
|
||||
return orchestrationSessionStatusFromRuntimeState(event.payload.state);
|
||||
case "session.state.changed": {
|
||||
const runtimeStatus = orchestrationSessionStatusFromRuntimeState(event.payload.state);
|
||||
return hasPendingTurnStart && runtimeStatus === "ready" ? "starting" : runtimeStatus;
|
||||
}
|
||||
case "turn.started":
|
||||
return "running";
|
||||
case "session.exited":
|
||||
@@ -1383,8 +1413,8 @@ const make = Effect.gen(function* () {
|
||||
case "session.started":
|
||||
case "thread.started":
|
||||
// Provider thread/session start notifications can arrive during an
|
||||
// active turn; preserve turn-running state in that case.
|
||||
return activeTurnId !== null ? "running" : "ready";
|
||||
// active or pending turn; preserve that lifecycle state.
|
||||
return activeTurnId !== null ? "running" : hasPendingTurnStart ? "starting" : "ready";
|
||||
}
|
||||
})();
|
||||
const nextActiveTurnId =
|
||||
@@ -1392,7 +1422,10 @@ const make = Effect.gen(function* () {
|
||||
? (eventTurnId ?? null)
|
||||
: event.type === "turn.completed" || event.type === "session.exited"
|
||||
? null
|
||||
: event.type === "session.state.changed" && !sessionStatusAllowsActiveTurn(status)
|
||||
: event.type === "session.state.changed" &&
|
||||
!sessionStatusAllowsActiveTurn(
|
||||
orchestrationSessionStatusFromRuntimeState(event.payload.state),
|
||||
)
|
||||
? null
|
||||
: activeTurnId;
|
||||
const lastError =
|
||||
@@ -1444,6 +1477,15 @@ const make = Effect.gen(function* () {
|
||||
},
|
||||
createdAt: now,
|
||||
});
|
||||
|
||||
// Auto-drain queued follow-ups only on natural completion —
|
||||
// never after an interrupt (the user stopped the agent to take
|
||||
// control) or a failure. The dispatch happens after the
|
||||
// assistant-finalization block below so the drained user message
|
||||
// sequences after the assistant text it follows up on.
|
||||
drainQueueAfterTurnFinalize =
|
||||
event.type === "turn.completed" &&
|
||||
normalizeRuntimeTurnState(event.payload.state) === "completed";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1662,6 +1704,10 @@ const make = Effect.gen(function* () {
|
||||
updatedAt: now,
|
||||
});
|
||||
}
|
||||
|
||||
if (drainQueueAfterTurnFinalize) {
|
||||
yield* dispatchQueueDrain(thread.id, event, now);
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === "session.exited") {
|
||||
@@ -1822,4 +1868,7 @@ const make = Effect.gen(function* () {
|
||||
export const ProviderRuntimeIngestionLive = Layer.effect(
|
||||
ProviderRuntimeIngestionService,
|
||||
make,
|
||||
).pipe(Layer.provide(ProjectionTurnRepositoryLive));
|
||||
).pipe(
|
||||
Layer.provide(ProjectionTurnRepositoryLive),
|
||||
Layer.provide(ProjectionQueuedMessageRepositoryLive),
|
||||
);
|
||||
@@ -1,53 +1,17 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
type ClientOrchestrationCommand,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type ClientOrchestrationCommand,
|
||||
type UploadChatAttachment,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
|
||||
import { canonicalizeClientCommandTimestamps, normalizeDispatchCommand } from "./Normalizer.ts";
|
||||
|
||||
const testLayer = Layer.mergeAll(
|
||||
ServerConfig.ServerConfig.layerTest(process.cwd(), { prefix: "t3-normalizer-test-" }),
|
||||
WorkspacePaths.layer,
|
||||
).pipe(Layer.provideMerge(NodeServices.layer));
|
||||
import { canonicalizeClientCommandTimestamps } from "./Normalizer.ts";
|
||||
|
||||
const clientCreatedAt = "2031-01-01T00:00:00.000Z";
|
||||
const serverReceivedAt = "2026-07-18T00:00:00.000Z";
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
const turnStartCommand = (
|
||||
attachments: ReadonlyArray<UploadChatAttachment>,
|
||||
): ClientOrchestrationCommand => ({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: MessageId.make("user-message-1"),
|
||||
role: "user",
|
||||
text: "hello normalizer",
|
||||
attachments,
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
createdAt: now,
|
||||
});
|
||||
|
||||
const asDataUrl = (mimeType: string, bytes: Buffer) =>
|
||||
`data:${mimeType};base64,${bytes.toString("base64")}`;
|
||||
|
||||
describe("canonicalizeClientCommandTimestamps", () => {
|
||||
it("replaces a client command timestamp with the server receipt timestamp", () => {
|
||||
@@ -107,86 +71,3 @@ describe("canonicalizeClientCommandTimestamps", () => {
|
||||
expect(result.bootstrap?.createThread?.createdAt).toBe(serverReceivedAt);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Normalizer", () => {
|
||||
it.effect("persists file attachments and writes their bytes to the attachments dir", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const { attachmentsDir } = yield* ServerConfig.ServerConfig;
|
||||
const bytes = Buffer.from("hello world");
|
||||
|
||||
const normalized = yield* normalizeDispatchCommand(
|
||||
turnStartCommand([
|
||||
{
|
||||
type: "file",
|
||||
name: "notes.txt",
|
||||
mimeType: "text/plain",
|
||||
sizeBytes: bytes.byteLength,
|
||||
dataUrl: asDataUrl("text/plain", bytes),
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
expect(normalized.type).toBe("thread.turn.start");
|
||||
if (normalized.type !== "thread.turn.start") {
|
||||
return;
|
||||
}
|
||||
const attachment = normalized.message.attachments[0];
|
||||
expect(attachment).toMatchObject({
|
||||
type: "file",
|
||||
name: "notes.txt",
|
||||
mimeType: "text/plain",
|
||||
sizeBytes: bytes.byteLength,
|
||||
});
|
||||
expect(attachment?.id).toMatch(
|
||||
/^thread-1-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,
|
||||
);
|
||||
if (!attachment) {
|
||||
return;
|
||||
}
|
||||
|
||||
const attachmentPath = path.join(attachmentsDir, `${attachment.id}.txt`);
|
||||
expect(yield* fileSystem.readFileString(attachmentPath)).toBe("hello world");
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("rejects image attachments with a non-image data URL mime type", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* normalizeDispatchCommand(
|
||||
turnStartCommand([
|
||||
{
|
||||
type: "image",
|
||||
name: "fake.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
dataUrl: asDataUrl("text/plain", Buffer.from("hello")),
|
||||
},
|
||||
]),
|
||||
).pipe(Effect.flip);
|
||||
|
||||
expect(error._tag).toBe("OrchestrationDispatchCommandError");
|
||||
expect(error.message).toBe("Invalid image attachment payload for 'fake.png'.");
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("rejects file attachments over the maximum attachment size", () =>
|
||||
Effect.gen(function* () {
|
||||
const bytes = Buffer.alloc(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1, "a");
|
||||
const error = yield* normalizeDispatchCommand(
|
||||
turnStartCommand([
|
||||
{
|
||||
type: "file",
|
||||
name: "big.txt",
|
||||
mimeType: "text/plain",
|
||||
sizeBytes: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
dataUrl: asDataUrl("text/plain", bytes),
|
||||
},
|
||||
]),
|
||||
).pipe(Effect.flip);
|
||||
|
||||
expect(error._tag).toBe("OrchestrationDispatchCommandError");
|
||||
expect(error.message).toBe("Attachment 'big.txt' is empty or too large.");
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
});
|
||||
@@ -109,16 +109,16 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
|
||||
(attachment) =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = parseBase64DataUrl(attachment.dataUrl);
|
||||
if (!parsed || (attachment.type === "image" && !parsed.mimeType.startsWith("image/"))) {
|
||||
if (!parsed || !parsed.mimeType.startsWith("image/")) {
|
||||
return yield* new OrchestrationDispatchCommandError({
|
||||
message: `Invalid ${attachment.type} attachment payload for '${attachment.name}'.`,
|
||||
message: `Invalid image attachment payload for '${attachment.name}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
const bytes = Buffer.from(parsed.base64, "base64");
|
||||
if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
|
||||
return yield* new OrchestrationDispatchCommandError({
|
||||
message: `Attachment '${attachment.name}' is empty or too large.`,
|
||||
message: `Image attachment '${attachment.name}' is empty or too large.`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -130,7 +130,7 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
|
||||
}
|
||||
|
||||
const persistedAttachment = {
|
||||
type: attachment.type,
|
||||
type: "image" as const,
|
||||
id: attachmentId,
|
||||
name: attachment.name,
|
||||
mimeType: parsed.mimeType.toLowerCase(),
|
||||
|
||||
@@ -4,12 +4,16 @@ import {
|
||||
ProjectDeletedPayload as ContractsProjectDeletedPayloadSchema,
|
||||
ThreadCreatedPayload as ContractsThreadCreatedPayloadSchema,
|
||||
ThreadArchivedPayload as ContractsThreadArchivedPayloadSchema,
|
||||
ThreadSettledPayload as ContractsThreadSettledPayloadSchema,
|
||||
ThreadMetaUpdatedPayload as ContractsThreadMetaUpdatedPayloadSchema,
|
||||
ThreadRuntimeModeSetPayload as ContractsThreadRuntimeModeSetPayloadSchema,
|
||||
ThreadInteractionModeSetPayload as ContractsThreadInteractionModeSetPayloadSchema,
|
||||
ThreadDeletedPayload as ContractsThreadDeletedPayloadSchema,
|
||||
ThreadUnarchivedPayload as ContractsThreadUnarchivedPayloadSchema,
|
||||
ThreadUnsettledPayload as ContractsThreadUnsettledPayloadSchema,
|
||||
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
|
||||
ThreadMessageQueuedPayload as ContractsThreadMessageQueuedPayloadSchema,
|
||||
ThreadQueuedMessageRemovedPayload as ContractsThreadQueuedMessageRemovedPayloadSchema,
|
||||
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
|
||||
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
|
||||
ThreadTurnDiffCompletedPayload as ContractsThreadTurnDiffCompletedPayloadSchema,
|
||||
@@ -29,13 +33,17 @@ export const ProjectDeletedPayload = ContractsProjectDeletedPayloadSchema;
|
||||
|
||||
export const ThreadCreatedPayload = ContractsThreadCreatedPayloadSchema;
|
||||
export const ThreadArchivedPayload = ContractsThreadArchivedPayloadSchema;
|
||||
export const ThreadSettledPayload = ContractsThreadSettledPayloadSchema;
|
||||
export const ThreadMetaUpdatedPayload = ContractsThreadMetaUpdatedPayloadSchema;
|
||||
export const ThreadRuntimeModeSetPayload = ContractsThreadRuntimeModeSetPayloadSchema;
|
||||
export const ThreadInteractionModeSetPayload = ContractsThreadInteractionModeSetPayloadSchema;
|
||||
export const ThreadDeletedPayload = ContractsThreadDeletedPayloadSchema;
|
||||
export const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema;
|
||||
export const ThreadUnsettledPayload = ContractsThreadUnsettledPayloadSchema;
|
||||
|
||||
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
|
||||
export const ThreadMessageQueuedPayload = ContractsThreadMessageQueuedPayloadSchema;
|
||||
export const ThreadQueuedMessageRemovedPayload = ContractsThreadQueuedMessageRemovedPayloadSchema;
|
||||
export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;
|
||||
export const ThreadSessionSetPayload = ContractsThreadSessionSetPayloadSchema;
|
||||
export const ThreadTurnDiffCompletedPayload = ContractsThreadTurnDiffCompletedPayloadSchema;
|
||||
|
||||
@@ -68,8 +68,12 @@ const readModel: OrchestrationReadModel = {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
queuedMessages: [],
|
||||
pendingTurnStart: null,
|
||||
session: null,
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
@@ -91,8 +95,12 @@ const readModel: OrchestrationReadModel = {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
queuedMessages: [],
|
||||
pendingTurnStart: null,
|
||||
session: null,
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
|
||||
@@ -0,0 +1,487 @@
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationReadModel,
|
||||
type OrchestrationSessionStatus,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
|
||||
import { decideOrchestrationCommand } from "./decider.ts";
|
||||
import { createEmptyReadModel, projectEvent } from "./projector.ts";
|
||||
|
||||
const NOW = "2026-01-01T00:00:00.000Z";
|
||||
const asCommandId = (value: string): CommandId => CommandId.make(value);
|
||||
const asEventId = (value: string): EventId => EventId.make(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.make(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
|
||||
|
||||
const THREAD_ID = asThreadId("thread-queue");
|
||||
|
||||
const seedReadModel = Effect.gen(function* () {
|
||||
const initial = createEmptyReadModel(NOW);
|
||||
const withProject = yield* projectEvent(initial, {
|
||||
sequence: 1,
|
||||
eventId: asEventId("evt-project-create"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: asProjectId("project-queue"),
|
||||
type: "project.created",
|
||||
occurredAt: NOW,
|
||||
commandId: asCommandId("cmd-project-create"),
|
||||
causationEventId: null,
|
||||
correlationId: asCommandId("cmd-project-create"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: asProjectId("project-queue"),
|
||||
title: "Project Queue",
|
||||
workspaceRoot: "/tmp/project-queue",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: NOW,
|
||||
updatedAt: NOW,
|
||||
},
|
||||
});
|
||||
|
||||
return yield* projectEvent(withProject, {
|
||||
sequence: 2,
|
||||
eventId: asEventId("evt-thread-create"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: THREAD_ID,
|
||||
type: "thread.created",
|
||||
occurredAt: NOW,
|
||||
commandId: asCommandId("cmd-thread-create"),
|
||||
causationEventId: null,
|
||||
correlationId: asCommandId("cmd-thread-create"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: THREAD_ID,
|
||||
projectId: asProjectId("project-queue"),
|
||||
title: "Thread Queue",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: NOW,
|
||||
updatedAt: NOW,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const withSessionStatus = (
|
||||
readModel: OrchestrationReadModel,
|
||||
status: OrchestrationSessionStatus,
|
||||
sequence: number,
|
||||
) =>
|
||||
projectEvent(readModel, {
|
||||
sequence,
|
||||
eventId: asEventId(`evt-session-${status}-${sequence}`),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: THREAD_ID,
|
||||
type: "thread.session-set",
|
||||
occurredAt: NOW,
|
||||
commandId: asCommandId(`cmd-session-${status}-${sequence}`),
|
||||
causationEventId: null,
|
||||
correlationId: null,
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: THREAD_ID,
|
||||
session: {
|
||||
threadId: THREAD_ID,
|
||||
status,
|
||||
providerName: "codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: status === "running" ? TurnId.make("turn-active") : null,
|
||||
lastError: null,
|
||||
updatedAt: NOW,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const turnStartCommand = (suffix: string) =>
|
||||
({
|
||||
type: "thread.turn.start",
|
||||
commandId: asCommandId(`cmd-turn-start-${suffix}`),
|
||||
threadId: THREAD_ID,
|
||||
message: {
|
||||
messageId: asMessageId(`message-${suffix}`),
|
||||
role: "user",
|
||||
text: `Follow up ${suffix}`,
|
||||
attachments: [],
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
createdAt: NOW,
|
||||
}) as const;
|
||||
|
||||
const applyPlanned = (
|
||||
readModel: OrchestrationReadModel,
|
||||
planned:
|
||||
| Omit<OrchestrationEvent, "sequence">
|
||||
| ReadonlyArray<Omit<OrchestrationEvent, "sequence">>,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
let nextReadModel = readModel;
|
||||
let nextSequence = readModel.snapshotSequence;
|
||||
for (const event of Array.isArray(planned) ? planned : [planned]) {
|
||||
nextSequence += 1;
|
||||
nextReadModel = yield* projectEvent(nextReadModel, { ...event, sequence: nextSequence });
|
||||
}
|
||||
return nextReadModel;
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("decider queue flows", (it) => {
|
||||
it.effect("starts a turn immediately when the thread is idle", () =>
|
||||
Effect.gen(function* () {
|
||||
const readModel = yield* seedReadModel;
|
||||
const planned = yield* decideOrchestrationCommand({
|
||||
command: turnStartCommand("idle"),
|
||||
readModel,
|
||||
});
|
||||
const events = Array.isArray(planned) ? planned : [planned];
|
||||
expect(events.map((event) => event.type)).toEqual([
|
||||
"thread.message-sent",
|
||||
"thread.turn-start-requested",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("queues a follow-up while a turn is running", () =>
|
||||
Effect.gen(function* () {
|
||||
const readModel = yield* withSessionStatus(yield* seedReadModel, "running", 3);
|
||||
const planned = yield* decideOrchestrationCommand({
|
||||
command: turnStartCommand("busy"),
|
||||
readModel,
|
||||
});
|
||||
const events = Array.isArray(planned) ? planned : [planned];
|
||||
expect(events.map((event) => event.type)).toEqual(["thread.message-queued"]);
|
||||
|
||||
const projected = yield* applyPlanned(readModel, planned);
|
||||
const thread = projected.threads.find((entry) => entry.id === THREAD_ID);
|
||||
expect(thread?.queuedMessages.map((entry) => entry.messageId)).toEqual([
|
||||
asMessageId("message-busy"),
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("queues a follow-up racing in behind a just-dispatched turn start", () =>
|
||||
Effect.gen(function* () {
|
||||
// First send on an idle thread: dispatches message-sent +
|
||||
// turn-start-requested, but the provider has not reported any
|
||||
// session status yet — the pending-start window.
|
||||
let readModel = yield* seedReadModel;
|
||||
readModel = yield* applyPlanned(
|
||||
readModel,
|
||||
yield* decideOrchestrationCommand({ command: turnStartCommand("pending-1"), readModel }),
|
||||
);
|
||||
|
||||
// Second send in that window must queue, not open a second turn.
|
||||
const planned = yield* decideOrchestrationCommand({
|
||||
command: turnStartCommand("pending-2"),
|
||||
readModel,
|
||||
});
|
||||
const events = Array.isArray(planned) ? planned : [planned];
|
||||
expect(events.map((event) => event.type)).toEqual(["thread.message-queued"]);
|
||||
|
||||
// A drain in the same window is rejected and keeps the queue intact.
|
||||
readModel = yield* applyPlanned(readModel, planned);
|
||||
const drainError = yield* Effect.flip(
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.queue.drain",
|
||||
commandId: asCommandId("cmd-drain-pending"),
|
||||
threadId: THREAD_ID,
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel,
|
||||
}),
|
||||
);
|
||||
expect(drainError.message).toContain("busy");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("drains after a mid-turn steer once the turn settles to ready", () =>
|
||||
Effect.gen(function* () {
|
||||
// Two messages queue while running; the first is steered mid-turn
|
||||
// (re-arming pendingTurnStart), then the turn completes → ready.
|
||||
let readModel = yield* withSessionStatus(yield* seedReadModel, "running", 3);
|
||||
readModel = yield* applyPlanned(
|
||||
readModel,
|
||||
yield* decideOrchestrationCommand({ command: turnStartCommand("settle-1"), readModel }),
|
||||
);
|
||||
readModel = yield* applyPlanned(
|
||||
readModel,
|
||||
yield* decideOrchestrationCommand({ command: turnStartCommand("settle-2"), readModel }),
|
||||
);
|
||||
readModel = yield* applyPlanned(
|
||||
readModel,
|
||||
yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.queue.steer",
|
||||
commandId: asCommandId("cmd-steer-settle"),
|
||||
threadId: THREAD_ID,
|
||||
messageId: asMessageId("message-settle-1"),
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel,
|
||||
}),
|
||||
);
|
||||
// The steer left pendingTurnStart armed with the session still running.
|
||||
let thread = readModel.threads.find((entry) => entry.id === THREAD_ID);
|
||||
expect(thread?.pendingTurnStart?.messageId).toEqual(asMessageId("message-settle-1"));
|
||||
|
||||
// Turn end: session settles to ready, which must release the pending
|
||||
// flag so the queued follow-up can drain.
|
||||
readModel = yield* withSessionStatus(readModel, "ready", readModel.snapshotSequence + 1);
|
||||
thread = readModel.threads.find((entry) => entry.id === THREAD_ID);
|
||||
expect(thread?.pendingTurnStart).toBeNull();
|
||||
|
||||
const planned = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.queue.drain",
|
||||
commandId: asCommandId("cmd-drain-settle"),
|
||||
threadId: THREAD_ID,
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel,
|
||||
});
|
||||
const events = Array.isArray(planned) ? planned : [planned];
|
||||
expect(events.map((event) => event.type)).toEqual([
|
||||
"thread.queued-message-removed",
|
||||
"thread.message-sent",
|
||||
"thread.turn-start-requested",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects queueing past the per-thread cap", () =>
|
||||
Effect.gen(function* () {
|
||||
let readModel = yield* withSessionStatus(yield* seedReadModel, "running", 3);
|
||||
for (let index = 0; index < 50; index += 1) {
|
||||
readModel = yield* applyPlanned(
|
||||
readModel,
|
||||
yield* decideOrchestrationCommand({
|
||||
command: turnStartCommand(`cap-${index}`),
|
||||
readModel,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
decideOrchestrationCommand({ command: turnStartCommand("cap-overflow"), readModel }),
|
||||
);
|
||||
expect(error.message).toContain("queued messages");
|
||||
|
||||
const thread = readModel.threads.find((entry) => entry.id === THREAD_ID);
|
||||
expect(thread?.queuedMessages).toHaveLength(50);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("steer dispatches a queued message even while running", () =>
|
||||
Effect.gen(function* () {
|
||||
let readModel = yield* withSessionStatus(yield* seedReadModel, "running", 3);
|
||||
readModel = yield* applyPlanned(
|
||||
readModel,
|
||||
yield* decideOrchestrationCommand({ command: turnStartCommand("steer"), readModel }),
|
||||
);
|
||||
|
||||
const planned = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.queue.steer",
|
||||
commandId: asCommandId("cmd-steer"),
|
||||
threadId: THREAD_ID,
|
||||
messageId: asMessageId("message-steer"),
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel,
|
||||
});
|
||||
const events = Array.isArray(planned) ? planned : [planned];
|
||||
expect(events.map((event) => event.type)).toEqual([
|
||||
"thread.queued-message-removed",
|
||||
"thread.message-sent",
|
||||
"thread.turn-start-requested",
|
||||
]);
|
||||
|
||||
const projected = yield* applyPlanned(readModel, planned);
|
||||
const thread = projected.threads.find((entry) => entry.id === THREAD_ID);
|
||||
expect(thread?.queuedMessages).toEqual([]);
|
||||
expect(thread?.messages.map((entry) => entry.id)).toContain(asMessageId("message-steer"));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("steer rejects while the session is still starting", () =>
|
||||
Effect.gen(function* () {
|
||||
let readModel = yield* withSessionStatus(yield* seedReadModel, "starting", 3);
|
||||
readModel = yield* applyPlanned(
|
||||
readModel,
|
||||
yield* decideOrchestrationCommand({
|
||||
command: turnStartCommand("steer-starting"),
|
||||
readModel,
|
||||
}),
|
||||
);
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.queue.steer",
|
||||
commandId: asCommandId("cmd-steer-starting"),
|
||||
threadId: THREAD_ID,
|
||||
messageId: asMessageId("message-steer-starting"),
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel,
|
||||
}),
|
||||
);
|
||||
expect(error.message).toContain("starting");
|
||||
|
||||
// The queued message survives the rejected steer.
|
||||
const thread = readModel.threads.find((entry) => entry.id === THREAD_ID);
|
||||
expect(thread?.queuedMessages.map((entry) => entry.messageId)).toEqual([
|
||||
asMessageId("message-steer-starting"),
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("remove deletes a queued message without dispatching", () =>
|
||||
Effect.gen(function* () {
|
||||
let readModel = yield* withSessionStatus(yield* seedReadModel, "running", 3);
|
||||
readModel = yield* applyPlanned(
|
||||
readModel,
|
||||
yield* decideOrchestrationCommand({ command: turnStartCommand("remove"), readModel }),
|
||||
);
|
||||
|
||||
const planned = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.queue.remove",
|
||||
commandId: asCommandId("cmd-remove"),
|
||||
threadId: THREAD_ID,
|
||||
messageId: asMessageId("message-remove"),
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel,
|
||||
});
|
||||
const events = Array.isArray(planned) ? planned : [planned];
|
||||
expect(events.map((event) => event.type)).toEqual(["thread.queued-message-removed"]);
|
||||
|
||||
const projected = yield* applyPlanned(readModel, planned);
|
||||
const thread = projected.threads.find((entry) => entry.id === THREAD_ID);
|
||||
expect(thread?.queuedMessages).toEqual([]);
|
||||
expect(thread?.messages.map((entry) => entry.id)).not.toContain(
|
||||
asMessageId("message-remove"),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("steer and remove reject unknown queued messages", () =>
|
||||
Effect.gen(function* () {
|
||||
const readModel = yield* seedReadModel;
|
||||
for (const type of ["thread.queue.steer", "thread.queue.remove"] as const) {
|
||||
const error = yield* Effect.flip(
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type,
|
||||
commandId: asCommandId(`cmd-${type}-missing`),
|
||||
threadId: THREAD_ID,
|
||||
messageId: asMessageId("message-missing"),
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel,
|
||||
}),
|
||||
);
|
||||
expect(error.message).toContain("does not exist");
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("drain dispatches the queue head once the thread is idle", () =>
|
||||
Effect.gen(function* () {
|
||||
let readModel = yield* withSessionStatus(yield* seedReadModel, "running", 3);
|
||||
readModel = yield* applyPlanned(
|
||||
readModel,
|
||||
yield* decideOrchestrationCommand({ command: turnStartCommand("drain-1"), readModel }),
|
||||
);
|
||||
readModel = yield* applyPlanned(
|
||||
readModel,
|
||||
yield* decideOrchestrationCommand({ command: turnStartCommand("drain-2"), readModel }),
|
||||
);
|
||||
readModel = yield* withSessionStatus(readModel, "ready", readModel.snapshotSequence + 1);
|
||||
|
||||
const planned = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.queue.drain",
|
||||
commandId: asCommandId("cmd-drain"),
|
||||
threadId: THREAD_ID,
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel,
|
||||
});
|
||||
const events = Array.isArray(planned) ? planned : [planned];
|
||||
expect(events.map((event) => event.type)).toEqual([
|
||||
"thread.queued-message-removed",
|
||||
"thread.message-sent",
|
||||
"thread.turn-start-requested",
|
||||
]);
|
||||
|
||||
const projected = yield* applyPlanned(readModel, planned);
|
||||
const thread = projected.threads.find((entry) => entry.id === THREAD_ID);
|
||||
// FIFO: the first queued message dispatches, the second stays queued.
|
||||
expect(thread?.messages.map((entry) => entry.id)).toContain(asMessageId("message-drain-1"));
|
||||
expect(thread?.queuedMessages.map((entry) => entry.messageId)).toEqual([
|
||||
asMessageId("message-drain-2"),
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("drain rejects while the thread is busy and keeps the queue intact", () =>
|
||||
Effect.gen(function* () {
|
||||
let readModel = yield* withSessionStatus(yield* seedReadModel, "running", 3);
|
||||
readModel = yield* applyPlanned(
|
||||
readModel,
|
||||
yield* decideOrchestrationCommand({ command: turnStartCommand("drain-busy"), readModel }),
|
||||
);
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.queue.drain",
|
||||
commandId: asCommandId("cmd-drain-busy"),
|
||||
threadId: THREAD_ID,
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel,
|
||||
}),
|
||||
);
|
||||
expect(error.message).toContain("busy");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("drain rejects when the queue is empty", () =>
|
||||
Effect.gen(function* () {
|
||||
const readModel = yield* seedReadModel;
|
||||
const error = yield* Effect.flip(
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.queue.drain",
|
||||
commandId: asCommandId("cmd-drain-empty"),
|
||||
threadId: THREAD_ID,
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel,
|
||||
}),
|
||||
);
|
||||
expect(error.message).toContain("no queued messages");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,523 @@
|
||||
import {
|
||||
CommandId,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type OrchestrationReadModel,
|
||||
type OrchestrationSession,
|
||||
type OrchestrationThread,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import { decideOrchestrationCommand } from "./decider.ts";
|
||||
|
||||
const NOW = "2026-01-01T00:00:00.000Z";
|
||||
const SETTLED_AT = "2025-12-30T00:00:00.000Z";
|
||||
|
||||
function makeReadModel(
|
||||
settledOverride: OrchestrationThread["settledOverride"],
|
||||
archivedAt: string | null = null,
|
||||
session: OrchestrationSession | null = null,
|
||||
activities: OrchestrationThread["activities"] = [],
|
||||
messages: OrchestrationThread["messages"] = [],
|
||||
): OrchestrationReadModel {
|
||||
return {
|
||||
snapshotSequence: 0,
|
||||
projects: [],
|
||||
threads: [
|
||||
{
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: NOW,
|
||||
updatedAt: NOW,
|
||||
archivedAt,
|
||||
settledOverride,
|
||||
settledAt: settledOverride === "settled" ? SETTLED_AT : null,
|
||||
deletedAt: null,
|
||||
messages,
|
||||
queuedMessages: [],
|
||||
pendingTurnStart: null,
|
||||
proposedPlans: [],
|
||||
activities,
|
||||
checkpoints: [],
|
||||
session,
|
||||
},
|
||||
],
|
||||
updatedAt: NOW,
|
||||
};
|
||||
}
|
||||
|
||||
function makeSession(status: OrchestrationSession["status"]): OrchestrationSession {
|
||||
return {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status,
|
||||
providerName: "Codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: NOW,
|
||||
};
|
||||
}
|
||||
|
||||
it.layer(NodeServices.layer)("settled thread decider", (it) => {
|
||||
it.effect("settles active threads and re-emits idempotently for settled ones", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make("cmd-settle"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel(null),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
expect(events).toHaveLength(1);
|
||||
expect(events[0]?.type).toBe("thread.settled");
|
||||
if (events[0]?.type === "thread.settled") {
|
||||
expect(events[0].payload.settledAt).toBe(events[0].payload.updatedAt);
|
||||
}
|
||||
|
||||
// Already settled: the engine rejects zero-event commands, so idempotency
|
||||
// is by re-emission — preserving the original settledAt.
|
||||
const reEmit = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make("cmd-settle-again"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel("settled"),
|
||||
});
|
||||
const reEmitEvents = Array.isArray(reEmit) ? reEmit : [reEmit];
|
||||
expect(reEmitEvents).toHaveLength(1);
|
||||
expect(reEmitEvents[0]?.type).toBe("thread.settled");
|
||||
if (reEmitEvents[0]?.type === "thread.settled") {
|
||||
expect(reEmitEvents[0].payload.settledAt).toBe(SETTLED_AT);
|
||||
// updatedAt must NOT rewind to the historical settledAt: sorting and
|
||||
// relative-time labels key on it.
|
||||
expect(reEmitEvents[0].payload.updatedAt).not.toBe(SETTLED_AT);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects settling a thread with a live session", () =>
|
||||
Effect.gen(function* () {
|
||||
for (const status of ["starting", "running"] as const) {
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make(`cmd-settle-live-${status}`),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel(null, null, makeSession(status)),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}
|
||||
// Stopped/error sessions are settleable — only live work is protected.
|
||||
const settled = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make("cmd-settle-stopped"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel(null, null, makeSession("stopped")),
|
||||
});
|
||||
const settledEvents = Array.isArray(settled) ? settled : [settled];
|
||||
expect(settledEvents[0]?.type).toBe("thread.settled");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects settling a thread with an open approval or user-input request", () =>
|
||||
Effect.gen(function* () {
|
||||
const requestActivity = (kind: string, requestId: string, at: string) =>
|
||||
({
|
||||
id: EventId.make(`activity-${requestId}-${kind}`),
|
||||
tone: "approval" as const,
|
||||
kind,
|
||||
summary: kind,
|
||||
payload: { requestId },
|
||||
turnId: null,
|
||||
createdAt: at,
|
||||
}) as OrchestrationThread["activities"][number];
|
||||
|
||||
// Open approval request: settle rejected.
|
||||
const openError = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make("cmd-settle-pending"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel(null, null, null, [
|
||||
requestActivity("approval.requested", "req-1", NOW),
|
||||
]),
|
||||
}).pipe(Effect.flip);
|
||||
expect(openError._tag).toBe("OrchestrationCommandInvariantError");
|
||||
|
||||
// Same request later resolved: settleable again.
|
||||
const settled = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make("cmd-settle-resolved"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel(null, null, null, [
|
||||
requestActivity("approval.requested", "req-1", NOW),
|
||||
requestActivity("approval.resolved", "req-1", NOW),
|
||||
]),
|
||||
});
|
||||
const settledEvents = Array.isArray(settled) ? settled : [settled];
|
||||
expect(settledEvents[0]?.type).toBe("thread.settled");
|
||||
|
||||
// Open user-input request: also rejected.
|
||||
const inputError = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make("cmd-settle-pending-input"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel(null, null, null, [
|
||||
requestActivity("user-input.requested", "req-2", NOW),
|
||||
]),
|
||||
}).pipe(Effect.flip);
|
||||
expect(inputError._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("clears an open request when its respond failure marks it stale", () =>
|
||||
Effect.gen(function* () {
|
||||
const activity = (
|
||||
kind: string,
|
||||
requestId: string,
|
||||
payload: Record<string, unknown>,
|
||||
): OrchestrationThread["activities"][number] =>
|
||||
({
|
||||
id: EventId.make(`activity-${requestId}-${kind}`),
|
||||
tone: "approval" as const,
|
||||
kind,
|
||||
summary: kind,
|
||||
payload: { requestId, ...payload },
|
||||
turnId: null,
|
||||
createdAt: NOW,
|
||||
}) as OrchestrationThread["activities"][number];
|
||||
|
||||
// Stale-failure detail clears the request — mirrors the projection's
|
||||
// pending accounting, which is what the client's canSettle sees.
|
||||
const settled = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make("cmd-settle-stale-failed"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel(null, null, null, [
|
||||
activity("approval.requested", "req-1", {}),
|
||||
activity("provider.approval.respond.failed", "req-1", {
|
||||
detail: "Unknown pending approval request req-1",
|
||||
}),
|
||||
activity("user-input.requested", "req-2", {}),
|
||||
activity("provider.user-input.respond.failed", "req-2", {
|
||||
detail: "stale pending user-input request req-2",
|
||||
}),
|
||||
]),
|
||||
});
|
||||
const settledEvents = Array.isArray(settled) ? settled : [settled];
|
||||
expect(settledEvents[0]?.type).toBe("thread.settled");
|
||||
|
||||
// A non-stale respond failure (transient provider error) keeps the
|
||||
// request open: the user can retry, so it is still blocked-on-you.
|
||||
const stillOpen = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make("cmd-settle-transient-failed"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel(null, null, null, [
|
||||
activity("approval.requested", "req-3", {}),
|
||||
activity("provider.approval.respond.failed", "req-3", {
|
||||
detail: "provider connection reset",
|
||||
}),
|
||||
]),
|
||||
}).pipe(Effect.flip);
|
||||
expect(stillOpen._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("bounds the queued-turn grace window against client clock skew", () =>
|
||||
Effect.gen(function* () {
|
||||
const userMessage = (createdAt: string): OrchestrationThread["messages"][number] => ({
|
||||
id: MessageId.make("message-queued"),
|
||||
role: "user",
|
||||
text: "Continue",
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
});
|
||||
|
||||
// The decider's clock is the Effect test clock, pinned to the epoch:
|
||||
// timestamps here are relative to 1970-01-01T00:00:00.000Z.
|
||||
|
||||
// Within the grace window: genuinely queued, settle rejected.
|
||||
const queuedError = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make("cmd-settle-queued"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel(null, null, null, [], [userMessage("1969-12-31T23:59:30.000Z")]),
|
||||
}).pipe(Effect.flip);
|
||||
expect(queuedError._tag).toBe("OrchestrationCommandInvariantError");
|
||||
|
||||
// Message timestamp far in the FUTURE (client clock ahead of server):
|
||||
// a negative age must not read as queued forever — past the grace
|
||||
// bound in either direction the thread is settleable.
|
||||
const skewed = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make("cmd-settle-skewed"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel(null, null, null, [], [userMessage("1970-01-01T01:00:00.000Z")]),
|
||||
});
|
||||
const skewedEvents = Array.isArray(skewed) ? skewed : [skewed];
|
||||
expect(skewedEvents[0]?.type).toBe("thread.settled");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects settling and unsettling archived threads", () =>
|
||||
Effect.gen(function* () {
|
||||
const settleError = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make("cmd-settle-archived"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel(null, NOW),
|
||||
}).pipe(Effect.flip);
|
||||
expect(settleError._tag).toBe("OrchestrationCommandInvariantError");
|
||||
|
||||
const unsettleError = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.unsettle",
|
||||
commandId: CommandId.make("cmd-unsettle-archived"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
reason: "user",
|
||||
},
|
||||
readModel: makeReadModel("settled", NOW),
|
||||
}).pipe(Effect.flip);
|
||||
expect(unsettleError._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("maps unsettle reasons to overrides and re-emits idempotently", () =>
|
||||
Effect.gen(function* () {
|
||||
const userEvent = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.unsettle",
|
||||
commandId: CommandId.make("cmd-unsettle-user"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
reason: "user",
|
||||
},
|
||||
readModel: makeReadModel("settled"),
|
||||
});
|
||||
const userEvents = Array.isArray(userEvent) ? userEvent : [userEvent];
|
||||
expect(userEvents).toHaveLength(1);
|
||||
expect(userEvents[0]?.type).toBe("thread.unsettled");
|
||||
if (userEvents[0]?.type === "thread.unsettled") {
|
||||
expect(userEvents[0].payload.reason).toBe("user");
|
||||
}
|
||||
|
||||
// Re-dispatching against the already-reached state re-emits rather than
|
||||
// producing zero events (the engine rejects empty commands).
|
||||
const userAgain = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.unsettle",
|
||||
commandId: CommandId.make("cmd-unsettle-user-again"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
reason: "user",
|
||||
},
|
||||
readModel: makeReadModel("active"),
|
||||
});
|
||||
const userAgainEvents = Array.isArray(userAgain) ? userAgain : [userAgain];
|
||||
expect(userAgainEvents).toHaveLength(1);
|
||||
expect(userAgainEvents[0]?.type).toBe("thread.unsettled");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prepends activity unsets for turn starts and live session updates", () =>
|
||||
Effect.gen(function* () {
|
||||
const turnResult = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: MessageId.make("message-1"),
|
||||
role: "user",
|
||||
text: "Continue",
|
||||
attachments: [],
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel: makeReadModel("settled"),
|
||||
});
|
||||
const turnEvents = Array.isArray(turnResult) ? turnResult : [turnResult];
|
||||
expect(turnEvents.map((event) => event.type)).toEqual([
|
||||
"thread.unsettled",
|
||||
"thread.message-sent",
|
||||
"thread.turn-start-requested",
|
||||
]);
|
||||
|
||||
const sessionResult = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("cmd-session-set"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: makeSession("running"),
|
||||
createdAt: NOW,
|
||||
},
|
||||
// A keep-active pin is also an override: real activity clears it
|
||||
// back to neutral so auto-settle can apply again later.
|
||||
readModel: makeReadModel("active"),
|
||||
});
|
||||
const sessionEvents = Array.isArray(sessionResult) ? sessionResult : [sessionResult];
|
||||
expect(sessionEvents.map((event) => event.type)).toEqual([
|
||||
"thread.unsettled",
|
||||
"thread.session-set",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("clears a keep-active pin on real activity", () =>
|
||||
Effect.gen(function* () {
|
||||
const turnResult = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-active-turn-start"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: MessageId.make("message-active"),
|
||||
role: "user",
|
||||
text: "Continue",
|
||||
attachments: [],
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel: makeReadModel("active"),
|
||||
});
|
||||
const turnEvents = Array.isArray(turnResult) ? turnResult : [turnResult];
|
||||
// The pin exists to suppress AUTO-settle, not to survive real work:
|
||||
// activity resets it to neutral, restoring the default lifecycle.
|
||||
expect(turnEvents.map((event) => event.type)).toEqual([
|
||||
"thread.unsettled",
|
||||
"thread.message-sent",
|
||||
"thread.turn-start-requested",
|
||||
]);
|
||||
|
||||
const activityResult = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.activity.append",
|
||||
commandId: CommandId.make("cmd-active-approval"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
activity: {
|
||||
id: EventId.make("activity-active"),
|
||||
tone: "approval",
|
||||
kind: "approval.requested",
|
||||
summary: "Command approval requested",
|
||||
payload: null,
|
||||
turnId: null,
|
||||
createdAt: NOW,
|
||||
},
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel: makeReadModel("active"),
|
||||
});
|
||||
const activityEvents = Array.isArray(activityResult) ? activityResult : [activityResult];
|
||||
expect(activityEvents.map((event) => event.type)).toEqual([
|
||||
"thread.unsettled",
|
||||
"thread.activity-appended",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not unsettle for session stop/error status writes", () =>
|
||||
Effect.gen(function* () {
|
||||
for (const status of ["stopped", "error", "ready", "idle"] as const) {
|
||||
const result = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make(`cmd-session-${status}`),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: makeSession(status),
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel: makeReadModel("settled"),
|
||||
});
|
||||
const events = Array.isArray(result) ? result : [result];
|
||||
expect(events.map((event) => event.type)).toEqual(["thread.session-set"]);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("unsettles for approval and user-input activities but not others", () =>
|
||||
Effect.gen(function* () {
|
||||
const approvalResult = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.activity.append",
|
||||
commandId: CommandId.make("cmd-activity-approval"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
activity: {
|
||||
id: EventId.make("activity-1"),
|
||||
tone: "approval",
|
||||
kind: "approval.requested",
|
||||
summary: "Command approval requested",
|
||||
payload: null,
|
||||
turnId: null,
|
||||
createdAt: NOW,
|
||||
},
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel: makeReadModel("settled"),
|
||||
});
|
||||
const approvalEvents = Array.isArray(approvalResult) ? approvalResult : [approvalResult];
|
||||
expect(approvalEvents.map((event) => event.type)).toEqual([
|
||||
"thread.unsettled",
|
||||
"thread.activity-appended",
|
||||
]);
|
||||
|
||||
const routineResult = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.activity.append",
|
||||
commandId: CommandId.make("cmd-activity-routine"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
activity: {
|
||||
id: EventId.make("activity-2"),
|
||||
tone: "info",
|
||||
kind: "tool.completed",
|
||||
summary: "Tool completed",
|
||||
payload: null,
|
||||
turnId: null,
|
||||
createdAt: NOW,
|
||||
},
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel: makeReadModel("settled"),
|
||||
});
|
||||
const routineEvents = Array.isArray(routineResult) ? routineResult : [routineResult];
|
||||
expect(routineEvents.map((event) => event.type)).toEqual(["thread.activity-appended"]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -2,7 +2,9 @@ import {
|
||||
EventId,
|
||||
type OrchestrationCommand,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationQueuedMessage,
|
||||
type OrchestrationReadModel,
|
||||
type OrchestrationThread,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
@@ -24,6 +26,61 @@ import { projectEvent } from "./projector.ts";
|
||||
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
|
||||
// Session adoption takes seconds; a user message still unadopted after this
|
||||
// window is a failed/stale start, not pending work. Mirrors the client's
|
||||
// QUEUED_TURN_START_GRACE_MS in client-runtime threadSettled.ts.
|
||||
const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;
|
||||
|
||||
/**
|
||||
* Blocked-on-you work derived from the thread's retained activities: an
|
||||
* approval or user-input request with no later resolution for the same
|
||||
* requestId. The server-side twin of the shell's hasPendingApprovals /
|
||||
* hasPendingUserInput flags, which the decider read model does not carry.
|
||||
* The clearing rules MUST match ProjectionPipeline's pending accounting —
|
||||
* resolved activities always clear, respond.failed clears only when the
|
||||
* failure detail marks the request stale/unknown — or settle would be
|
||||
* rejected on threads whose shell flags read as clear.
|
||||
*/
|
||||
function isStaleRequestFailureDetail(payload: Record<string, unknown> | null): boolean {
|
||||
const detail = typeof payload?.detail === "string" ? payload.detail.toLowerCase() : null;
|
||||
if (detail === null) return false;
|
||||
return (
|
||||
detail.includes("stale pending approval request") ||
|
||||
detail.includes("unknown pending approval request") ||
|
||||
detail.includes("unknown pending permission request") ||
|
||||
detail.includes("stale pending user-input request") ||
|
||||
detail.includes("unknown pending user-input request") ||
|
||||
detail.includes("unknown pending user input request") ||
|
||||
detail.includes("unknown pending codex user input request")
|
||||
);
|
||||
}
|
||||
|
||||
function hasOpenBlockingRequest(thread: {
|
||||
readonly activities: ReadonlyArray<{ readonly kind: string; readonly payload: unknown }>;
|
||||
}): boolean {
|
||||
const openRequestIds = new Set<string>();
|
||||
for (const activity of thread.activities) {
|
||||
const payload =
|
||||
typeof activity.payload === "object" && activity.payload !== null
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: null;
|
||||
const requestId = typeof payload?.requestId === "string" ? payload.requestId : null;
|
||||
if (requestId === null) continue;
|
||||
if (activity.kind === "approval.requested" || activity.kind === "user-input.requested") {
|
||||
openRequestIds.add(requestId);
|
||||
} else if (activity.kind === "approval.resolved" || activity.kind === "user-input.resolved") {
|
||||
openRequestIds.delete(requestId);
|
||||
} else if (
|
||||
(activity.kind === "provider.approval.respond.failed" ||
|
||||
activity.kind === "provider.user-input.respond.failed") &&
|
||||
isStaleRequestFailureDetail(payload)
|
||||
) {
|
||||
openRequestIds.delete(requestId);
|
||||
}
|
||||
}
|
||||
return openRequestIds.size > 0;
|
||||
}
|
||||
|
||||
function withEventBase(
|
||||
input: Pick<OrchestrationCommand, "commandId"> & {
|
||||
readonly aggregateKind: OrchestrationEvent["aggregateKind"];
|
||||
@@ -60,6 +117,216 @@ type DecideOrchestrationCommandResult =
|
||||
| PlannedOrchestrationEvent
|
||||
| ReadonlyArray<PlannedOrchestrationEvent>;
|
||||
|
||||
/**
|
||||
* A turn is considered active while its session is starting or running.
|
||||
* Follow-up `thread.turn.start` commands arriving in that window are queued
|
||||
* instead of dispatched; explicit `thread.queue.steer` bypasses the queue.
|
||||
*/
|
||||
function isThreadTurnActive(thread: OrchestrationThread): boolean {
|
||||
const status = thread.session?.status;
|
||||
return status === "running" || status === "starting";
|
||||
}
|
||||
|
||||
/**
|
||||
* Settle-guard heuristic: the latest user message is newer than any turn
|
||||
* activity, i.e. a turn start that no session has picked up yet. Message
|
||||
* timestamps are client-supplied, so queue/dispatch decisions must NOT
|
||||
* hang off this (see `pendingTurnStart` on the thread for the event-driven
|
||||
* signal); settle tolerates the skew — it merely delays settling within
|
||||
* the grace window.
|
||||
*/
|
||||
function hasRecentUnadoptedUserMessage(thread: OrchestrationThread, occurredAt: string): boolean {
|
||||
const latestUserMessageAtMs = thread.messages.reduce(
|
||||
(latest, message) =>
|
||||
message.role === "user" ? Math.max(latest, Date.parse(message.createdAt)) : latest,
|
||||
Number.NEGATIVE_INFINITY,
|
||||
);
|
||||
const latestTurnAtMs =
|
||||
thread.latestTurn === null
|
||||
? Number.NEGATIVE_INFINITY
|
||||
: Math.max(
|
||||
...[
|
||||
thread.latestTurn.requestedAt,
|
||||
thread.latestTurn.startedAt,
|
||||
thread.latestTurn.completedAt,
|
||||
].map((candidate) =>
|
||||
candidate == null ? Number.NEGATIVE_INFINITY : Date.parse(candidate),
|
||||
),
|
||||
);
|
||||
const queuedAgeMs = Date.parse(occurredAt) - latestUserMessageAtMs;
|
||||
return (
|
||||
thread.session?.status !== "error" &&
|
||||
Number.isFinite(latestUserMessageAtMs) &&
|
||||
latestUserMessageAtMs > latestTurnAtMs &&
|
||||
Math.abs(queuedAgeMs) <= QUEUED_TURN_START_GRACE_MS
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enforced here in the decider so a `thread.message-queued` event past the
|
||||
* cap is never emitted — projections and persistence stay in lockstep with
|
||||
* the event stream instead of each clamping independently.
|
||||
*/
|
||||
const MAX_THREAD_QUEUED_MESSAGES = 50;
|
||||
|
||||
interface TurnStartMessageInput {
|
||||
readonly messageId: OrchestrationQueuedMessage["messageId"];
|
||||
readonly text: string;
|
||||
readonly attachments: OrchestrationQueuedMessage["attachments"];
|
||||
readonly modelSelection?: OrchestrationQueuedMessage["modelSelection"];
|
||||
readonly titleSeed?: string;
|
||||
readonly sourceProposedPlan?: OrchestrationQueuedMessage["sourceProposedPlan"];
|
||||
}
|
||||
|
||||
/**
|
||||
* Plan the `thread.message-sent` + `thread.turn-start-requested` event pair
|
||||
* shared by immediate turn starts, queued-message steers, and queue drains.
|
||||
*/
|
||||
const planTurnStartEvents = Effect.fn("planTurnStartEvents")(function* ({
|
||||
commandId,
|
||||
thread,
|
||||
message,
|
||||
occurredAt,
|
||||
}: {
|
||||
readonly commandId: OrchestrationCommand["commandId"];
|
||||
readonly thread: OrchestrationThread;
|
||||
readonly message: TurnStartMessageInput;
|
||||
readonly occurredAt: string;
|
||||
}): Effect.fn.Return<
|
||||
ReadonlyArray<PlannedOrchestrationEvent>,
|
||||
PlatformError.PlatformError,
|
||||
Crypto.Crypto
|
||||
> {
|
||||
const userMessageEvent: PlannedOrchestrationEvent = {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: thread.id,
|
||||
occurredAt,
|
||||
commandId,
|
||||
})),
|
||||
type: "thread.message-sent",
|
||||
payload: {
|
||||
threadId: thread.id,
|
||||
messageId: message.messageId,
|
||||
role: "user",
|
||||
text: message.text,
|
||||
attachments: message.attachments,
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: occurredAt,
|
||||
updatedAt: occurredAt,
|
||||
},
|
||||
};
|
||||
const turnStartRequestedEvent: PlannedOrchestrationEvent = {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: thread.id,
|
||||
occurredAt,
|
||||
commandId,
|
||||
})),
|
||||
causationEventId: userMessageEvent.eventId,
|
||||
type: "thread.turn-start-requested",
|
||||
payload: {
|
||||
threadId: thread.id,
|
||||
messageId: message.messageId,
|
||||
...(message.modelSelection !== undefined ? { modelSelection: message.modelSelection } : {}),
|
||||
...(message.titleSeed !== undefined ? { titleSeed: message.titleSeed } : {}),
|
||||
runtimeMode: thread.runtimeMode,
|
||||
interactionMode: thread.interactionMode,
|
||||
...(message.sourceProposedPlan !== undefined
|
||||
? { sourceProposedPlan: message.sourceProposedPlan }
|
||||
: {}),
|
||||
createdAt: occurredAt,
|
||||
},
|
||||
};
|
||||
// Real activity resets ANY override: it wakes an explicitly settled
|
||||
// thread, and it clears a keep-active pin back to neutral so the
|
||||
// thread can auto-settle again after this burst of work goes stale.
|
||||
if (thread.settledOverride === null) {
|
||||
return [userMessageEvent, turnStartRequestedEvent];
|
||||
}
|
||||
const unsettledEvent: PlannedOrchestrationEvent = {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: thread.id,
|
||||
occurredAt,
|
||||
commandId,
|
||||
})),
|
||||
type: "thread.unsettled",
|
||||
payload: {
|
||||
threadId: thread.id,
|
||||
reason: "activity",
|
||||
updatedAt: occurredAt,
|
||||
},
|
||||
};
|
||||
return [unsettledEvent, userMessageEvent, turnStartRequestedEvent];
|
||||
});
|
||||
|
||||
/**
|
||||
* Plan the dispatch of one queued message: remove it from the queue and
|
||||
* start (or steer into) a turn with it. `sourceProposedPlan` is dropped
|
||||
* rather than failed when the referenced plan no longer exists — the
|
||||
* message itself must still send.
|
||||
*/
|
||||
const planQueuedMessageDispatch = Effect.fn("planQueuedMessageDispatch")(function* ({
|
||||
commandId,
|
||||
readModel,
|
||||
thread,
|
||||
queuedMessage,
|
||||
occurredAt,
|
||||
}: {
|
||||
readonly commandId: OrchestrationCommand["commandId"];
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
readonly thread: OrchestrationThread;
|
||||
readonly queuedMessage: OrchestrationQueuedMessage;
|
||||
readonly occurredAt: string;
|
||||
}): Effect.fn.Return<
|
||||
ReadonlyArray<PlannedOrchestrationEvent>,
|
||||
PlatformError.PlatformError,
|
||||
Crypto.Crypto
|
||||
> {
|
||||
const sourceProposedPlan = queuedMessage.sourceProposedPlan;
|
||||
const sourceThread = sourceProposedPlan
|
||||
? readModel.threads.find((entry) => entry.id === sourceProposedPlan.threadId)
|
||||
: undefined;
|
||||
const sourcePlanStillValid =
|
||||
sourceProposedPlan !== undefined &&
|
||||
sourceThread !== undefined &&
|
||||
sourceThread.projectId === thread.projectId &&
|
||||
sourceThread.proposedPlans.some((entry) => entry.id === sourceProposedPlan.planId);
|
||||
|
||||
const removedEvent: PlannedOrchestrationEvent = {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: thread.id,
|
||||
occurredAt,
|
||||
commandId,
|
||||
})),
|
||||
type: "thread.queued-message-removed",
|
||||
payload: {
|
||||
threadId: thread.id,
|
||||
messageId: queuedMessage.messageId,
|
||||
reason: "dispatched",
|
||||
removedAt: occurredAt,
|
||||
},
|
||||
};
|
||||
const turnStartEvents = yield* planTurnStartEvents({
|
||||
commandId,
|
||||
thread,
|
||||
message: {
|
||||
messageId: queuedMessage.messageId,
|
||||
text: queuedMessage.text,
|
||||
attachments: queuedMessage.attachments,
|
||||
...(queuedMessage.modelSelection !== undefined
|
||||
? { modelSelection: queuedMessage.modelSelection }
|
||||
: {}),
|
||||
...(sourcePlanStillValid ? { sourceProposedPlan } : {}),
|
||||
},
|
||||
occurredAt,
|
||||
});
|
||||
return [removedEvent, ...turnStartEvents];
|
||||
});
|
||||
|
||||
const decideCommandSequence = Effect.fn("decideCommandSequence")(function* ({
|
||||
commands,
|
||||
readModel,
|
||||
@@ -327,6 +594,104 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.settle": {
|
||||
const thread = yield* requireThreadNotArchived({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
// Server-side twin of the client's canSettle session check: a stale
|
||||
// or raced client must not settle a thread whose session is coming
|
||||
// alive or working.
|
||||
if (thread.session?.status === "starting" || thread.session?.status === "running") {
|
||||
return yield* Effect.fail(
|
||||
new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `thread ${command.threadId} has an active session and cannot be settled`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
// Pending approval / user-input requests are blocked-on-you work: a
|
||||
// raced or stale client must not park them behind a settled override
|
||||
// that would surface only after the request resolves.
|
||||
if (hasOpenBlockingRequest(thread)) {
|
||||
return yield* Effect.fail(
|
||||
new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `thread ${command.threadId} has a pending approval or user-input request and cannot be settled`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
const occurredAt = yield* nowIso;
|
||||
// A queued turn start — a user message no turn has picked up yet — is
|
||||
// work in flight even though session is still null (turn.start emits
|
||||
// message-sent + turn-start-requested; the session arrives later).
|
||||
// Settling in that window would hide just-requested work. Detection
|
||||
// mirrors the client's hasQueuedTurnStart: the newest user message is
|
||||
// strictly newer than every latestTurn timestamp (adoption stamps the
|
||||
// new turn's requestedAt with the message time, clearing this), and
|
||||
// only within the adoption grace window — historical threads whose
|
||||
// last user message postdates their turn timestamps (older-server
|
||||
// data, mid-turn messages) must stay settleable. A failed session
|
||||
// start (status "error") clears the block immediately.
|
||||
if (hasRecentUnadoptedUserMessage(thread, occurredAt)) {
|
||||
return yield* Effect.fail(
|
||||
new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `thread ${command.threadId} has a queued turn start and cannot be settled`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
// Settling an already-settled thread re-emits with the original
|
||||
// settledAt: the engine rejects zero-event commands, and bulk-settle /
|
||||
// double-click must stay silent no-ops rather than surface errors.
|
||||
const alreadySettled = thread.settledOverride === "settled" && thread.settledAt !== null;
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.settled",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
settledAt: alreadySettled ? thread.settledAt : occurredAt,
|
||||
// A re-emission is a projected no-op: keep the existing updatedAt
|
||||
// so duplicate settles neither rewind nor churn ordering. A fresh
|
||||
// settle stamps the command time.
|
||||
updatedAt: alreadySettled ? thread.updatedAt : occurredAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.unsettle": {
|
||||
const thread = yield* requireThreadNotArchived({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
// Idempotent by re-emission (see thread.settle): reducing the event a
|
||||
// second time lands on the same override state. A re-emission keeps
|
||||
// the existing updatedAt so duplicates do not churn ordering.
|
||||
const alreadyPinnedActive = thread.settledOverride === "active";
|
||||
const occurredAt = yield* nowIso;
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsettled",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: command.reason,
|
||||
updatedAt: alreadyPinnedActive ? thread.updatedAt : occurredAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.meta.update": {
|
||||
const thread = yield* requireThread({
|
||||
readModel,
|
||||
@@ -437,49 +802,169 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
detail: `Proposed plan '${sourceProposedPlan?.planId}' belongs to thread '${sourceThread.id}' in a different project.`,
|
||||
});
|
||||
}
|
||||
const userMessageEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.message-sent",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
// Queue-by-default: a follow-up arriving while a turn is active is
|
||||
// held server-side and drained on natural turn completion. Explicit
|
||||
// mid-turn injection goes through `thread.queue.steer`. Bootstrap
|
||||
// starts are exempt — their thread was created in the same dispatch.
|
||||
// `pendingTurnStart` covers the window where a turn start was just
|
||||
// dispatched (by a send or a queue drain) but the provider has not
|
||||
// reported the session status yet — a send in that gap must queue,
|
||||
// not open a second concurrent turn ahead of already-queued chips.
|
||||
if (
|
||||
command.bootstrap === undefined &&
|
||||
(isThreadTurnActive(targetThread) || targetThread.pendingTurnStart !== null)
|
||||
) {
|
||||
if (targetThread.queuedMessages.length >= MAX_THREAD_QUEUED_MESSAGES) {
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `Thread '${command.threadId}' already has ${MAX_THREAD_QUEUED_MESSAGES} queued messages.`,
|
||||
});
|
||||
}
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.message-queued",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
messageId: command.message.messageId,
|
||||
text: command.message.text,
|
||||
attachments: command.message.attachments,
|
||||
...(command.modelSelection !== undefined
|
||||
? { modelSelection: command.modelSelection }
|
||||
: {}),
|
||||
...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}),
|
||||
queuedAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return yield* planTurnStartEvents({
|
||||
commandId: command.commandId,
|
||||
thread: targetThread,
|
||||
message: {
|
||||
messageId: command.message.messageId,
|
||||
role: "user",
|
||||
text: command.message.text,
|
||||
attachments: command.message.attachments,
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: command.createdAt,
|
||||
updatedAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
const turnStartRequestedEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
causationEventId: userMessageEvent.eventId,
|
||||
type: "thread.turn-start-requested",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
messageId: command.message.messageId,
|
||||
...(command.modelSelection !== undefined
|
||||
? { modelSelection: command.modelSelection }
|
||||
: {}),
|
||||
...(command.titleSeed !== undefined ? { titleSeed: command.titleSeed } : {}),
|
||||
runtimeMode: targetThread.runtimeMode,
|
||||
interactionMode: targetThread.interactionMode,
|
||||
...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}),
|
||||
createdAt: command.createdAt,
|
||||
},
|
||||
occurredAt: command.createdAt,
|
||||
});
|
||||
}
|
||||
|
||||
case "thread.queue.steer": {
|
||||
const thread = yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
const queuedMessage = thread.queuedMessages.find(
|
||||
(entry) => entry.messageId === command.messageId,
|
||||
);
|
||||
if (!queuedMessage) {
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `Queued message '${command.messageId}' does not exist on thread '${command.threadId}'.`,
|
||||
});
|
||||
}
|
||||
// While a turn start is still pending there is no provider turn to
|
||||
// steer into — dispatching now would race the pending turn/start with
|
||||
// a second one. The message stays queued; steer again once running.
|
||||
// A session that already tracks an active turn (running, or a
|
||||
// provider reconnect mid-turn) is steerable. Rejected shapes: starting
|
||||
// with no active turn, and any session without an active turn while a
|
||||
// just-dispatched turn start is still awaiting adoption — including
|
||||
// "running" with a null activeTurnId (provider waiting).
|
||||
const steerRacesPendingStart =
|
||||
(thread.session?.status === "starting" && thread.session.activeTurnId === null) ||
|
||||
(thread.pendingTurnStart !== null && (thread.session?.activeTurnId ?? null) === null);
|
||||
if (steerRacesPendingStart) {
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `Thread '${command.threadId}' is still starting a turn; steer once it is running.`,
|
||||
});
|
||||
}
|
||||
// Otherwise dispatch unconditionally: with a running turn the provider
|
||||
// adapters treat the resulting sendTurn as a steer; on an idle thread
|
||||
// this degrades to a normal turn start.
|
||||
return yield* planQueuedMessageDispatch({
|
||||
commandId: command.commandId,
|
||||
readModel,
|
||||
thread,
|
||||
queuedMessage,
|
||||
occurredAt: command.createdAt,
|
||||
});
|
||||
}
|
||||
|
||||
case "thread.queue.remove": {
|
||||
const thread = yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
const queuedMessage = thread.queuedMessages.find(
|
||||
(entry) => entry.messageId === command.messageId,
|
||||
);
|
||||
if (!queuedMessage) {
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `Queued message '${command.messageId}' does not exist on thread '${command.threadId}'.`,
|
||||
});
|
||||
}
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.queued-message-removed",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
messageId: command.messageId,
|
||||
reason: "user",
|
||||
removedAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
return [userMessageEvent, turnStartRequestedEvent];
|
||||
}
|
||||
|
||||
case "thread.queue.drain": {
|
||||
const thread = yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
const queuedMessage = thread.queuedMessages.at(0);
|
||||
if (!queuedMessage) {
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `Thread '${command.threadId}' has no queued messages to drain.`,
|
||||
});
|
||||
}
|
||||
// The user may have raced a new message in between turn completion and
|
||||
// this drain; keep the queue intact and let the next completion retry.
|
||||
// The pending-start check also stops a duplicate drain from double-
|
||||
// dispatching while the first drained turn's session is still unset.
|
||||
if (isThreadTurnActive(thread) || thread.pendingTurnStart !== null) {
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `Thread '${command.threadId}' is busy; queued messages drain on turn completion.`,
|
||||
});
|
||||
}
|
||||
return yield* planQueuedMessageDispatch({
|
||||
commandId: command.commandId,
|
||||
readModel,
|
||||
thread,
|
||||
queuedMessage,
|
||||
occurredAt: command.createdAt,
|
||||
});
|
||||
}
|
||||
|
||||
case "thread.turn.interrupt": {
|
||||
@@ -600,12 +1085,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
}
|
||||
|
||||
case "thread.session.set": {
|
||||
yield* requireThread({
|
||||
const thread = yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
const sessionSetEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
@@ -619,6 +1104,30 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
session: command.session,
|
||||
},
|
||||
};
|
||||
// Only a session coming alive is activity worth waking a settled thread
|
||||
// for — status writes like ready/stopped/error arrive after the fact and
|
||||
// must not fight a user's explicit settle.
|
||||
const isSessionActivity =
|
||||
command.session.status === "starting" || command.session.status === "running";
|
||||
// Real activity resets ANY override (settled wakes, active unpins).
|
||||
if (thread.settledOverride === null || !isSessionActivity) {
|
||||
return sessionSetEvent;
|
||||
}
|
||||
const unsettledEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsettled",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: "activity",
|
||||
updatedAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
return [unsettledEvent, sessionSetEvent];
|
||||
}
|
||||
|
||||
case "thread.message.assistant.delta": {
|
||||
@@ -745,7 +1254,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
}
|
||||
|
||||
case "thread.activity.append": {
|
||||
yield* requireThread({
|
||||
const thread = yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
@@ -758,7 +1267,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
? ((command.activity.payload as { requestId: string })
|
||||
.requestId as OrchestrationEvent["metadata"]["requestId"])
|
||||
: undefined;
|
||||
return {
|
||||
const activityAppendedEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
@@ -772,6 +1281,30 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
activity: command.activity,
|
||||
},
|
||||
};
|
||||
// An approval or user-input request is blocked-on-you work — it must
|
||||
// never stay hidden inside a settled slim row.
|
||||
const wakesSettledThread =
|
||||
command.activity.kind === "approval.requested" ||
|
||||
command.activity.kind === "user-input.requested";
|
||||
// Real activity resets ANY override (settled wakes, active unpins).
|
||||
if (thread.settledOverride === null || !wakesSettledThread) {
|
||||
return activityAppendedEvent;
|
||||
}
|
||||
const unsettledEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsettled",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: "activity",
|
||||
updatedAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
return [unsettledEvent, activityAppendedEvent];
|
||||
}
|
||||
|
||||
default: {
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import {
|
||||
CommandId,
|
||||
EventId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
type OrchestrationEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import { createEmptyReadModel, projectEvent } from "./projector.ts";
|
||||
|
||||
function makeEvent(input: {
|
||||
readonly sequence: number;
|
||||
readonly type: OrchestrationEvent["type"];
|
||||
readonly payload: unknown;
|
||||
}): OrchestrationEvent {
|
||||
return {
|
||||
sequence: input.sequence,
|
||||
eventId: EventId.make(`event-${input.sequence}`),
|
||||
type: input.type,
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-1"),
|
||||
occurredAt: "2026-01-01T00:00:00.000Z",
|
||||
commandId: CommandId.make(`command-${input.sequence}`),
|
||||
causationEventId: null,
|
||||
correlationId: null,
|
||||
metadata: {},
|
||||
payload: input.payload as never,
|
||||
} as OrchestrationEvent;
|
||||
}
|
||||
|
||||
it.effect("projects settled lifecycle events", () =>
|
||||
Effect.gen(function* () {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const created = yield* projectEvent(
|
||||
createEmptyReadModel(now),
|
||||
makeEvent({
|
||||
sequence: 1,
|
||||
type: "thread.created",
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: { provider: "codex", model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const settled = yield* projectEvent(
|
||||
created,
|
||||
makeEvent({
|
||||
sequence: 2,
|
||||
type: "thread.settled",
|
||||
payload: { threadId: ThreadId.make("thread-1"), settledAt: now, updatedAt: now },
|
||||
}),
|
||||
);
|
||||
expect(settled.threads[0]?.settledOverride).toBe("settled");
|
||||
expect(settled.threads[0]?.settledAt).toBe(now);
|
||||
|
||||
const userUnsettled = yield* projectEvent(
|
||||
settled,
|
||||
makeEvent({
|
||||
sequence: 3,
|
||||
type: "thread.unsettled",
|
||||
payload: { threadId: ThreadId.make("thread-1"), reason: "user", updatedAt: now },
|
||||
}),
|
||||
);
|
||||
expect(userUnsettled.threads[0]?.settledOverride).toBe("active");
|
||||
expect(userUnsettled.threads[0]?.settledAt).toBeNull();
|
||||
|
||||
const activityUnsettled = yield* projectEvent(
|
||||
userUnsettled,
|
||||
makeEvent({
|
||||
sequence: 4,
|
||||
type: "thread.unsettled",
|
||||
payload: { threadId: ThreadId.make("thread-1"), reason: "activity", updatedAt: now },
|
||||
}),
|
||||
);
|
||||
expect(activityUnsettled.threads[0]?.settledOverride).toBeNull();
|
||||
expect(activityUnsettled.threads[0]?.settledAt).toBeNull();
|
||||
}),
|
||||
);
|
||||
@@ -89,8 +89,12 @@ describe("orchestration projector", () => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
queuedMessages: [],
|
||||
pendingTurnStart: null,
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
|
||||
@@ -11,6 +11,8 @@ import * as Schema from "effect/Schema";
|
||||
import { toProjectorDecodeError, type OrchestrationProjectorDecodeError } from "./Errors.ts";
|
||||
import {
|
||||
MessageSentPayloadSchema,
|
||||
ThreadMessageQueuedPayload,
|
||||
ThreadQueuedMessageRemovedPayload,
|
||||
ProjectCreatedPayload,
|
||||
ProjectDeletedPayload,
|
||||
ProjectMetaUpdatedPayload,
|
||||
@@ -22,10 +24,13 @@ import {
|
||||
ThreadMetaUpdatedPayload,
|
||||
ThreadProposedPlanUpsertedPayload,
|
||||
ThreadRuntimeModeSetPayload,
|
||||
ThreadSettledPayload,
|
||||
ThreadUnarchivedPayload,
|
||||
ThreadUnsettledPayload,
|
||||
ThreadRevertedPayload,
|
||||
ThreadSessionSetPayload,
|
||||
ThreadTurnDiffCompletedPayload,
|
||||
ThreadTurnStartRequestedPayload,
|
||||
} from "./Schemas.ts";
|
||||
|
||||
type ThreadPatch = Partial<Omit<OrchestrationThread, "id" | "projectId">>;
|
||||
@@ -286,8 +291,12 @@ export function projectEvent(
|
||||
createdAt: payload.createdAt,
|
||||
updatedAt: payload.updatedAt,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
queuedMessages: [],
|
||||
pendingTurnStart: null,
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
@@ -311,6 +320,10 @@ export function projectEvent(
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
deletedAt: payload.deletedAt,
|
||||
updatedAt: payload.deletedAt,
|
||||
// Persistence drops this thread's queued-message rows on delete;
|
||||
// mirror that here so queue commands can't act on a deleted
|
||||
// thread's stale in-memory queue.
|
||||
queuedMessages: [],
|
||||
}),
|
||||
})),
|
||||
);
|
||||
@@ -337,6 +350,30 @@ export function projectEvent(
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.settled":
|
||||
return decodeForEvent(ThreadSettledPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
settledOverride: "settled",
|
||||
settledAt: payload.settledAt,
|
||||
updatedAt: payload.updatedAt,
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.unsettled":
|
||||
return decodeForEvent(ThreadUnsettledPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
settledOverride: payload.reason === "user" ? "active" : null,
|
||||
settledAt: null,
|
||||
updatedAt: payload.updatedAt,
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.meta-updated":
|
||||
return decodeForEvent(ThreadMetaUpdatedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
@@ -441,6 +478,93 @@ export function projectEvent(
|
||||
};
|
||||
});
|
||||
|
||||
case "thread.message-queued":
|
||||
return decodeForEvent(ThreadMessageQueuedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => {
|
||||
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
|
||||
if (!thread) {
|
||||
return nextBase;
|
||||
}
|
||||
|
||||
// No cap here: the decider refuses to emit `thread.message-queued`
|
||||
// past its queue limit, so replaying the event stream stays in
|
||||
// lockstep with the persisted projection.
|
||||
const queuedMessages = [
|
||||
...thread.queuedMessages.filter((entry) => entry.messageId !== payload.messageId),
|
||||
{
|
||||
messageId: payload.messageId,
|
||||
text: payload.text,
|
||||
attachments: payload.attachments,
|
||||
...(payload.modelSelection !== undefined
|
||||
? { modelSelection: payload.modelSelection }
|
||||
: {}),
|
||||
...(payload.sourceProposedPlan !== undefined
|
||||
? { sourceProposedPlan: payload.sourceProposedPlan }
|
||||
: {}),
|
||||
queuedAt: payload.queuedAt,
|
||||
},
|
||||
];
|
||||
|
||||
return {
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
queuedMessages,
|
||||
updatedAt: event.occurredAt,
|
||||
}),
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
case "thread.queued-message-removed":
|
||||
return decodeForEvent(
|
||||
ThreadQueuedMessageRemovedPayload,
|
||||
event.payload,
|
||||
event.type,
|
||||
"payload",
|
||||
).pipe(
|
||||
Effect.map((payload) => {
|
||||
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
|
||||
if (!thread) {
|
||||
return nextBase;
|
||||
}
|
||||
|
||||
return {
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
queuedMessages: thread.queuedMessages.filter(
|
||||
(entry) => entry.messageId !== payload.messageId,
|
||||
),
|
||||
updatedAt: event.occurredAt,
|
||||
}),
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
case "thread.turn-start-requested":
|
||||
return decodeForEvent(
|
||||
ThreadTurnStartRequestedPayload,
|
||||
event.payload,
|
||||
event.type,
|
||||
"payload",
|
||||
).pipe(
|
||||
Effect.map((payload) => {
|
||||
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
|
||||
if (!thread) {
|
||||
return nextBase;
|
||||
}
|
||||
return {
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
pendingTurnStart: {
|
||||
messageId: payload.messageId,
|
||||
requestedAt: payload.createdAt,
|
||||
},
|
||||
updatedAt: event.occurredAt,
|
||||
}),
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
case "thread.session-set":
|
||||
return Effect.gen(function* () {
|
||||
const payload = yield* decodeForEvent(
|
||||
@@ -464,10 +588,23 @@ export function projectEvent(
|
||||
// Leaving the "running" session status is the turn-end signal: settle
|
||||
// a still-running latest turn so its duration reflects the whole turn.
|
||||
const settledTurnState = settledTurnStateForSessionStatus(session.status);
|
||||
// Mirrors the SQL pipeline's pending-turn-start clearing: a running
|
||||
// session with an active turn adopts the pending start; every settled
|
||||
// or terminal status (ready/idle/error/stopped/interrupted) clears it
|
||||
// — a mid-turn steer re-arms the flag without any adopting session
|
||||
// transition, so the turn-end ready must release it or drains would
|
||||
// be rejected forever. Only "starting" (and running while waiting on
|
||||
// a turn id) keeps it pending.
|
||||
const pendingTurnStart =
|
||||
(session.status === "running" && session.activeTurnId !== null) ||
|
||||
settledTurnStateForSessionStatus(session.status) !== null
|
||||
? null
|
||||
: thread.pendingTurnStart;
|
||||
return {
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
session,
|
||||
pendingTurnStart,
|
||||
latestTurn:
|
||||
session.status === "running" && session.activeTurnId !== null
|
||||
? {
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Struct from "effect/Struct";
|
||||
import { ChatAttachment, ModelSelection } from "@t3tools/contracts";
|
||||
|
||||
import { toPersistenceSqlError } from "../Errors.ts";
|
||||
import {
|
||||
DeleteProjectionQueuedMessageInput,
|
||||
DeleteProjectionQueuedMessagesInput,
|
||||
ListProjectionQueuedMessagesInput,
|
||||
ProjectionQueuedMessage,
|
||||
ProjectionQueuedMessageRepository,
|
||||
type ProjectionQueuedMessageRepositoryShape,
|
||||
} from "../Services/ProjectionQueuedMessages.ts";
|
||||
|
||||
const ProjectionQueuedMessageDbRowSchema = ProjectionQueuedMessage.mapFields(
|
||||
Struct.assign({
|
||||
attachments: Schema.fromJsonString(Schema.Array(ChatAttachment)),
|
||||
modelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),
|
||||
}),
|
||||
);
|
||||
|
||||
const makeProjectionQueuedMessageRepository = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
// Replace-then-insert (not ON CONFLICT UPDATE) so a re-queued messageId
|
||||
// gets a fresh rowid and moves to the queue tail — the same semantics as
|
||||
// the in-memory projector. Drain order is rowid order: a monotonic
|
||||
// insertion sequence that never ties, unlike queued_at timestamps.
|
||||
const upsertProjectionQueuedMessageRow = SqlSchema.void({
|
||||
Request: ProjectionQueuedMessage,
|
||||
execute: (row) => sql`
|
||||
INSERT OR REPLACE INTO projection_queued_messages (
|
||||
message_id,
|
||||
thread_id,
|
||||
text,
|
||||
attachments_json,
|
||||
model_selection_json,
|
||||
source_proposed_plan_thread_id,
|
||||
source_proposed_plan_id,
|
||||
queued_at
|
||||
)
|
||||
VALUES (
|
||||
${row.messageId},
|
||||
${row.threadId},
|
||||
${row.text},
|
||||
${JSON.stringify(row.attachments)},
|
||||
${row.modelSelection !== null ? JSON.stringify(row.modelSelection) : null},
|
||||
${row.sourceProposedPlanThreadId},
|
||||
${row.sourceProposedPlanId},
|
||||
${row.queuedAt}
|
||||
)
|
||||
`,
|
||||
});
|
||||
|
||||
const listProjectionQueuedMessageRows = SqlSchema.findAll({
|
||||
Request: ListProjectionQueuedMessagesInput,
|
||||
Result: ProjectionQueuedMessageDbRowSchema,
|
||||
execute: ({ threadId }) => sql`
|
||||
SELECT
|
||||
message_id AS "messageId",
|
||||
thread_id AS "threadId",
|
||||
text,
|
||||
attachments_json AS "attachments",
|
||||
model_selection_json AS "modelSelection",
|
||||
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
|
||||
source_proposed_plan_id AS "sourceProposedPlanId",
|
||||
queued_at AS "queuedAt"
|
||||
FROM projection_queued_messages
|
||||
WHERE thread_id = ${threadId}
|
||||
ORDER BY rowid ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const deleteProjectionQueuedMessageRow = SqlSchema.void({
|
||||
Request: DeleteProjectionQueuedMessageInput,
|
||||
execute: ({ threadId, messageId }) => sql`
|
||||
DELETE FROM projection_queued_messages
|
||||
WHERE thread_id = ${threadId} AND message_id = ${messageId}
|
||||
`,
|
||||
});
|
||||
|
||||
const deleteProjectionQueuedMessageRows = SqlSchema.void({
|
||||
Request: DeleteProjectionQueuedMessagesInput,
|
||||
execute: ({ threadId }) => sql`
|
||||
DELETE FROM projection_queued_messages
|
||||
WHERE thread_id = ${threadId}
|
||||
`,
|
||||
});
|
||||
|
||||
const upsert: ProjectionQueuedMessageRepositoryShape["upsert"] = (row) =>
|
||||
upsertProjectionQueuedMessageRow(row).pipe(
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionQueuedMessageRepository.upsert:query")),
|
||||
);
|
||||
|
||||
const listByThreadId: ProjectionQueuedMessageRepositoryShape["listByThreadId"] = (input) =>
|
||||
listProjectionQueuedMessageRows(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlError("ProjectionQueuedMessageRepository.listByThreadId:query"),
|
||||
),
|
||||
);
|
||||
|
||||
const deleteByMessageId: ProjectionQueuedMessageRepositoryShape["deleteByMessageId"] = (input) =>
|
||||
deleteProjectionQueuedMessageRow(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlError("ProjectionQueuedMessageRepository.deleteByMessageId:query"),
|
||||
),
|
||||
);
|
||||
|
||||
const deleteByThreadId: ProjectionQueuedMessageRepositoryShape["deleteByThreadId"] = (input) =>
|
||||
deleteProjectionQueuedMessageRows(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlError("ProjectionQueuedMessageRepository.deleteByThreadId:query"),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
upsert,
|
||||
listByThreadId,
|
||||
deleteByMessageId,
|
||||
deleteByThreadId,
|
||||
} satisfies ProjectionQueuedMessageRepositoryShape;
|
||||
});
|
||||
|
||||
export const ProjectionQueuedMessageRepositoryLive = Layer.effect(
|
||||
ProjectionQueuedMessageRepository,
|
||||
makeProjectionQueuedMessageRepository,
|
||||
);
|
||||
@@ -91,6 +91,8 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
createdAt: "2026-03-24T00:00:00.000Z",
|
||||
updatedAt: "2026-03-24T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
@@ -128,4 +130,58 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("round-trips non-null settlement values through the thread row", () =>
|
||||
Effect.gen(function* () {
|
||||
const threads = yield* ProjectionThreadRepository;
|
||||
|
||||
yield* threads.upsert({
|
||||
threadId: ThreadId.make("thread-settled"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Settled thread",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurnId: null,
|
||||
createdAt: "2026-03-24T00:00:00.000Z",
|
||||
updatedAt: "2026-03-25T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: "settled",
|
||||
settledAt: "2026-03-25T00:00:00.000Z",
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
hasActionableProposedPlan: 0,
|
||||
deletedAt: null,
|
||||
});
|
||||
|
||||
const persisted = yield* threads.getById({
|
||||
threadId: ThreadId.make("thread-settled"),
|
||||
});
|
||||
const row = Option.getOrNull(persisted);
|
||||
if (!row) {
|
||||
return yield* Effect.die("Expected settled projection_threads row to exist.");
|
||||
}
|
||||
assert.strictEqual(row.settledOverride, "settled");
|
||||
assert.strictEqual(row.settledAt, "2026-03-25T00:00:00.000Z");
|
||||
|
||||
// Un-settle to the keep-active pin and confirm the flip persists.
|
||||
yield* threads.upsert({
|
||||
...row,
|
||||
settledOverride: "active",
|
||||
settledAt: null,
|
||||
});
|
||||
const repersisted = yield* threads.getById({
|
||||
threadId: ThreadId.make("thread-settled"),
|
||||
});
|
||||
const updated = Option.getOrNull(repersisted);
|
||||
assert.strictEqual(updated?.settledOverride, "active");
|
||||
assert.strictEqual(updated?.settledAt, null);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -43,6 +43,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
created_at,
|
||||
updated_at,
|
||||
archived_at,
|
||||
settled_override,
|
||||
settled_at,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
@@ -62,6 +64,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
${row.createdAt},
|
||||
${row.updatedAt},
|
||||
${row.archivedAt},
|
||||
${row.settledOverride},
|
||||
${row.settledAt},
|
||||
${row.latestUserMessageAt},
|
||||
${row.pendingApprovalCount},
|
||||
${row.pendingUserInputCount},
|
||||
@@ -81,6 +85,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
created_at = excluded.created_at,
|
||||
updated_at = excluded.updated_at,
|
||||
archived_at = excluded.archived_at,
|
||||
settled_override = excluded.settled_override,
|
||||
settled_at = excluded.settled_at,
|
||||
latest_user_message_at = excluded.latest_user_message_at,
|
||||
pending_approval_count = excluded.pending_approval_count,
|
||||
pending_user_input_count = excluded.pending_user_input_count,
|
||||
@@ -107,6 +113,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -135,6 +143,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
|
||||
@@ -45,6 +45,8 @@ import Migration0029 from "./Migrations/029_ProjectionThreadDetailOrderingIndexe
|
||||
import Migration0030 from "./Migrations/030_ProjectionThreadShellArchiveIndexes.ts";
|
||||
import Migration0031 from "./Migrations/031_AuthAuthorizationScopes.ts";
|
||||
import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts";
|
||||
import Migration0033 from "./Migrations/033_ProjectionThreadsSettled.ts";
|
||||
import Migration0034 from "./Migrations/034_ProjectionQueuedMessages.ts";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -89,6 +91,8 @@ export const migrationEntries = [
|
||||
[30, "ProjectionThreadShellArchiveIndexes", Migration0030],
|
||||
[31, "AuthAuthorizationScopes", Migration0031],
|
||||
[32, "AuthPairingProofKeyThumbprint", Migration0032],
|
||||
[33, "ProjectionThreadsSettled", Migration0033],
|
||||
[34, "ProjectionQueuedMessages", Migration0034],
|
||||
] as const;
|
||||
|
||||
export const makeMigrationLoader = (throughId?: number) =>
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const columns = yield* sql<{ readonly name: string }>`
|
||||
PRAGMA table_info(projection_threads)
|
||||
`;
|
||||
|
||||
if (!columns.some((column) => column.name === "settled_override")) {
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN settled_override TEXT
|
||||
`;
|
||||
}
|
||||
|
||||
if (!columns.some((column) => column.name === "settled_at")) {
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN settled_at TEXT
|
||||
`;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
CREATE TABLE IF NOT EXISTS projection_queued_messages (
|
||||
message_id TEXT PRIMARY KEY,
|
||||
thread_id TEXT NOT NULL,
|
||||
text TEXT NOT NULL,
|
||||
attachments_json TEXT NOT NULL,
|
||||
model_selection_json TEXT,
|
||||
source_proposed_plan_thread_id TEXT,
|
||||
source_proposed_plan_id TEXT,
|
||||
queued_at TEXT NOT NULL
|
||||
)
|
||||
`;
|
||||
|
||||
// Drain order is rowid (insertion) order; the index only serves the
|
||||
// per-thread filter.
|
||||
yield* sql`
|
||||
CREATE INDEX IF NOT EXISTS idx_projection_queued_messages_thread
|
||||
ON projection_queued_messages(thread_id)
|
||||
`;
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import {
|
||||
ChatAttachment,
|
||||
IsoDateTime,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
OrchestrationProposedPlanId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
|
||||
import type { ProjectionRepositoryError } from "../Errors.ts";
|
||||
|
||||
export const ProjectionQueuedMessage = Schema.Struct({
|
||||
messageId: MessageId,
|
||||
threadId: ThreadId,
|
||||
text: Schema.String,
|
||||
attachments: Schema.Array(ChatAttachment),
|
||||
modelSelection: Schema.NullOr(ModelSelection),
|
||||
sourceProposedPlanThreadId: Schema.NullOr(ThreadId),
|
||||
sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),
|
||||
queuedAt: IsoDateTime,
|
||||
});
|
||||
export type ProjectionQueuedMessage = typeof ProjectionQueuedMessage.Type;
|
||||
|
||||
export const ListProjectionQueuedMessagesInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
});
|
||||
export type ListProjectionQueuedMessagesInput = typeof ListProjectionQueuedMessagesInput.Type;
|
||||
|
||||
export const DeleteProjectionQueuedMessageInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
messageId: MessageId,
|
||||
});
|
||||
export type DeleteProjectionQueuedMessageInput = typeof DeleteProjectionQueuedMessageInput.Type;
|
||||
|
||||
export const DeleteProjectionQueuedMessagesInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
});
|
||||
export type DeleteProjectionQueuedMessagesInput = typeof DeleteProjectionQueuedMessagesInput.Type;
|
||||
|
||||
export interface ProjectionQueuedMessageRepositoryShape {
|
||||
readonly upsert: (
|
||||
queuedMessage: ProjectionQueuedMessage,
|
||||
) => Effect.Effect<void, ProjectionRepositoryError>;
|
||||
readonly listByThreadId: (
|
||||
input: ListProjectionQueuedMessagesInput,
|
||||
) => Effect.Effect<ReadonlyArray<ProjectionQueuedMessage>, ProjectionRepositoryError>;
|
||||
readonly deleteByMessageId: (
|
||||
input: DeleteProjectionQueuedMessageInput,
|
||||
) => Effect.Effect<void, ProjectionRepositoryError>;
|
||||
readonly deleteByThreadId: (
|
||||
input: DeleteProjectionQueuedMessagesInput,
|
||||
) => Effect.Effect<void, ProjectionRepositoryError>;
|
||||
}
|
||||
|
||||
export class ProjectionQueuedMessageRepository extends Context.Service<
|
||||
ProjectionQueuedMessageRepository,
|
||||
ProjectionQueuedMessageRepositoryShape
|
||||
>()("t3/persistence/Services/ProjectionQueuedMessages/ProjectionQueuedMessageRepository") {}
|
||||
@@ -36,6 +36,8 @@ export const ProjectionThread = Schema.Struct({
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
archivedAt: Schema.NullOr(IsoDateTime),
|
||||
settledOverride: Schema.NullOr(Schema.Literals(["settled", "active"])),
|
||||
settledAt: Schema.NullOr(IsoDateTime),
|
||||
latestUserMessageAt: Schema.NullOr(IsoDateTime),
|
||||
pendingApprovalCount: NonNegativeInt,
|
||||
pendingUserInputCount: NonNegativeInt,
|
||||
|
||||
@@ -1711,6 +1711,133 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("consumes undeclared and UX-internal system subtypes without warning rows", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
const runtimeEvents: Array<ProviderRuntimeEvent> = [];
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => runtimeEvents.push(event)),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
// Undeclared wire-only roster snapshot + every typed UX-internal
|
||||
// subtype and top-level type consumed silently: none may surface as
|
||||
// unknown-subtype warnings.
|
||||
for (const message of [
|
||||
{
|
||||
type: "system",
|
||||
subtype: "background_tasks_changed",
|
||||
tasks: [{ task_id: "t1", task_type: "local_agent", description: "Say hi" }],
|
||||
session_id: "session",
|
||||
uuid: "roster",
|
||||
},
|
||||
{
|
||||
type: "system",
|
||||
subtype: "task_updated",
|
||||
task_id: "t1",
|
||||
patch: { status: "running" },
|
||||
session_id: "session",
|
||||
uuid: "tu",
|
||||
},
|
||||
{ type: "system", subtype: "commands_changed", session_id: "session", uuid: "cc" },
|
||||
{ type: "system", subtype: "model_refusal_fallback", session_id: "session", uuid: "mrf" },
|
||||
{ type: "system", subtype: "local_command_output", session_id: "session", uuid: "lco" },
|
||||
{ type: "system", subtype: "plugin_install", session_id: "session", uuid: "pi" },
|
||||
{ type: "system", subtype: "memory_recall", session_id: "session", uuid: "mr" },
|
||||
{ type: "system", subtype: "elicitation_complete", session_id: "session", uuid: "ec" },
|
||||
{ type: "prompt_suggestion", suggestion: "try this", session_id: "session", uuid: "ps" },
|
||||
{
|
||||
type: "system",
|
||||
subtype: "notification",
|
||||
key: "context",
|
||||
text: "low priority note",
|
||||
priority: "low",
|
||||
session_id: "session",
|
||||
uuid: "notif",
|
||||
},
|
||||
]) {
|
||||
harness.query.emit(message as unknown as SDKMessage);
|
||||
}
|
||||
// High-priority notifications DO surface as a warning row.
|
||||
harness.query.emit({
|
||||
type: "system",
|
||||
subtype: "notification",
|
||||
key: "limit",
|
||||
text: "context window nearly full",
|
||||
priority: "high",
|
||||
session_id: "session",
|
||||
uuid: "notif-high",
|
||||
} as unknown as SDKMessage);
|
||||
// session_state_changed maps to the matching session states.
|
||||
for (const [state, uuid] of [
|
||||
["running", "ssc-run"],
|
||||
["requires_action", "ssc-req"],
|
||||
["idle", "ssc-idle"],
|
||||
]) {
|
||||
harness.query.emit({
|
||||
type: "system",
|
||||
subtype: "session_state_changed",
|
||||
state,
|
||||
session_id: "session",
|
||||
uuid,
|
||||
} as unknown as SDKMessage);
|
||||
}
|
||||
// api_retry maps to a session heartbeat, not a warning row.
|
||||
harness.query.emit({
|
||||
type: "system",
|
||||
subtype: "api_retry",
|
||||
attempt: 3,
|
||||
max_retries: 10,
|
||||
retry_delay_ms: 1000,
|
||||
error_status: 502,
|
||||
error: { type: "api_error" },
|
||||
session_id: "session",
|
||||
uuid: "retry",
|
||||
} as unknown as SDKMessage);
|
||||
yield* Effect.yieldNow;
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const warnings = runtimeEvents.filter((event) => event.type === "runtime.warning");
|
||||
// Exactly one warning: the high-priority notification. Nothing else.
|
||||
assert.deepEqual(
|
||||
warnings.map((event) => event.payload.message),
|
||||
["context window nearly full"],
|
||||
);
|
||||
const sessionStates = runtimeEvents
|
||||
.filter((event) => event.type === "session.state.changed")
|
||||
.map((event) =>
|
||||
event.type === "session.state.changed"
|
||||
? `${event.payload.state}:${event.payload.reason ?? ""}`
|
||||
: "",
|
||||
)
|
||||
.filter(
|
||||
(entry) => entry.startsWith("running:session_state") || entry.includes("session_state"),
|
||||
);
|
||||
assert.deepEqual(sessionStates, [
|
||||
"running:session_state:running",
|
||||
"waiting:session_state:requires_action",
|
||||
"ready:session_state:idle",
|
||||
]);
|
||||
const heartbeat = runtimeEvents.find(
|
||||
(event) =>
|
||||
event.type === "session.state.changed" &&
|
||||
typeof event.payload.reason === "string" &&
|
||||
event.payload.reason.startsWith("api_retry:"),
|
||||
);
|
||||
assert.equal(heartbeat?.type, "session.state.changed");
|
||||
runtimeEventsFiber.interruptUnsafe();
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("emits thread token usage updates from Claude task progress", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
@@ -3045,7 +3172,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
assert.deepEqual(harness.query.setModelCalls, ["claude-opus-4-6"]);
|
||||
assert.deepEqual(harness.query.setModelCalls, ["claude-opus-4-6[1m]"]);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
@@ -3143,10 +3270,11 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello again",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
||||
model: "claude-opus-4-6",
|
||||
},
|
||||
modelSelection: createModelSelection(
|
||||
ProviderInstanceId.make("claudeAgent"),
|
||||
"claude-opus-4-6",
|
||||
[{ id: "contextWindow", value: "200k" }],
|
||||
),
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
|
||||
@@ -77,6 +77,7 @@ import {
|
||||
isClaudeUltracodeEffort,
|
||||
normalizeClaudeCliEffort,
|
||||
resolveClaudeApiModelId,
|
||||
resolveClaudeContextWindow,
|
||||
resolveClaudeEffort,
|
||||
} from "./ClaudeProvider.ts";
|
||||
import {
|
||||
@@ -341,24 +342,18 @@ function selectedClaudeContextWindow(
|
||||
switch (modelSelection?.model) {
|
||||
case "claude-opus-4-8":
|
||||
case "claude-opus-4-7":
|
||||
// Always 1M at the API; these models expose no contextWindow option.
|
||||
return 1_000_000;
|
||||
}
|
||||
|
||||
const optionValue = getModelSelectionStringOptionValue(modelSelection, "contextWindow");
|
||||
if (optionValue === "1m") {
|
||||
return 1_000_000;
|
||||
switch (resolveClaudeContextWindow(modelSelection)) {
|
||||
case "1m":
|
||||
return 1_000_000;
|
||||
case "200k":
|
||||
return 200_000;
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
if (optionValue === "200k") {
|
||||
return 200_000;
|
||||
}
|
||||
const caps = getClaudeModelCapabilities(modelSelection?.model);
|
||||
const hasContextWindowOption = getProviderOptionDescriptors({ caps }).some(
|
||||
(descriptor) => descriptor.type === "select" && descriptor.id === "contextWindow",
|
||||
);
|
||||
if (hasContextWindowOption) {
|
||||
return 200_000;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function finiteNonNegativeInteger(value: unknown): number | undefined {
|
||||
@@ -2590,6 +2585,17 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
},
|
||||
};
|
||||
|
||||
// Undeclared-but-real subtypes (absent from the SDK's union, so they can't
|
||||
// be switch cases): consumed intentionally without emitting, otherwise
|
||||
// they fall through to the unknown-subtype warning and surface as spurious
|
||||
// error rows in client work logs. `background_tasks_changed` is a roster
|
||||
// snapshot ({tasks: [...]}) — the task_* lifecycle events carry the
|
||||
// authoritative per-agent data and the typed background_tasks control
|
||||
// request is the reconciliation source.
|
||||
if ((message.subtype as string) === "background_tasks_changed") {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (message.subtype) {
|
||||
case "init":
|
||||
yield* offerRuntimeEvent({
|
||||
@@ -2702,6 +2708,11 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
},
|
||||
});
|
||||
return;
|
||||
// Task state patch (status/backgrounded/end_time). No runtime mapping
|
||||
// yet — the terminal task_notification reports the outcome — but it
|
||||
// must not surface as an unknown-subtype warning row.
|
||||
case "task_updated":
|
||||
return;
|
||||
case "task_notification":
|
||||
yield* emitThreadTokenUsage(
|
||||
context,
|
||||
@@ -2746,6 +2757,52 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
return;
|
||||
case "thinking_tokens":
|
||||
return;
|
||||
case "api_retry":
|
||||
// Transport-level retry heartbeat. Surfacing each attempt as a
|
||||
// warning row spammed the work log (10 rows during a 502 storm);
|
||||
// the terminal result/error path reports the actual failure. Keep
|
||||
// the session visibly alive instead.
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "session.state.changed",
|
||||
payload: {
|
||||
state: "running",
|
||||
reason: `api_retry:${message.attempt}/${message.max_retries}`,
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "session_state_changed":
|
||||
// Authoritative turn-over signal from the CLI.
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "session.state.changed",
|
||||
payload: {
|
||||
state:
|
||||
message.state === "running"
|
||||
? "running"
|
||||
: message.state === "requires_action"
|
||||
? "waiting"
|
||||
: "ready",
|
||||
reason: `session_state:${message.state}`,
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "notification":
|
||||
// User-facing CLI notification (e.g. context-limit warnings). Only
|
||||
// high-priority ones warrant a work-log row.
|
||||
if (message.priority === "high" || message.priority === "immediate") {
|
||||
yield* emitRuntimeWarning(context, message.text, message);
|
||||
}
|
||||
return;
|
||||
// Inner protocol/UX details with no T3 surface today — consumed
|
||||
// deliberately so they don't masquerade as unknown-subtype warnings.
|
||||
case "model_refusal_fallback":
|
||||
case "local_command_output":
|
||||
case "plugin_install":
|
||||
case "commands_changed":
|
||||
case "memory_recall":
|
||||
case "elicitation_complete":
|
||||
return;
|
||||
case "permission_denied":
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
@@ -2765,13 +2822,21 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
message,
|
||||
);
|
||||
return;
|
||||
default:
|
||||
default: {
|
||||
// Exhaustiveness guard: every subtype in the SDK's typed union is
|
||||
// handled above, so `message` narrows to never here — a new SDK
|
||||
// release adding a subtype fails this typecheck instead of silently
|
||||
// warning at runtime. The runtime fallback still catches undeclared
|
||||
// wire-only subtypes (like background_tasks_changed used to be).
|
||||
message satisfies never;
|
||||
const unknownMessage = message as never as { subtype: string };
|
||||
yield* emitRuntimeWarning(
|
||||
context,
|
||||
describeUnknownSdkMessage(`Claude system message '${message.subtype}'`, message),
|
||||
describeUnknownSdkMessage(`Claude system message '${unknownMessage.subtype}'`, message),
|
||||
message,
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -2879,13 +2944,21 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
case "rate_limit_event":
|
||||
yield* handleSdkTelemetryMessage(context, message);
|
||||
return;
|
||||
default:
|
||||
// Composer prompt suggestions have no T3 surface; consumed deliberately.
|
||||
case "prompt_suggestion":
|
||||
return;
|
||||
default: {
|
||||
// Exhaustiveness guard (see handleSystemMessage): new SDK top-level
|
||||
// message types fail typecheck here instead of warning at runtime.
|
||||
message satisfies never;
|
||||
const unknownMessage = message as never as { type: string };
|
||||
yield* emitRuntimeWarning(
|
||||
context,
|
||||
describeUnknownSdkMessage(`Claude SDK message '${message.type}'`, message),
|
||||
describeUnknownSdkMessage(`Claude SDK message '${unknownMessage.type}'`, message),
|
||||
message,
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
import { ClaudeSettings } from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
buildClaudeCapabilitiesProbeQueryOptions,
|
||||
CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES,
|
||||
probeClaudeCapabilities,
|
||||
} from "./ClaudeProvider.ts";
|
||||
|
||||
const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
|
||||
|
||||
it("isolates Claude capability probes without dropping workspace setting sources", () => {
|
||||
const abortController = new AbortController();
|
||||
const options = buildClaudeCapabilitiesProbeQueryOptions({
|
||||
executablePath: "/usr/bin/claude",
|
||||
abortController,
|
||||
environment: {
|
||||
HOME: "/home/user",
|
||||
ENABLE_CLAUDEAI_MCP_SERVERS: "true",
|
||||
},
|
||||
cwd: "/workspace/project",
|
||||
});
|
||||
|
||||
assert.deepEqual(options.mcpServers, {});
|
||||
assert.equal(options.strictMcpConfig, true);
|
||||
assert.equal(options.cwd, "/workspace/project");
|
||||
assert.deepEqual(options.settingSources, [...CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES]);
|
||||
assert.deepEqual(options.allowedTools, []);
|
||||
assert.equal(options.persistSession, false);
|
||||
assert.equal(options.pathToClaudeCodeExecutable, "/usr/bin/claude");
|
||||
assert.equal(options.abortController, abortController);
|
||||
assert.equal(options.env?.HOME, "/home/user");
|
||||
assert.equal(options.env?.ENABLE_CLAUDEAI_MCP_SERVERS, "false");
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("Claude capability probe SDK boundary", (it) => {
|
||||
it.effect("serializes strict no-MCP options and still resolves account capabilities", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-probe-sdk-" });
|
||||
const executablePath = path.join(tempDir, "fake-claude.mjs");
|
||||
const invocationPath = path.join(tempDir, "invocation.json");
|
||||
const workspaceCwd = path.join(tempDir, "workspace");
|
||||
yield* fs.makeDirectory(workspaceCwd, { recursive: true });
|
||||
|
||||
yield* fs.writeFileString(
|
||||
executablePath,
|
||||
[
|
||||
"#!/usr/bin/env node",
|
||||
'import { existsSync, readFileSync, writeFileSync } from "node:fs";',
|
||||
'import { createInterface } from "node:readline";',
|
||||
"const args = process.argv.slice(2);",
|
||||
'const mcpConfigIndex = args.indexOf("--mcp-config");',
|
||||
"const rawMcpConfig = mcpConfigIndex >= 0 ? args[mcpConfigIndex + 1] : undefined;",
|
||||
"let mcpConfig;",
|
||||
"if (rawMcpConfig) {",
|
||||
' const contents = existsSync(rawMcpConfig) ? readFileSync(rawMcpConfig, "utf8") : rawMcpConfig;',
|
||||
" try { mcpConfig = JSON.parse(contents); } catch { mcpConfig = contents; }",
|
||||
"}",
|
||||
"writeFileSync(process.env.T3_PROBE_INVOCATION_PATH, JSON.stringify({",
|
||||
" args,",
|
||||
" cwd: process.cwd(),",
|
||||
" connectorEnv: process.env.ENABLE_CLAUDEAI_MCP_SERVERS,",
|
||||
" mcpConfig,",
|
||||
"}));",
|
||||
"const lines = createInterface({ input: process.stdin });",
|
||||
'lines.on("line", (line) => {',
|
||||
" const message = JSON.parse(line);",
|
||||
' if (message.type !== "control_request" || message.request?.subtype !== "initialize") return;',
|
||||
" process.stdout.write(JSON.stringify({",
|
||||
' type: "control_response",',
|
||||
" response: {",
|
||||
' subtype: "success",',
|
||||
" request_id: message.request_id,",
|
||||
" response: {",
|
||||
' commands: [{ name: "review", description: "Review changes", argumentHint: "[path]" }],',
|
||||
" agents: [],",
|
||||
' output_style: "default",',
|
||||
' available_output_styles: ["default"],',
|
||||
" models: [],",
|
||||
' account: { email: "[email protected]", subscriptionType: "pro", tokenSource: "oauth" },',
|
||||
" },",
|
||||
" },",
|
||||
' }) + "\\n");',
|
||||
"});",
|
||||
"setInterval(() => {}, 1_000);",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
yield* fs.chmod(executablePath, 0o755);
|
||||
|
||||
const capabilities = yield* probeClaudeCapabilities(
|
||||
decodeClaudeSettings({ binaryPath: executablePath }),
|
||||
{
|
||||
...process.env,
|
||||
T3_PROBE_INVOCATION_PATH: invocationPath,
|
||||
ENABLE_CLAUDEAI_MCP_SERVERS: "true",
|
||||
},
|
||||
workspaceCwd,
|
||||
);
|
||||
|
||||
assert.deepEqual(capabilities, {
|
||||
email: "[email protected]",
|
||||
subscriptionType: "pro",
|
||||
tokenSource: "oauth",
|
||||
apiProvider: undefined,
|
||||
slashCommands: [
|
||||
{
|
||||
name: "review",
|
||||
description: "Review changes",
|
||||
input: { hint: "[path]" },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
const invocation = JSON.parse(yield* fs.readFileString(invocationPath)) as {
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly cwd: string;
|
||||
readonly connectorEnv: string;
|
||||
readonly mcpConfig: unknown;
|
||||
};
|
||||
assert.equal(invocation.cwd, yield* fs.realPath(workspaceCwd));
|
||||
assert.equal(invocation.connectorEnv, "false");
|
||||
assert.equal(invocation.args.includes("--strict-mcp-config"), true);
|
||||
assert.equal(invocation.args.includes("--mcp-config"), false);
|
||||
assert.equal(invocation.mcpConfig, undefined);
|
||||
|
||||
assert.equal(invocation.args.includes("--setting-sources=user,project,local"), true);
|
||||
}).pipe(Effect.scoped),
|
||||
);
|
||||
});
|
||||
@@ -21,8 +21,10 @@ import { resolveSpawnCommand } from "@t3tools/shared/shell";
|
||||
import { compareSemverVersions } from "@t3tools/shared/semver";
|
||||
import {
|
||||
query as claudeQuery,
|
||||
type Options as ClaudeQueryOptions,
|
||||
type SlashCommand as ClaudeSlashCommand,
|
||||
type SDKUserMessage,
|
||||
type SettingSource,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
import {
|
||||
@@ -76,8 +78,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
id: "contextWindow",
|
||||
label: "Context Window",
|
||||
options: [
|
||||
{ value: "200k", label: "200k", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
{ value: "200k", label: "200k" },
|
||||
{ value: "1m", label: "1M", isDefault: true },
|
||||
],
|
||||
}),
|
||||
],
|
||||
@@ -162,8 +164,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
id: "contextWindow",
|
||||
label: "Context Window",
|
||||
options: [
|
||||
{ value: "200k", label: "200k", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
{ value: "200k", label: "200k" },
|
||||
{ value: "1m", label: "1M", isDefault: true },
|
||||
],
|
||||
}),
|
||||
],
|
||||
@@ -214,6 +216,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
buildSelectOptionDescriptor({
|
||||
id: "contextWindow",
|
||||
label: "Context Window",
|
||||
// Sonnet is 200k-default in Claude Code (1M is opt-in there too).
|
||||
options: [
|
||||
{ value: "200k", label: "200k", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
@@ -243,6 +246,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
buildSelectOptionDescriptor({
|
||||
id: "contextWindow",
|
||||
label: "Context Window",
|
||||
// Sonnet is 200k-default in Claude Code (1M is opt-in there too).
|
||||
options: [
|
||||
{ value: "200k", label: "200k", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
@@ -369,8 +373,22 @@ export function isClaudeUltracodeEffort(effort: string | null | undefined): bool
|
||||
return effort === "ultracode";
|
||||
}
|
||||
|
||||
export function resolveClaudeContextWindow(
|
||||
modelSelection: ModelSelection | undefined,
|
||||
): string | undefined {
|
||||
const caps = getClaudeModelCapabilities(modelSelection?.model);
|
||||
const raw = getModelSelectionStringOptionValue(modelSelection, "contextWindow");
|
||||
const descriptors = getProviderOptionDescriptors({
|
||||
caps,
|
||||
...(raw ? { selections: [{ id: "contextWindow", value: raw }] } : {}),
|
||||
});
|
||||
const descriptor = descriptors.find((candidate) => candidate.id === "contextWindow");
|
||||
const value = getProviderOptionCurrentValue(descriptor);
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
export function resolveClaudeApiModelId(modelSelection: ModelSelection): string {
|
||||
switch (getModelSelectionStringOptionValue(modelSelection, "contextWindow")) {
|
||||
switch (resolveClaudeContextWindow(modelSelection)) {
|
||||
case "1m":
|
||||
return `${modelSelection.model}[1m]`;
|
||||
default:
|
||||
@@ -492,6 +510,44 @@ function apiProviderAuthMetadata(
|
||||
// `undefined` and left the provider unverified and unselectable in the picker.
|
||||
const CAPABILITIES_PROBE_TIMEOUT_MS = 25_000;
|
||||
|
||||
/**
|
||||
* Keep workspace-scoped command discovery intact while isolating the periodic
|
||||
* health check from configured MCP servers.
|
||||
*/
|
||||
export const CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES = [
|
||||
"user",
|
||||
"project",
|
||||
"local",
|
||||
] as const satisfies ReadonlyArray<SettingSource>;
|
||||
|
||||
/** Build the exact SDK options used by the periodic Claude capability probe. */
|
||||
export function buildClaudeCapabilitiesProbeQueryOptions(input: {
|
||||
readonly executablePath: string;
|
||||
readonly abortController: AbortController;
|
||||
readonly environment: NodeJS.ProcessEnv;
|
||||
readonly cwd: string | undefined;
|
||||
}): ClaudeQueryOptions {
|
||||
return {
|
||||
persistSession: false,
|
||||
pathToClaudeCodeExecutable: input.executablePath,
|
||||
abortController: input.abortController,
|
||||
settingSources: [...CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES],
|
||||
allowedTools: [],
|
||||
// Ignore MCP definitions from every filesystem setting source above. The
|
||||
// SDK combines this empty explicit map with --strict-mcp-config.
|
||||
mcpServers: {},
|
||||
strictMcpConfig: true,
|
||||
env: {
|
||||
...input.environment,
|
||||
// Connected claude.ai MCP servers are discovered outside filesystem
|
||||
// config; disable them independently for this health check.
|
||||
ENABLE_CLAUDEAI_MCP_SERVERS: "false",
|
||||
},
|
||||
...(input.cwd ? { cwd: input.cwd } : {}),
|
||||
stderr: () => {},
|
||||
};
|
||||
}
|
||||
|
||||
function nonEmptyProbeString(value: string): string | undefined {
|
||||
const candidate = value.trim();
|
||||
return candidate ? candidate : undefined;
|
||||
@@ -615,16 +671,12 @@ const probeClaudeCapabilities = (
|
||||
prompt: (async function* (): AsyncGenerator<SDKUserMessage> {
|
||||
await waitForAbortSignal(abort.signal);
|
||||
})(),
|
||||
options: {
|
||||
persistSession: false,
|
||||
pathToClaudeCodeExecutable: executablePath,
|
||||
options: buildClaudeCapabilitiesProbeQueryOptions({
|
||||
executablePath,
|
||||
abortController: abort,
|
||||
settingSources: ["user", "project", "local"],
|
||||
allowedTools: [],
|
||||
env: claudeEnvironment,
|
||||
...(cwd ? { cwd } : {}),
|
||||
stderr: () => {},
|
||||
},
|
||||
environment: claudeEnvironment,
|
||||
cwd,
|
||||
}),
|
||||
});
|
||||
const init = await q.initializationResult();
|
||||
const account = init.account as
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import { mapCodexModelCapabilities } from "./CodexProvider.ts";
|
||||
import { applyPreferredCodexDefaultModel, mapCodexModelCapabilities } from "./CodexProvider.ts";
|
||||
|
||||
it("maps current Codex model capability fields", () => {
|
||||
const capabilities = mapCodexModelCapabilities({
|
||||
@@ -102,3 +102,45 @@ it("uses standard routing when the catalog has no default service tier", () => {
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("marks the most preferred available model as default", () => {
|
||||
const models = applyPreferredCodexDefaultModel([
|
||||
{ slug: "gpt-5.6-terra", name: "GPT-5.6-Terra", isCustom: false, capabilities: null },
|
||||
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, isDefault: true, capabilities: null },
|
||||
]);
|
||||
|
||||
assert.deepStrictEqual(
|
||||
models.map((model) => ({ slug: model.slug, isDefault: model.isDefault })),
|
||||
[
|
||||
{ slug: "gpt-5.6-terra", isDefault: true },
|
||||
{ slug: "gpt-5.4", isDefault: undefined },
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
it("prefers sol over terra when both are available", () => {
|
||||
const models = applyPreferredCodexDefaultModel([
|
||||
{ slug: "gpt-5.6-terra", name: "GPT-5.6-Terra", isCustom: false, capabilities: null },
|
||||
{ slug: "gpt-5.6-sol", name: "GPT-5.6-Sol", isCustom: false, capabilities: null },
|
||||
]);
|
||||
|
||||
assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.6-sol");
|
||||
});
|
||||
|
||||
it("keeps Codex's own default when no preferred model is available", () => {
|
||||
const models = applyPreferredCodexDefaultModel([
|
||||
{ slug: "gpt-5.5", name: "GPT-5.5", isCustom: false, capabilities: null },
|
||||
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, isDefault: true, capabilities: null },
|
||||
]);
|
||||
|
||||
assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.4");
|
||||
});
|
||||
|
||||
it("ignores custom models that shadow a preferred slug", () => {
|
||||
const models = applyPreferredCodexDefaultModel([
|
||||
{ slug: "gpt-5.6-sol", name: "gpt-5.6-sol", isCustom: true, capabilities: null },
|
||||
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, isDefault: true, capabilities: null },
|
||||
]);
|
||||
|
||||
assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.4");
|
||||
});
|
||||
@@ -22,7 +22,7 @@ import type {
|
||||
ServerProviderModel,
|
||||
ServerProviderSkill,
|
||||
} from "@t3tools/contracts";
|
||||
import { ServerSettingsError } from "@t3tools/contracts";
|
||||
import { PREFERRED_DEFAULT_CODEX_MODELS, ServerSettingsError } from "@t3tools/contracts";
|
||||
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
import { resolveSpawnCommand } from "@t3tools/shared/shell";
|
||||
@@ -189,10 +189,36 @@ function parseCodexModelListResponse(
|
||||
slug: model.model,
|
||||
name: toDisplayName(model),
|
||||
isCustom: false,
|
||||
...(model.isDefault ? { isDefault: true } : {}),
|
||||
capabilities: mapCodexModelCapabilities(model),
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefer our own default-model ranking when one of the preferred slugs is in
|
||||
* the live catalog; otherwise keep whatever Codex itself flagged as default.
|
||||
*/
|
||||
export function applyPreferredCodexDefaultModel(
|
||||
models: ReadonlyArray<ServerProviderModel>,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
const preferredSlug = PREFERRED_DEFAULT_CODEX_MODELS.find((slug) =>
|
||||
models.some((model) => model.slug === slug && !model.isCustom),
|
||||
);
|
||||
if (!preferredSlug) {
|
||||
return models;
|
||||
}
|
||||
return models.map((model) => {
|
||||
if (model.slug === preferredSlug) {
|
||||
return model.isDefault ? model : { ...model, isDefault: true };
|
||||
}
|
||||
if (!model.isDefault) {
|
||||
return model;
|
||||
}
|
||||
const { isDefault: _isDefault, ...rest } = model;
|
||||
return rest;
|
||||
});
|
||||
}
|
||||
|
||||
function appendCustomCodexModels(
|
||||
models: ReadonlyArray<ServerProviderModel>,
|
||||
customModels: ReadonlyArray<string>,
|
||||
@@ -376,7 +402,9 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun
|
||||
return {
|
||||
account: accountResponse,
|
||||
version,
|
||||
models: appendCustomCodexModels(models, input.customModels ?? []),
|
||||
models: applyPreferredCodexDefaultModel(
|
||||
appendCustomCodexModels(models, input.customModels ?? []),
|
||||
),
|
||||
skills: parseCodexSkillsListResponse(skillsResponse, input.cwd),
|
||||
} satisfies CodexAppServerProviderSnapshot;
|
||||
});
|
||||
|
||||
@@ -1287,6 +1287,52 @@ export const makeCodexSessionRuntime = (
|
||||
...(input.effort ? { effort: input.effort } : {}),
|
||||
...(input.interactionMode ? { interactionMode: input.interactionMode } : {}),
|
||||
});
|
||||
|
||||
// Steer the active turn via the protocol-native `turn/steer` —
|
||||
// appending input mid-turn instead of opening a second provider
|
||||
// turn while the first is still settling. The `expectedTurnId`
|
||||
// precondition fails when the turn just ended or is not steerable
|
||||
// (e.g. review/compact); only a server rejection of the request
|
||||
// itself (operation "receive-response" — the steer was NOT
|
||||
// applied) falls back to a fresh `turn/start`. Decode failures on
|
||||
// an accepted steer's response, and transport/protocol failures,
|
||||
// propagate: the input may already be appended, and retrying via
|
||||
// turn/start would duplicate it.
|
||||
const activeSession = yield* Ref.get(sessionRef);
|
||||
if (activeSession.status === "running" && activeSession.activeTurnId !== undefined) {
|
||||
const steeredTurnId = yield* client
|
||||
.request("turn/steer", {
|
||||
threadId: providerThreadId,
|
||||
expectedTurnId: activeSession.activeTurnId,
|
||||
input: params.input,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((steerResponse) => TurnId.make(steerResponse.turnId)),
|
||||
Effect.catchIf(
|
||||
(cause): cause is CodexErrors.CodexAppServerRequestError =>
|
||||
cause._tag === "CodexAppServerRequestError" &&
|
||||
cause.operation === "receive-response",
|
||||
(cause) =>
|
||||
Effect.as(
|
||||
Effect.logDebug("Codex turn/steer rejected; falling back to turn/start.", {
|
||||
cause,
|
||||
}),
|
||||
null,
|
||||
),
|
||||
),
|
||||
);
|
||||
if (steeredTurnId !== null) {
|
||||
const steeredProviderThreadId = currentProviderThreadId(yield* Ref.get(sessionRef));
|
||||
return {
|
||||
threadId: options.threadId,
|
||||
turnId: steeredTurnId,
|
||||
...(steeredProviderThreadId
|
||||
? { resumeCursor: { threadId: steeredProviderThreadId } }
|
||||
: {}),
|
||||
} satisfies ProviderTurnStartResult;
|
||||
}
|
||||
}
|
||||
|
||||
const rawResponse = yield* client.raw.request("turn/start", params);
|
||||
const response = yield* decodeV2TurnStartResponse(rawResponse).pipe(
|
||||
Effect.mapError((error) =>
|
||||
|
||||
@@ -97,10 +97,13 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
|
||||
: Effect.succeed(runtimeMock.state.inventory as OpenCodeInventory),
|
||||
loadInventoryFromCli: () =>
|
||||
runtimeMock.state.inventoryError
|
||||
? Effect.succeed({
|
||||
providerList: { all: [], default: {}, connected: [] as string[] },
|
||||
agents: [],
|
||||
} as OpenCodeInventory)
|
||||
? Effect.fail(
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "loadInventoryFromCli",
|
||||
detail: runtimeMock.state.inventoryError.message,
|
||||
cause: runtimeMock.state.inventoryError,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(runtimeMock.state.inventory as OpenCodeInventory),
|
||||
};
|
||||
|
||||
@@ -212,14 +215,18 @@ it.layer(testLayer)("checkOpenCodeProviderStatus", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("degrades gracefully on CLI failure for local installs", () =>
|
||||
it.effect("reports local model inventory failures without treating them as empty", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.inventoryError = new Error("opencode models failed");
|
||||
const snapshot = yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd());
|
||||
|
||||
NodeAssert.equal(snapshot.status, "warning");
|
||||
NodeAssert.equal(snapshot.status, "error");
|
||||
NodeAssert.equal(snapshot.installed, true);
|
||||
NodeAssert.equal(snapshot.models.length, 0);
|
||||
NodeAssert.equal(
|
||||
snapshot.message,
|
||||
"Failed to execute OpenCode CLI health check: opencode models failed",
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -563,6 +563,176 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
]);
|
||||
});
|
||||
|
||||
it("drops stale OpenCode models missing from a successful refresh", () => {
|
||||
const previousProvider = {
|
||||
instanceId: ProviderInstanceId.make("opencode"),
|
||||
driver: ProviderDriverKind.make("opencode"),
|
||||
status: "ready",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-07-17T00:00:00.000Z",
|
||||
version: "1.0.0",
|
||||
models: [
|
||||
{
|
||||
slug: "github/gpt-5",
|
||||
name: "GPT-5",
|
||||
subProvider: "GitHub",
|
||||
isCustom: false,
|
||||
capabilities: null,
|
||||
},
|
||||
{
|
||||
slug: "removed-plugin/model",
|
||||
name: "Removed Plugin Model",
|
||||
subProvider: "Removed Plugin",
|
||||
isCustom: false,
|
||||
capabilities: null,
|
||||
},
|
||||
],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
} as const satisfies ServerProvider;
|
||||
const refreshedProvider = {
|
||||
...previousProvider,
|
||||
checkedAt: "2026-07-17T00:01:00.000Z",
|
||||
models: [
|
||||
{
|
||||
slug: "github/gpt-5",
|
||||
name: "GPT-5",
|
||||
subProvider: "GitHub",
|
||||
isCustom: false,
|
||||
capabilities: null,
|
||||
},
|
||||
],
|
||||
} satisfies ServerProvider;
|
||||
|
||||
assert.deepStrictEqual(mergeProviderSnapshot(previousProvider, refreshedProvider).models, [
|
||||
...refreshedProvider.models,
|
||||
]);
|
||||
});
|
||||
|
||||
it("retains stale OpenCode models when a refresh fails", () => {
|
||||
const previousProvider = {
|
||||
instanceId: ProviderInstanceId.make("opencode"),
|
||||
driver: ProviderDriverKind.make("opencode"),
|
||||
status: "ready",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-07-17T00:00:00.000Z",
|
||||
version: "1.0.0",
|
||||
models: [
|
||||
{
|
||||
slug: "github/gpt-5",
|
||||
name: "GPT-5",
|
||||
subProvider: "GitHub",
|
||||
isCustom: false,
|
||||
capabilities: null,
|
||||
},
|
||||
],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
} as const satisfies ServerProvider;
|
||||
const refreshedProvider = {
|
||||
...previousProvider,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
checkedAt: "2026-07-17T00:01:00.000Z",
|
||||
models: [],
|
||||
message: "Failed to refresh OpenCode models.",
|
||||
} satisfies ServerProvider;
|
||||
|
||||
assert.deepStrictEqual(mergeProviderSnapshot(previousProvider, refreshedProvider).models, [
|
||||
...previousProvider.models,
|
||||
]);
|
||||
});
|
||||
|
||||
it("classifies pending, logout, uninstall, and reconnect OpenCode inventories", () => {
|
||||
const previousProvider = {
|
||||
instanceId: ProviderInstanceId.make("opencode"),
|
||||
driver: ProviderDriverKind.make("opencode"),
|
||||
status: "ready",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-07-17T00:00:00.000Z",
|
||||
version: "1.0.0",
|
||||
models: [
|
||||
{
|
||||
slug: "github/gpt-5",
|
||||
name: "GPT-5",
|
||||
subProvider: "GitHub",
|
||||
isCustom: false,
|
||||
capabilities: null,
|
||||
},
|
||||
{
|
||||
slug: "removed-plugin/model",
|
||||
name: "Removed Plugin Model",
|
||||
subProvider: "Removed Plugin",
|
||||
isCustom: false,
|
||||
capabilities: null,
|
||||
},
|
||||
],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
} as const satisfies ServerProvider;
|
||||
const pendingProvider = {
|
||||
...previousProvider,
|
||||
status: "warning",
|
||||
installed: false,
|
||||
auth: { status: "unknown" },
|
||||
checkedAt: "2026-07-17T00:01:00.000Z",
|
||||
version: null,
|
||||
models: [],
|
||||
message: "OpenCode provider status has not been checked in this session yet.",
|
||||
} satisfies ServerProvider;
|
||||
const loggedOutProvider = {
|
||||
...previousProvider,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
checkedAt: "2026-07-17T00:02:00.000Z",
|
||||
models: [],
|
||||
message: "OpenCode is available, but it did not report any connected upstream providers.",
|
||||
} satisfies ServerProvider;
|
||||
const missingProvider = {
|
||||
...previousProvider,
|
||||
status: "error",
|
||||
installed: false,
|
||||
auth: { status: "unknown" },
|
||||
checkedAt: "2026-07-17T00:03:00.000Z",
|
||||
version: null,
|
||||
models: [],
|
||||
message: "OpenCode CLI (`opencode`) is not installed or not on PATH.",
|
||||
} satisfies ServerProvider;
|
||||
const authoritativeProvider = {
|
||||
...previousProvider,
|
||||
checkedAt: "2026-07-17T00:04:00.000Z",
|
||||
models: [previousProvider.models[0]!],
|
||||
} satisfies ServerProvider;
|
||||
const failedProvider = {
|
||||
...authoritativeProvider,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
checkedAt: "2026-07-17T00:05:00.000Z",
|
||||
models: [],
|
||||
message: "Failed to refresh OpenCode models.",
|
||||
} satisfies ServerProvider;
|
||||
|
||||
assert.deepStrictEqual(mergeProviderSnapshot(previousProvider, pendingProvider).models, [
|
||||
...previousProvider.models,
|
||||
]);
|
||||
assert.deepStrictEqual(
|
||||
mergeProviderSnapshot(previousProvider, loggedOutProvider).models,
|
||||
[],
|
||||
);
|
||||
assert.deepStrictEqual(mergeProviderSnapshot(previousProvider, missingProvider).models, []);
|
||||
|
||||
const afterRemoval = mergeProviderSnapshot(previousProvider, authoritativeProvider);
|
||||
const afterFailure = mergeProviderSnapshot(afterRemoval, failedProvider);
|
||||
|
||||
assert.deepStrictEqual(afterFailure.models, [authoritativeProvider.models[0]!]);
|
||||
});
|
||||
|
||||
it("fills missing capabilities from the previous provider snapshot", () => {
|
||||
const previousProvider = {
|
||||
instanceId: ProviderInstanceId.make("cursor"),
|
||||
@@ -866,6 +1036,144 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"persists authoritative OpenCode removals without resurrecting them on a failed live refresh",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const openCodeDriver = ProviderDriverKind.make("opencode");
|
||||
const openCodeInstanceId = ProviderInstanceId.make("opencode");
|
||||
const initialProvider = {
|
||||
instanceId: openCodeInstanceId,
|
||||
driver: openCodeDriver,
|
||||
status: "ready",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-07-17T00:00:00.000Z",
|
||||
version: "1.0.0",
|
||||
models: [
|
||||
{
|
||||
slug: "github/gpt-5",
|
||||
name: "GPT-5",
|
||||
subProvider: "GitHub",
|
||||
isCustom: false,
|
||||
capabilities: null,
|
||||
},
|
||||
{
|
||||
slug: "removed-plugin/model",
|
||||
name: "Removed Plugin Model",
|
||||
subProvider: "Removed Plugin",
|
||||
isCustom: false,
|
||||
capabilities: null,
|
||||
},
|
||||
],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
} as const satisfies ServerProvider;
|
||||
const authoritativeProvider = {
|
||||
...initialProvider,
|
||||
checkedAt: "2026-07-17T00:01:00.000Z",
|
||||
models: [initialProvider.models[0]!],
|
||||
} satisfies ServerProvider;
|
||||
const failedProvider = {
|
||||
...authoritativeProvider,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
checkedAt: "2026-07-17T00:02:00.000Z",
|
||||
models: [],
|
||||
message: "Failed to refresh OpenCode models.",
|
||||
} satisfies ServerProvider;
|
||||
const changes = yield* PubSub.unbounded<ServerProvider>();
|
||||
const instance = {
|
||||
instanceId: openCodeInstanceId,
|
||||
driverKind: openCodeDriver,
|
||||
continuationIdentity: {
|
||||
driverKind: openCodeDriver,
|
||||
continuationKey: "opencode:instance:opencode",
|
||||
},
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: openCodeDriver,
|
||||
packageName: null,
|
||||
}),
|
||||
getSnapshot: Effect.succeed(initialProvider),
|
||||
refresh: Effect.succeed(authoritativeProvider),
|
||||
streamChanges: Stream.fromPubSub(changes),
|
||||
},
|
||||
adapter: {} as ProviderInstance["adapter"],
|
||||
textGeneration: {} as ProviderInstance["textGeneration"],
|
||||
} satisfies ProviderInstance;
|
||||
const instanceRegistryLayer = Layer.succeed(
|
||||
ProviderInstanceRegistry.ProviderInstanceRegistry,
|
||||
{
|
||||
getInstance: (instanceId) =>
|
||||
Effect.succeed(instanceId === openCodeInstanceId ? instance : undefined),
|
||||
listInstances: Effect.succeed([instance]),
|
||||
listUnavailable: Effect.succeed([]),
|
||||
streamChanges: Stream.empty,
|
||||
subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) =>
|
||||
PubSub.subscribe(pubsub),
|
||||
),
|
||||
},
|
||||
);
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const runtimeServices = yield* Layer.build(
|
||||
ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(instanceRegistryLayer),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-provider-registry-opencode-authoritative-persist-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const registry = yield* ProviderRegistry.ProviderRegistry;
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const filePath = yield* resolveProviderStatusCachePath({
|
||||
cacheDir: config.providerStatusCacheDir,
|
||||
instanceId: openCodeInstanceId,
|
||||
});
|
||||
|
||||
yield* PubSub.publish(changes, authoritativeProvider);
|
||||
|
||||
let cachedProvider = yield* readProviderStatusCache(filePath);
|
||||
for (
|
||||
let attempt = 0;
|
||||
attempt < 50 && cachedProvider?.checkedAt !== authoritativeProvider.checkedAt;
|
||||
attempt += 1
|
||||
) {
|
||||
yield* TestClock.adjust("10 millis");
|
||||
yield* Effect.yieldNow;
|
||||
cachedProvider = yield* readProviderStatusCache(filePath);
|
||||
}
|
||||
|
||||
assert.deepStrictEqual(cachedProvider?.models, [authoritativeProvider.models[0]!]);
|
||||
|
||||
yield* PubSub.publish(changes, failedProvider);
|
||||
for (
|
||||
let attempt = 0;
|
||||
attempt < 50 && cachedProvider?.checkedAt !== failedProvider.checkedAt;
|
||||
attempt += 1
|
||||
) {
|
||||
yield* TestClock.adjust("10 millis");
|
||||
yield* Effect.yieldNow;
|
||||
cachedProvider = yield* readProviderStatusCache(filePath);
|
||||
}
|
||||
|
||||
assert.deepStrictEqual(cachedProvider?.models, [authoritativeProvider.models[0]!]);
|
||||
assert.deepStrictEqual((yield* registry.getProviders)[0]?.models, [
|
||||
authoritativeProvider.models[0]!,
|
||||
]);
|
||||
}).pipe(Effect.provide(runtimeServices));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns the cached provider list when a manual refresh fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const codexDriver = ProviderDriverKind.make("codex");
|
||||
|
||||
@@ -78,11 +78,31 @@ const makeManualProviderMaintenanceCapabilities = (provider: ProviderDriverKind)
|
||||
const hasModelCapabilities = (model: ServerProvider["models"][number]): boolean =>
|
||||
(model.capabilities?.optionDescriptors?.length ?? 0) > 0;
|
||||
|
||||
const shouldRetainMissingProviderModels = (provider: ServerProvider): boolean => {
|
||||
if (provider.driver !== ProviderDriverKind.make("opencode")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// OpenCode's initial snapshot is deliberately non-authoritative while its
|
||||
// first probe is still running. A probe error from an installed CLI/server
|
||||
// is likewise partial: it could not establish the current inventory.
|
||||
// Conversely, disabled and missing-CLI snapshots are authoritative removals,
|
||||
// as are successful ready/warning inventories (including an empty one after
|
||||
// logout or plugin removal).
|
||||
const isPendingInitialProbe =
|
||||
provider.enabled && !provider.installed && provider.status === "warning";
|
||||
const didInstalledProviderProbeFail = provider.installed && provider.status === "error";
|
||||
return isPendingInitialProbe || didInstalledProviderProbeFail;
|
||||
};
|
||||
|
||||
const mergeProviderModels = (
|
||||
provider: ServerProvider,
|
||||
previousModels: ReadonlyArray<ServerProvider["models"][number]>,
|
||||
nextModels: ReadonlyArray<ServerProvider["models"][number]>,
|
||||
): ReadonlyArray<ServerProvider["models"][number]> => {
|
||||
if (nextModels.length === 0 && previousModels.length > 0) {
|
||||
const shouldRetainMissingModels = shouldRetainMissingProviderModels(provider);
|
||||
|
||||
if (shouldRetainMissingModels && nextModels.length === 0 && previousModels.length > 0) {
|
||||
return previousModels;
|
||||
}
|
||||
|
||||
@@ -98,7 +118,9 @@ const mergeProviderModels = (
|
||||
};
|
||||
});
|
||||
const nextSlugs = new Set(nextModels.map((model) => model.slug));
|
||||
return [...mergedModels, ...previousModels.filter((model) => !nextSlugs.has(model.slug))];
|
||||
return shouldRetainMissingModels
|
||||
? [...mergedModels, ...previousModels.filter((model) => !nextSlugs.has(model.slug))]
|
||||
: mergedModels;
|
||||
};
|
||||
|
||||
export const mergeProviderSnapshot = (
|
||||
@@ -109,7 +131,7 @@ export const mergeProviderSnapshot = (
|
||||
? nextProvider
|
||||
: {
|
||||
...nextProvider,
|
||||
models: mergeProviderModels(previousProvider.models, nextProvider.models),
|
||||
models: mergeProviderModels(nextProvider, previousProvider.models, nextProvider.models),
|
||||
};
|
||||
|
||||
export const mergeProviderSnapshots = (
|
||||
|
||||
@@ -100,12 +100,15 @@ function makeReadModel(
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
queuedMessages: [],
|
||||
session: thread.session,
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
|
||||
@@ -690,22 +690,36 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
|
||||
agentsResult = a2;
|
||||
}
|
||||
|
||||
// Degrade gracefully on failure — return empty inventory (warning status, not error)
|
||||
let connected: string[] = [];
|
||||
let allProviders: ProviderListResponse["all"] = [];
|
||||
if (modelsResult._tag === "Success" && modelsResult.value.code === 0) {
|
||||
const parsed = parseModelsCliOutput(modelsResult.value.stdout);
|
||||
connected = [...parsed.connected];
|
||||
allProviders = [...parsed.providers.values()].map((p) => ({
|
||||
id: p.id,
|
||||
name: p.name,
|
||||
if (modelsResult._tag === "Failure") {
|
||||
const cause = Cause.squash(modelsResult.cause);
|
||||
return yield* ensureRuntimeError(
|
||||
"loadInventoryFromCli",
|
||||
`Failed to load OpenCode models: ${openCodeRuntimeErrorDetail(cause)}`,
|
||||
cause,
|
||||
);
|
||||
}
|
||||
if (modelsResult.value.code !== 0) {
|
||||
return yield* new OpenCodeRuntimeError({
|
||||
operation: "loadInventoryFromCli",
|
||||
detail: `OpenCode models command exited with code ${modelsResult.value.code}.`,
|
||||
});
|
||||
}
|
||||
|
||||
const parsed = parseModelsCliOutput(modelsResult.value.stdout);
|
||||
const connected = [...parsed.connected];
|
||||
const allProviders: ProviderListResponse["all"] = [...parsed.providers.values()].map(
|
||||
(provider) => ({
|
||||
id: provider.id,
|
||||
name: provider.name,
|
||||
source: "config" as const,
|
||||
env: [],
|
||||
options: {},
|
||||
models: p.models,
|
||||
}));
|
||||
}
|
||||
models: provider.models,
|
||||
}),
|
||||
);
|
||||
|
||||
// Agent metadata enriches model capabilities but is not required for an
|
||||
// authoritative model inventory, so it may still degrade to an empty list.
|
||||
let agents: ReadonlyArray<Agent> = [];
|
||||
if (agentsResult._tag === "Success" && agentsResult.value.code === 0) {
|
||||
agents = parseAgentListCliOutput(agentsResult.value.stdout);
|
||||
|
||||
@@ -305,6 +305,8 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
@@ -451,6 +453,8 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: {
|
||||
threadId,
|
||||
status: "running",
|
||||
@@ -607,6 +611,8 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: {
|
||||
threadId,
|
||||
status: "running",
|
||||
|
||||
@@ -164,8 +164,12 @@ const makeDefaultOrchestrationReadModel = () => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
queuedMessages: [],
|
||||
pendingTurnStart: null,
|
||||
session: null,
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
@@ -193,6 +197,8 @@ const makeDefaultOrchestrationThreadShell = (
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
@@ -5281,6 +5287,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
gitManager: {
|
||||
invalidateLocalStatus: () => Effect.void,
|
||||
invalidateRemoteStatus: () => Effect.void,
|
||||
invalidateStatus: () => Effect.void,
|
||||
localStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
@@ -5327,6 +5334,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
gitManager: {
|
||||
invalidateLocalStatus: () => Effect.void,
|
||||
invalidateRemoteStatus: () => Effect.void,
|
||||
invalidateStatus: () => Effect.void,
|
||||
localStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
@@ -5403,6 +5411,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
gitManager: {
|
||||
invalidateLocalStatus: () => Effect.void,
|
||||
invalidateRemoteStatus: () => Effect.void,
|
||||
invalidateStatus: () => Effect.void,
|
||||
localStatus: () =>
|
||||
Deferred.succeed(localRefreshStarted, undefined).pipe(
|
||||
Effect.ignore,
|
||||
@@ -5499,8 +5508,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
queuedMessages: [],
|
||||
pendingTurnStart: null,
|
||||
session: null,
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
|
||||
@@ -208,6 +208,61 @@ describe("GitHubCli.layer", () => {
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("keeps pull requests from gh versions without headRepository.nameWithOwner", () =>
|
||||
// gh < 2.47 (e.g. Ubuntu-packaged 2.46) exports headRepository as
|
||||
// {id, name} only. These entries must decode instead of being dropped,
|
||||
// with nameWithOwner rebuilt from the owner login.
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 2829,
|
||||
title: "Codex turn mapping",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/2829",
|
||||
baseRefName: "main",
|
||||
headRefName: "t3code/codex-turn-mapping",
|
||||
state: "OPEN",
|
||||
mergedAt: null,
|
||||
isCrossRepository: false,
|
||||
headRepository: {
|
||||
id: "R_kgDORLtfbQ",
|
||||
name: "codething-mvp",
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
id: "MDEyOk9yZ2FuaXphdGlvbjg5MTkxNzI3",
|
||||
login: "pingdotgg",
|
||||
},
|
||||
},
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
const result = yield* gh.listOpenPullRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "t3code/codex-turn-mapping",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, [
|
||||
{
|
||||
number: 2829,
|
||||
title: "Codex turn mapping",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/2829",
|
||||
baseRefName: "main",
|
||||
headRefName: "t3code/codex-turn-mapping",
|
||||
state: "open",
|
||||
isCrossRepository: false,
|
||||
headRepositoryNameWithOwner: "pingdotgg/codething-mvp",
|
||||
headRepositoryOwnerLogin: "pingdotgg",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("reads repository clone URLs", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(
|
||||
|
||||
@@ -30,17 +30,21 @@ const GitHubPullRequestSchema = Schema.Struct({
|
||||
mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
updatedAt: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),
|
||||
isCrossRepository: Schema.optional(Schema.Boolean),
|
||||
// gh < 2.47 exports headRepository as {id, name} only; nameWithOwner was
|
||||
// added later. Both fields stay optional so a version-drifted gh CLI can
|
||||
// never fail the decode and silently drop the PR from the list.
|
||||
headRepository: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
nameWithOwner: Schema.String,
|
||||
nameWithOwner: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
name: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
}),
|
||||
),
|
||||
),
|
||||
headRepositoryOwner: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
login: Schema.String,
|
||||
login: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -71,11 +75,15 @@ function normalizeGitHubPullRequestState(input: {
|
||||
function normalizeGitHubPullRequestRecord(
|
||||
raw: Schema.Schema.Type<typeof GitHubPullRequestSchema>,
|
||||
): NormalizedGitHubPullRequestRecord {
|
||||
const headRepositoryNameWithOwner = trimOptionalString(raw.headRepository?.nameWithOwner);
|
||||
const explicitNameWithOwner = trimOptionalString(raw.headRepository?.nameWithOwner);
|
||||
const headRepositoryName = trimOptionalString(raw.headRepository?.name);
|
||||
const headRepositoryOwnerLogin =
|
||||
trimOptionalString(raw.headRepositoryOwner?.login) ??
|
||||
(typeof headRepositoryNameWithOwner === "string" && headRepositoryNameWithOwner.includes("/")
|
||||
? (headRepositoryNameWithOwner.split("/")[0] ?? null)
|
||||
(explicitNameWithOwner?.includes("/") ? (explicitNameWithOwner.split("/")[0] ?? null) : null);
|
||||
const headRepositoryNameWithOwner =
|
||||
explicitNameWithOwner ??
|
||||
(headRepositoryOwnerLogin && headRepositoryName
|
||||
? `${headRepositoryOwnerLogin}/${headRepositoryName}`
|
||||
: null);
|
||||
|
||||
return {
|
||||
|
||||
@@ -596,6 +596,26 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("marks the origin default ref as default when no local copy exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
const remote = yield* makeTmpDir("git-vcs-driver-remote-");
|
||||
const { initialBranch } = yield* initRepoWithCommit(cwd);
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
yield* git(cwd, ["remote", "add", "origin", remote]);
|
||||
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
|
||||
yield* git(cwd, ["remote", "set-head", "origin", initialBranch]);
|
||||
yield* git(cwd, ["checkout", "-b", "feature/only-local"]);
|
||||
yield* git(cwd, ["branch", "-D", initialBranch]);
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
|
||||
const refs = yield* driver.listRefs({ cwd });
|
||||
const remoteDefault = refs.refs.find((ref) => ref.name === `origin/${initialBranch}`);
|
||||
assert.equal(remoteDefault?.isRemote, true);
|
||||
assert.equal(remoteDefault?.isDefault, true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates, checks out, renames, and lists refs", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
@@ -670,6 +690,47 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("remote operations", () => {
|
||||
it.effect("ensureRemote reuses an existing remote across ssh/https transport variants", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(cwd);
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
|
||||
yield* git(cwd, ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"]);
|
||||
|
||||
const reusedForSsh = yield* driver.ensureRemote({
|
||||
cwd,
|
||||
preferredName: "pingdotgg",
|
||||
url: "[email protected]:pingdotgg/t3code.git",
|
||||
});
|
||||
assert.equal(reusedForSsh, "origin");
|
||||
|
||||
const reusedForSshScheme = yield* driver.ensureRemote({
|
||||
cwd,
|
||||
preferredName: "pingdotgg",
|
||||
url: "ssh://[email protected]/pingdotgg/t3code",
|
||||
});
|
||||
assert.equal(reusedForSshScheme, "origin");
|
||||
|
||||
const reusedForSshWithPort = yield* driver.ensureRemote({
|
||||
cwd,
|
||||
preferredName: "pingdotgg",
|
||||
url: "ssh://[email protected]:22/pingdotgg/t3code.git",
|
||||
});
|
||||
assert.equal(reusedForSshWithPort, "origin");
|
||||
|
||||
const addedForFork = yield* driver.ensureRemote({
|
||||
cwd,
|
||||
preferredName: "octocat",
|
||||
url: "[email protected]:octocat/t3code.git",
|
||||
});
|
||||
assert.equal(addedForFork, "octocat");
|
||||
assert.equal(yield* git(cwd, ["remote"]), "octocat\norigin");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("commit context", () => {
|
||||
it.effect("stages selected files and commits only those files", () =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
type ReviewDiffPreviewSource,
|
||||
type VcsRef,
|
||||
} from "@t3tools/contracts";
|
||||
import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git";
|
||||
import { dedupeRemoteBranchesWithLocalMatches, normalizeGitRemoteUrl } from "@t3tools/shared/git";
|
||||
import { compactTraceAttributes } from "@t3tools/shared/observability";
|
||||
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
|
||||
import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observability/Metrics.ts";
|
||||
@@ -235,14 +235,6 @@ function sanitizeRemoteName(value: string): string {
|
||||
return sanitized.length > 0 ? sanitized : "fork";
|
||||
}
|
||||
|
||||
function normalizeRemoteUrl(value: string): string {
|
||||
return value
|
||||
.trim()
|
||||
.replace(/\/+$/g, "")
|
||||
.replace(/\.git$/i, "")
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function parseRemoteFetchUrls(stdout: string): Map<string, string> {
|
||||
const remotes = new Map<string, string>();
|
||||
for (const line of stdout.split("\n")) {
|
||||
@@ -1092,7 +1084,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
"ensureRemote",
|
||||
)(function* (input) {
|
||||
const preferredName = sanitizeRemoteName(input.preferredName);
|
||||
const normalizedTargetUrl = normalizeRemoteUrl(input.url);
|
||||
const normalizedTargetUrl = normalizeGitRemoteUrl(input.url);
|
||||
const remoteFetchUrls = yield* runGitStdout(
|
||||
"GitVcsDriver.ensureRemote.listRemoteUrls",
|
||||
input.cwd,
|
||||
@@ -1100,7 +1092,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
).pipe(Effect.map((stdout) => parseRemoteFetchUrls(stdout)));
|
||||
|
||||
for (const [remoteName, remoteUrl] of remoteFetchUrls.entries()) {
|
||||
if (normalizeRemoteUrl(remoteUrl) === normalizedTargetUrl) {
|
||||
if (normalizeGitRemoteUrl(remoteUrl) === normalizedTargetUrl) {
|
||||
return remoteName;
|
||||
}
|
||||
}
|
||||
@@ -2217,7 +2209,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
name: refName.name,
|
||||
current: false,
|
||||
isRemote: true,
|
||||
isDefault: false,
|
||||
// origin/HEAD's target is the repo default even when no local
|
||||
// copy of the default branch exists.
|
||||
isDefault:
|
||||
defaultBranch !== null &&
|
||||
parsedRemoteRef?.remoteName === "origin" &&
|
||||
parsedRemoteRef.branchName === defaultBranch,
|
||||
worktreePath: null,
|
||||
};
|
||||
if (parsedRemoteRef) {
|
||||
@@ -2232,9 +2229,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
})
|
||||
: [];
|
||||
|
||||
const allBranches = input.includeMatchingRemoteRefs
|
||||
const combinedBranches = input.includeMatchingRemoteRefs
|
||||
? [...localBranches, ...remoteBranches]
|
||||
: dedupeRemoteBranchesWithLocalMatches([...localBranches, ...remoteBranches]);
|
||||
// Keep current/default refs on the first page even when the default
|
||||
// only exists as origin/<default> (remote refs sort after all locals).
|
||||
const allBranches = combinedBranches.toSorted((a, b) => {
|
||||
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
|
||||
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
|
||||
return aPriority - bPriority;
|
||||
});
|
||||
const branchesForKind =
|
||||
input.refKind === "local"
|
||||
? allBranches.filter((ref) => !ref.isRemote)
|
||||
|
||||
@@ -94,6 +94,11 @@ function makeTestLayer(state: {
|
||||
Effect.sync(() => {
|
||||
state.remoteInvalidationCalls += 1;
|
||||
}),
|
||||
invalidateStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localInvalidationCalls += 1;
|
||||
state.remoteInvalidationCalls += 1;
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -206,6 +211,11 @@ describe("VcsStatusBroadcaster", () => {
|
||||
Effect.sync(() => {
|
||||
state.remoteInvalidationCalls += 1;
|
||||
}),
|
||||
invalidateStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localInvalidationCalls += 1;
|
||||
state.remoteInvalidationCalls += 1;
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -366,10 +366,9 @@ export const make = Effect.gen(function* () {
|
||||
"VcsStatusBroadcaster.refreshStatus",
|
||||
)(function* (rawCwd) {
|
||||
const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
|
||||
yield* Effect.all([workflow.invalidateLocalStatus(cwd), workflow.invalidateRemoteStatus(cwd)], {
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
});
|
||||
// invalidateStatus (not the two partial invalidations) so an explicit
|
||||
// refresh also bypasses GitManager's slow PR-lookup cache.
|
||||
yield* workflow.invalidateStatus(cwd);
|
||||
const [local, remote] = yield* Effect.all(
|
||||
[workflow.localStatus({ cwd }), workflow.remoteStatus({ cwd })],
|
||||
{ concurrency: "unbounded" },
|
||||
|
||||
@@ -258,6 +258,8 @@ function isThreadDetailEvent(event: OrchestrationEvent): event is Extract<
|
||||
{
|
||||
type:
|
||||
| "thread.message-sent"
|
||||
| "thread.message-queued"
|
||||
| "thread.queued-message-removed"
|
||||
| "thread.proposed-plan-upserted"
|
||||
| "thread.activity-appended"
|
||||
| "thread.turn-diff-completed"
|
||||
@@ -267,6 +269,8 @@ function isThreadDetailEvent(event: OrchestrationEvent): event is Extract<
|
||||
> {
|
||||
return (
|
||||
event.type === "thread.message-sent" ||
|
||||
event.type === "thread.message-queued" ||
|
||||
event.type === "thread.queued-message-removed" ||
|
||||
event.type === "thread.proposed-plan-upserted" ||
|
||||
event.type === "thread.activity-appended" ||
|
||||
event.type === "thread.turn-diff-completed" ||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
// Tiny event bus allowing components to programmatically open the command palette
|
||||
// without owning its React state.
|
||||
const COMMAND_PALETTE_OPEN_EVENT = "t3code:open-command-palette";
|
||||
|
||||
export interface CommandPaletteOpenDetail {
|
||||
readonly open?: "add-project" | "new-thread-in";
|
||||
}
|
||||
|
||||
export function openCommandPalette(detail?: CommandPaletteOpenDetail): void {
|
||||
window.dispatchEvent(
|
||||
new CustomEvent(COMMAND_PALETTE_OPEN_EVENT, detail ? { detail } : undefined),
|
||||
);
|
||||
}
|
||||
|
||||
export function onOpenCommandPalette(
|
||||
listener: (detail: CommandPaletteOpenDetail) => void,
|
||||
): () => void {
|
||||
const handler = (event: Event) => {
|
||||
listener((event as CustomEvent<CommandPaletteOpenDetail>).detail ?? {});
|
||||
};
|
||||
window.addEventListener(COMMAND_PALETTE_OPEN_EVENT, handler);
|
||||
return () => window.removeEventListener(COMMAND_PALETTE_OPEN_EVENT, handler);
|
||||
}
|
||||
|
||||
/** Read at event time so consumers do not subscribe to transient dialog state. */
|
||||
export function isCommandPaletteOpen(): boolean {
|
||||
return (
|
||||
typeof document !== "undefined" && document.querySelector("[data-command-palette]") !== null
|
||||
);
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import { createContext, use, type ReactNode } from "react";
|
||||
|
||||
const OpenAddProjectCommandPaletteContext = createContext<(() => void) | null>(null);
|
||||
|
||||
export function OpenAddProjectCommandPaletteProvider(props: {
|
||||
readonly children: ReactNode;
|
||||
readonly openAddProject: () => void;
|
||||
}) {
|
||||
return (
|
||||
<OpenAddProjectCommandPaletteContext value={props.openAddProject}>
|
||||
{props.children}
|
||||
</OpenAddProjectCommandPaletteContext>
|
||||
);
|
||||
}
|
||||
|
||||
export function useOpenAddProjectCommandPalette(): () => void {
|
||||
const openAddProject = use(OpenAddProjectCommandPaletteContext);
|
||||
if (!openAddProject) {
|
||||
throw new Error("Command palette actions must be used inside CommandPalette");
|
||||
}
|
||||
return openAddProject;
|
||||
}
|
||||
|
||||
/** Read at event time so the chat tree does not subscribe to transient dialog state. */
|
||||
export function isCommandPaletteOpen(): boolean {
|
||||
return (
|
||||
typeof document !== "undefined" && document.querySelector("[data-command-palette]") !== null
|
||||
);
|
||||
}
|
||||
@@ -8,7 +8,9 @@ import { getLocalStorageItem } from "../hooks/useLocalStorage";
|
||||
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
|
||||
import { cn, isMacPlatform } from "../lib/utils";
|
||||
import { primaryServerKeybindingsAtom } from "../state/server";
|
||||
import { useClientSettings } from "../hooks/useSettings";
|
||||
import ThreadSidebar from "./Sidebar";
|
||||
import ThreadSidebarV2 from "./SidebarV2";
|
||||
import { useSidebarStageBackdropVariant } from "./SidebarStageBackdrop";
|
||||
import {
|
||||
resolveInitialThreadSidebarWidth,
|
||||
@@ -98,7 +100,12 @@ function SidebarControl() {
|
||||
|
||||
export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
const navigate = useNavigate();
|
||||
const sidebarV2Enabled = useClientSettings((settings) => settings.sidebarV2Enabled);
|
||||
// Settings routes render the settings nav, which lives in the v1 component
|
||||
// and is identical for both sidebars — so v1 stays mounted there.
|
||||
const pathname = useLocation({ select: (location) => location.pathname });
|
||||
const isOnSettings = pathname === "/settings" || pathname.startsWith("/settings/");
|
||||
const useSidebarV2 = sidebarV2Enabled && !isOnSettings;
|
||||
const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
|
||||
const [sidebarWidth, setSidebarWidth] = useState(readInitialThreadSidebarWidth);
|
||||
const sidebarMaximumWidth = resolveThreadSidebarMaximumWidth(window.innerWidth);
|
||||
@@ -157,7 +164,10 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
<Sidebar
|
||||
side="left"
|
||||
collapsible="offcanvas"
|
||||
className="border-r border-border bg-card text-foreground"
|
||||
className={cn(
|
||||
"border-r border-border text-foreground",
|
||||
useSidebarV2 ? "app-sidebar" : "bg-card",
|
||||
)}
|
||||
resizable={{
|
||||
maxWidth: sidebarMaximumWidth,
|
||||
minWidth: THREAD_SIDEBAR_MIN_WIDTH,
|
||||
@@ -168,7 +178,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
onResize: setSidebarWidth,
|
||||
}}
|
||||
>
|
||||
<ThreadSidebar />
|
||||
{useSidebarV2 ? <ThreadSidebarV2 /> : <ThreadSidebar />}
|
||||
<SidebarRail />
|
||||
</Sidebar>
|
||||
{children}
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
resolveBranchToolbarValue,
|
||||
resolveLockedWorkspaceLabel,
|
||||
shouldIncludeBranchPickerItem,
|
||||
shouldShowEnvironmentIndicator,
|
||||
} from "./BranchToolbar.logic";
|
||||
|
||||
const localEnvironmentId = EnvironmentId.make("environment-local");
|
||||
@@ -119,6 +120,44 @@ describe("resolveEnvironmentOptionLabel", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("shouldShowEnvironmentIndicator", () => {
|
||||
it("shows the indicator whenever multiple environments are pickable", () => {
|
||||
expect(
|
||||
shouldShowEnvironmentIndicator({
|
||||
activeEnvironment: { isPrimary: true },
|
||||
canPickEnvironment: true,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("shows a sole remote environment so the user knows where the project runs", () => {
|
||||
expect(
|
||||
shouldShowEnvironmentIndicator({
|
||||
activeEnvironment: { isPrimary: false },
|
||||
canPickEnvironment: false,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("hides a sole primary (this-device) environment", () => {
|
||||
expect(
|
||||
shouldShowEnvironmentIndicator({
|
||||
activeEnvironment: { isPrimary: true },
|
||||
canPickEnvironment: false,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("hides the indicator when the active environment is unknown", () => {
|
||||
expect(
|
||||
shouldShowEnvironmentIndicator({
|
||||
activeEnvironment: null,
|
||||
canPickEnvironment: false,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveEffectiveEnvMode", () => {
|
||||
it("treats draft threads already attached to a worktree as current-checkout mode", () => {
|
||||
expect(
|
||||
|
||||
@@ -42,6 +42,17 @@ export function resolveEnvironmentOptionLabel(input: {
|
||||
return runtimeLabel ?? savedLabel ?? input.environmentId;
|
||||
}
|
||||
|
||||
// A remote (non-primary) environment is always surfaced, even when it is the
|
||||
// only environment available: with a single connected machine there is nothing
|
||||
// to pick, but the user still needs to see where the project runs.
|
||||
export function shouldShowEnvironmentIndicator(input: {
|
||||
activeEnvironment: Pick<EnvironmentOption, "isPrimary"> | null;
|
||||
canPickEnvironment: boolean;
|
||||
}): boolean {
|
||||
if (input.canPickEnvironment) return true;
|
||||
return input.activeEnvironment !== null && !input.activeEnvironment.isPrimary;
|
||||
}
|
||||
|
||||
export function resolveEnvModeLabel(mode: EnvMode): string {
|
||||
return mode === "worktree" ? "New worktree" : "Current checkout";
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
resolveEnvModeLabel,
|
||||
resolveEffectiveEnvMode,
|
||||
resolveLockedWorkspaceLabel,
|
||||
shouldShowEnvironmentIndicator,
|
||||
} from "./BranchToolbar.logic";
|
||||
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
|
||||
import { BranchToolbarEnvironmentSelector } from "./BranchToolbarEnvironmentSelector";
|
||||
@@ -60,6 +61,7 @@ interface MobileRunContextSelectorProps {
|
||||
environmentId: EnvironmentId;
|
||||
availableEnvironments: readonly EnvironmentOption[] | undefined;
|
||||
showEnvironmentPicker: boolean;
|
||||
showEnvironmentIndicator: boolean;
|
||||
onEnvironmentChange: ((environmentId: EnvironmentId) => void) | undefined;
|
||||
effectiveEnvMode: EnvMode;
|
||||
activeWorktreePath: string | null;
|
||||
@@ -72,6 +74,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
|
||||
environmentId,
|
||||
availableEnvironments,
|
||||
showEnvironmentPicker,
|
||||
showEnvironmentIndicator,
|
||||
onEnvironmentChange,
|
||||
effectiveEnvMode,
|
||||
activeWorktreePath,
|
||||
@@ -94,7 +97,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
|
||||
: resolveCurrentWorkspaceLabel(activeWorktreePath);
|
||||
const isLocked = envLocked || envModeLocked;
|
||||
const EnvironmentIcon = activeEnvironment?.isPrimary ? MonitorIcon : CloudIcon;
|
||||
const icon = showEnvironmentPicker ? (
|
||||
const icon = showEnvironmentIndicator ? (
|
||||
// Button's base styles apply `-mx-0.5` to descendant SVGs, which eats 4px
|
||||
// out of whatever gap we set. mx-0! cancels that so gap-0.5 reads as 2px.
|
||||
<span className="inline-flex shrink-0 items-center gap-0.5">
|
||||
@@ -108,7 +111,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
|
||||
<>
|
||||
{icon}
|
||||
<span className="min-w-0 truncate">
|
||||
{showEnvironmentPicker ? (activeEnvironment?.label ?? "Run on") : workspaceLabel}
|
||||
{showEnvironmentIndicator ? (activeEnvironment?.label ?? "Run on") : workspaceLabel}
|
||||
</span>
|
||||
</>
|
||||
);
|
||||
@@ -234,6 +237,12 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
const showEnvironmentPicker = Boolean(
|
||||
availableEnvironments && availableEnvironments.length > 1 && onEnvironmentChange,
|
||||
);
|
||||
const activeEnvironmentOption =
|
||||
availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null;
|
||||
const showEnvironmentIndicator = shouldShowEnvironmentIndicator({
|
||||
activeEnvironment: activeEnvironmentOption,
|
||||
canPickEnvironment: showEnvironmentPicker,
|
||||
});
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
if (!hasActiveThread || !activeProject) return null;
|
||||
@@ -247,6 +256,7 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
environmentId={environmentId}
|
||||
availableEnvironments={availableEnvironments}
|
||||
showEnvironmentPicker={showEnvironmentPicker}
|
||||
showEnvironmentIndicator={showEnvironmentIndicator}
|
||||
onEnvironmentChange={onEnvironmentChange}
|
||||
effectiveEnvMode={effectiveEnvMode}
|
||||
activeWorktreePath={activeWorktreePath}
|
||||
@@ -254,13 +264,13 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
/>
|
||||
) : (
|
||||
<div className="flex min-w-0 shrink-0 items-center gap-1">
|
||||
{showEnvironmentPicker && availableEnvironments && onEnvironmentChange && (
|
||||
{showEnvironmentIndicator && availableEnvironments && (
|
||||
<>
|
||||
<BranchToolbarEnvironmentSelector
|
||||
envLocked={envLocked}
|
||||
environmentId={environmentId}
|
||||
availableEnvironments={availableEnvironments}
|
||||
onEnvironmentChange={onEnvironmentChange}
|
||||
{...(showEnvironmentPicker && onEnvironmentChange ? { onEnvironmentChange } : {})}
|
||||
/>
|
||||
<Separator orientation="vertical" className="mx-0.5 h-3.5!" />
|
||||
</>
|
||||
|
||||
@@ -422,17 +422,32 @@ export function BranchToolbarBranchSelector({
|
||||
});
|
||||
};
|
||||
|
||||
// Default the worktree base to the repo default branch (origin/HEAD), only
|
||||
// falling back to the checked-out branch when no default is known.
|
||||
const defaultBranchName = useMemo(
|
||||
() => refs.find((refName) => refName.isDefault)?.name ?? null,
|
||||
[refs],
|
||||
);
|
||||
const worktreeBaseBranchCandidate = isInitialBranchesLoadPending
|
||||
? null
|
||||
: (defaultBranchName ?? currentGitBranch);
|
||||
useEffect(() => {
|
||||
if (
|
||||
effectiveEnvMode !== "worktree" ||
|
||||
activeWorktreePath ||
|
||||
activeThreadBranch ||
|
||||
!currentGitBranch
|
||||
!worktreeBaseBranchCandidate
|
||||
) {
|
||||
return;
|
||||
}
|
||||
setThreadBranch(currentGitBranch, null);
|
||||
}, [activeThreadBranch, activeWorktreePath, currentGitBranch, effectiveEnvMode, setThreadBranch]);
|
||||
setThreadBranch(worktreeBaseBranchCandidate, null);
|
||||
}, [
|
||||
activeThreadBranch,
|
||||
activeWorktreePath,
|
||||
effectiveEnvMode,
|
||||
setThreadBranch,
|
||||
worktreeBaseBranchCandidate,
|
||||
]);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Combobox / list plumbing
|
||||
|
||||
@@ -17,7 +17,9 @@ interface BranchToolbarEnvironmentSelectorProps {
|
||||
envLocked: boolean;
|
||||
environmentId: EnvironmentId;
|
||||
availableEnvironments: readonly EnvironmentOption[];
|
||||
onEnvironmentChange: (environmentId: EnvironmentId) => void;
|
||||
// Absent when there is only one environment to show: the indicator still
|
||||
// renders (as a static label) so remote projects are always identifiable.
|
||||
onEnvironmentChange?: (environmentId: EnvironmentId) => void;
|
||||
}
|
||||
|
||||
export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvironmentSelector({
|
||||
@@ -39,7 +41,7 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
|
||||
[availableEnvironments],
|
||||
);
|
||||
|
||||
if (envLocked) {
|
||||
if (envLocked || onEnvironmentChange === undefined) {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs">
|
||||
{activeEnvironment?.isPrimary ? (
|
||||
|
||||
@@ -42,6 +42,10 @@ import remarkGfm from "remark-gfm";
|
||||
import { renderSkillInlineMarkdownChildren } from "./chat/SkillInlineText";
|
||||
import { CHAT_FILE_TAG_CHIP_CLASS_NAME, FileTagChipContent } from "./chat/FileTagChip";
|
||||
import { PierreEntryIcon } from "./chat/PierreEntryIcon";
|
||||
import {
|
||||
resolveExternalWebLinkHost,
|
||||
showExternalLinkContextMenu,
|
||||
} from "./chat/externalLinkContextMenu";
|
||||
import { hasSpecificPierreIconForFileName, syntheticFileNameForLanguageId } from "../pierre-icons";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
import { Button } from "./ui/button";
|
||||
@@ -76,6 +80,7 @@ import { usePreparedConnection } from "../state/session";
|
||||
import { previewEnvironment } from "../state/preview";
|
||||
import { useAtomCommand } from "../state/use-atom-command";
|
||||
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
|
||||
import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
|
||||
import { isPreviewSupportedInRuntime } from "../previewStateStore";
|
||||
import {
|
||||
isBrowserPreviewFile,
|
||||
@@ -831,17 +836,6 @@ const MARKDOWN_LINK_FAVICON_CLASS_NAME = "block size-full shrink-0 select-none";
|
||||
/** Hosts whose favicon request already failed this session — skip straight to the globe. */
|
||||
const failedFaviconHosts = new Set<string>();
|
||||
|
||||
function resolveExternalLinkHost(href: string | undefined): string | null {
|
||||
if (!href) return null;
|
||||
try {
|
||||
const url = new URL(href);
|
||||
if (url.protocol !== "http:" && url.protocol !== "https:") return null;
|
||||
return url.hostname || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const MarkdownLinkFavicon = memo(function MarkdownLinkFavicon({ host }: { host: string }) {
|
||||
const [failedHost, setFailedHost] = useState<string | null>(null);
|
||||
return (
|
||||
@@ -1393,7 +1387,7 @@ function ChatMarkdown({
|
||||
const normalizedHref = href ? normalizeMarkdownLinkHrefKey(href) : "";
|
||||
const fileLinkMeta = normalizedHref ? markdownFileLinkMetaByHref.get(normalizedHref) : null;
|
||||
if (!fileLinkMeta) {
|
||||
const faviconHost = resolveExternalLinkHost(href);
|
||||
const faviconHost = resolveExternalWebLinkHost(href);
|
||||
const isSameDocumentLink = href?.startsWith("#") ?? false;
|
||||
const onClick = props.onClick;
|
||||
const canOpenInPreview = Boolean(threadRef) && isPreviewSupportedInRuntime();
|
||||
@@ -1410,37 +1404,30 @@ function ChatMarkdown({
|
||||
}
|
||||
}}
|
||||
onContextMenu={(event) => {
|
||||
if (!canOpenInPreview || !href) return;
|
||||
if (!canOpenInPreview || !href || !faviconHost) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const api = readLocalApi();
|
||||
if (!api) return;
|
||||
void (async () => {
|
||||
let operation = "show-link-context-menu";
|
||||
try {
|
||||
const clicked = await api.contextMenu.show(
|
||||
[
|
||||
{ id: "open-in-browser", label: "Open in integrated browser" },
|
||||
{ id: "open-external", label: "Open in system browser" },
|
||||
] as const,
|
||||
{ x: event.clientX, y: event.clientY },
|
||||
);
|
||||
if (clicked === "open-in-browser") {
|
||||
operation = "open-link-in-preview";
|
||||
const result = await openExternalLinkInPreview(href);
|
||||
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
|
||||
reportMarkdownActionFailure({ operation, target: href }, result.cause);
|
||||
}
|
||||
return;
|
||||
void showExternalLinkContextMenu({
|
||||
href,
|
||||
position: { x: event.clientX, y: event.clientY },
|
||||
showContextMenu: (items, position) => api.contextMenu.show(items, position),
|
||||
openInPreview: async (target) => {
|
||||
const result = await openExternalLinkInPreview(target);
|
||||
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
|
||||
reportMarkdownActionFailure(
|
||||
{ operation: "open-link-in-preview", target },
|
||||
result.cause,
|
||||
);
|
||||
}
|
||||
if (clicked === "open-external") {
|
||||
operation = "open-link-external";
|
||||
await api.shell.openExternal(href);
|
||||
}
|
||||
} catch (cause) {
|
||||
},
|
||||
openExternal: (target) => api.shell.openExternal(target),
|
||||
copyLink: (target) => writeTextToClipboard(target, "link"),
|
||||
reportFailure: (operation, cause) => {
|
||||
reportMarkdownActionFailure({ operation, target: href }, cause);
|
||||
}
|
||||
})();
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
{faviconHost ? (
|
||||
|
||||
@@ -6,9 +6,9 @@ import {
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import type { ChatMessage, Thread } from "../types";
|
||||
import type { Thread } from "../types";
|
||||
import {
|
||||
MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
|
||||
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
|
||||
@@ -20,10 +20,6 @@ import {
|
||||
hasServerAcknowledgedLocalDispatch,
|
||||
reconcileMountedTerminalThreadIds,
|
||||
reconcileRetainedMountedThreadIds,
|
||||
collectUserMessageBlobPreviewUrls,
|
||||
normalizeDataUrlMimeType,
|
||||
resolveComposerAttachmentMimeType,
|
||||
revokeUserMessagePreviewUrls,
|
||||
resolveSendEnvMode,
|
||||
shouldWriteThreadErrorToCurrentServerThread,
|
||||
} from "./ChatView.logic";
|
||||
@@ -47,12 +43,16 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
interactionMode: "default",
|
||||
session: null,
|
||||
messages: [],
|
||||
queuedMessages: [],
|
||||
pendingTurnStart: null,
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
latestTurn: null,
|
||||
branch: null,
|
||||
@@ -81,81 +81,6 @@ const readySession = {
|
||||
updatedAt: "2026-03-29T00:00:10.000Z",
|
||||
};
|
||||
|
||||
function makeAttachmentMessage(): ChatMessage {
|
||||
return {
|
||||
id: MessageId.make("message-with-attachments"),
|
||||
role: "user",
|
||||
text: "Inspect these files",
|
||||
turnId: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
streaming: false,
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "image-1",
|
||||
name: "screenshot.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 10,
|
||||
previewUrl: "blob:image-preview",
|
||||
},
|
||||
{
|
||||
type: "file",
|
||||
id: "file-1",
|
||||
name: "debug.log",
|
||||
mimeType: "text/plain",
|
||||
sizeBytes: 20,
|
||||
previewUrl: "blob:file-preview",
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
describe("attachment preview lifecycle", () => {
|
||||
it("collects and revokes blob previews for images and files", () => {
|
||||
const revokeObjectURL = vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
|
||||
const message = makeAttachmentMessage();
|
||||
|
||||
expect(collectUserMessageBlobPreviewUrls(message)).toEqual([
|
||||
"blob:image-preview",
|
||||
"blob:file-preview",
|
||||
]);
|
||||
revokeUserMessagePreviewUrls(message);
|
||||
|
||||
expect(revokeObjectURL).toHaveBeenCalledTimes(2);
|
||||
expect(revokeObjectURL).toHaveBeenNthCalledWith(1, "blob:image-preview");
|
||||
expect(revokeObjectURL).toHaveBeenNthCalledWith(2, "blob:file-preview");
|
||||
revokeObjectURL.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
describe("composer attachment MIME types", () => {
|
||||
it("recovers image MIME types from names when the browser reports a generic type", () => {
|
||||
expect(resolveComposerAttachmentMimeType({ name: "capture.PNG", type: "" })).toBe("image/png");
|
||||
expect(
|
||||
resolveComposerAttachmentMimeType({
|
||||
name: "capture.webp",
|
||||
type: "application/octet-stream",
|
||||
}),
|
||||
).toBe("image/webp");
|
||||
});
|
||||
|
||||
it("preserves a specific browser MIME type and keeps unknown files generic", () => {
|
||||
expect(resolveComposerAttachmentMimeType({ name: "capture.png", type: "text/plain" })).toBe(
|
||||
"text/plain",
|
||||
);
|
||||
expect(resolveComposerAttachmentMimeType({ name: "payload.bin", type: "" })).toBe(
|
||||
"application/octet-stream",
|
||||
);
|
||||
});
|
||||
|
||||
it("rewrites a FileReader data URL with the resolved attachment MIME type", () => {
|
||||
expect(
|
||||
normalizeDataUrlMimeType("data:application/octet-stream;base64,iVBORw0KGgo=", "image/png"),
|
||||
).toBe("data:image/png;base64,iVBORw0KGgo=");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildThreadTurnInterruptInput", () => {
|
||||
it("targets the session's active running turn", () => {
|
||||
const activeTurnId = TurnId.make("turn-running");
|
||||
@@ -446,6 +371,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
phase: "ready",
|
||||
latestTurn: completedTurn,
|
||||
latestUserMessageId: localDispatch.latestUserMessageId,
|
||||
projectedMessageIds: new Set<string>(),
|
||||
session: readySession,
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
@@ -472,6 +398,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
phase: "ready",
|
||||
latestTurn: newerTurn,
|
||||
latestUserMessageId: localDispatch.latestUserMessageId,
|
||||
projectedMessageIds: new Set<string>(),
|
||||
session: { ...readySession, updatedAt: newerTurn.completedAt },
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
@@ -499,6 +426,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
phase: "running",
|
||||
latestTurn: runningTurn,
|
||||
latestUserMessageId: localDispatch.latestUserMessageId,
|
||||
projectedMessageIds: new Set<string>(),
|
||||
session: {
|
||||
...readySession,
|
||||
status: "running",
|
||||
@@ -515,6 +443,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
phase: "running",
|
||||
latestTurn: runningTurn,
|
||||
latestUserMessageId: localDispatch.latestUserMessageId,
|
||||
projectedMessageIds: new Set<string>(),
|
||||
session: {
|
||||
...readySession,
|
||||
status: "running",
|
||||
@@ -556,18 +485,63 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
// Dispatch without a known messageId keeps the legacy heuristic: a new
|
||||
// latest user message acknowledges it.
|
||||
expect(
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch,
|
||||
phase: "running",
|
||||
latestTurn: runningTurn,
|
||||
latestUserMessageId: MessageId.make("message-steer"),
|
||||
projectedMessageIds: new Set<string>(),
|
||||
session: runningSession,
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
threadError: null,
|
||||
}),
|
||||
).toBe(true);
|
||||
|
||||
const correlatedDispatch = createLocalDispatchSnapshot(
|
||||
makeThread({ latestTurn: runningTurn, session: runningSession }),
|
||||
{ messageId: MessageId.make("message-mine") },
|
||||
);
|
||||
|
||||
// A correlated dispatch acknowledges when its exact message appears in
|
||||
// the timeline or the queue...
|
||||
for (const projectedMessageIds of [
|
||||
new Set(["message-mine"]),
|
||||
new Set(["message-other", "message-mine"]),
|
||||
]) {
|
||||
expect(
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch: correlatedDispatch,
|
||||
phase: "running",
|
||||
latestTurn: runningTurn,
|
||||
latestUserMessageId: correlatedDispatch.latestUserMessageId,
|
||||
projectedMessageIds,
|
||||
session: runningSession,
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
threadError: null,
|
||||
}),
|
||||
).toBe(true);
|
||||
}
|
||||
|
||||
// ...but ignores unrelated queue/timeline changes (another client's
|
||||
// queued message, or a different queued chip being steered/removed).
|
||||
expect(
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch: correlatedDispatch,
|
||||
phase: "running",
|
||||
latestTurn: runningTurn,
|
||||
latestUserMessageId: MessageId.make("message-someone-else"),
|
||||
projectedMessageIds: new Set(["message-someone-else"]),
|
||||
session: runningSession,
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
threadError: null,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("acknowledges pending user interaction and errors immediately", () => {
|
||||
@@ -577,6 +551,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
phase: "ready" as const,
|
||||
latestTurn: null,
|
||||
latestUserMessageId: localDispatch.latestUserMessageId,
|
||||
projectedMessageIds: new Set<string>(),
|
||||
session: null,
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
type TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { type ChatMessage, type SessionPhase, type Thread } from "../types";
|
||||
import { type ComposerAttachment, type DraftThreadState } from "../composerDraftStore";
|
||||
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { appAtomRegistry } from "../rpc/atomRegistry";
|
||||
import { environmentThreadDetails } from "../state/threads";
|
||||
@@ -42,9 +42,13 @@ export function buildLocalDraftThread(
|
||||
interactionMode: draftThread.interactionMode,
|
||||
session: null,
|
||||
messages: [],
|
||||
queuedMessages: [],
|
||||
pendingTurnStart: null,
|
||||
createdAt: draftThread.createdAt,
|
||||
updatedAt: draftThread.createdAt,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
latestTurn: null,
|
||||
branch: draftThread.branch,
|
||||
@@ -144,6 +148,9 @@ export function revokeUserMessagePreviewUrls(message: ChatMessage): void {
|
||||
return;
|
||||
}
|
||||
for (const attachment of message.attachments) {
|
||||
if (attachment.type !== "image") {
|
||||
continue;
|
||||
}
|
||||
revokeBlobPreviewUrl(attachment.previewUrl);
|
||||
}
|
||||
}
|
||||
@@ -154,78 +161,30 @@ export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[
|
||||
}
|
||||
const previewUrls: string[] = [];
|
||||
for (const attachment of message.attachments) {
|
||||
if (attachment.type !== "image") continue;
|
||||
if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
|
||||
previewUrls.push(attachment.previewUrl);
|
||||
}
|
||||
return previewUrls;
|
||||
}
|
||||
|
||||
const FALLBACK_IMAGE_MIME_TYPE_BY_EXTENSION: Readonly<Record<string, string>> = {
|
||||
".avif": "image/avif",
|
||||
".bmp": "image/bmp",
|
||||
".gif": "image/gif",
|
||||
".heic": "image/heic",
|
||||
".heif": "image/heif",
|
||||
".jpeg": "image/jpeg",
|
||||
".jpg": "image/jpeg",
|
||||
".png": "image/png",
|
||||
".svg": "image/svg+xml",
|
||||
".tif": "image/tiff",
|
||||
".tiff": "image/tiff",
|
||||
".webp": "image/webp",
|
||||
};
|
||||
|
||||
const GENERIC_BINARY_MIME_TYPES = new Set([
|
||||
"",
|
||||
"application/octet-stream",
|
||||
"application/unknown",
|
||||
"application/x-unknown",
|
||||
"binary/octet-stream",
|
||||
]);
|
||||
|
||||
export function resolveComposerAttachmentMimeType(file: {
|
||||
readonly name: string;
|
||||
readonly type: string;
|
||||
}): string {
|
||||
const declaredMimeType = file.type.trim().toLowerCase();
|
||||
if (!GENERIC_BINARY_MIME_TYPES.has(declaredMimeType)) {
|
||||
return declaredMimeType;
|
||||
}
|
||||
const normalizedName = file.name.trim().toLowerCase();
|
||||
const extensionIndex = normalizedName.lastIndexOf(".");
|
||||
const extension = extensionIndex >= 0 ? normalizedName.slice(extensionIndex) : "";
|
||||
return (
|
||||
FALLBACK_IMAGE_MIME_TYPE_BY_EXTENSION[extension] ||
|
||||
declaredMimeType ||
|
||||
"application/octet-stream"
|
||||
);
|
||||
}
|
||||
|
||||
export function normalizeDataUrlMimeType(dataUrl: string, mimeType: string): string {
|
||||
const separatorIndex = dataUrl.indexOf(",");
|
||||
if (!dataUrl.startsWith("data:") || separatorIndex < 0) {
|
||||
return dataUrl;
|
||||
}
|
||||
return `data:${mimeType};base64,${dataUrl.slice(separatorIndex + 1)}`;
|
||||
}
|
||||
|
||||
export interface PullRequestDialogState {
|
||||
initialReference: string | null;
|
||||
key: number;
|
||||
}
|
||||
|
||||
export function readFileAsDataUrl(file: File, mimeType?: string): Promise<string> {
|
||||
export function readFileAsDataUrl(file: File): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.addEventListener("load", () => {
|
||||
if (typeof reader.result === "string") {
|
||||
resolve(mimeType ? normalizeDataUrlMimeType(reader.result, mimeType) : reader.result);
|
||||
resolve(reader.result);
|
||||
return;
|
||||
}
|
||||
reject(new Error("Could not read attachment data."));
|
||||
reject(new Error("Could not read image data."));
|
||||
});
|
||||
reader.addEventListener("error", () => {
|
||||
reject(reader.error ?? new Error("Failed to read attachment."));
|
||||
reject(reader.error ?? new Error("Failed to read image."));
|
||||
});
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
@@ -238,7 +197,9 @@ export function resolveSendEnvMode(input: {
|
||||
return input.isGitRepo ? input.requestedEnvMode : "local";
|
||||
}
|
||||
|
||||
export function cloneComposerImageForRetry(image: ComposerAttachment): ComposerAttachment {
|
||||
export function cloneComposerImageForRetry(
|
||||
image: ComposerImageAttachment,
|
||||
): ComposerImageAttachment {
|
||||
if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
|
||||
return image;
|
||||
}
|
||||
@@ -430,6 +391,13 @@ export async function waitForStartedServerThread(
|
||||
export interface LocalDispatchSnapshot {
|
||||
startedAt: string;
|
||||
preparingWorktree: boolean;
|
||||
/**
|
||||
* The messageId of the send this dispatch is waiting on, when the send
|
||||
* path knows it. Acknowledgment then correlates with this exact message
|
||||
* being projected (timeline or queue) instead of global tail heuristics
|
||||
* that other clients' activity could satisfy.
|
||||
*/
|
||||
expectedMessageId: ChatMessage["id"] | null;
|
||||
latestUserMessageId: ChatMessage["id"] | null;
|
||||
latestTurnTurnId: TurnId | null;
|
||||
latestTurnRequestedAt: string | null;
|
||||
@@ -441,7 +409,7 @@ export interface LocalDispatchSnapshot {
|
||||
|
||||
export function createLocalDispatchSnapshot(
|
||||
activeThread: Thread | undefined,
|
||||
options?: { preparingWorktree?: boolean },
|
||||
options?: { preparingWorktree?: boolean; messageId?: ChatMessage["id"] },
|
||||
): LocalDispatchSnapshot {
|
||||
const latestTurn = activeThread?.latestTurn ?? null;
|
||||
const session = activeThread?.session ?? null;
|
||||
@@ -449,6 +417,7 @@ export function createLocalDispatchSnapshot(
|
||||
return {
|
||||
startedAt: new Date().toISOString(),
|
||||
preparingWorktree: Boolean(options?.preparingWorktree),
|
||||
expectedMessageId: options?.messageId ?? null,
|
||||
latestUserMessageId: latestUserMessage?.id ?? null,
|
||||
latestTurnTurnId: latestTurn?.turnId ?? null,
|
||||
latestTurnRequestedAt: latestTurn?.requestedAt ?? null,
|
||||
@@ -464,6 +433,7 @@ export function hasServerAcknowledgedLocalDispatch(input: {
|
||||
phase: SessionPhase;
|
||||
latestTurn: Thread["latestTurn"] | null;
|
||||
latestUserMessageId: ChatMessage["id"] | null;
|
||||
projectedMessageIds: ReadonlySet<string>;
|
||||
session: Thread["session"] | null;
|
||||
hasPendingApproval: boolean;
|
||||
hasPendingUserInput: boolean;
|
||||
@@ -478,6 +448,7 @@ export function hasServerAcknowledgedLocalDispatch(input: {
|
||||
|
||||
const latestTurn = input.latestTurn ?? null;
|
||||
const session = input.session ?? null;
|
||||
const expectedMessageId = input.localDispatch.expectedMessageId;
|
||||
const latestUserMessageChanged =
|
||||
input.localDispatch.latestUserMessageId !== input.latestUserMessageId;
|
||||
const latestTurnChanged =
|
||||
@@ -486,12 +457,18 @@ export function hasServerAcknowledgedLocalDispatch(input: {
|
||||
input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) ||
|
||||
input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null);
|
||||
|
||||
// The dispatched message being projected (timeline or queue) is the
|
||||
// strongest acknowledgment in every phase: the server also queues sends
|
||||
// while a session is starting ("connecting" phase), where neither turn
|
||||
// nor session fields necessarily change.
|
||||
if (expectedMessageId !== null && input.projectedMessageIds.has(expectedMessageId)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (input.phase === "running") {
|
||||
// Steering adds a user message to the current running turn without
|
||||
// necessarily changing any of the turn timestamps. Treat that projected
|
||||
// message as the server acknowledgment so the composer does not remain
|
||||
// stuck in its local "Sending" state until the turn settles.
|
||||
if (latestUserMessageChanged) {
|
||||
// Dispatches without a known messageId (e.g. plan-implementation flows)
|
||||
// keep the legacy latest-user-message heuristic.
|
||||
if (expectedMessageId === null && latestUserMessageChanged) {
|
||||
return true;
|
||||
}
|
||||
if (!latestTurnChanged) {
|
||||
|
||||
@@ -112,7 +112,7 @@ import {
|
||||
} from "../types";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import { isCommandPaletteOpen } from "../commandPaletteContext";
|
||||
import { isCommandPaletteOpen } from "../commandPaletteBus";
|
||||
import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
|
||||
import { useMediaQuery } from "../hooks/useMediaQuery";
|
||||
import { RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY } from "../rightPanelLayout";
|
||||
@@ -152,6 +152,7 @@ import {
|
||||
} from "~/projectScripts";
|
||||
import { newDraftId, newMessageId, newThreadId } from "~/lib/utils";
|
||||
import { getProviderModelCapabilities, resolveSelectableProvider } from "../providerModels";
|
||||
import { NO_PROVIDER_MODEL_SELECTION } from "../providerInstances";
|
||||
import { useEnvironmentSettings } from "../hooks/useSettings";
|
||||
import { resolveAppModelSelectionForInstance } from "../modelSelection";
|
||||
import { getTerminalFocusOwner } from "../lib/terminalFocus";
|
||||
@@ -162,7 +163,7 @@ import {
|
||||
} from "../logicalProject";
|
||||
import { buildDraftThreadRouteParams } from "../threadRoutes";
|
||||
import {
|
||||
type ComposerAttachment,
|
||||
type ComposerImageAttachment,
|
||||
type DraftThreadEnvMode,
|
||||
useComposerDraftStore,
|
||||
type DraftId,
|
||||
@@ -215,6 +216,7 @@ import { resolveEffectiveEnvMode } from "./BranchToolbar.logic";
|
||||
import { ProviderStatusBanner } from "./chat/ProviderStatusBanner";
|
||||
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
|
||||
import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack";
|
||||
import { QueuedMessageChips } from "./chat/QueuedMessageChips";
|
||||
import {
|
||||
DRAFT_HERO_TRANSITION_ANIMATION_ID,
|
||||
DRAFT_HERO_TRANSITION_DURATION_MS,
|
||||
@@ -261,8 +263,8 @@ import {
|
||||
} from "../versionSkew";
|
||||
import { useAssetUrls } from "../assets/assetUrls";
|
||||
|
||||
const ATTACHMENT_ONLY_BOOTSTRAP_PROMPT =
|
||||
"[User attached one or more files without additional text. Respond using the conversation context and the attached file(s).]";
|
||||
const IMAGE_ONLY_BOOTSTRAP_PROMPT =
|
||||
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
|
||||
const EMPTY_ACTIVITIES: OrchestrationThreadActivity[] = [];
|
||||
const EMPTY_PROVIDERS: ServerProvider[] = [];
|
||||
const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];
|
||||
@@ -455,6 +457,20 @@ function useLocalDispatchState(input: {
|
||||
const [localDispatch, setLocalDispatch] = useState<LocalDispatchSnapshot | null>(null);
|
||||
const latestUserMessageId =
|
||||
input.activeThread?.messages.findLast((message) => message.role === "user")?.id ?? null;
|
||||
const activeThreadMessages = input.activeThread?.messages;
|
||||
const activeThreadQueuedMessages = input.activeThread?.queuedMessages;
|
||||
// Every server-projected id for this thread — timeline messages plus the
|
||||
// held queue — so acknowledgment can match the exact dispatched message.
|
||||
const projectedMessageIds = useMemo(() => {
|
||||
const ids = new Set<string>();
|
||||
for (const message of activeThreadMessages ?? []) {
|
||||
ids.add(message.id);
|
||||
}
|
||||
for (const queuedMessage of activeThreadQueuedMessages ?? []) {
|
||||
ids.add(queuedMessage.messageId);
|
||||
}
|
||||
return ids;
|
||||
}, [activeThreadMessages, activeThreadQueuedMessages]);
|
||||
|
||||
const resetLocalDispatch = useCallback(() => {
|
||||
setLocalDispatch(null);
|
||||
@@ -467,6 +483,7 @@ function useLocalDispatchState(input: {
|
||||
phase: input.phase,
|
||||
latestTurn: input.activeLatestTurn,
|
||||
latestUserMessageId,
|
||||
projectedMessageIds,
|
||||
session: input.activeThread?.session ?? null,
|
||||
hasPendingApproval: input.activePendingApproval !== null,
|
||||
hasPendingUserInput: input.activePendingUserInput !== null,
|
||||
@@ -480,12 +497,13 @@ function useLocalDispatchState(input: {
|
||||
input.phase,
|
||||
input.threadError,
|
||||
latestUserMessageId,
|
||||
projectedMessageIds,
|
||||
localDispatch,
|
||||
],
|
||||
);
|
||||
const activeLocalDispatch = serverAcknowledgedLocalDispatch ? null : localDispatch;
|
||||
const beginLocalDispatch = useCallback(
|
||||
(options?: { preparingWorktree?: boolean }) => {
|
||||
(options?: { preparingWorktree?: boolean; messageId?: MessageId }) => {
|
||||
const preparingWorktree = Boolean(options?.preparingWorktree);
|
||||
setLocalDispatch((current) => {
|
||||
const active = serverAcknowledgedLocalDispatch ? null : current;
|
||||
@@ -1113,6 +1131,12 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const steerQueuedThreadMessage = useAtomCommand(threadEnvironment.steerQueuedMessage, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const removeQueuedThreadMessage = useAtomCommand(threadEnvironment.removeQueuedMessage, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const respondToThreadApproval = useAtomCommand(threadEnvironment.respondToApproval, {
|
||||
reportFailure: false,
|
||||
});
|
||||
@@ -1190,7 +1214,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
: null,
|
||||
);
|
||||
const promptRef = useRef("");
|
||||
const composerImagesRef = useRef<ComposerAttachment[]>([]);
|
||||
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
|
||||
const composerTerminalContextsRef = useRef<TerminalContextDraft[]>([]);
|
||||
const composerElementContextsRef = useRef<ElementContextDraft[]>([]);
|
||||
const localComposerRef = useRef<ChatComposerHandle | null>(null);
|
||||
@@ -1361,10 +1385,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
? buildLocalDraftThread(
|
||||
threadId,
|
||||
draftThread,
|
||||
fallbackDraftProject?.defaultModelSelection ?? {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: DEFAULT_MODEL,
|
||||
},
|
||||
fallbackDraftProject?.defaultModelSelection ?? NO_PROVIDER_MODEL_SELECTION,
|
||||
)
|
||||
: undefined,
|
||||
[draftThread, fallbackDraftProject?.defaultModelSelection, threadId],
|
||||
@@ -1856,7 +1877,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
const providerStatuses = serverConfig?.providers ?? EMPTY_PROVIDERS;
|
||||
const unlockedSelectedProvider = resolveSelectableProvider(
|
||||
providerStatuses,
|
||||
selectedProviderByThreadId ?? threadProvider ?? ProviderDriverKind.make("codex"),
|
||||
selectedProviderByThreadId ?? threadProvider,
|
||||
);
|
||||
const selectedProvider: ProviderDriverKind = lockedProvider ?? unlockedSelectedProvider;
|
||||
const phase = derivePhase(activeThread?.session ?? null);
|
||||
@@ -3669,10 +3690,16 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThread?.id) return;
|
||||
if (activeThread.messages.length === 0) {
|
||||
if (activeThread.messages.length === 0 && activeThread.queuedMessages.length === 0) {
|
||||
return;
|
||||
}
|
||||
const serverIds = new Set(activeThread.messages.map((message) => message.id));
|
||||
// A queued message is server-acknowledged too — it renders as a chip
|
||||
// above the composer, so its optimistic timeline copy must go.
|
||||
const persistedMessageIds = new Set(activeThread.messages.map((message) => message.id));
|
||||
const serverIds = new Set([
|
||||
...persistedMessageIds,
|
||||
...activeThread.queuedMessages.map((message) => message.messageId),
|
||||
]);
|
||||
const removedMessages = optimisticUserMessages.filter((message) => serverIds.has(message.id));
|
||||
if (removedMessages.length === 0) {
|
||||
return;
|
||||
@@ -3684,7 +3711,10 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}, 0);
|
||||
for (const removedMessage of removedMessages) {
|
||||
const previewUrls = collectUserMessageBlobPreviewUrls(removedMessage);
|
||||
if (previewUrls.length > 0) {
|
||||
// Handoff keeps blob previews alive only for messages entering the
|
||||
// timeline; a queued-only acknowledgment renders as a text chip, so
|
||||
// its previews would never be promoted — revoke them instead.
|
||||
if (previewUrls.length > 0 && persistedMessageIds.has(removedMessage.id)) {
|
||||
handoffAttachmentPreviews(removedMessage.id, previewUrls);
|
||||
continue;
|
||||
}
|
||||
@@ -3693,7 +3723,13 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
return () => {
|
||||
window.clearTimeout(timer);
|
||||
};
|
||||
}, [activeThread?.id, activeThread?.messages, handoffAttachmentPreviews, optimisticUserMessages]);
|
||||
}, [
|
||||
activeThread?.id,
|
||||
activeThread?.messages,
|
||||
activeThread?.queuedMessages,
|
||||
handoffAttachmentPreviews,
|
||||
optimisticUserMessages,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
setOptimisticUserMessages((existing) => {
|
||||
@@ -4038,7 +4074,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
return;
|
||||
}
|
||||
const sendCtx = composerRef.current?.getSendContext();
|
||||
if (!sendCtx) return;
|
||||
if (!sendCtx?.providerAvailable) return;
|
||||
const {
|
||||
images: composerImages,
|
||||
terminalContexts: composerTerminalContexts,
|
||||
@@ -4153,7 +4189,11 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
void dockTransition.catch(() => resolveDockStarted?.());
|
||||
await dockStarted;
|
||||
}
|
||||
beginLocalDispatch({ preparingWorktree: Boolean(baseBranchForWorktree) });
|
||||
const messageIdForSend = newMessageId();
|
||||
beginLocalDispatch({
|
||||
preparingWorktree: Boolean(baseBranchForWorktree),
|
||||
messageId: messageIdForSend,
|
||||
});
|
||||
|
||||
const composerImagesSnapshot = [...composerImages];
|
||||
const composerTerminalContextsSnapshot = [...sendableComposerTerminalContexts];
|
||||
@@ -4172,26 +4212,25 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
messageTextWithPreviewAnnotations,
|
||||
composerReviewCommentsSnapshot,
|
||||
);
|
||||
const messageIdForSend = newMessageId();
|
||||
const messageCreatedAt = new Date().toISOString();
|
||||
const outgoingMessageText = formatOutgoingPrompt({
|
||||
provider: ctxSelectedProvider,
|
||||
model: ctxSelectedModel,
|
||||
models: ctxSelectedProviderModels,
|
||||
effort: ctxSelectedPromptEffort,
|
||||
text: messageTextForSend || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
|
||||
text: messageTextForSend || IMAGE_ONLY_BOOTSTRAP_PROMPT,
|
||||
});
|
||||
const turnAttachmentsPromise = Promise.all(
|
||||
composerImagesSnapshot.map(async (image) => ({
|
||||
type: image.type,
|
||||
type: "image" as const,
|
||||
name: image.name,
|
||||
mimeType: image.mimeType,
|
||||
sizeBytes: image.sizeBytes,
|
||||
dataUrl: await readFileAsDataUrl(image.file, image.mimeType),
|
||||
dataUrl: await readFileAsDataUrl(image.file),
|
||||
})),
|
||||
);
|
||||
const optimisticAttachments = composerImagesSnapshot.map((image) => ({
|
||||
type: image.type,
|
||||
type: "image" as const,
|
||||
id: image.id,
|
||||
name: image.name,
|
||||
mimeType: image.mimeType,
|
||||
@@ -4253,7 +4292,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
let titleSeed = trimmed;
|
||||
if (!titleSeed) {
|
||||
if (firstComposerImageName) {
|
||||
titleSeed = `${composerImagesSnapshot[0]?.type === "file" ? "File" : "Image"}: ${firstComposerImageName}`;
|
||||
titleSeed = `Image: ${firstComposerImageName}`;
|
||||
} else if (composerTerminalContextsSnapshot.length > 0) {
|
||||
titleSeed = formatTerminalContextLabel(composerTerminalContextsSnapshot[0]!);
|
||||
} else if (composerElementContextsSnapshot.length > 0) {
|
||||
@@ -4334,7 +4373,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
: {}),
|
||||
}
|
||||
: undefined;
|
||||
beginLocalDispatch({ preparingWorktree: false });
|
||||
beginLocalDispatch({ preparingWorktree: false, messageId: messageIdForSend });
|
||||
const startResult = await startThreadTurn({
|
||||
environmentId,
|
||||
input: {
|
||||
@@ -4428,6 +4467,36 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}
|
||||
};
|
||||
|
||||
const onSteerQueuedMessage = async (messageId: MessageId) => {
|
||||
if (!activeThread) return;
|
||||
const result = await steerQueuedThreadMessage({
|
||||
environmentId,
|
||||
input: { threadId: activeThread.id, messageId },
|
||||
});
|
||||
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
setThreadError(
|
||||
activeThread.id,
|
||||
error instanceof Error ? error.message : "Failed to steer the queued message.",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const onRemoveQueuedMessage = async (messageId: MessageId) => {
|
||||
if (!activeThread) return;
|
||||
const result = await removeQueuedThreadMessage({
|
||||
environmentId,
|
||||
input: { threadId: activeThread.id, messageId },
|
||||
});
|
||||
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
setThreadError(
|
||||
activeThread.id,
|
||||
error instanceof Error ? error.message : "Failed to remove the queued message.",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const onRespondToApproval = useCallback(
|
||||
async (requestId: ApprovalRequestId, decision: ProviderApprovalDecision) => {
|
||||
if (!activeThreadId) return;
|
||||
@@ -4614,7 +4683,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}
|
||||
|
||||
const sendCtx = composerRef.current?.getSendContext();
|
||||
if (!sendCtx) {
|
||||
if (!sendCtx?.providerAvailable) {
|
||||
return;
|
||||
}
|
||||
const {
|
||||
@@ -4637,7 +4706,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
});
|
||||
|
||||
sendInFlightRef.current = true;
|
||||
beginLocalDispatch({ preparingWorktree: false });
|
||||
beginLocalDispatch({ preparingWorktree: false, messageId: messageIdForSend });
|
||||
setThreadError(threadIdForSend, null);
|
||||
|
||||
// Position this sent row once LegendList has measured the anchored tail.
|
||||
@@ -4773,7 +4842,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}
|
||||
|
||||
const sendCtx = composerRef.current?.getSendContext();
|
||||
if (!sendCtx) {
|
||||
if (!sendCtx?.providerAvailable) {
|
||||
return;
|
||||
}
|
||||
const {
|
||||
@@ -5220,6 +5289,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
{...(routeKind === "draft" && draftId ? { draftId } : {})}
|
||||
activeThreadTitle={activeThread.title}
|
||||
activeProjectName={activeProject?.title}
|
||||
activeProjectCwd={activeProject?.workspaceRoot ?? null}
|
||||
openInCwd={gitCwd}
|
||||
activeProjectScripts={activeProject?.scripts}
|
||||
preferredScriptId={
|
||||
@@ -5350,7 +5420,17 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
<ComposerBannerStack className="relative z-0" items={composerBannerItems} />
|
||||
</div>
|
||||
) : (
|
||||
<ComposerBannerStack className="relative z-0" items={composerBannerItems} />
|
||||
<>
|
||||
{isServerThread && activeThread ? (
|
||||
<QueuedMessageChips
|
||||
queuedMessages={activeThread.queuedMessages}
|
||||
disabled={Boolean(activeEnvironmentUnavailableState)}
|
||||
onSteer={(messageId) => void onSteerQueuedMessage(messageId)}
|
||||
onRemove={(messageId) => void onRemoveQueuedMessage(messageId)}
|
||||
/>
|
||||
) : null}
|
||||
<ComposerBannerStack className="relative z-0" items={composerBannerItems} />
|
||||
</>
|
||||
)}
|
||||
<div
|
||||
className="relative"
|
||||
|
||||
@@ -21,9 +21,13 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
interactionMode: "default",
|
||||
session: null,
|
||||
messages: [],
|
||||
queuedMessages: [],
|
||||
pendingTurnStart: null,
|
||||
proposedPlans: [],
|
||||
createdAt: "2026-03-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
updatedAt: "2026-03-01T00:00:00.000Z",
|
||||
latestTurn: null,
|
||||
|
||||
@@ -7,12 +7,10 @@ import {
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import {
|
||||
DEFAULT_MODEL,
|
||||
type DesktopWslState,
|
||||
type EnvironmentId,
|
||||
type FilesystemBrowseResult,
|
||||
type ProjectId,
|
||||
ProviderInstanceId,
|
||||
type SourceControlDiscoveryResult,
|
||||
type SourceControlProviderKind,
|
||||
type SourceControlRepositoryInfo,
|
||||
@@ -45,7 +43,7 @@ import {
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { OpenAddProjectCommandPaletteProvider } from "../commandPaletteContext";
|
||||
|
||||
import { isDesktopLocalConnectionTarget } from "../connection/desktopLocal";
|
||||
import { useDesktopLocalBootstraps } from "../connection/useDesktopLocalBootstraps";
|
||||
import { useHandleNewThread } from "../hooks/useHandleNewThread";
|
||||
@@ -79,6 +77,7 @@ import {
|
||||
isUnsupportedWindowsProjectPath,
|
||||
resolveProjectPathForDispatch,
|
||||
} from "../lib/projectPaths";
|
||||
import { onOpenCommandPalette } from "../commandPaletteBus";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import { getLatestThreadForProject } from "../lib/threadSort";
|
||||
import { cn, isMacPlatform, isWindowsPlatform, newProjectId } from "../lib/utils";
|
||||
@@ -111,7 +110,8 @@ import { CommandPaletteResults } from "./CommandPaletteResults";
|
||||
import { AzureDevOpsIcon, BitbucketIcon, GitHubIcon, GitLabIcon } from "./Icons";
|
||||
import { ProjectFavicon } from "./ProjectFavicon";
|
||||
import { ThreadRowLeadingStatus, ThreadRowTrailingStatus } from "./ThreadStatusIndicators";
|
||||
import { primaryServerKeybindingsAtom } from "../state/server";
|
||||
import { primaryServerKeybindingsAtom, primaryServerProvidersAtom } from "../state/server";
|
||||
import { resolveDefaultProviderModelSelection } from "../providerInstances";
|
||||
import { resolveShortcutCommand } from "../keybindings";
|
||||
import {
|
||||
Command,
|
||||
@@ -335,7 +335,7 @@ function errorMessage(error: unknown): string {
|
||||
}
|
||||
|
||||
interface CommandPaletteOpenIntent {
|
||||
readonly kind: "add-project";
|
||||
readonly kind: "add-project" | "new-thread-in";
|
||||
}
|
||||
|
||||
interface CommandPaletteUiState {
|
||||
@@ -347,6 +347,7 @@ type CommandPaletteUiAction =
|
||||
| { readonly _tag: "SetOpen"; readonly open: boolean }
|
||||
| { readonly _tag: "Toggle" }
|
||||
| { readonly _tag: "OpenAddProject" }
|
||||
| { readonly _tag: "OpenNewThreadIn" }
|
||||
| { readonly _tag: "ClearOpenIntent" };
|
||||
|
||||
function reduceCommandPaletteUiState(
|
||||
@@ -363,6 +364,8 @@ function reduceCommandPaletteUiState(
|
||||
return { open: !state.open, openIntent: null };
|
||||
case "OpenAddProject":
|
||||
return { open: true, openIntent: { kind: "add-project" } };
|
||||
case "OpenNewThreadIn":
|
||||
return { open: true, openIntent: { kind: "new-thread-in" } };
|
||||
case "ClearOpenIntent":
|
||||
return state.openIntent ? { ...state, openIntent: null } : state;
|
||||
}
|
||||
@@ -376,6 +379,7 @@ export function CommandPalette({ children }: { children: ReactNode }) {
|
||||
const setOpen = useCallback((open: boolean) => dispatch({ _tag: "SetOpen", open }), []);
|
||||
const toggleOpen = useCallback(() => dispatch({ _tag: "Toggle" }), []);
|
||||
const openAddProject = useCallback(() => dispatch({ _tag: "OpenAddProject" }), []);
|
||||
const openNewThreadIn = useCallback(() => dispatch({ _tag: "OpenNewThreadIn" }), []);
|
||||
const clearOpenIntent = useCallback(() => dispatch({ _tag: "ClearOpenIntent" }), []);
|
||||
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
|
||||
const composerHandleRef = useRef<ChatComposerHandle | null>(null);
|
||||
@@ -410,20 +414,32 @@ export function CommandPalette({ children }: { children: ReactNode }) {
|
||||
return () => window.removeEventListener("keydown", onKeyDown);
|
||||
}, [keybindings, terminalOpen, toggleOpen]);
|
||||
|
||||
useEffect(
|
||||
() =>
|
||||
onOpenCommandPalette((detail) => {
|
||||
if (detail.open === "new-thread-in") {
|
||||
openNewThreadIn();
|
||||
} else if (detail.open === "add-project") {
|
||||
openAddProject();
|
||||
} else {
|
||||
setOpen(true);
|
||||
}
|
||||
}),
|
||||
[openAddProject, openNewThreadIn, setOpen],
|
||||
);
|
||||
|
||||
return (
|
||||
<OpenAddProjectCommandPaletteProvider openAddProject={openAddProject}>
|
||||
<ComposerHandleContext value={composerHandleRef}>
|
||||
<CommandDialog open={state.open} onOpenChange={setOpen}>
|
||||
{children}
|
||||
<CommandPaletteDialog
|
||||
open={state.open}
|
||||
openIntent={state.openIntent}
|
||||
setOpen={setOpen}
|
||||
clearOpenIntent={clearOpenIntent}
|
||||
/>
|
||||
</CommandDialog>
|
||||
</ComposerHandleContext>
|
||||
</OpenAddProjectCommandPaletteProvider>
|
||||
<ComposerHandleContext value={composerHandleRef}>
|
||||
<CommandDialog open={state.open} onOpenChange={setOpen}>
|
||||
{children}
|
||||
<CommandPaletteDialog
|
||||
open={state.open}
|
||||
openIntent={state.openIntent}
|
||||
setOpen={setOpen}
|
||||
clearOpenIntent={clearOpenIntent}
|
||||
/>
|
||||
</CommandDialog>
|
||||
</ComposerHandleContext>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -476,6 +492,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
const projects = useProjects();
|
||||
const threads = useThreadShells();
|
||||
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
|
||||
const providers = useAtomValue(primaryServerProvidersAtom);
|
||||
const [viewStack, setViewStack] = useState<CommandPaletteView[]>([]);
|
||||
const currentView = viewStack.at(-1) ?? null;
|
||||
const [browseGeneration, setBrowseGeneration] = useState(0);
|
||||
@@ -960,6 +977,36 @@ function OpenCommandPaletteDialog(props: {
|
||||
openAddProjectFlow();
|
||||
}, [clearOpenIntent, openAddProjectFlow, openIntent]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (openIntent?.kind !== "new-thread-in" || projectThreadItems.length === 0) {
|
||||
return;
|
||||
}
|
||||
clearOpenIntent();
|
||||
setAddProjectCloneFlow(null);
|
||||
setViewStack([]);
|
||||
setQuery("");
|
||||
const currentPrefix =
|
||||
currentProjectEnvironmentId && currentProjectId
|
||||
? `new-thread-in:${currentProjectEnvironmentId}:${currentProjectId}`
|
||||
: null;
|
||||
const prioritized = currentPrefix
|
||||
? [
|
||||
...projectThreadItems.filter((item) => item.value === currentPrefix),
|
||||
...projectThreadItems.filter((item) => item.value !== currentPrefix),
|
||||
]
|
||||
: projectThreadItems;
|
||||
pushPaletteView({
|
||||
addonIcon: <SquarePenIcon className={ADDON_ICON_CLASS} />,
|
||||
groups: [{ value: "projects", label: "Projects", items: prioritized }],
|
||||
});
|
||||
}, [
|
||||
clearOpenIntent,
|
||||
currentProjectEnvironmentId,
|
||||
currentProjectId,
|
||||
openIntent,
|
||||
projectThreadItems,
|
||||
]);
|
||||
|
||||
const actionItems: Array<CommandPaletteActionItem | CommandPaletteSubmenuItem> = [];
|
||||
|
||||
if (projects.length > 0) {
|
||||
@@ -1149,6 +1196,10 @@ function OpenCommandPaletteDialog(props: {
|
||||
}
|
||||
|
||||
const projectId = newProjectId();
|
||||
const targetEnvironmentProviders =
|
||||
environments.find((environment) => environment.environmentId === input.environmentId)
|
||||
?.serverConfig?.providers ??
|
||||
(input.environmentId === primaryEnvironmentId ? providers : []);
|
||||
const createResult = await createProject({
|
||||
environmentId: input.environmentId,
|
||||
input: {
|
||||
@@ -1156,10 +1207,10 @@ function OpenCommandPaletteDialog(props: {
|
||||
title: inferProjectTitleFromPath(cwd),
|
||||
workspaceRoot: cwd,
|
||||
createWorkspaceRootIfMissing: true,
|
||||
defaultModelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: DEFAULT_MODEL,
|
||||
},
|
||||
defaultModelSelection: resolveDefaultProviderModelSelection(
|
||||
targetEnvironmentProviders,
|
||||
null,
|
||||
),
|
||||
},
|
||||
});
|
||||
if (createResult._tag === "Failure") {
|
||||
@@ -1195,8 +1246,11 @@ function OpenCommandPaletteDialog(props: {
|
||||
[
|
||||
handleNewThread,
|
||||
createProject,
|
||||
environments,
|
||||
navigate,
|
||||
primaryEnvironmentId,
|
||||
projects,
|
||||
providers,
|
||||
setOpen,
|
||||
clientSettings.sidebarThreadSortOrder,
|
||||
threads,
|
||||
|
||||
@@ -70,4 +70,83 @@ describe("registerComposerInlineTokenPaste", () => {
|
||||
"<mention:.changeset/improve-deploy-error-logging.md> ",
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"yarn expo install @expo/ui",
|
||||
"npm install @jane/foo.js",
|
||||
"import '@scope/pkg/sub/path'",
|
||||
])("leaves scoped package command %s to the plain-text paste fallback", (command) => {
|
||||
vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
|
||||
const editor = createEditor();
|
||||
const plainTextFallback = vi.fn((event: ClipboardEvent) => {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection)) return false;
|
||||
selection.insertText(event.clipboardData?.getData("text/plain") ?? "");
|
||||
return true;
|
||||
});
|
||||
|
||||
editor.update(
|
||||
() => {
|
||||
const paragraph = $createParagraphNode();
|
||||
$getRoot().append(paragraph);
|
||||
paragraph.selectEnd();
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
registerComposerInlineTokenPaste(editor, {
|
||||
createMentionNode: (path) => $createTextNode(`<mention:${path}>`),
|
||||
getExpandedAbsoluteOffsetForPoint: () => 0,
|
||||
});
|
||||
editor.registerCommand(PASTE_COMMAND, plainTextFallback, COMMAND_PRIORITY_EDITOR);
|
||||
|
||||
const event = new TestClipboardEvent(command);
|
||||
let handled = false;
|
||||
editor.update(
|
||||
() => {
|
||||
handled = editor.dispatchCommand(PASTE_COMMAND, event as ClipboardEvent);
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
|
||||
expect(handled).toBe(true);
|
||||
expect(plainTextFallback).toHaveBeenCalledOnce();
|
||||
expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(command);
|
||||
});
|
||||
|
||||
it("pastes a canonical scoped folder link as a mention", () => {
|
||||
vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
|
||||
const editor = createEditor();
|
||||
const mention = "[sub](@scope/pkg/sub)";
|
||||
const plainTextFallback = vi.fn(() => true);
|
||||
|
||||
editor.update(
|
||||
() => {
|
||||
const paragraph = $createParagraphNode();
|
||||
$getRoot().append(paragraph);
|
||||
paragraph.selectEnd();
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
registerComposerInlineTokenPaste(editor, {
|
||||
createMentionNode: (path) => $createTextNode(`<mention:${path}>`),
|
||||
getExpandedAbsoluteOffsetForPoint: () => 0,
|
||||
});
|
||||
editor.registerCommand(PASTE_COMMAND, plainTextFallback, COMMAND_PRIORITY_EDITOR);
|
||||
|
||||
const event = new TestClipboardEvent(mention);
|
||||
let handled = false;
|
||||
editor.update(
|
||||
() => {
|
||||
handled = editor.dispatchCommand(PASTE_COMMAND, event as ClipboardEvent);
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
|
||||
expect(handled).toBe(true);
|
||||
expect(plainTextFallback).not.toHaveBeenCalled();
|
||||
expect(event.defaultPrevented).toBe(true);
|
||||
expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(
|
||||
"<mention:@scope/pkg/sub> ",
|
||||
);
|
||||
});
|
||||
});
|
||||
Loaded 100 of 173 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user