Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8f19cb6a20 | ||
|
|
061ad09329 | ||
|
|
3bb0b9c484 |
No files matched your search
@@ -20,7 +20,6 @@ const clientSettings: ClientSettings = {
|
||||
diffIgnoreWhitespace: true,
|
||||
favorites: [],
|
||||
providerModelPreferences: {},
|
||||
sidebarAutoSettleAfterDays: 3,
|
||||
sidebarProjectGroupingMode: "repository_path",
|
||||
sidebarProjectGroupingOverrides: {
|
||||
"environment-1:/tmp/project-a": "separate",
|
||||
@@ -28,7 +27,6 @@ const clientSettings: ClientSettings = {
|
||||
sidebarProjectSortOrder: "manual",
|
||||
sidebarThreadSortOrder: "created_at",
|
||||
sidebarThreadPreviewCount: 6,
|
||||
sidebarV2Enabled: false,
|
||||
timestampFormat: "24-hour",
|
||||
wordWrap: true,
|
||||
};
|
||||
|
||||
@@ -41,8 +41,6 @@ function makeThread(
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -28,8 +28,7 @@ export function HomeRouteScreen() {
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
const navigation = useNavigation();
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const { archiveThread, confirmDeleteThread, settleThread, unsettleThread } =
|
||||
useThreadListActions();
|
||||
const { archiveThread, confirmDeleteThread } = useThreadListActions();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
|
||||
const environments = useMemo(
|
||||
@@ -112,8 +111,6 @@ export function HomeRouteScreen() {
|
||||
}
|
||||
onArchiveThread={archiveThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
onSettleThread={settleThread}
|
||||
onUnsettleThread={unsettleThread}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onOpenEnvironments={() =>
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
|
||||
@@ -123,8 +120,6 @@ 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,22 +14,18 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import { useAtomSet, useAtomValue } from "@effect/atom-react";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { ActivityIndicator, FlatList, Platform, Pressable, ScrollView, View } from "react-native";
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import { ActivityIndicator, Platform, 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,
|
||||
@@ -37,8 +33,6 @@ 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,
|
||||
@@ -80,9 +74,6 @@ 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;
|
||||
@@ -91,10 +82,6 @@ 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
|
||||
@@ -169,80 +156,6 @@ 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) {
|
||||
@@ -250,9 +163,6 @@ 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);
|
||||
@@ -357,193 +267,6 @@ 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],
|
||||
@@ -637,10 +360,6 @@ 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;
|
||||
@@ -717,44 +436,6 @@ 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}".`} />
|
||||
@@ -767,69 +448,6 @@ 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,8 +47,6 @@ 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,8 +41,6 @@ function makeThread(
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -167,13 +167,6 @@ 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;
|
||||
@@ -246,11 +239,7 @@ export function ThreadSwipeable(props: {
|
||||
if (fullSwipeArmedRef.current) {
|
||||
fullSwipeArmedRef.current = false;
|
||||
methods.close();
|
||||
if (props.fullSwipeAction === "primary") {
|
||||
props.primaryAction.onPress();
|
||||
} else {
|
||||
props.onDelete();
|
||||
}
|
||||
props.onDelete();
|
||||
}
|
||||
}}
|
||||
overshootFriction={1}
|
||||
@@ -258,7 +247,6 @@ export function ThreadSwipeable(props: {
|
||||
renderRightActions={(_progress, translation, methods) => (
|
||||
<ThreadSwipeActions
|
||||
backgroundColor={props.backgroundColor}
|
||||
fullSwipeAction={props.fullSwipeAction ?? "delete"}
|
||||
fullSwipeThreshold={fullSwipeThreshold}
|
||||
onDelete={props.onDelete}
|
||||
onFullSwipeArmedChange={handleFullSwipeArmedChange}
|
||||
@@ -434,7 +422,6 @@ 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;
|
||||
@@ -443,7 +430,6 @@ export function ThreadSwipeActions(props: {
|
||||
readonly threadTitle: string;
|
||||
readonly translation: SharedValue<number>;
|
||||
}) {
|
||||
const fullSwipeIsPrimary = props.fullSwipeAction === "primary";
|
||||
useAnimatedReaction(
|
||||
() => -props.translation.value >= props.fullSwipeThreshold,
|
||||
(armed, previous) => {
|
||||
@@ -471,7 +457,7 @@ export function ThreadSwipeActions(props: {
|
||||
icon={props.primaryAction.icon}
|
||||
label={props.primaryAction.label}
|
||||
onPress={props.primaryAction.onPress}
|
||||
stretchesOnFullSwipe={fullSwipeIsPrimary}
|
||||
stretchesOnFullSwipe={false}
|
||||
translation={props.translation}
|
||||
/>
|
||||
<SwipeActionButton
|
||||
@@ -485,7 +471,7 @@ export function ThreadSwipeActions(props: {
|
||||
props.swipeableMethods.close();
|
||||
props.onDelete();
|
||||
}}
|
||||
stretchesOnFullSwipe={!fullSwipeIsPrimary}
|
||||
stretchesOnFullSwipe
|
||||
translation={props.translation}
|
||||
/>
|
||||
</View>
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
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";
|
||||
@@ -7,37 +6,19 @@ 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";
|
||||
|
||||
/** 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",
|
||||
};
|
||||
type ThreadListAction = "archive" | "unarchive" | "delete";
|
||||
|
||||
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;
|
||||
}
|
||||
return `The thread could not be ${ACTION_VERBS[action]}.`;
|
||||
const verb =
|
||||
action === "archive" ? "archived" : action === "unarchive" ? "unarchived" : "deleted";
|
||||
return `The thread could not be ${verb}.`;
|
||||
}
|
||||
|
||||
function selectionHaptic(): void {
|
||||
@@ -47,115 +28,54 @@ 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 false;
|
||||
return;
|
||||
}
|
||||
|
||||
inFlightThreadKeys.current.add(key);
|
||||
selectionHaptic();
|
||||
try {
|
||||
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 },
|
||||
});
|
||||
const mutation =
|
||||
action === "archive"
|
||||
? archiveMutation
|
||||
: action === "unarchive"
|
||||
? unarchiveMutation
|
||||
: deleteMutation;
|
||||
const result = await mutation({
|
||||
environmentId: thread.environmentId,
|
||||
input: { threadId: thread.id },
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
Alert.alert(actionFailureTitle(action), actionFailureMessage(action, result.cause));
|
||||
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);
|
||||
return;
|
||||
}
|
||||
onCompleted?.(action, thread);
|
||||
return true;
|
||||
} finally {
|
||||
inFlightThreadKeys.current.delete(key);
|
||||
}
|
||||
},
|
||||
[
|
||||
archiveMutation,
|
||||
deleteMutation,
|
||||
onCompleted,
|
||||
settleMutation,
|
||||
unarchiveMutation,
|
||||
unsettleMutation,
|
||||
],
|
||||
[archiveMutation, deleteMutation, onCompleted, unarchiveMutation],
|
||||
);
|
||||
|
||||
return executeAction;
|
||||
}
|
||||
|
||||
function useConfirmDeleteThread(
|
||||
executeAction: (action: ThreadListAction, thread: EnvironmentThreadShell) => Promise<boolean>,
|
||||
executeAction: (action: ThreadListAction, thread: EnvironmentThreadShell) => Promise<void>,
|
||||
) {
|
||||
return useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
@@ -191,8 +111,6 @@ 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();
|
||||
|
||||
@@ -202,18 +120,10 @@ 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, settleThread, unsettleThread };
|
||||
return { archiveThread, confirmDeleteThread };
|
||||
}
|
||||
|
||||
export function useArchivedThreadListActions(
|
||||
|
||||
@@ -123,8 +123,6 @@ function LocalSettingsRouteScreen() {
|
||||
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
|
||||
</SettingsSection>
|
||||
|
||||
<BetaSettingsSection />
|
||||
|
||||
<ArchivedThreadsSettingsSection />
|
||||
|
||||
<AppSettingsSection />
|
||||
@@ -508,8 +506,6 @@ function ConfiguredSettingsRouteScreen() {
|
||||
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
|
||||
</SettingsSection>
|
||||
|
||||
<BetaSettingsSection />
|
||||
|
||||
<ArchivedThreadsSettingsSection />
|
||||
|
||||
<AppSettingsSection />
|
||||
@@ -518,35 +514,6 @@ 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");
|
||||
|
||||
|
||||
@@ -58,8 +58,6 @@ 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}`;
|
||||
}
|
||||
@@ -350,14 +348,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? "local";
|
||||
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
|
||||
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
|
||||
// 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 startFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin ?? false;
|
||||
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
|
||||
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
|
||||
|
||||
@@ -377,7 +368,6 @@ 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
|
||||
@@ -485,14 +475,13 @@ 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(
|
||||
allBranchRefs,
|
||||
branchState.data?.refs ?? [],
|
||||
Arr.filter((branch) => !branch.isRemote),
|
||||
),
|
||||
[allBranchRefs],
|
||||
[branchState.data?.refs],
|
||||
);
|
||||
|
||||
const filteredBranches = useMemo(() => {
|
||||
@@ -554,11 +543,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
mode,
|
||||
branch: selectedBranchName,
|
||||
worktreePath: selectedWorktreePath,
|
||||
...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
|
||||
startFromOrigin,
|
||||
},
|
||||
});
|
||||
},
|
||||
[draftStartFromOrigin, selectedBranchName, selectedProjectDraftKey, selectedWorktreePath],
|
||||
[selectedBranchName, selectedProjectDraftKey, selectedWorktreePath, startFromOrigin],
|
||||
);
|
||||
|
||||
const selectBranch = useCallback(
|
||||
@@ -571,11 +560,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
mode: workspaceMode,
|
||||
branch: branch.name,
|
||||
worktreePath: normalizeSelectedWorktreePath(selectedProject, branch),
|
||||
...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
|
||||
startFromOrigin,
|
||||
},
|
||||
});
|
||||
},
|
||||
[draftStartFromOrigin, selectedProject, selectedProjectDraftKey, workspaceMode],
|
||||
[selectedProject, selectedProjectDraftKey, startFromOrigin, workspaceMode],
|
||||
);
|
||||
|
||||
const setStartFromOrigin = useCallback(
|
||||
@@ -608,16 +597,14 @@ 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);
|
||||
}
|
||||
}, [allBranchRefs, availableBranches, selectBranch, selectedBranchName, workspaceMode]);
|
||||
}, [availableBranches, selectBranch, selectedBranchName, workspaceMode]);
|
||||
|
||||
const setRuntimeMode = useCallback(
|
||||
(value: RuntimeMode) => {
|
||||
@@ -709,12 +696,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
workspaceMode: mode,
|
||||
branch: workspaceSelection?.branch ?? null,
|
||||
worktreePath: mode === "worktree" ? null : (workspaceSelection?.worktreePath ?? null),
|
||||
// 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 }
|
||||
: {}),
|
||||
...(workspaceSelection?.startFromOrigin ? { startFromOrigin: true } : {}),
|
||||
},
|
||||
createdAt: metadata.createdAt,
|
||||
};
|
||||
@@ -725,7 +707,6 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
selectedModel,
|
||||
selectedProject,
|
||||
selectedProjectDraftKey,
|
||||
startFromOrigin,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -1,329 +0,0 @@
|
||||
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>
|
||||
</>
|
||||
);
|
||||
});
|
||||
@@ -1,220 +0,0 @@
|
||||
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",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,167 +0,0 @@
|
||||
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,7 +15,6 @@ export type ModelOption = {
|
||||
readonly providerKey: string;
|
||||
readonly providerLabel: string;
|
||||
readonly providerDriver: string;
|
||||
readonly isDefault: boolean;
|
||||
readonly capabilities: ModelCapabilities | null;
|
||||
readonly selection: ModelSelection;
|
||||
};
|
||||
@@ -79,7 +78,6 @@ export function buildModelOptions(
|
||||
providerKey: provider.instanceId,
|
||||
providerLabel,
|
||||
providerDriver: provider.driver,
|
||||
isDefault: model.isDefault === true,
|
||||
capabilities: model.capabilities,
|
||||
selection: normalizeSelectionOptions(
|
||||
{
|
||||
@@ -109,7 +107,6 @@ export function buildModelOptions(
|
||||
providerKey: fallbackModelSelection.instanceId,
|
||||
providerLabel,
|
||||
providerDriver: fallbackModelSelection.instanceId,
|
||||
isDefault: false,
|
||||
capabilities: null,
|
||||
selection: fallbackModelSelection,
|
||||
});
|
||||
|
||||
@@ -38,8 +38,6 @@ function makeThread(
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -50,8 +50,6 @@ function makeThread(
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -22,12 +22,6 @@ 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>()(
|
||||
@@ -77,7 +71,6 @@ function sanitizePreferences(parsed: Preferences): Preferences {
|
||||
codeWordBreak?: boolean;
|
||||
connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
|
||||
collapsedProjectGroups?: readonly string[];
|
||||
threadListV2Enabled?: boolean;
|
||||
} = {};
|
||||
|
||||
if (typeof parsed.liveActivitiesEnabled === "boolean") {
|
||||
@@ -104,9 +97,6 @@ function sanitizePreferences(parsed: Preferences): Preferences {
|
||||
(key): key is string => typeof key === "string",
|
||||
);
|
||||
}
|
||||
if (typeof parsed.threadListV2Enabled === "boolean") {
|
||||
preferences.threadListV2Enabled = parsed.threadListV2Enabled;
|
||||
}
|
||||
return preferences;
|
||||
}
|
||||
|
||||
|
||||
@@ -58,8 +58,6 @@ 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,
|
||||
|
||||
@@ -136,7 +136,6 @@ export const make = Effect.gen(function* () {
|
||||
capabilities: {
|
||||
repositoryIdentity: true,
|
||||
connectionProbe: true,
|
||||
threadSettlement: true,
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -146,8 +146,6 @@ 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: [],
|
||||
proposedPlans: [],
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
CheckpointRef,
|
||||
CommandId,
|
||||
CorrelationId,
|
||||
@@ -172,70 +171,6 @@ 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 }]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -2463,188 +2398,6 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("only clears pending turn starts targeted by failure signals", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const threadId = ThreadId.make("thread-start-failed");
|
||||
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
|
||||
eventStore
|
||||
.append(event)
|
||||
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
|
||||
const listPendingStarts = () => sql<{ readonly messageId: string }>`
|
||||
SELECT pending_message_id AS "messageId"
|
||||
FROM projection_turns
|
||||
WHERE thread_id = ${threadId}
|
||||
AND turn_id IS NULL
|
||||
AND state = 'pending'
|
||||
`;
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.turn-start-requested",
|
||||
eventId: EventId.make("evt-start-failed-1"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: "2026-02-26T13:00:00.000Z",
|
||||
commandId: CommandId.make("cmd-start-failed-1"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-start-failed-1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
messageId: MessageId.make("message-start-old"),
|
||||
runtimeMode: "full-access",
|
||||
createdAt: "2026-02-26T13:00:00.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.turn-start-requested",
|
||||
eventId: EventId.make("evt-start-failed-2"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: "2026-02-26T13:00:00.100Z",
|
||||
commandId: CommandId.make("cmd-start-failed-2"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-start-failed-2"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
messageId: MessageId.make("message-start-new"),
|
||||
runtimeMode: "full-access",
|
||||
createdAt: "2026-02-26T13:00:00.100Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.activity-appended",
|
||||
eventId: EventId.make("evt-start-failed-3"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: "2026-02-26T13:00:00.200Z",
|
||||
commandId: CommandId.make("cmd-start-failed-3"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-start-failed-3"),
|
||||
metadata: { requestId: ApprovalRequestId.make("message-start-old") },
|
||||
payload: {
|
||||
threadId,
|
||||
activity: {
|
||||
id: EventId.make("activity-start-failed-old"),
|
||||
tone: "error",
|
||||
kind: "provider.turn.start.failed",
|
||||
summary: "Provider turn start failed",
|
||||
payload: { requestId: "message-start-old", detail: "Provider startup failed" },
|
||||
turnId: null,
|
||||
createdAt: "2026-02-26T13:00:00.200Z",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const pendingRows = yield* listPendingStarts();
|
||||
assert.deepEqual(pendingRows, [{ messageId: "message-start-new" }]);
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.activity-appended",
|
||||
eventId: EventId.make("evt-start-failed-4"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: "2026-02-26T13:00:00.300Z",
|
||||
commandId: CommandId.make("cmd-start-failed-4"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-start-failed-4"),
|
||||
metadata: { requestId: ApprovalRequestId.make("message-start-new") },
|
||||
payload: {
|
||||
threadId,
|
||||
activity: {
|
||||
id: EventId.make("activity-start-failed-new"),
|
||||
tone: "error",
|
||||
kind: "provider.turn.start.failed",
|
||||
summary: "Provider turn start failed",
|
||||
payload: { requestId: "message-start-new", detail: "Provider startup failed" },
|
||||
turnId: null,
|
||||
createdAt: "2026-02-26T13:00:00.300Z",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const clearedRows = yield* listPendingStarts();
|
||||
assert.deepEqual(clearedRows, []);
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.turn-start-requested",
|
||||
eventId: EventId.make("evt-start-failed-5"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: "2026-02-26T13:00:00.500Z",
|
||||
commandId: CommandId.make("cmd-start-failed-5"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-start-failed-5"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
messageId: MessageId.make("message-start-terminal"),
|
||||
runtimeMode: "full-access",
|
||||
createdAt: "2026-02-26T13:00:00.500Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.session-set",
|
||||
eventId: EventId.make("evt-start-failed-6"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: "2026-02-26T13:00:00.600Z",
|
||||
commandId: CommandId.make("cmd-start-failed-6"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-start-failed-6"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: "error",
|
||||
providerName: "codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: "Earlier session failed",
|
||||
updatedAt: "2026-02-26T13:00:00.400Z",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const rowsAfterStaleSession = yield* listPendingStarts();
|
||||
assert.deepEqual(rowsAfterStaleSession, [{ messageId: "message-start-terminal" }]);
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.session-set",
|
||||
eventId: EventId.make("evt-start-failed-7"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: "2026-02-26T13:00:00.700Z",
|
||||
commandId: CommandId.make("cmd-start-failed-7"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-start-failed-7"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: "stopped",
|
||||
providerName: "codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: "2026-02-26T13:00:00.700Z",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const rowsAfterCurrentSession = yield* listPendingStarts();
|
||||
assert.deepEqual(rowsAfterCurrentSession, []);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("restores pending turn-start metadata across projection pipeline restart", () =>
|
||||
|
||||
@@ -607,8 +607,6 @@ 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,
|
||||
@@ -647,38 +645,6 @@ 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,
|
||||
@@ -1056,52 +1022,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.activity-appended": {
|
||||
if (event.payload.activity.kind !== "provider.turn.start.failed") {
|
||||
return;
|
||||
}
|
||||
const requestId = event.metadata.requestId;
|
||||
if (requestId === undefined) {
|
||||
return;
|
||||
}
|
||||
const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (
|
||||
Option.isNone(pendingTurnStart) ||
|
||||
String(requestId) !== pendingTurnStart.value.messageId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
yield* projectionTurnRepository.deletePendingTurnStartByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.session-set": {
|
||||
const turnId = event.payload.session.activeTurnId;
|
||||
if (turnId === null || event.payload.session.status !== "running") {
|
||||
if (
|
||||
event.payload.session.lastError !== null ||
|
||||
event.payload.session.status === "error" ||
|
||||
event.payload.session.status === "interrupted" ||
|
||||
event.payload.session.status === "stopped"
|
||||
) {
|
||||
const pendingTurnStart =
|
||||
yield* projectionTurnRepository.getPendingTurnStartByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (
|
||||
Option.isSome(pendingTurnStart) &&
|
||||
pendingTurnStart.value.requestedAt <= event.payload.session.updatedAt
|
||||
) {
|
||||
yield* projectionTurnRepository.deletePendingTurnStartByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Leaving the "running" session status is the turn-end signal:
|
||||
// settle still-running turns so their duration reflects the whole
|
||||
// turn rather than the last assistant message.
|
||||
|
||||
@@ -217,39 +217,22 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
checkpoint_status,
|
||||
checkpoint_files_json
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
NULL,
|
||||
'thread-1',
|
||||
'plan-1',
|
||||
'message-1',
|
||||
'completed',
|
||||
'2026-02-24T00:00:08.000Z',
|
||||
'2026-02-24T00:00:08.000Z',
|
||||
'2026-02-24T00:00:08.000Z',
|
||||
1,
|
||||
'checkpoint-1',
|
||||
'ready',
|
||||
'[{"path":"README.md","kind":"modified","additions":2,"deletions":1}]'
|
||||
),
|
||||
(
|
||||
'thread-1',
|
||||
NULL,
|
||||
'message-pending',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
'pending',
|
||||
'2026-02-24T00:00:09.000Z',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
'[]'
|
||||
)
|
||||
VALUES (
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
NULL,
|
||||
'thread-1',
|
||||
'plan-1',
|
||||
'message-1',
|
||||
'completed',
|
||||
'2026-02-24T00:00:08.000Z',
|
||||
'2026-02-24T00:00:08.000Z',
|
||||
'2026-02-24T00:00:08.000Z',
|
||||
1,
|
||||
'checkpoint-1',
|
||||
'ready',
|
||||
'[{"path":"README.md","kind":"modified","additions":2,"deletions":1}]'
|
||||
)
|
||||
`;
|
||||
|
||||
let sequence = 5;
|
||||
@@ -325,8 +308,6 @@ 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: [
|
||||
{
|
||||
@@ -437,8 +418,6 @@ 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",
|
||||
@@ -449,17 +428,12 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
updatedAt: "2026-02-24T00:00:07.000Z",
|
||||
},
|
||||
latestUserMessageAt: "2026-02-24T00:00:04.000Z",
|
||||
hasPendingTurnStart: true,
|
||||
hasPendingApprovals: true,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
},
|
||||
]);
|
||||
|
||||
const threadShell = yield* snapshotQuery.getThreadShellById(ThreadId.make("thread-1"));
|
||||
assert.equal(threadShell._tag, "Some");
|
||||
assert.equal(threadShell._tag === "Some" && threadShell.value.hasPendingTurnStart, true);
|
||||
|
||||
const threadDetail = yield* snapshotQuery.getThreadDetailById(ThreadId.make("thread-1"));
|
||||
assert.equal(threadDetail._tag, "Some");
|
||||
if (threadDetail._tag === "Some") {
|
||||
@@ -588,115 +562,6 @@ 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",
|
||||
() =>
|
||||
|
||||
@@ -103,9 +103,6 @@ const ProjectionLatestTurnDbRowSchema = Schema.Struct({
|
||||
sourceProposedPlanThreadId: Schema.NullOr(ThreadId),
|
||||
sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),
|
||||
});
|
||||
const ProjectionPendingTurnStartDbRowSchema = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
});
|
||||
const ProjectionStateDbRowSchema = ProjectionState;
|
||||
const ProjectionCountsRowSchema = Schema.Struct({
|
||||
projectCount: Schema.Number,
|
||||
@@ -337,8 +334,6 @@ 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",
|
||||
@@ -367,8 +362,6 @@ 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",
|
||||
@@ -399,8 +392,6 @@ 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",
|
||||
@@ -617,23 +608,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const listActivePendingTurnStartRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProjectionPendingTurnStartDbRowSchema,
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT turns.thread_id AS "threadId"
|
||||
FROM projection_turns turns
|
||||
INNER JOIN projection_threads threads
|
||||
ON threads.thread_id = turns.thread_id
|
||||
WHERE threads.deleted_at IS NULL
|
||||
AND threads.archived_at IS NULL
|
||||
AND turns.turn_id IS NULL
|
||||
AND turns.state = 'pending'
|
||||
ORDER BY turns.thread_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const listArchivedLatestTurnRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProjectionLatestTurnDbRowSchema,
|
||||
@@ -780,8 +754,6 @@ 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",
|
||||
@@ -906,20 +878,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const getPendingTurnStartRowByThread = SqlSchema.findOneOption({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionPendingTurnStartDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT thread_id AS "threadId"
|
||||
FROM projection_turns
|
||||
WHERE thread_id = ${threadId}
|
||||
AND turn_id IS NULL
|
||||
AND state = 'pending'
|
||||
LIMIT 1
|
||||
`,
|
||||
});
|
||||
|
||||
const listCheckpointRowsByThread = SqlSchema.findAll({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionCheckpointDbRowSchema,
|
||||
@@ -1228,8 +1186,6 @@ 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) ?? [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
@@ -1428,8 +1384,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
deletedAt: row.deletedAt,
|
||||
messages: [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
@@ -1483,24 +1437,14 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.all({
|
||||
latestTurnRows: listActiveLatestTurnRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:query",
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:decodeRows",
|
||||
),
|
||||
listActiveLatestTurnRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:query",
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:decodeRows",
|
||||
),
|
||||
),
|
||||
pendingTurnStartRows: listActivePendingTurnStartRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listPendingTurnStarts:query",
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listPendingTurnStarts:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
),
|
||||
listProjectionStateRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
@@ -1512,9 +1456,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
]),
|
||||
)
|
||||
.pipe(
|
||||
Effect.flatMap(([projectRows, threadRows, sessionRows, turnRows, stateRows]) =>
|
||||
Effect.flatMap(([projectRows, threadRows, sessionRows, latestTurnRows, stateRows]) =>
|
||||
Effect.gen(function* () {
|
||||
const { latestTurnRows, pendingTurnStartRows } = turnRows;
|
||||
let updatedAt: string | null = null;
|
||||
for (const row of projectRows) {
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
@@ -1545,9 +1488,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
const sessionByThread = new Map(
|
||||
sessionRows.map((row) => [row.threadId, mapSessionRow(row)] as const),
|
||||
);
|
||||
const pendingTurnStartThreadIds = new Set(
|
||||
pendingTurnStartRows.map((row) => row.threadId),
|
||||
);
|
||||
|
||||
const snapshot = {
|
||||
snapshotSequence: computeSnapshotSequence(stateRows),
|
||||
@@ -1573,11 +1513,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,
|
||||
hasPendingTurnStart: pendingTurnStartThreadIds.has(row.threadId),
|
||||
hasPendingApprovals: row.pendingApprovalCount > 0,
|
||||
hasPendingUserInput: row.pendingUserInputCount > 0,
|
||||
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
|
||||
@@ -1710,8 +1647,6 @@ 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,
|
||||
@@ -1907,81 +1842,58 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const getThreadShellById: ProjectionSnapshotQueryShape["getThreadShellById"] = (threadId) =>
|
||||
sql
|
||||
.withTransaction(
|
||||
Effect.gen(function* () {
|
||||
const [threadRow, latestTurnRow, sessionRow, pendingTurnStartRow] = yield* Effect.all([
|
||||
getActiveThreadRowById({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getThread:query",
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getThread:decodeRow",
|
||||
),
|
||||
),
|
||||
Effect.gen(function* () {
|
||||
const [threadRow, latestTurnRow, sessionRow] = yield* Effect.all([
|
||||
getActiveThreadRowById({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getThread:query",
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getThread:decodeRow",
|
||||
),
|
||||
getLatestTurnRowByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getLatestTurn:query",
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getLatestTurn:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
getThreadSessionRowByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getSession:query",
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getSession:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
getPendingTurnStartRowByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getPendingTurnStart:query",
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getPendingTurnStart:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
]);
|
||||
|
||||
if (Option.isNone(threadRow)) {
|
||||
return Option.none<OrchestrationThreadShell>();
|
||||
}
|
||||
|
||||
return Option.some({
|
||||
id: threadRow.value.threadId,
|
||||
projectId: threadRow.value.projectId,
|
||||
title: threadRow.value.title,
|
||||
modelSelection: threadRow.value.modelSelection,
|
||||
runtimeMode: threadRow.value.runtimeMode,
|
||||
interactionMode: threadRow.value.interactionMode,
|
||||
branch: threadRow.value.branch,
|
||||
worktreePath: threadRow.value.worktreePath,
|
||||
latestTurn: Option.isSome(latestTurnRow) ? mapLatestTurn(latestTurnRow.value) : null,
|
||||
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,
|
||||
hasPendingTurnStart: Option.isSome(pendingTurnStartRow),
|
||||
hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,
|
||||
hasPendingUserInput: threadRow.value.pendingUserInputCount > 0,
|
||||
hasActionableProposedPlan: threadRow.value.hasActionableProposedPlan > 0,
|
||||
} satisfies OrchestrationThreadShell);
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
isPersistenceError(error)
|
||||
? error
|
||||
: toPersistenceSqlError("ProjectionSnapshotQuery.getThreadShellById:transaction")(
|
||||
error,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
getLatestTurnRowByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getLatestTurn:query",
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getLatestTurn:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
getThreadSessionRowByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getSession:query",
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getSession:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
]);
|
||||
|
||||
if (Option.isNone(threadRow)) {
|
||||
return Option.none<OrchestrationThreadShell>();
|
||||
}
|
||||
|
||||
return Option.some({
|
||||
id: threadRow.value.threadId,
|
||||
projectId: threadRow.value.projectId,
|
||||
title: threadRow.value.title,
|
||||
modelSelection: threadRow.value.modelSelection,
|
||||
runtimeMode: threadRow.value.runtimeMode,
|
||||
interactionMode: threadRow.value.interactionMode,
|
||||
branch: threadRow.value.branch,
|
||||
worktreePath: threadRow.value.worktreePath,
|
||||
latestTurn: Option.isSome(latestTurnRow) ? mapLatestTurn(latestTurnRow.value) : null,
|
||||
createdAt: threadRow.value.createdAt,
|
||||
updatedAt: threadRow.value.updatedAt,
|
||||
archivedAt: threadRow.value.archivedAt,
|
||||
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
|
||||
latestUserMessageAt: threadRow.value.latestUserMessageAt,
|
||||
hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,
|
||||
hasPendingUserInput: threadRow.value.pendingUserInputCount > 0,
|
||||
hasActionableProposedPlan: threadRow.value.hasActionableProposedPlan > 0,
|
||||
} satisfies OrchestrationThreadShell);
|
||||
});
|
||||
|
||||
const getThreadDetailById: ProjectionSnapshotQueryShape["getThreadDetailById"] = (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -2069,8 +1981,6 @@ 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 = {
|
||||
|
||||
@@ -371,7 +371,6 @@ describe("ProviderCommandReactor", () => {
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
runtime = ManagedRuntime.make(layer);
|
||||
|
||||
@@ -412,7 +411,6 @@ describe("ProviderCommandReactor", () => {
|
||||
return {
|
||||
engine,
|
||||
readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()),
|
||||
snapshotQuery,
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
@@ -468,97 +466,6 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||
});
|
||||
|
||||
effectIt.effect("clears pending work when session startup fails before binding", () =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* Effect.promise(() => createHarness());
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const messageId = asMessageId("user-message-start-failed");
|
||||
harness.startSession.mockImplementationOnce(
|
||||
(_: unknown, __: unknown) => Effect.fail("simulated startup failure") as never,
|
||||
);
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-failed"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId,
|
||||
role: "user",
|
||||
text: "hello reactor",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
});
|
||||
|
||||
yield* Effect.promise(() =>
|
||||
waitFor(async () => {
|
||||
const readModel = await harness.readModel();
|
||||
return (
|
||||
readModel.threads[0]?.activities.some(
|
||||
(activity) => activity.kind === "provider.turn.start.failed",
|
||||
) ?? false
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const readModel = yield* harness.snapshotQuery.getSnapshot();
|
||||
expect(readModel.threads[0]?.session).toBeNull();
|
||||
expect(
|
||||
readModel.threads[0]?.activities.find(
|
||||
(activity) => activity.kind === "provider.turn.start.failed",
|
||||
),
|
||||
).toMatchObject({ payload: { requestId: messageId } });
|
||||
const shellSnapshot = yield* harness.snapshotQuery.getShellSnapshot();
|
||||
expect(shellSnapshot.threads[0]?.hasPendingTurnStart).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
effectIt.effect("clears pending work when turn startup is interrupted", () =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* Effect.promise(() => createHarness());
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const messageId = asMessageId("user-message-start-interrupted");
|
||||
harness.sendTurn.mockImplementationOnce(() => Effect.interrupt);
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-interrupted"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId,
|
||||
role: "user",
|
||||
text: "hello reactor",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
});
|
||||
|
||||
yield* Effect.promise(() =>
|
||||
waitFor(async () => {
|
||||
const readModel = await harness.readModel();
|
||||
return (
|
||||
readModel.threads[0]?.activities.some(
|
||||
(activity) => activity.kind === "provider.turn.start.failed",
|
||||
) ?? false
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const readModel = yield* harness.snapshotQuery.getSnapshot();
|
||||
expect(
|
||||
readModel.threads[0]?.activities.find(
|
||||
(activity) => activity.kind === "provider.turn.start.failed",
|
||||
),
|
||||
).toMatchObject({ payload: { requestId: messageId } });
|
||||
const shellSnapshot = yield* harness.snapshotQuery.getShellSnapshot();
|
||||
expect(shellSnapshot.threads[0]?.hasPendingTurnStart).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it("generates a thread title on the first turn", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
@@ -29,8 +29,6 @@ import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
||||
import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts";
|
||||
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
|
||||
import type { ProviderServiceError } from "../../provider/Errors.ts";
|
||||
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
|
||||
import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
|
||||
import { TextGeneration } from "../../textGeneration/TextGeneration.ts";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { ProviderRegistry } from "../../provider/Services/ProviderRegistry.ts";
|
||||
@@ -192,7 +190,6 @@ const make = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
||||
const providerService = yield* ProviderService;
|
||||
const providerRegistry = yield* ProviderRegistry;
|
||||
const gitWorkflow = yield* GitWorkflowService;
|
||||
@@ -769,7 +766,6 @@ const make = Effect.gen(function* () {
|
||||
detail: `User message '${event.payload.messageId}' was not found for turn start request.`,
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
requestId: event.payload.messageId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -805,40 +801,29 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
}
|
||||
|
||||
const handleTurnStartFailure = Effect.fnUntraced(function* (cause: Cause.Cause<unknown>) {
|
||||
const interrupted = Cause.hasInterruptsOnly(cause);
|
||||
if (interrupted) {
|
||||
const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (
|
||||
Option.isNone(pendingTurnStart) ||
|
||||
pendingTurnStart.value.messageId !== event.payload.messageId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const handleTurnStartFailure = (cause: Cause.Cause<unknown>) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.void;
|
||||
}
|
||||
|
||||
const detail = interrupted
|
||||
? "Provider turn start was interrupted before it began."
|
||||
: formatFailureDetail(cause);
|
||||
if (!interrupted) {
|
||||
yield* setThreadSessionErrorOnTurnStartFailure({
|
||||
threadId: event.payload.threadId,
|
||||
detail,
|
||||
createdAt: event.payload.createdAt,
|
||||
});
|
||||
}
|
||||
yield* appendProviderFailureActivity({
|
||||
const detail = formatFailureDetail(cause);
|
||||
return setThreadSessionErrorOnTurnStartFailure({
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.turn.start.failed",
|
||||
summary: "Provider turn start failed",
|
||||
detail,
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
requestId: event.payload.messageId,
|
||||
});
|
||||
});
|
||||
}).pipe(
|
||||
Effect.flatMap(() =>
|
||||
appendProviderFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.turn.start.failed",
|
||||
summary: "Provider turn start failed",
|
||||
detail,
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
}),
|
||||
),
|
||||
Effect.asVoid,
|
||||
);
|
||||
};
|
||||
|
||||
const recoverTurnStartFailure = (cause: Cause.Cause<unknown>) =>
|
||||
handleTurnStartFailure(cause).pipe(
|
||||
@@ -1100,6 +1085,4 @@ const make = Effect.gen(function* () {
|
||||
} satisfies ProviderCommandReactorShape;
|
||||
});
|
||||
|
||||
export const ProviderCommandReactorLive = Layer.effect(ProviderCommandReactor, make).pipe(
|
||||
Layer.provide(ProjectionTurnRepositoryLive),
|
||||
);
|
||||
export const ProviderCommandReactorLive = Layer.effect(ProviderCommandReactor, make);
|
||||
@@ -4,13 +4,11 @@ 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,
|
||||
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
|
||||
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
|
||||
@@ -31,13 +29,11 @@ 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 ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;
|
||||
|
||||
@@ -68,8 +68,6 @@ const readModel: OrchestrationReadModel = {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
session: null,
|
||||
@@ -93,8 +91,6 @@ const readModel: OrchestrationReadModel = {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
session: null,
|
||||
|
||||
@@ -1,521 +0,0 @@
|
||||
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,
|
||||
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"]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -24,61 +24,6 @@ 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"];
|
||||
@@ -382,132 +327,6 @@ 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.
|
||||
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),
|
||||
),
|
||||
);
|
||||
// The age check is bounded on BOTH sides: message timestamps are
|
||||
// client-supplied, so a client clock ahead of the server yields a
|
||||
// negative age. Without the lower bound that negative age satisfies
|
||||
// `<= grace` for as long as the skew lasts, extending the settle
|
||||
// block far past the intended two minutes.
|
||||
const queuedAgeMs = Date.parse(occurredAt) - latestUserMessageAtMs;
|
||||
const hasQueuedTurnStart =
|
||||
thread.session?.status !== "error" &&
|
||||
Number.isFinite(latestUserMessageAtMs) &&
|
||||
latestUserMessageAtMs > latestTurnAtMs &&
|
||||
Math.abs(queuedAgeMs) <= QUEUED_TURN_START_GRACE_MS;
|
||||
if (hasQueuedTurnStart) {
|
||||
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,
|
||||
@@ -660,27 +479,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
createdAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
// 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 (targetThread.settledOverride === null) {
|
||||
return [userMessageEvent, turnStartRequestedEvent];
|
||||
}
|
||||
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, userMessageEvent, turnStartRequestedEvent];
|
||||
return [userMessageEvent, turnStartRequestedEvent];
|
||||
}
|
||||
|
||||
case "thread.turn.interrupt": {
|
||||
@@ -801,12 +600,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
}
|
||||
|
||||
case "thread.session.set": {
|
||||
const thread = yield* requireThread({
|
||||
yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
const sessionSetEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
@@ -820,30 +619,6 @@ 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": {
|
||||
@@ -970,7 +745,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
}
|
||||
|
||||
case "thread.activity.append": {
|
||||
const thread = yield* requireThread({
|
||||
yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
@@ -983,7 +758,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
? ((command.activity.payload as { requestId: string })
|
||||
.requestId as OrchestrationEvent["metadata"]["requestId"])
|
||||
: undefined;
|
||||
const activityAppendedEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
@@ -997,30 +772,6 @@ 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: {
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
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,6 @@ describe("orchestration projector", () => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
|
||||
@@ -22,9 +22,7 @@ import {
|
||||
ThreadMetaUpdatedPayload,
|
||||
ThreadProposedPlanUpsertedPayload,
|
||||
ThreadRuntimeModeSetPayload,
|
||||
ThreadSettledPayload,
|
||||
ThreadUnarchivedPayload,
|
||||
ThreadUnsettledPayload,
|
||||
ThreadRevertedPayload,
|
||||
ThreadSessionSetPayload,
|
||||
ThreadTurnDiffCompletedPayload,
|
||||
@@ -288,8 +286,6 @@ export function projectEvent(
|
||||
createdAt: payload.createdAt,
|
||||
updatedAt: payload.updatedAt,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
activities: [],
|
||||
@@ -341,30 +337,6 @@ 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) => ({
|
||||
|
||||
@@ -91,8 +91,6 @@ 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,
|
||||
@@ -130,58 +128,4 @@ 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,8 +43,6 @@ 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,
|
||||
@@ -64,8 +62,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
${row.createdAt},
|
||||
${row.updatedAt},
|
||||
${row.archivedAt},
|
||||
${row.settledOverride},
|
||||
${row.settledAt},
|
||||
${row.latestUserMessageAt},
|
||||
${row.pendingApprovalCount},
|
||||
${row.pendingUserInputCount},
|
||||
@@ -85,8 +81,6 @@ 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,
|
||||
@@ -113,8 +107,6 @@ 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",
|
||||
@@ -143,8 +135,6 @@ 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,7 +45,6 @@ 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";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -90,7 +89,6 @@ export const migrationEntries = [
|
||||
[30, "ProjectionThreadShellArchiveIndexes", Migration0030],
|
||||
[31, "AuthAuthorizationScopes", Migration0031],
|
||||
[32, "AuthPairingProofKeyThumbprint", Migration0032],
|
||||
[33, "ProjectionThreadsSettled", Migration0033],
|
||||
] as const;
|
||||
|
||||
export const makeMigrationLoader = (throughId?: number) =>
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
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
|
||||
`;
|
||||
}
|
||||
});
|
||||
@@ -36,8 +36,6 @@ 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,133 +1711,6 @@ 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* () {
|
||||
@@ -3172,7 +3045,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
assert.deepEqual(harness.query.setModelCalls, ["claude-opus-4-6[1m]"]);
|
||||
assert.deepEqual(harness.query.setModelCalls, ["claude-opus-4-6"]);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
@@ -3270,11 +3143,10 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello again",
|
||||
modelSelection: createModelSelection(
|
||||
ProviderInstanceId.make("claudeAgent"),
|
||||
"claude-opus-4-6",
|
||||
[{ id: "contextWindow", value: "200k" }],
|
||||
),
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
||||
model: "claude-opus-4-6",
|
||||
},
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
|
||||
@@ -77,7 +77,6 @@ import {
|
||||
isClaudeUltracodeEffort,
|
||||
normalizeClaudeCliEffort,
|
||||
resolveClaudeApiModelId,
|
||||
resolveClaudeContextWindow,
|
||||
resolveClaudeEffort,
|
||||
} from "./ClaudeProvider.ts";
|
||||
import {
|
||||
@@ -342,18 +341,24 @@ 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;
|
||||
}
|
||||
|
||||
switch (resolveClaudeContextWindow(modelSelection)) {
|
||||
case "1m":
|
||||
return 1_000_000;
|
||||
case "200k":
|
||||
return 200_000;
|
||||
default:
|
||||
return undefined;
|
||||
const optionValue = getModelSelectionStringOptionValue(modelSelection, "contextWindow");
|
||||
if (optionValue === "1m") {
|
||||
return 1_000_000;
|
||||
}
|
||||
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 {
|
||||
@@ -2585,17 +2590,6 @@ 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({
|
||||
@@ -2708,11 +2702,6 @@ 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,
|
||||
@@ -2757,52 +2746,6 @@ 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,
|
||||
@@ -2822,21 +2765,13 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
message,
|
||||
);
|
||||
return;
|
||||
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 };
|
||||
default:
|
||||
yield* emitRuntimeWarning(
|
||||
context,
|
||||
describeUnknownSdkMessage(`Claude system message '${unknownMessage.subtype}'`, message),
|
||||
describeUnknownSdkMessage(`Claude system message '${message.subtype}'`, message),
|
||||
message,
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -2944,21 +2879,13 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
case "rate_limit_event":
|
||||
yield* handleSdkTelemetryMessage(context, message);
|
||||
return;
|
||||
// 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 };
|
||||
default:
|
||||
yield* emitRuntimeWarning(
|
||||
context,
|
||||
describeUnknownSdkMessage(`Claude SDK message '${unknownMessage.type}'`, message),
|
||||
describeUnknownSdkMessage(`Claude SDK message '${message.type}'`, message),
|
||||
message,
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -76,8 +76,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
id: "contextWindow",
|
||||
label: "Context Window",
|
||||
options: [
|
||||
{ value: "200k", label: "200k" },
|
||||
{ value: "1m", label: "1M", isDefault: true },
|
||||
{ value: "200k", label: "200k", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
],
|
||||
}),
|
||||
],
|
||||
@@ -162,8 +162,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
id: "contextWindow",
|
||||
label: "Context Window",
|
||||
options: [
|
||||
{ value: "200k", label: "200k" },
|
||||
{ value: "1m", label: "1M", isDefault: true },
|
||||
{ value: "200k", label: "200k", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
],
|
||||
}),
|
||||
],
|
||||
@@ -214,7 +214,6 @@ 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" },
|
||||
@@ -244,7 +243,6 @@ 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" },
|
||||
@@ -371,22 +369,8 @@ 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 (resolveClaudeContextWindow(modelSelection)) {
|
||||
switch (getModelSelectionStringOptionValue(modelSelection, "contextWindow")) {
|
||||
case "1m":
|
||||
return `${modelSelection.model}[1m]`;
|
||||
default:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import { applyPreferredCodexDefaultModel, mapCodexModelCapabilities } from "./CodexProvider.ts";
|
||||
import { mapCodexModelCapabilities } from "./CodexProvider.ts";
|
||||
|
||||
it("maps current Codex model capability fields", () => {
|
||||
const capabilities = mapCodexModelCapabilities({
|
||||
@@ -102,45 +102,3 @@ 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 { PREFERRED_DEFAULT_CODEX_MODELS, ServerSettingsError } from "@t3tools/contracts";
|
||||
import { ServerSettingsError } from "@t3tools/contracts";
|
||||
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
import { resolveSpawnCommand } from "@t3tools/shared/shell";
|
||||
@@ -189,36 +189,10 @@ 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>,
|
||||
@@ -402,9 +376,7 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun
|
||||
return {
|
||||
account: accountResponse,
|
||||
version,
|
||||
models: applyPreferredCodexDefaultModel(
|
||||
appendCustomCodexModels(models, input.customModels ?? []),
|
||||
),
|
||||
models: appendCustomCodexModels(models, input.customModels ?? []),
|
||||
skills: parseCodexSkillsListResponse(skillsResponse, input.cwd),
|
||||
} satisfies CodexAppServerProviderSnapshot;
|
||||
});
|
||||
|
||||
@@ -100,8 +100,6 @@ function makeReadModel(
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
|
||||
@@ -305,8 +305,6 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
@@ -453,8 +451,6 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: {
|
||||
threadId,
|
||||
status: "running",
|
||||
@@ -611,8 +607,6 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: {
|
||||
threadId,
|
||||
status: "running",
|
||||
|
||||
@@ -164,8 +164,6 @@ const makeDefaultOrchestrationReadModel = () => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
session: null,
|
||||
@@ -195,8 +193,6 @@ const makeDefaultOrchestrationThreadShell = (
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
@@ -5503,8 +5499,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
session: null,
|
||||
|
||||
@@ -596,26 +596,6 @@ 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();
|
||||
|
||||
@@ -2217,12 +2217,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
name: refName.name,
|
||||
current: false,
|
||||
isRemote: true,
|
||||
// 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,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
};
|
||||
if (parsedRemoteRef) {
|
||||
@@ -2237,16 +2232,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
})
|
||||
: [];
|
||||
|
||||
const combinedBranches = input.includeMatchingRemoteRefs
|
||||
const allBranches = 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)
|
||||
|
||||
@@ -8,9 +8,7 @@ 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,
|
||||
@@ -100,12 +98,7 @@ 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);
|
||||
@@ -164,10 +157,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
<Sidebar
|
||||
side="left"
|
||||
collapsible="offcanvas"
|
||||
className={cn(
|
||||
"border-r border-border text-foreground",
|
||||
useSidebarV2 ? "app-sidebar" : "bg-card",
|
||||
)}
|
||||
className="border-r border-border bg-card text-foreground"
|
||||
resizable={{
|
||||
maxWidth: sidebarMaximumWidth,
|
||||
minWidth: THREAD_SIDEBAR_MIN_WIDTH,
|
||||
@@ -178,7 +168,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
onResize: setSidebarWidth,
|
||||
}}
|
||||
>
|
||||
{useSidebarV2 ? <ThreadSidebarV2 /> : <ThreadSidebar />}
|
||||
<ThreadSidebar />
|
||||
<SidebarRail />
|
||||
</Sidebar>
|
||||
{children}
|
||||
|
||||
@@ -12,7 +12,6 @@ import {
|
||||
resolveBranchToolbarValue,
|
||||
resolveLockedWorkspaceLabel,
|
||||
shouldIncludeBranchPickerItem,
|
||||
shouldShowEnvironmentIndicator,
|
||||
} from "./BranchToolbar.logic";
|
||||
|
||||
const localEnvironmentId = EnvironmentId.make("environment-local");
|
||||
@@ -120,44 +119,6 @@ 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,17 +42,6 @@ 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,7 +20,6 @@ import {
|
||||
resolveEnvModeLabel,
|
||||
resolveEffectiveEnvMode,
|
||||
resolveLockedWorkspaceLabel,
|
||||
shouldShowEnvironmentIndicator,
|
||||
} from "./BranchToolbar.logic";
|
||||
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
|
||||
import { BranchToolbarEnvironmentSelector } from "./BranchToolbarEnvironmentSelector";
|
||||
@@ -61,7 +60,6 @@ interface MobileRunContextSelectorProps {
|
||||
environmentId: EnvironmentId;
|
||||
availableEnvironments: readonly EnvironmentOption[] | undefined;
|
||||
showEnvironmentPicker: boolean;
|
||||
showEnvironmentIndicator: boolean;
|
||||
onEnvironmentChange: ((environmentId: EnvironmentId) => void) | undefined;
|
||||
effectiveEnvMode: EnvMode;
|
||||
activeWorktreePath: string | null;
|
||||
@@ -74,7 +72,6 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
|
||||
environmentId,
|
||||
availableEnvironments,
|
||||
showEnvironmentPicker,
|
||||
showEnvironmentIndicator,
|
||||
onEnvironmentChange,
|
||||
effectiveEnvMode,
|
||||
activeWorktreePath,
|
||||
@@ -97,7 +94,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
|
||||
: resolveCurrentWorkspaceLabel(activeWorktreePath);
|
||||
const isLocked = envLocked || envModeLocked;
|
||||
const EnvironmentIcon = activeEnvironment?.isPrimary ? MonitorIcon : CloudIcon;
|
||||
const icon = showEnvironmentIndicator ? (
|
||||
const icon = showEnvironmentPicker ? (
|
||||
// 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">
|
||||
@@ -111,7 +108,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
|
||||
<>
|
||||
{icon}
|
||||
<span className="min-w-0 truncate">
|
||||
{showEnvironmentIndicator ? (activeEnvironment?.label ?? "Run on") : workspaceLabel}
|
||||
{showEnvironmentPicker ? (activeEnvironment?.label ?? "Run on") : workspaceLabel}
|
||||
</span>
|
||||
</>
|
||||
);
|
||||
@@ -237,12 +234,6 @@ 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;
|
||||
@@ -256,7 +247,6 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
environmentId={environmentId}
|
||||
availableEnvironments={availableEnvironments}
|
||||
showEnvironmentPicker={showEnvironmentPicker}
|
||||
showEnvironmentIndicator={showEnvironmentIndicator}
|
||||
onEnvironmentChange={onEnvironmentChange}
|
||||
effectiveEnvMode={effectiveEnvMode}
|
||||
activeWorktreePath={activeWorktreePath}
|
||||
@@ -264,13 +254,13 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
/>
|
||||
) : (
|
||||
<div className="flex min-w-0 shrink-0 items-center gap-1">
|
||||
{showEnvironmentIndicator && availableEnvironments && (
|
||||
{showEnvironmentPicker && availableEnvironments && onEnvironmentChange && (
|
||||
<>
|
||||
<BranchToolbarEnvironmentSelector
|
||||
envLocked={envLocked}
|
||||
environmentId={environmentId}
|
||||
availableEnvironments={availableEnvironments}
|
||||
{...(showEnvironmentPicker && onEnvironmentChange ? { onEnvironmentChange } : {})}
|
||||
onEnvironmentChange={onEnvironmentChange}
|
||||
/>
|
||||
<Separator orientation="vertical" className="mx-0.5 h-3.5!" />
|
||||
</>
|
||||
|
||||
@@ -422,32 +422,17 @@ 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 ||
|
||||
!worktreeBaseBranchCandidate
|
||||
!currentGitBranch
|
||||
) {
|
||||
return;
|
||||
}
|
||||
setThreadBranch(worktreeBaseBranchCandidate, null);
|
||||
}, [
|
||||
activeThreadBranch,
|
||||
activeWorktreePath,
|
||||
effectiveEnvMode,
|
||||
setThreadBranch,
|
||||
worktreeBaseBranchCandidate,
|
||||
]);
|
||||
setThreadBranch(currentGitBranch, null);
|
||||
}, [activeThreadBranch, activeWorktreePath, currentGitBranch, effectiveEnvMode, setThreadBranch]);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Combobox / list plumbing
|
||||
|
||||
@@ -17,9 +17,7 @@ interface BranchToolbarEnvironmentSelectorProps {
|
||||
envLocked: boolean;
|
||||
environmentId: EnvironmentId;
|
||||
availableEnvironments: readonly EnvironmentOption[];
|
||||
// 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;
|
||||
onEnvironmentChange: (environmentId: EnvironmentId) => void;
|
||||
}
|
||||
|
||||
export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvironmentSelector({
|
||||
@@ -41,7 +39,7 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
|
||||
[availableEnvironments],
|
||||
);
|
||||
|
||||
if (envLocked || onEnvironmentChange === undefined) {
|
||||
if (envLocked) {
|
||||
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 ? (
|
||||
|
||||
@@ -49,8 +49,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
latestTurn: null,
|
||||
branch: null,
|
||||
|
||||
@@ -45,8 +45,6 @@ export function buildLocalDraftThread(
|
||||
createdAt: draftThread.createdAt,
|
||||
updatedAt: draftThread.createdAt,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
latestTurn: null,
|
||||
branch: draftThread.branch,
|
||||
|
||||
@@ -5220,7 +5220,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
{...(routeKind === "draft" && draftId ? { draftId } : {})}
|
||||
activeThreadTitle={activeThread.title}
|
||||
activeProjectName={activeProject?.title}
|
||||
activeProjectCwd={activeProject?.workspaceRoot ?? null}
|
||||
openInCwd={gitCwd}
|
||||
activeProjectScripts={activeProject?.scripts}
|
||||
preferredScriptId={
|
||||
|
||||
@@ -24,8 +24,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
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,
|
||||
|
||||
@@ -18,10 +18,8 @@ import {
|
||||
resolveSidebarNewThreadEnvMode,
|
||||
resolveSidebarStageBadgeLabel,
|
||||
resolveThreadRowClassName,
|
||||
resolveSidebarV2Status,
|
||||
resolveThreadStatusPill,
|
||||
shouldClearThreadSelectionOnMouseDown,
|
||||
sortThreadsForSidebarV2,
|
||||
sortProjectsForSidebar,
|
||||
sortScopedProjectsForSidebar,
|
||||
THREAD_JUMP_HINT_SHOW_DELAY_MS,
|
||||
@@ -636,119 +634,10 @@ describe("isContextMenuPointerDown", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveSidebarV2Status", () => {
|
||||
const session = {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "running" as const,
|
||||
providerName: "Codex",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
activeTurnId: "turn-1" as never,
|
||||
lastError: null,
|
||||
updatedAt: "2026-03-09T10:00:00.000Z",
|
||||
};
|
||||
|
||||
const idle = {
|
||||
hasPendingApprovals: false,
|
||||
hasPendingTurnStart: false,
|
||||
hasPendingUserInput: false,
|
||||
};
|
||||
|
||||
it("prioritizes approval over a running session", () => {
|
||||
expect(resolveSidebarV2Status({ ...idle, hasPendingApprovals: true, session })).toBe(
|
||||
"approval",
|
||||
);
|
||||
});
|
||||
|
||||
it("prioritizes awaiting input over a running session, below approval", () => {
|
||||
expect(resolveSidebarV2Status({ ...idle, hasPendingUserInput: true, session })).toBe("input");
|
||||
expect(
|
||||
resolveSidebarV2Status({
|
||||
...idle,
|
||||
hasPendingApprovals: true,
|
||||
hasPendingUserInput: true,
|
||||
session,
|
||||
}),
|
||||
).toBe("approval");
|
||||
});
|
||||
|
||||
it("reports working for running and starting sessions", () => {
|
||||
expect(resolveSidebarV2Status({ ...idle, session })).toBe("working");
|
||||
expect(
|
||||
resolveSidebarV2Status({
|
||||
...idle,
|
||||
session: { ...session, status: "starting" as const },
|
||||
}),
|
||||
).toBe("working");
|
||||
});
|
||||
|
||||
it("reports working while a turn start is pending without a session", () => {
|
||||
expect(
|
||||
resolveSidebarV2Status({
|
||||
...idle,
|
||||
hasPendingTurnStart: true,
|
||||
session: null,
|
||||
}),
|
||||
).toBe("working");
|
||||
});
|
||||
|
||||
it("reports failed only while the session status is error", () => {
|
||||
expect(
|
||||
resolveSidebarV2Status({
|
||||
...idle,
|
||||
session: { ...session, status: "error" as const, lastError: "boom" },
|
||||
}),
|
||||
).toBe("failed");
|
||||
expect(
|
||||
resolveSidebarV2Status({
|
||||
...idle,
|
||||
session: { ...session, status: "stopped" as const, lastError: "persisted" },
|
||||
}),
|
||||
).toBe("ready");
|
||||
expect(
|
||||
resolveSidebarV2Status({
|
||||
...idle,
|
||||
session: { ...session, status: "ready" as const, lastError: "persisted" },
|
||||
}),
|
||||
).toBe("ready");
|
||||
});
|
||||
|
||||
it("defaults to ready with no session", () => {
|
||||
expect(resolveSidebarV2Status({ ...idle, session: null })).toBe("ready");
|
||||
});
|
||||
});
|
||||
|
||||
describe("sortThreadsForSidebarV2", () => {
|
||||
const sortable = (input: { id: string; createdAt: string }) => ({
|
||||
id: input.id,
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
|
||||
it("orders by creation time, newest first, ignoring activity", () => {
|
||||
const sorted = sortThreadsForSidebarV2([
|
||||
sortable({ id: "oldest", createdAt: "2026-03-09T08:00:00.000Z" }),
|
||||
sortable({ id: "newest", createdAt: "2026-03-09T12:00:00.000Z" }),
|
||||
sortable({ id: "middle", createdAt: "2026-03-09T10:00:00.000Z" }),
|
||||
]);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual(["newest", "middle", "oldest"]);
|
||||
});
|
||||
|
||||
it("breaks creation-time ties by id so the order is stable", () => {
|
||||
const sorted = sortThreadsForSidebarV2([
|
||||
sortable({ id: "b", createdAt: "2026-03-09T10:00:00.000Z" }),
|
||||
sortable({ id: "a", createdAt: "2026-03-09T10:00:00.000Z" }),
|
||||
]);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual(["a", "b"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveThreadStatusPill", () => {
|
||||
const baseThread = {
|
||||
hasActionableProposedPlan: false,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingTurnStart: false,
|
||||
hasPendingUserInput: false,
|
||||
interactionMode: "plan" as const,
|
||||
latestTurn: null,
|
||||
@@ -796,35 +685,6 @@ describe("resolveThreadStatusPill", () => {
|
||||
).toMatchObject({ label: "Working", pulse: true });
|
||||
});
|
||||
|
||||
it("shows working while a new thread turn is waiting for its first session update", () => {
|
||||
expect(
|
||||
resolveThreadStatusPill({
|
||||
thread: {
|
||||
...baseThread,
|
||||
hasPendingTurnStart: true,
|
||||
session: null,
|
||||
},
|
||||
}),
|
||||
).toMatchObject({ label: "Working", pulse: true });
|
||||
});
|
||||
|
||||
it("keeps showing working through a ready session before the turn starts", () => {
|
||||
expect(
|
||||
resolveThreadStatusPill({
|
||||
thread: {
|
||||
...baseThread,
|
||||
hasPendingTurnStart: true,
|
||||
session: {
|
||||
...baseThread.session,
|
||||
status: "ready",
|
||||
activeTurnId: null,
|
||||
updatedAt: "2026-03-09T10:00:02.000Z",
|
||||
},
|
||||
},
|
||||
}),
|
||||
).toMatchObject({ label: "Working", pulse: true });
|
||||
});
|
||||
|
||||
it("shows plan ready when a settled plan turn has a proposed plan ready for follow-up", () => {
|
||||
expect(
|
||||
resolveThreadStatusPill({
|
||||
@@ -1040,8 +900,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
proposedPlans: [],
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
updatedAt: "2026-03-09T10:00:00.000Z",
|
||||
latestTurn: null,
|
||||
|
||||
@@ -112,7 +112,6 @@ type ThreadStatusInput = Pick<
|
||||
SidebarThreadSummary,
|
||||
| "hasActionableProposedPlan"
|
||||
| "hasPendingApprovals"
|
||||
| "hasPendingTurnStart"
|
||||
| "hasPendingUserInput"
|
||||
| "interactionMode"
|
||||
| "latestTurn"
|
||||
@@ -418,75 +417,6 @@ export function resolveThreadRowClassName(input: {
|
||||
return cn(baseClassName, "text-muted-foreground hover:bg-accent hover:text-foreground");
|
||||
}
|
||||
|
||||
// ── Sidebar v2 status model ─────────────────────────────────────────
|
||||
// Five visual states, three colors: color is reserved for "act now"
|
||||
// (approval), "in motion" (working), and "broken" (failed). Ready is the
|
||||
// unlabeled resting state — the agent stopped and is waiting on the user,
|
||||
// whether it finished, asked a question, or proposed a plan.
|
||||
// Unread completion is tracked separately: it describes whether a ready
|
||||
// thread needs attention, not what the thread is currently doing.
|
||||
export type SidebarV2Status = "approval" | "input" | "working" | "failed" | "ready";
|
||||
|
||||
type SidebarV2StatusInput = Pick<
|
||||
SidebarThreadSummary,
|
||||
"hasPendingApprovals" | "hasPendingTurnStart" | "hasPendingUserInput" | "session"
|
||||
>;
|
||||
|
||||
export function resolveSidebarV2Status(thread: SidebarV2StatusInput): SidebarV2Status {
|
||||
if (thread.hasPendingApprovals) {
|
||||
return "approval";
|
||||
}
|
||||
if (thread.hasPendingUserInput) {
|
||||
return "input";
|
||||
}
|
||||
if (
|
||||
thread.session?.status === "running" ||
|
||||
thread.session?.status === "starting" ||
|
||||
thread.hasPendingTurnStart === true
|
||||
) {
|
||||
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. */
|
||||
export function parseTimestampMs(isoDate: string): number {
|
||||
const parsed = Date.parse(isoDate);
|
||||
return Number.isNaN(parsed) ? 0 : parsed;
|
||||
}
|
||||
|
||||
/** First VALID timestamp wins: `a ?? b` falls through on null, but a present-
|
||||
yet-malformed string must also fall through to the next candidate rather
|
||||
than sink the row to the epoch. */
|
||||
export 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. Status (including pending
|
||||
// approval) is carried by each card's edge strip, not by position.
|
||||
export function sortThreadsForSidebarV2<
|
||||
T extends { readonly id: string; readonly createdAt: string },
|
||||
>(threads: readonly T[]): T[] {
|
||||
return [...threads].toSorted(
|
||||
(left, right) =>
|
||||
parseTimestampMs(right.createdAt) - parseTimestampMs(left.createdAt) ||
|
||||
left.id.localeCompare(right.id),
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveThreadStatusPill(input: {
|
||||
thread: ThreadStatusInput;
|
||||
}): ThreadStatusPill | null {
|
||||
@@ -510,7 +440,7 @@ export function resolveThreadStatusPill(input: {
|
||||
};
|
||||
}
|
||||
|
||||
if (thread.session?.status === "running" || thread.hasPendingTurnStart === true) {
|
||||
if (thread.session?.status === "running") {
|
||||
return {
|
||||
label: "Working",
|
||||
colorClass: "text-sky-600 dark:text-sky-300/80",
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
Globe2Icon,
|
||||
LoaderIcon,
|
||||
SearchIcon,
|
||||
SettingsIcon,
|
||||
SquarePenIcon,
|
||||
TerminalIcon,
|
||||
TriangleAlertIcon,
|
||||
@@ -62,7 +63,7 @@ import {
|
||||
settlePromise,
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import { useLocation, useNavigate, useParams, useRouter } from "@tanstack/react-router";
|
||||
import { Link, useLocation, useNavigate, useParams, useRouter } from "@tanstack/react-router";
|
||||
import {
|
||||
MAX_SIDEBAR_THREAD_PREVIEW_COUNT,
|
||||
MIN_SIDEBAR_THREAD_PREVIEW_COUNT,
|
||||
@@ -73,9 +74,10 @@ import {
|
||||
import { isDesktopLocalConnectionTarget } from "../connection/desktopLocal";
|
||||
import { useDesktopLocalBootstraps } from "../connection/useDesktopLocalBootstraps";
|
||||
import { isElectron } from "../env";
|
||||
import { APP_STAGE_LABEL } from "../branding";
|
||||
import { useOpenPrLink } from "../lib/openPullRequestLink";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import { isMacPlatform } from "../lib/utils";
|
||||
import { cn, isMacPlatform } from "../lib/utils";
|
||||
import {
|
||||
readThreadShell,
|
||||
useProject,
|
||||
@@ -124,6 +126,7 @@ import {
|
||||
import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
import { formatRelativeTimeLabel } from "../timestampFormat";
|
||||
import { SettingsSidebarNav } from "./settings/SettingsSidebarNav";
|
||||
import { SidebarStageBackdrop, resolveSidebarStageBackdropVariant } from "./SidebarStageBackdrop";
|
||||
import { Kbd } from "./ui/kbd";
|
||||
import {
|
||||
getArm64IntelBuildWarningDescription,
|
||||
@@ -166,7 +169,9 @@ import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./u
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
import {
|
||||
SidebarContent,
|
||||
SidebarFooter,
|
||||
SidebarGroup,
|
||||
SidebarHeader,
|
||||
SidebarMenu,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
@@ -174,6 +179,7 @@ import {
|
||||
SidebarMenuSubButton,
|
||||
SidebarMenuSubItem,
|
||||
SidebarSeparator,
|
||||
SidebarTrigger,
|
||||
useSidebar,
|
||||
} from "./ui/sidebar";
|
||||
import { useThreadSelectionStore } from "../threadSelectionStore";
|
||||
@@ -188,6 +194,7 @@ import {
|
||||
resolveProjectStatusIndicator,
|
||||
resolveSidebarNewThreadSeedContext,
|
||||
resolveSidebarNewThreadEnvMode,
|
||||
resolveSidebarStageBadgeLabel,
|
||||
resolveThreadRowClassName,
|
||||
resolveThreadStatusPill,
|
||||
orderItemsByPreferredIds,
|
||||
@@ -197,12 +204,12 @@ import {
|
||||
ThreadStatusPill,
|
||||
} from "./Sidebar.logic";
|
||||
import { sortThreads } from "../lib/threadSort";
|
||||
import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome";
|
||||
import { SidebarUpdatePill } from "./sidebar/SidebarUpdatePill";
|
||||
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
import { useIsMobile } from "~/hooks/useMediaQuery";
|
||||
import { CommandDialogTrigger } from "./ui/command";
|
||||
import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings";
|
||||
import { primaryServerKeybindingsAtom } from "../state/server";
|
||||
import { primaryServerConfigAtom, primaryServerKeybindingsAtom } from "../state/server";
|
||||
import {
|
||||
derivePhysicalProjectKey,
|
||||
deriveProjectGroupingOverrideKey,
|
||||
@@ -216,6 +223,7 @@ import {
|
||||
type SidebarProjectGroupMember,
|
||||
type SidebarProjectSnapshot,
|
||||
} from "../sidebarProjectGrouping";
|
||||
import { SidebarProviderUpdatePill } from "./sidebar/SidebarProviderUpdatePill";
|
||||
const SIDEBAR_SORT_LABELS: Record<SidebarProjectSortOrder, string> = {
|
||||
updated_at: "Last user message",
|
||||
created_at: "Created at",
|
||||
@@ -2779,6 +2787,112 @@ function SortableProjectItem({
|
||||
);
|
||||
}
|
||||
|
||||
const SidebarChromeHeader = memo(function SidebarChromeHeader({
|
||||
isElectron,
|
||||
}: {
|
||||
isElectron: boolean;
|
||||
}) {
|
||||
const stageLabel = useSidebarStageLabel();
|
||||
const backdropVariant = resolveSidebarStageBackdropVariant(stageLabel);
|
||||
|
||||
return (
|
||||
<SidebarHeader
|
||||
className={cn(
|
||||
"@container/sidebar-header relative h-[var(--workspace-topbar-height)] shrink-0 flex-row items-center px-3 py-0 md:px-0",
|
||||
isElectron && "drag-region",
|
||||
)}
|
||||
>
|
||||
{backdropVariant ? <SidebarStageBackdrop variant={backdropVariant} /> : null}
|
||||
<SidebarTrigger
|
||||
className={cn(
|
||||
"relative z-10 md:hidden",
|
||||
backdropVariant && "hover:bg-white/15 [&_svg]:text-white/85! [&_svg]:hover:text-white!",
|
||||
)}
|
||||
/>
|
||||
<SidebarBrand onBackdrop={backdropVariant !== null} />
|
||||
</SidebarHeader>
|
||||
);
|
||||
});
|
||||
|
||||
function SidebarBrand({ onBackdrop }: { onBackdrop: boolean }) {
|
||||
return (
|
||||
<Link
|
||||
aria-label="Go to threads"
|
||||
className={cn(
|
||||
"sidebar-brand relative z-10 ml-[var(--workspace-titlebar-content-left)] h-7 w-fit min-w-0 shrink-0 items-center gap-1 overflow-hidden rounded-md outline-hidden ring-ring focus-visible:ring-2",
|
||||
onBackdrop ? "text-white" : "text-foreground",
|
||||
)}
|
||||
to="/"
|
||||
>
|
||||
<T3Wordmark />
|
||||
<span
|
||||
className={cn(
|
||||
"truncate text-sm font-medium tracking-tight",
|
||||
onBackdrop ? "text-white/70" : "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
Code
|
||||
</span>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
function useSidebarStageLabel() {
|
||||
const primaryServerVersion =
|
||||
useAtomValue(primaryServerConfigAtom)?.environment.serverVersion ?? null;
|
||||
|
||||
return resolveSidebarStageBadgeLabel({
|
||||
primaryServerVersion,
|
||||
fallbackStageLabel: APP_STAGE_LABEL,
|
||||
});
|
||||
}
|
||||
|
||||
function T3Wordmark() {
|
||||
return (
|
||||
<svg
|
||||
aria-label="T3"
|
||||
className="h-2.5 w-auto shrink-0"
|
||||
viewBox="15.5309 37 94.3941 56.96"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
d="M33.4509 93V47.56H15.5309V37H64.3309V47.56H46.4109V93H33.4509ZM86.7253 93.96C82.832 93.96 78.9653 93.4533 75.1253 92.44C71.2853 91.3733 68.032 89.88 65.3653 87.96L70.4053 78.04C72.5386 79.5867 75.0186 80.8133 77.8453 81.72C80.672 82.6267 83.5253 83.08 86.4053 83.08C89.6586 83.08 92.2186 82.44 94.0853 81.16C95.952 79.88 96.8853 78.12 96.8853 75.88C96.8853 73.7467 96.0586 72.0667 94.4053 70.84C92.752 69.6133 90.0853 69 86.4053 69H80.4853V60.44L96.0853 42.76L97.5253 47.4H68.1653V37H107.365V45.4L91.8453 63.08L85.2853 59.32H89.0453C95.9253 59.32 101.125 60.8667 104.645 63.96C108.165 67.0533 109.925 71.0267 109.925 75.88C109.925 79.0267 109.099 81.9867 107.445 84.76C105.792 87.48 103.259 89.6933 99.8453 91.4C96.432 93.1067 92.0586 93.96 86.7253 93.96Z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
const SidebarChromeFooter = memo(function SidebarChromeFooter() {
|
||||
const navigate = useNavigate();
|
||||
const { isMobile, setOpenMobile } = useSidebar();
|
||||
const handleSettingsClick = useCallback(() => {
|
||||
if (isMobile) {
|
||||
setOpenMobile(false);
|
||||
}
|
||||
void navigate({ to: "/settings" });
|
||||
}, [isMobile, navigate, setOpenMobile]);
|
||||
|
||||
return (
|
||||
<SidebarFooter className="p-2">
|
||||
<SidebarProviderUpdatePill />
|
||||
<SidebarUpdatePill />
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
size="sm"
|
||||
className="gap-2 px-2 py-1.5 text-muted-foreground/70 hover:bg-accent hover:text-foreground"
|
||||
onClick={handleSettingsClick}
|
||||
>
|
||||
<SettingsIcon className="size-3.5" />
|
||||
<span className="text-xs">Settings</span>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarFooter>
|
||||
);
|
||||
});
|
||||
|
||||
interface SidebarProjectsContentProps {
|
||||
showArm64IntelBuildWarning: boolean;
|
||||
arm64IntelBuildWarningDescription: string | null;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1159,7 +1159,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
isSendBusy ||
|
||||
isConnecting ||
|
||||
projectSelectionRequired ||
|
||||
environmentUnavailable !== null ||
|
||||
!composerSendState.hasSendableContent;
|
||||
const collapsedComposerPrimaryActionLabel = "Send message";
|
||||
const showMobilePendingAnswerActions =
|
||||
@@ -1698,9 +1697,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
|
||||
const shouldBlurMobileComposerOnSubmit = useCallback(() => {
|
||||
if (!isMobileViewport) return false;
|
||||
if (isSendBusy || isConnecting || environmentUnavailable !== null || phase === "running") {
|
||||
return false;
|
||||
}
|
||||
if (isSendBusy || isConnecting || phase === "running") return false;
|
||||
if (activePendingProgress) {
|
||||
return activePendingProgress.isLastQuestion && Boolean(activePendingResolvedAnswers);
|
||||
}
|
||||
@@ -1709,7 +1706,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
activePendingProgress,
|
||||
activePendingResolvedAnswers,
|
||||
composerSendState.hasSendableContent,
|
||||
environmentUnavailable,
|
||||
isConnecting,
|
||||
isMobileViewport,
|
||||
isSendBusy,
|
||||
@@ -1896,7 +1892,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
isConnecting ||
|
||||
isComposerApprovalState ||
|
||||
pendingUserInputs.length > 0 ||
|
||||
projectSelectionRequired
|
||||
projectSelectionRequired ||
|
||||
(environmentUnavailable !== null && activePendingProgress === null)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
@@ -2104,6 +2101,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
isComposerApprovalState,
|
||||
pendingUserInputs.length,
|
||||
projectSelectionRequired,
|
||||
environmentUnavailable,
|
||||
activePendingProgress,
|
||||
applyPromptReplacement,
|
||||
isComposerModelPickerOpen,
|
||||
readComposerSnapshot,
|
||||
@@ -2143,11 +2142,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
ref={composerSurfaceRef}
|
||||
data-chat-composer-mobile-collapsed={isComposerCollapsedMobile ? "true" : "false"}
|
||||
className={cn(
|
||||
"chat-composer-glass rounded-[20px] border transition-[background-color] duration-200 has-focus-visible:border-foreground/40",
|
||||
isDragOverComposer
|
||||
? "border-primary/70 bg-accent/45"
|
||||
: "border-black/12 dark:border-white/12",
|
||||
projectSelectionRequired ? "opacity-75" : null,
|
||||
"chat-composer-glass rounded-[20px] border transition-[background-color] duration-200 has-focus-visible:border-ring/45",
|
||||
isDragOverComposer ? "border-primary/70 bg-accent/45" : "border-border",
|
||||
environmentUnavailable || projectSelectionRequired ? "opacity-75" : null,
|
||||
composerProviderState.composerSurfaceClassName,
|
||||
)}
|
||||
onFocusCapture={(event) => {
|
||||
@@ -2505,7 +2502,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
? "Ask for follow-up changes or attach images"
|
||||
: "Ask anything, @tag files/folders, $use skills, or / for commands"
|
||||
}
|
||||
disabled={isConnecting || isComposerApprovalState || projectSelectionRequired}
|
||||
disabled={
|
||||
isConnecting ||
|
||||
isComposerApprovalState ||
|
||||
projectSelectionRequired ||
|
||||
(environmentUnavailable !== null && activePendingProgress === null)
|
||||
}
|
||||
/>
|
||||
{showMobilePendingAnswerActions ? (
|
||||
<div
|
||||
|
||||
@@ -16,7 +16,6 @@ import ProjectScriptsControl, {
|
||||
} from "../ProjectScriptsControl";
|
||||
import { OpenInPicker } from "./OpenInPicker";
|
||||
import { usePrimaryEnvironmentId } from "../../state/environments";
|
||||
import { ProjectFavicon } from "../ProjectFavicon";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
interface ChatHeaderProps {
|
||||
@@ -25,7 +24,6 @@ interface ChatHeaderProps {
|
||||
draftId?: DraftId;
|
||||
activeThreadTitle: string;
|
||||
activeProjectName: string | undefined;
|
||||
activeProjectCwd: string | null;
|
||||
openInCwd: string | null;
|
||||
activeProjectScripts: ReadonlyArray<ProjectScript> | undefined;
|
||||
preferredScriptId: string | null;
|
||||
@@ -60,7 +58,6 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
draftId,
|
||||
activeThreadTitle,
|
||||
activeProjectName,
|
||||
activeProjectCwd,
|
||||
openInCwd,
|
||||
activeProjectScripts,
|
||||
preferredScriptId,
|
||||
@@ -82,26 +79,6 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
return (
|
||||
<div className="@container/header-actions flex min-w-0 flex-1 items-center gap-2 sm:gap-3">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden sm:gap-3">
|
||||
{/* The project always leads the header: knowing which project a
|
||||
thread lives in is priority zero, and the thread title alone
|
||||
doesn't answer it. */}
|
||||
{activeProjectName ? (
|
||||
<span className="inline-flex shrink-0 items-center gap-2">
|
||||
<span className="inline-flex min-w-0 items-center gap-1.5">
|
||||
<ProjectFavicon
|
||||
environmentId={activeThreadEnvironmentId}
|
||||
cwd={activeProjectCwd ?? ""}
|
||||
className="size-3.5"
|
||||
/>
|
||||
<span className="max-w-40 truncate text-sm font-medium text-muted-foreground">
|
||||
{activeProjectName}
|
||||
</span>
|
||||
</span>
|
||||
<span aria-hidden className="text-muted-foreground/40">
|
||||
/
|
||||
</span>
|
||||
</span>
|
||||
) : null}
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { resolveExternalWebLinkHost, showExternalLinkContextMenu } from "./externalLinkContextMenu";
|
||||
|
||||
function createHarness(selection: "open-in-preview" | "open-external" | "copy-link" | null) {
|
||||
const showContextMenu = vi.fn().mockResolvedValue(selection);
|
||||
const openInPreview = vi.fn().mockResolvedValue(undefined);
|
||||
const openExternal = vi.fn().mockResolvedValue(undefined);
|
||||
const copyLink = vi.fn().mockResolvedValue(undefined);
|
||||
const reportFailure = vi.fn();
|
||||
|
||||
return {
|
||||
showContextMenu,
|
||||
openInPreview,
|
||||
openExternal,
|
||||
copyLink,
|
||||
reportFailure,
|
||||
};
|
||||
}
|
||||
|
||||
describe("external chat link context menu", () => {
|
||||
it("offers both open actions and Copy Link", async () => {
|
||||
const harness = createHarness(null);
|
||||
|
||||
await showExternalLinkContextMenu({
|
||||
href: "https://example.com/docs?topic=menus#copy",
|
||||
position: { x: 12, y: 24 },
|
||||
...harness,
|
||||
});
|
||||
|
||||
expect(harness.showContextMenu).toHaveBeenCalledWith(
|
||||
[
|
||||
{ id: "open-in-preview", label: "Open in integrated browser" },
|
||||
{ id: "open-external", label: "Open in system browser" },
|
||||
{ id: "copy-link", label: "Copy Link" },
|
||||
],
|
||||
{ x: 12, y: 24 },
|
||||
);
|
||||
expect(harness.openInPreview).not.toHaveBeenCalled();
|
||||
expect(harness.openExternal).not.toHaveBeenCalled();
|
||||
expect(harness.copyLink).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("copies the exact destination without opening it", async () => {
|
||||
const harness = createHarness("copy-link");
|
||||
const href = "https://example.com/docs?topic=menus#copy";
|
||||
|
||||
await showExternalLinkContextMenu({ href, position: { x: 1, y: 2 }, ...harness });
|
||||
|
||||
expect(harness.copyLink).toHaveBeenCalledWith(href);
|
||||
expect(harness.openInPreview).not.toHaveBeenCalled();
|
||||
expect(harness.openExternal).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["open-in-preview" as const, "openInPreview" as const],
|
||||
["open-external" as const, "openExternal" as const],
|
||||
])("preserves the %s action", async (selection, expectedCallback) => {
|
||||
const harness = createHarness(selection);
|
||||
const href = "https://example.com/docs";
|
||||
|
||||
await showExternalLinkContextMenu({ href, position: { x: 1, y: 2 }, ...harness });
|
||||
|
||||
expect(harness[expectedCallback]).toHaveBeenCalledWith(href);
|
||||
expect(harness.copyLink).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports the selected action when it fails", async () => {
|
||||
const harness = createHarness("copy-link");
|
||||
const cause = new Error("clipboard denied");
|
||||
harness.copyLink.mockRejectedValue(cause);
|
||||
|
||||
await showExternalLinkContextMenu({
|
||||
href: "https://example.com/docs",
|
||||
position: { x: 1, y: 2 },
|
||||
...harness,
|
||||
});
|
||||
|
||||
expect(harness.reportFailure).toHaveBeenCalledWith("copy-link", cause);
|
||||
});
|
||||
|
||||
it("reports the menu operation when the native menu cannot be shown", async () => {
|
||||
const harness = createHarness(null);
|
||||
const cause = new Error("menu unavailable");
|
||||
harness.showContextMenu.mockRejectedValue(cause);
|
||||
|
||||
await showExternalLinkContextMenu({
|
||||
href: "https://example.com/docs",
|
||||
position: { x: 1, y: 2 },
|
||||
...harness,
|
||||
});
|
||||
|
||||
expect(harness.reportFailure).toHaveBeenCalledWith("show-link-context-menu", cause);
|
||||
expect(harness.openInPreview).not.toHaveBeenCalled();
|
||||
expect(harness.openExternal).not.toHaveBeenCalled();
|
||||
expect(harness.copyLink).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["open-in-preview" as const, "openInPreview" as const, "open-link-in-preview"],
|
||||
["open-external" as const, "openExternal" as const, "open-link-external"],
|
||||
])("reports a failed %s action", async (selection, callback, operation) => {
|
||||
const harness = createHarness(selection);
|
||||
const cause = new Error("open failed");
|
||||
harness[callback].mockRejectedValue(cause);
|
||||
|
||||
await showExternalLinkContextMenu({
|
||||
href: "https://example.com/docs",
|
||||
position: { x: 1, y: 2 },
|
||||
...harness,
|
||||
});
|
||||
|
||||
expect(harness.reportFailure).toHaveBeenCalledWith(operation, cause);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["https://example.com", "example.com"],
|
||||
["http://localhost:3000/path", "localhost"],
|
||||
["#details", null],
|
||||
["mailto:[email protected]", null],
|
||||
["file:///tmp/example.txt", null],
|
||||
["javascript:void(0)", null],
|
||||
["not a URL", null],
|
||||
[undefined, null],
|
||||
])("resolves the external web-link host for %s as %s", (href, expected) => {
|
||||
expect(resolveExternalWebLinkHost(href)).toBe(expected);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import type { ContextMenuItem } from "@t3tools/contracts";
|
||||
|
||||
export type ExternalLinkContextMenuAction = "open-in-preview" | "open-external" | "copy-link";
|
||||
|
||||
export type ExternalLinkContextMenuFailureOperation =
|
||||
| "show-link-context-menu"
|
||||
| "open-link-in-preview"
|
||||
| "open-link-external"
|
||||
| "copy-link";
|
||||
|
||||
const FAILURE_OPERATION_BY_ACTION = {
|
||||
"open-in-preview": "open-link-in-preview",
|
||||
"open-external": "open-link-external",
|
||||
"copy-link": "copy-link",
|
||||
} as const satisfies Record<ExternalLinkContextMenuAction, ExternalLinkContextMenuFailureOperation>;
|
||||
|
||||
const EXTERNAL_LINK_CONTEXT_MENU_ITEMS = [
|
||||
{ id: "open-in-preview", label: "Open in integrated browser" },
|
||||
{ id: "open-external", label: "Open in system browser" },
|
||||
{ id: "copy-link", label: "Copy Link" },
|
||||
] as const satisfies readonly ContextMenuItem<ExternalLinkContextMenuAction>[];
|
||||
|
||||
interface ShowExternalLinkContextMenuOptions {
|
||||
readonly href: string;
|
||||
readonly position: { readonly x: number; readonly y: number };
|
||||
readonly showContextMenu: (
|
||||
items: readonly ContextMenuItem<ExternalLinkContextMenuAction>[],
|
||||
position: { readonly x: number; readonly y: number },
|
||||
) => Promise<ExternalLinkContextMenuAction | null>;
|
||||
readonly openInPreview: (href: string) => Promise<void>;
|
||||
readonly openExternal: (href: string) => Promise<void>;
|
||||
readonly copyLink: (href: string) => Promise<unknown>;
|
||||
readonly reportFailure: (
|
||||
operation: ExternalLinkContextMenuFailureOperation,
|
||||
cause: unknown,
|
||||
) => void;
|
||||
}
|
||||
|
||||
export function resolveExternalWebLinkHost(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;
|
||||
}
|
||||
}
|
||||
|
||||
export async function showExternalLinkContextMenu({
|
||||
href,
|
||||
position,
|
||||
showContextMenu,
|
||||
openInPreview,
|
||||
openExternal,
|
||||
copyLink,
|
||||
reportFailure,
|
||||
}: ShowExternalLinkContextMenuOptions): Promise<void> {
|
||||
let action: ExternalLinkContextMenuAction | null;
|
||||
try {
|
||||
action = await showContextMenu(EXTERNAL_LINK_CONTEXT_MENU_ITEMS, position);
|
||||
} catch (cause) {
|
||||
reportFailure("show-link-context-menu", cause);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (action === "open-in-preview") {
|
||||
await openInPreview(href);
|
||||
} else if (action === "open-external") {
|
||||
await openExternal(href);
|
||||
} else if (action === "copy-link") {
|
||||
await copyLink(href);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (action) reportFailure(FAILURE_OPERATION_BY_ACTION[action], cause);
|
||||
}
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { useClientSettings, useUpdateClientSettings } from "../../hooks/useSettings";
|
||||
import { Input } from "../ui/input";
|
||||
import { Switch } from "../ui/switch";
|
||||
import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";
|
||||
|
||||
const AUTO_SETTLE_MIN_DAYS = 1;
|
||||
const AUTO_SETTLE_MAX_DAYS = 90;
|
||||
const AUTO_SETTLE_DEFAULT_DAYS = 3;
|
||||
|
||||
function AutoSettleDaysInput({
|
||||
value,
|
||||
onCommit,
|
||||
}: {
|
||||
value: number;
|
||||
onCommit: (days: number) => void;
|
||||
}) {
|
||||
// Local draft so the field can be emptied mid-edit; the setting only moves
|
||||
// on valid input and snaps back to the persisted value on blur.
|
||||
const [draft, setDraft] = useState(String(value));
|
||||
useEffect(() => {
|
||||
setDraft(String(value));
|
||||
}, [value]);
|
||||
|
||||
return (
|
||||
<Input
|
||||
type="number"
|
||||
min={AUTO_SETTLE_MIN_DAYS}
|
||||
max={AUTO_SETTLE_MAX_DAYS}
|
||||
className="w-full sm:w-24"
|
||||
value={draft}
|
||||
onChange={(event) => {
|
||||
setDraft(event.target.value);
|
||||
// Number(), not parseInt: "3.5" must be rejected (not truncated to a
|
||||
// committed 3 while the field shows 3.5) — commit only when the
|
||||
// persisted value matches the displayed one.
|
||||
const parsed = Number(event.target.value);
|
||||
if (
|
||||
Number.isInteger(parsed) &&
|
||||
parsed >= AUTO_SETTLE_MIN_DAYS &&
|
||||
parsed <= AUTO_SETTLE_MAX_DAYS
|
||||
) {
|
||||
onCommit(parsed);
|
||||
}
|
||||
}}
|
||||
onBlur={() => setDraft(String(value))}
|
||||
aria-label="Days of inactivity before auto-settle"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function BetaSettingsPanel() {
|
||||
const sidebarV2Enabled = useClientSettings((settings) => settings.sidebarV2Enabled);
|
||||
const sidebarAutoSettleAfterDays = useClientSettings(
|
||||
(settings) => settings.sidebarAutoSettleAfterDays,
|
||||
);
|
||||
const updateSettings = useUpdateClientSettings();
|
||||
|
||||
return (
|
||||
<SettingsPageContainer>
|
||||
<SettingsSection title="Beta features">
|
||||
<SettingsRow
|
||||
title="Sidebar v2"
|
||||
description="One flat thread list in creation order. Active work renders as rich cards; settled threads collapse to compact rows. Settling requires an up-to-date server — on older servers threads simply stay active. Switch back any time."
|
||||
control={
|
||||
<Switch
|
||||
checked={sidebarV2Enabled}
|
||||
onCheckedChange={(checked) => updateSettings({ sidebarV2Enabled: Boolean(checked) })}
|
||||
aria-label="Enable the sidebar v2 beta"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{sidebarV2Enabled ? (
|
||||
<>
|
||||
<SettingsRow
|
||||
title="Auto-settle inactive threads"
|
||||
description="Threads with no activity for this long settle automatically. Threads on merged or closed PRs always settle."
|
||||
control={
|
||||
<Switch
|
||||
checked={sidebarAutoSettleAfterDays !== null}
|
||||
onCheckedChange={(checked) =>
|
||||
updateSettings({
|
||||
sidebarAutoSettleAfterDays: checked ? AUTO_SETTLE_DEFAULT_DAYS : null,
|
||||
})
|
||||
}
|
||||
aria-label="Auto-settle inactive threads"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{sidebarAutoSettleAfterDays !== null ? (
|
||||
<SettingsRow
|
||||
title="Days of inactivity before auto-settle"
|
||||
description="Any new activity un-settles a thread automatically."
|
||||
control={
|
||||
<AutoSettleDaysInput
|
||||
value={sidebarAutoSettleAfterDays}
|
||||
onCommit={(days) => updateSettings({ sidebarAutoSettleAfterDays: days })}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
</SettingsSection>
|
||||
</SettingsPageContainer>
|
||||
);
|
||||
}
|
||||
@@ -3,7 +3,6 @@ import {
|
||||
ArchiveIcon,
|
||||
ArrowLeftIcon,
|
||||
BotIcon,
|
||||
FlaskConicalIcon,
|
||||
GitBranchIcon,
|
||||
KeyboardIcon,
|
||||
Link2Icon,
|
||||
@@ -29,7 +28,6 @@ export type SettingsSectionPath =
|
||||
| "/settings/providers"
|
||||
| "/settings/source-control"
|
||||
| "/settings/connections"
|
||||
| "/settings/beta"
|
||||
| "/settings/archived";
|
||||
|
||||
export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
|
||||
@@ -42,7 +40,6 @@ export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
|
||||
{ label: "Providers", to: "/settings/providers", icon: BotIcon },
|
||||
{ label: "Source Control", to: "/settings/source-control", icon: GitBranchIcon },
|
||||
{ label: "Connections", to: "/settings/connections", icon: Link2Icon },
|
||||
{ label: "Beta", to: "/settings/beta", icon: FlaskConicalIcon },
|
||||
{ label: "Archive", to: "/settings/archived", icon: ArchiveIcon },
|
||||
];
|
||||
|
||||
|
||||
@@ -1,127 +0,0 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { SettingsIcon } from "lucide-react";
|
||||
import { memo, useCallback } from "react";
|
||||
import { Link, useNavigate } from "@tanstack/react-router";
|
||||
|
||||
import { APP_STAGE_LABEL } from "../../branding";
|
||||
import { cn } from "../../lib/utils";
|
||||
import { primaryServerConfigAtom } from "../../state/server";
|
||||
import { resolveSidebarStageBadgeLabel } from "../Sidebar.logic";
|
||||
import { SidebarStageBackdrop, resolveSidebarStageBackdropVariant } from "../SidebarStageBackdrop";
|
||||
import {
|
||||
SidebarFooter,
|
||||
SidebarHeader,
|
||||
SidebarMenu,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarTrigger,
|
||||
useSidebar,
|
||||
} from "../ui/sidebar";
|
||||
import { SidebarProviderUpdatePill } from "./SidebarProviderUpdatePill";
|
||||
import { SidebarUpdatePill } from "./SidebarUpdatePill";
|
||||
|
||||
export const SidebarChromeHeader = memo(function SidebarChromeHeader({
|
||||
isElectron,
|
||||
}: {
|
||||
isElectron: boolean;
|
||||
}) {
|
||||
const stageLabel = useSidebarStageLabel();
|
||||
const backdropVariant = resolveSidebarStageBackdropVariant(stageLabel);
|
||||
|
||||
return (
|
||||
<SidebarHeader
|
||||
className={cn(
|
||||
"@container/sidebar-header relative h-[var(--workspace-topbar-height)] shrink-0 flex-row items-center px-3 py-0 md:px-0",
|
||||
isElectron && "drag-region",
|
||||
)}
|
||||
>
|
||||
{backdropVariant ? <SidebarStageBackdrop variant={backdropVariant} /> : null}
|
||||
<SidebarTrigger
|
||||
className={cn(
|
||||
"relative z-10 md:hidden",
|
||||
backdropVariant && "hover:bg-white/15 [&_svg]:text-white/85! [&_svg]:hover:text-white!",
|
||||
)}
|
||||
/>
|
||||
<SidebarBrand onBackdrop={backdropVariant !== null} />
|
||||
</SidebarHeader>
|
||||
);
|
||||
});
|
||||
|
||||
function SidebarBrand({ onBackdrop }: { onBackdrop: boolean }) {
|
||||
return (
|
||||
<Link
|
||||
aria-label="Go to threads"
|
||||
className={cn(
|
||||
"sidebar-brand relative z-10 ml-[var(--workspace-titlebar-content-left)] h-7 w-fit min-w-0 shrink-0 items-center gap-1 overflow-hidden rounded-md outline-hidden ring-ring focus-visible:ring-2",
|
||||
onBackdrop ? "text-white" : "text-foreground",
|
||||
)}
|
||||
to="/"
|
||||
>
|
||||
<T3Wordmark />
|
||||
<span
|
||||
className={cn(
|
||||
"truncate text-sm font-medium tracking-tight",
|
||||
onBackdrop ? "text-white/70" : "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
Code
|
||||
</span>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
function useSidebarStageLabel() {
|
||||
const primaryServerVersion =
|
||||
useAtomValue(primaryServerConfigAtom)?.environment.serverVersion ?? null;
|
||||
|
||||
return resolveSidebarStageBadgeLabel({
|
||||
primaryServerVersion,
|
||||
fallbackStageLabel: APP_STAGE_LABEL,
|
||||
});
|
||||
}
|
||||
|
||||
function T3Wordmark() {
|
||||
return (
|
||||
<svg
|
||||
aria-label="T3"
|
||||
className="h-2.5 w-auto shrink-0"
|
||||
viewBox="15.5309 37 94.3941 56.96"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
d="M33.4509 93V47.56H15.5309V37H64.3309V47.56H46.4109V93H33.4509ZM86.7253 93.96C82.832 93.96 78.9653 93.4533 75.1253 92.44C71.2853 91.3733 68.032 89.88 65.3653 87.96L70.4053 78.04C72.5386 79.5867 75.0186 80.8133 77.8453 81.72C80.672 82.6267 83.5253 83.08 86.4053 83.08C89.6586 83.08 92.2186 82.44 94.0853 81.16C95.952 79.88 96.8853 78.12 96.8853 75.88C96.8853 73.7467 96.0586 72.0667 94.4053 70.84C92.752 69.6133 90.0853 69 86.4053 69H80.4853V60.44L96.0853 42.76L97.5253 47.4H68.1653V37H107.365V45.4L91.8453 63.08L85.2853 59.32H89.0453C95.9253 59.32 101.125 60.8667 104.645 63.96C108.165 67.0533 109.925 71.0267 109.925 75.88C109.925 79.0267 109.099 81.9867 107.445 84.76C105.792 87.48 103.259 89.6933 99.8453 91.4C96.432 93.1067 92.0586 93.96 86.7253 93.96Z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export const SidebarChromeFooter = memo(function SidebarChromeFooter() {
|
||||
const navigate = useNavigate();
|
||||
const { isMobile, setOpenMobile } = useSidebar();
|
||||
const handleSettingsClick = useCallback(() => {
|
||||
if (isMobile) {
|
||||
setOpenMobile(false);
|
||||
}
|
||||
void navigate({ to: "/settings" });
|
||||
}, [isMobile, navigate, setOpenMobile]);
|
||||
|
||||
return (
|
||||
<SidebarFooter className="p-2">
|
||||
<SidebarProviderUpdatePill />
|
||||
<SidebarUpdatePill />
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
size="sm"
|
||||
className="gap-2 px-2 py-1.5 text-muted-foreground/70 hover:bg-accent hover:text-foreground"
|
||||
onClick={handleSettingsClick}
|
||||
>
|
||||
<SettingsIcon className="size-3.5" />
|
||||
<span className="text-xs">Settings</span>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarFooter>
|
||||
);
|
||||
});
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
scopeThreadRef,
|
||||
} from "@t3tools/client-runtime/environment";
|
||||
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
|
||||
import { canSettle } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import { EnvironmentId, type ScopedThreadRef, ThreadId } from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -20,12 +19,7 @@ import { vcsEnvironment } from "../state/vcs";
|
||||
import { useNewThreadHandler } from "./useHandleNewThread";
|
||||
import { refreshArchivedThreadsForEnvironment } from "../lib/archivedThreadsState";
|
||||
import { readLocalApi } from "../localApi";
|
||||
import {
|
||||
readEnvironmentSupportsSettlement,
|
||||
readEnvironmentThreadRefs,
|
||||
readProject,
|
||||
readThreadShell,
|
||||
} from "../state/entities";
|
||||
import { readEnvironmentThreadRefs, readProject, readThreadShell } from "../state/entities";
|
||||
import { useTerminalUiStateStore } from "../terminalUiStateStore";
|
||||
import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes";
|
||||
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
|
||||
@@ -45,30 +39,6 @@ export class ThreadArchiveBlockedError extends Schema.TaggedErrorClass<ThreadArc
|
||||
}
|
||||
}
|
||||
|
||||
export class ThreadSettlementUnsupportedError extends Schema.TaggedErrorClass<ThreadSettlementUnsupportedError>()(
|
||||
"ThreadSettlementUnsupportedError",
|
||||
{
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "This environment's server does not support settling yet. Update the server to use Settle.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ThreadSettleBlockedError extends Schema.TaggedErrorClass<ThreadSettleBlockedError>()(
|
||||
"ThreadSettleBlockedError",
|
||||
{
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "This thread still needs attention. Resolve or interrupt it first, then try again.";
|
||||
}
|
||||
}
|
||||
|
||||
export function useThreadActions() {
|
||||
const closeTerminal = useAtomCommand(terminalEnvironment.close);
|
||||
const archiveThreadMutation = useAtomCommand(threadEnvironment.archive, {
|
||||
@@ -80,12 +50,6 @@ export function useThreadActions() {
|
||||
const deleteThreadMutation = useAtomCommand(threadEnvironment.delete, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const settleThreadMutation = useAtomCommand(threadEnvironment.settle, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const unsettleThreadMutation = useAtomCommand(threadEnvironment.unsettle, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const stopThreadSession = useAtomCommand(threadEnvironment.stopSession);
|
||||
const removeWorktree = useAtomCommand(vcsEnvironment.removeWorktree, {
|
||||
reportFailure: false,
|
||||
@@ -381,66 +345,6 @@ export function useThreadActions() {
|
||||
],
|
||||
);
|
||||
|
||||
const settleThread = useCallback(
|
||||
async (target: ScopedThreadRef) => {
|
||||
// Version skew: never send the command to a server that predates it —
|
||||
// the raw protocol rejection would read as a random failure.
|
||||
if (!readEnvironmentSupportsSettlement(target.environmentId)) {
|
||||
return AsyncResult.failure(
|
||||
Cause.fail(
|
||||
new ThreadSettlementUnsupportedError({
|
||||
environmentId: target.environmentId,
|
||||
threadId: target.threadId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
const resolved = resolveThreadTarget(target);
|
||||
// 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 (resolved && !canSettle(resolved.thread, { now: new Date().toISOString() })) {
|
||||
return AsyncResult.failure(
|
||||
Cause.fail(
|
||||
new ThreadSettleBlockedError({
|
||||
environmentId: resolved.threadRef.environmentId,
|
||||
threadId: resolved.threadRef.threadId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
// Settle is a high-frequency lifecycle action and stays silent — no
|
||||
// toast.
|
||||
return settleThreadMutation({
|
||||
environmentId: target.environmentId,
|
||||
input: { threadId: target.threadId },
|
||||
});
|
||||
},
|
||||
[resolveThreadTarget, settleThreadMutation],
|
||||
);
|
||||
|
||||
const unsettleThread = useCallback(
|
||||
async (target: ScopedThreadRef) => {
|
||||
if (!readEnvironmentSupportsSettlement(target.environmentId)) {
|
||||
return AsyncResult.failure(
|
||||
Cause.fail(
|
||||
new ThreadSettlementUnsupportedError({
|
||||
environmentId: target.environmentId,
|
||||
threadId: target.threadId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
// reason "user" pins the thread active: auto-settle (PR merged /
|
||||
// inactivity) stays suppressed until real activity clears the pin.
|
||||
return unsettleThreadMutation({
|
||||
environmentId: target.environmentId,
|
||||
input: { threadId: target.threadId, reason: "user" },
|
||||
});
|
||||
},
|
||||
[unsettleThreadMutation],
|
||||
);
|
||||
|
||||
const confirmAndDeleteThread = useCallback(
|
||||
async (target: ScopedThreadRef) => {
|
||||
const localApi = readLocalApi();
|
||||
@@ -475,16 +379,7 @@ export function useThreadActions() {
|
||||
unarchiveThread,
|
||||
deleteThread,
|
||||
confirmAndDeleteThread,
|
||||
settleThread,
|
||||
unsettleThread,
|
||||
}),
|
||||
[
|
||||
archiveThread,
|
||||
confirmAndDeleteThread,
|
||||
deleteThread,
|
||||
settleThread,
|
||||
unarchiveThread,
|
||||
unsettleThread,
|
||||
],
|
||||
[archiveThread, confirmAndDeleteThread, deleteThread, unarchiveThread],
|
||||
);
|
||||
}
|
||||
+10
-63
@@ -108,11 +108,11 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
|
||||
@theme inline {
|
||||
--animate-skeleton: skeleton 2s -1s infinite linear;
|
||||
/* Duty-cycled indicator animations: long holds with stepped ramps, so the
|
||||
compositor updates discrete frames instead of every vsync. */
|
||||
/* Duty-cycled indicator animations: long opacity holds with short stepped
|
||||
ramps, so the compositor only produces frames while the value changes
|
||||
(~20% of the cycle) instead of every vsync. Keep flat holds dominant. */
|
||||
--animate-status-pulse: status-pulse 2s infinite;
|
||||
--animate-status-ping: status-ping 2s infinite;
|
||||
--animate-sidebar-working-text: sidebar-working-text 3.4s infinite;
|
||||
--font-sans:
|
||||
"DM Sans Variable", "DM Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui,
|
||||
sans-serif;
|
||||
@@ -185,21 +185,6 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
scale: 2;
|
||||
}
|
||||
}
|
||||
@keyframes sidebar-working-text {
|
||||
0%,
|
||||
36% {
|
||||
opacity: 1;
|
||||
animation-timing-function: steps(10);
|
||||
}
|
||||
50%,
|
||||
86% {
|
||||
opacity: 0.75;
|
||||
animation-timing-function: steps(10);
|
||||
}
|
||||
100% {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@layer base {
|
||||
@@ -247,11 +232,8 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
}
|
||||
|
||||
/* Stage-channel sidebar art; ::after ramps to the sidebar bg color and the
|
||||
mask lets the surface grain show through at the boundary. Panels whose
|
||||
background differs from the app chrome (e.g. sidebar v2) override
|
||||
--sidebar-stage-fade so the art fades into their own surface color. */
|
||||
mask lets the surface grain show through at the boundary. */
|
||||
.sidebar-stage-backdrop {
|
||||
--stage-fade: var(--sidebar-stage-fade, var(--app-chrome-background));
|
||||
mask-image: linear-gradient(to bottom, black 0%, black 55%, transparent 92%);
|
||||
-webkit-mask-image: linear-gradient(to bottom, black 0%, black 55%, transparent 92%);
|
||||
}
|
||||
@@ -264,12 +246,12 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
to bottom,
|
||||
transparent 0%,
|
||||
transparent 28%,
|
||||
color-mix(in srgb, var(--stage-fade) 10%, transparent) 40%,
|
||||
color-mix(in srgb, var(--stage-fade) 30%, transparent) 52%,
|
||||
color-mix(in srgb, var(--stage-fade) 58%, transparent) 64%,
|
||||
color-mix(in srgb, var(--stage-fade) 82%, transparent) 75%,
|
||||
color-mix(in srgb, var(--stage-fade) 96%, transparent) 85%,
|
||||
var(--stage-fade) 93%
|
||||
color-mix(in srgb, var(--app-chrome-background) 10%, transparent) 40%,
|
||||
color-mix(in srgb, var(--app-chrome-background) 30%, transparent) 52%,
|
||||
color-mix(in srgb, var(--app-chrome-background) 58%, transparent) 64%,
|
||||
color-mix(in srgb, var(--app-chrome-background) 82%, transparent) 75%,
|
||||
color-mix(in srgb, var(--app-chrome-background) 96%, transparent) 85%,
|
||||
var(--app-chrome-background) 93%
|
||||
);
|
||||
}
|
||||
|
||||
@@ -468,41 +450,6 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
}
|
||||
}
|
||||
|
||||
/* Give the navigation rail its own cool graphite surface instead of borrowing
|
||||
the workspace card color. The scoped semantic tokens keep sidebar v2's
|
||||
controls in the same palette without changing v1 or the settings nav. */
|
||||
.app-sidebar {
|
||||
--background: oklch(0.965 0.009 265);
|
||||
--foreground: oklch(0.27 0.025 265);
|
||||
--card: oklch(0.945 0.014 265);
|
||||
--card-foreground: var(--foreground);
|
||||
--accent: oklch(0.875 0.008 265);
|
||||
--accent-foreground: oklch(0.24 0.012 265);
|
||||
--muted: oklch(0.9 0.018 265);
|
||||
--muted-foreground: oklch(0.49 0.03 265);
|
||||
--border: oklch(0.72 0.025 265 / 28%);
|
||||
--input: oklch(0.62 0.03 265 / 28%);
|
||||
--sidebar-stage-fade: var(--card);
|
||||
background-color: var(--card);
|
||||
}
|
||||
|
||||
.dark .app-sidebar {
|
||||
--background: #000;
|
||||
--foreground: #f1f3f7;
|
||||
--card: #000;
|
||||
--card-foreground: var(--foreground);
|
||||
--accent: #191a1d;
|
||||
--accent-foreground: #f7f9ff;
|
||||
--muted: #0a0a0a;
|
||||
--muted-foreground: #a3a3a3;
|
||||
--border: rgb(255 255 255 / 14%);
|
||||
--input: rgb(255 255 255 / 18%);
|
||||
/* The stage-channel header art must ramp to THIS panel's surface, not the
|
||||
global chrome background, or the fade shows a seam (same rule as the
|
||||
light palette above). */
|
||||
--sidebar-stage-fade: var(--card);
|
||||
}
|
||||
|
||||
body {
|
||||
font-family:
|
||||
"DM Sans Variable",
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
resolveNewDraftStartFromOrigin,
|
||||
startNewLocalThreadFromContext,
|
||||
startNewThreadFromContext,
|
||||
startNewThreadInProjectFromContext,
|
||||
type ChatThreadActionContext,
|
||||
} from "./chatThreadActions";
|
||||
|
||||
@@ -118,26 +117,6 @@ describe("chatThreadActions", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("does not carry branch or worktree context into a different project", async () => {
|
||||
const handleNewThread = vi.fn<ChatThreadActionContext["handleNewThread"]>(async () => {});
|
||||
const targetProjectRef = scopeProjectRef(ENVIRONMENT_ID, FALLBACK_PROJECT_ID);
|
||||
|
||||
await startNewThreadInProjectFromContext(
|
||||
createContext({
|
||||
activeThread: {
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
projectId: PROJECT_ID,
|
||||
branch: "feature/refactor",
|
||||
worktreePath: "/tmp/worktree",
|
||||
},
|
||||
handleNewThread,
|
||||
}),
|
||||
targetProjectRef,
|
||||
);
|
||||
|
||||
expect(handleNewThread).toHaveBeenCalledWith(targetProjectRef);
|
||||
});
|
||||
|
||||
it("delegates the target environment defaults to the new-thread handler", async () => {
|
||||
const handleNewThread = vi.fn<ChatThreadActionContext["handleNewThread"]>(async () => {});
|
||||
|
||||
|
||||
@@ -75,14 +75,6 @@ export async function startNewThreadInProjectFromContext(
|
||||
context: ChatThreadActionContext,
|
||||
projectRef: ScopedProjectRef,
|
||||
): Promise<void> {
|
||||
const contextualProjectRef = resolveThreadActionProjectRef(context);
|
||||
const matchesContext =
|
||||
contextualProjectRef?.environmentId === projectRef.environmentId &&
|
||||
contextualProjectRef.projectId === projectRef.projectId;
|
||||
if (!matchesContext) {
|
||||
await context.handleNewThread(projectRef);
|
||||
return;
|
||||
}
|
||||
await context.handleNewThread(projectRef, buildContextualThreadOptions(context));
|
||||
}
|
||||
|
||||
|
||||
@@ -26,8 +26,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
proposedPlans: [],
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
updatedAt: "2026-03-09T10:00:00.000Z",
|
||||
latestTurn: null,
|
||||
|
||||
@@ -75,7 +75,6 @@ export interface AppModelOption {
|
||||
shortName?: string;
|
||||
subProvider?: string;
|
||||
isCustom: boolean;
|
||||
isDefault?: boolean;
|
||||
}
|
||||
|
||||
function toAppModelOption(model: ServerProvider["models"][number]): AppModelOption {
|
||||
@@ -86,7 +85,6 @@ function toAppModelOption(model: ServerProvider["models"][number]): AppModelOpti
|
||||
};
|
||||
if (model.shortName) option.shortName = model.shortName;
|
||||
if (model.subProvider) option.subProvider = model.subProvider;
|
||||
if (model.isDefault) option.isDefault = true;
|
||||
return option;
|
||||
}
|
||||
|
||||
@@ -249,9 +247,7 @@ export function resolveAppModelSelectionForInstance(
|
||||
const options = getAppModelOptionsForInstance(settings, entry);
|
||||
return (
|
||||
resolveSelectableModel(entry.driverKind, selectedModel, options) ??
|
||||
options.find((option) => option.isDefault)?.slug ??
|
||||
options[0]?.slug ??
|
||||
entry.models.find((model) => model.isDefault)?.slug ??
|
||||
entry.models[0]?.slug ??
|
||||
null
|
||||
);
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
// Tiny event bus connecting the global chat.new shortcut (handled in the
|
||||
// _chat route layout) to SidebarV2's project picker dialog. The route layer
|
||||
// can't render the picker itself — it lives with the sidebar — and the
|
||||
// sidebar can't own the window keydown handler without racing the layout's.
|
||||
const NEW_THREAD_PICKER_EVENT = "t3code:open-new-thread-picker";
|
||||
|
||||
export function openNewThreadPicker(): void {
|
||||
window.dispatchEvent(new CustomEvent(NEW_THREAD_PICKER_EVENT));
|
||||
}
|
||||
|
||||
export function onOpenNewThreadPicker(listener: () => void): () => void {
|
||||
window.addEventListener(NEW_THREAD_PICKER_EVENT, listener);
|
||||
return () => window.removeEventListener(NEW_THREAD_PICKER_EVENT, listener);
|
||||
}
|
||||
@@ -92,7 +92,6 @@ export function getDefaultServerModel(
|
||||
): string {
|
||||
const models = getProviderModels(providers, provider);
|
||||
return (
|
||||
models.find((model) => model.isDefault && !model.isCustom)?.slug ??
|
||||
models.find((model) => !model.isCustom)?.slug ??
|
||||
models[0]?.slug ??
|
||||
DEFAULT_MODEL_BY_PROVIDER[provider] ??
|
||||
|
||||
@@ -20,7 +20,6 @@ import { Route as SettingsKeybindingsRouteImport } from './routes/settings.keybi
|
||||
import { Route as SettingsGeneralRouteImport } from './routes/settings.general'
|
||||
import { Route as SettingsDiagnosticsRouteImport } from './routes/settings.diagnostics'
|
||||
import { Route as SettingsConnectionsRouteImport } from './routes/settings.connections'
|
||||
import { Route as SettingsBetaRouteImport } from './routes/settings.beta'
|
||||
import { Route as SettingsArchivedRouteImport } from './routes/settings.archived'
|
||||
import { Route as ConnectCallbackRouteImport } from './routes/connect_.callback'
|
||||
import { Route as ChatDraftDraftIdRouteImport } from './routes/_chat.draft.$draftId'
|
||||
@@ -80,11 +79,6 @@ const SettingsConnectionsRoute = SettingsConnectionsRouteImport.update({
|
||||
path: '/connections',
|
||||
getParentRoute: () => SettingsRoute,
|
||||
} as any)
|
||||
const SettingsBetaRoute = SettingsBetaRouteImport.update({
|
||||
id: '/beta',
|
||||
path: '/beta',
|
||||
getParentRoute: () => SettingsRoute,
|
||||
} as any)
|
||||
const SettingsArchivedRoute = SettingsArchivedRouteImport.update({
|
||||
id: '/archived',
|
||||
path: '/archived',
|
||||
@@ -114,7 +108,6 @@ export interface FileRoutesByFullPath {
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/connect/callback': typeof ConnectCallbackRoute
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
'/settings/beta': typeof SettingsBetaRoute
|
||||
'/settings/connections': typeof SettingsConnectionsRoute
|
||||
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
|
||||
'/settings/general': typeof SettingsGeneralRoute
|
||||
@@ -130,7 +123,6 @@ export interface FileRoutesByTo {
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/connect/callback': typeof ConnectCallbackRoute
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
'/settings/beta': typeof SettingsBetaRoute
|
||||
'/settings/connections': typeof SettingsConnectionsRoute
|
||||
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
|
||||
'/settings/general': typeof SettingsGeneralRoute
|
||||
@@ -149,7 +141,6 @@ export interface FileRoutesById {
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/connect_/callback': typeof ConnectCallbackRoute
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
'/settings/beta': typeof SettingsBetaRoute
|
||||
'/settings/connections': typeof SettingsConnectionsRoute
|
||||
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
|
||||
'/settings/general': typeof SettingsGeneralRoute
|
||||
@@ -169,7 +160,6 @@ export interface FileRouteTypes {
|
||||
| '/settings'
|
||||
| '/connect/callback'
|
||||
| '/settings/archived'
|
||||
| '/settings/beta'
|
||||
| '/settings/connections'
|
||||
| '/settings/diagnostics'
|
||||
| '/settings/general'
|
||||
@@ -185,7 +175,6 @@ export interface FileRouteTypes {
|
||||
| '/settings'
|
||||
| '/connect/callback'
|
||||
| '/settings/archived'
|
||||
| '/settings/beta'
|
||||
| '/settings/connections'
|
||||
| '/settings/diagnostics'
|
||||
| '/settings/general'
|
||||
@@ -203,7 +192,6 @@ export interface FileRouteTypes {
|
||||
| '/settings'
|
||||
| '/connect_/callback'
|
||||
| '/settings/archived'
|
||||
| '/settings/beta'
|
||||
| '/settings/connections'
|
||||
| '/settings/diagnostics'
|
||||
| '/settings/general'
|
||||
@@ -302,13 +290,6 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof SettingsConnectionsRouteImport
|
||||
parentRoute: typeof SettingsRoute
|
||||
}
|
||||
'/settings/beta': {
|
||||
id: '/settings/beta'
|
||||
path: '/beta'
|
||||
fullPath: '/settings/beta'
|
||||
preLoaderRoute: typeof SettingsBetaRouteImport
|
||||
parentRoute: typeof SettingsRoute
|
||||
}
|
||||
'/settings/archived': {
|
||||
id: '/settings/archived'
|
||||
path: '/archived'
|
||||
@@ -356,7 +337,6 @@ const ChatRouteWithChildren = ChatRoute._addFileChildren(ChatRouteChildren)
|
||||
|
||||
interface SettingsRouteChildren {
|
||||
SettingsArchivedRoute: typeof SettingsArchivedRoute
|
||||
SettingsBetaRoute: typeof SettingsBetaRoute
|
||||
SettingsConnectionsRoute: typeof SettingsConnectionsRoute
|
||||
SettingsDiagnosticsRoute: typeof SettingsDiagnosticsRoute
|
||||
SettingsGeneralRoute: typeof SettingsGeneralRoute
|
||||
@@ -367,7 +347,6 @@ interface SettingsRouteChildren {
|
||||
|
||||
const SettingsRouteChildren: SettingsRouteChildren = {
|
||||
SettingsArchivedRoute: SettingsArchivedRoute,
|
||||
SettingsBetaRoute: SettingsBetaRoute,
|
||||
SettingsConnectionsRoute: SettingsConnectionsRoute,
|
||||
SettingsDiagnosticsRoute: SettingsDiagnosticsRoute,
|
||||
SettingsGeneralRoute: SettingsGeneralRoute,
|
||||
|
||||
@@ -3,9 +3,6 @@ import { useAtomValue } from "@effect/atom-react";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { isCommandPaletteOpen } from "../commandPaletteContext";
|
||||
import { useClientSettings } from "../hooks/useSettings";
|
||||
import { openNewThreadPicker } from "../newThreadPickerBus";
|
||||
import { useProjects } from "../state/entities";
|
||||
import { dispatchPreviewAction } from "../components/preview/previewActionBus";
|
||||
import { useHandleNewThread } from "../hooks/useHandleNewThread";
|
||||
import {
|
||||
@@ -28,8 +25,6 @@ function ChatRouteGlobalShortcuts() {
|
||||
const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread, routeThreadRef } =
|
||||
useHandleNewThread();
|
||||
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
|
||||
const sidebarV2Enabled = useClientSettings((settings) => settings.sidebarV2Enabled);
|
||||
const projectCount = useProjects().length;
|
||||
const terminalOpen = useTerminalUiStateStore((state) =>
|
||||
routeThreadRef
|
||||
? selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef).terminalOpen
|
||||
@@ -80,13 +75,6 @@ function ChatRouteGlobalShortcuts() {
|
||||
if (command === "chat.new") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
// Sidebar v2 routes creation through its project picker whenever
|
||||
// there is a real choice to make; v1 (and single-project setups)
|
||||
// keep the immediate contextual create.
|
||||
if (sidebarV2Enabled && projectCount > 1) {
|
||||
openNewThreadPicker();
|
||||
return;
|
||||
}
|
||||
void startNewThreadFromContext({
|
||||
activeDraftThread,
|
||||
activeThread: activeThread ?? undefined,
|
||||
@@ -152,10 +140,8 @@ function ChatRouteGlobalShortcuts() {
|
||||
keybindings,
|
||||
defaultProjectRef,
|
||||
previewOpen,
|
||||
projectCount,
|
||||
routeThreadRef,
|
||||
selectedThreadKeysSize,
|
||||
sidebarV2Enabled,
|
||||
terminalOpen,
|
||||
]);
|
||||
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
|
||||
import { BetaSettingsPanel } from "../components/settings/BetaSettingsPanel";
|
||||
|
||||
function SettingsBetaRoute() {
|
||||
return <BetaSettingsPanel />;
|
||||
}
|
||||
|
||||
export const Route = createFileRoute("/settings/beta")({
|
||||
component: SettingsBetaRoute,
|
||||
});
|
||||
@@ -185,16 +185,6 @@ export function readThreadShell(ref: ScopedThreadRef): EnvironmentThreadShell |
|
||||
return appAtomRegistry.get(environmentThreadShells.threadShellAtom(ref));
|
||||
}
|
||||
|
||||
/** Whether the environment's server understands thread.settle/unsettle.
|
||||
False for pre-settlement servers (capability defaults false on decode),
|
||||
so clients under version skew fall back instead of erroring. */
|
||||
export function readEnvironmentSupportsSettlement(environmentId: EnvironmentId): boolean {
|
||||
return (
|
||||
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
|
||||
.threadSettlement === true
|
||||
);
|
||||
}
|
||||
|
||||
export function readThreadDetail(ref: ScopedThreadRef): EnvironmentThread | null {
|
||||
return appAtomRegistry.get(environmentThreadDetails.detailAtom(ref));
|
||||
}
|
||||
|
||||
@@ -26,8 +26,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
createdAt: "2026-02-13T00:00:00.000Z",
|
||||
updatedAt: "2026-02-13T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
latestTurn: null,
|
||||
branch: null,
|
||||
|
||||
@@ -127,10 +127,6 @@
|
||||
"types": "./src/state/threadSort.ts",
|
||||
"default": "./src/state/threadSort.ts"
|
||||
},
|
||||
"./state/thread-settled": {
|
||||
"types": "./src/state/threadSettled.ts",
|
||||
"default": "./src/state/threadSettled.ts"
|
||||
},
|
||||
"./state/vcs": {
|
||||
"types": "./src/state/vcs.ts",
|
||||
"default": "./src/state/vcs.ts"
|
||||
|
||||
@@ -21,13 +21,7 @@ import {
|
||||
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
|
||||
import * as RpcSession from "../rpc/session.ts";
|
||||
import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
|
||||
import {
|
||||
archiveThread,
|
||||
createProject,
|
||||
settleThread,
|
||||
stopThreadSession,
|
||||
unsettleThread,
|
||||
} from "./commands.ts";
|
||||
import { archiveThread, createProject, stopThreadSession } from "./commands.ts";
|
||||
|
||||
const TEST_CRYPTO_LAYER = Layer.succeed(
|
||||
Crypto.Crypto,
|
||||
@@ -140,35 +134,4 @@ describe("environment commands", () => {
|
||||
]);
|
||||
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
|
||||
);
|
||||
|
||||
it.effect("dispatches settle and unsettle commands without timestamps", () =>
|
||||
Effect.gen(function* () {
|
||||
const dispatched: ClientOrchestrationCommand[] = [];
|
||||
const supervisor = yield* makeSupervisor(dispatched);
|
||||
|
||||
yield* settleThread({
|
||||
commandId: CommandId.make("settle-command"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
|
||||
yield* unsettleThread({
|
||||
commandId: CommandId.make("unsettle-command"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
reason: "user",
|
||||
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
|
||||
|
||||
expect(dispatched).toEqual([
|
||||
{
|
||||
type: "thread.settle",
|
||||
commandId: "settle-command",
|
||||
threadId: "thread-1",
|
||||
},
|
||||
{
|
||||
type: "thread.unsettle",
|
||||
commandId: "unsettle-command",
|
||||
threadId: "thread-1",
|
||||
reason: "user",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
|
||||
);
|
||||
});
|
||||
@@ -35,8 +35,6 @@ export type CreateThreadInput = CommandInput<"thread.create">;
|
||||
export type DeleteThreadInput = CommandInput<"thread.delete">;
|
||||
export type ArchiveThreadInput = CommandInput<"thread.archive">;
|
||||
export type UnarchiveThreadInput = CommandInput<"thread.unarchive">;
|
||||
export type SettleThreadInput = CommandInput<"thread.settle">;
|
||||
export type UnsettleThreadInput = CommandInput<"thread.unsettle">;
|
||||
export type UpdateThreadMetadataInput = CommandInput<"thread.meta.update">;
|
||||
export type SetThreadRuntimeModeInput = CommandInput<"thread.runtime-mode.set">;
|
||||
export type SetThreadInteractionModeInput = CommandInput<"thread.interaction-mode.set">;
|
||||
@@ -155,26 +153,6 @@ export const unarchiveThread: (input: UnarchiveThreadInput) => CommandEffect = E
|
||||
});
|
||||
});
|
||||
|
||||
export const settleThread: (input: SettleThreadInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.settleThread",
|
||||
)(function* (input) {
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.settle",
|
||||
commandId: yield* commandId(input),
|
||||
});
|
||||
});
|
||||
|
||||
export const unsettleThread: (input: UnsettleThreadInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.unsettleThread",
|
||||
)(function* (input) {
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.unsettle",
|
||||
commandId: yield* commandId(input),
|
||||
});
|
||||
});
|
||||
|
||||
export const updateThreadMetadata: (input: UpdateThreadMetadataInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.updateThreadMetadata",
|
||||
)(function* (input) {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import {
|
||||
DEFAULT_MODEL,
|
||||
EnvironmentId,
|
||||
ProjectId,
|
||||
CommandId,
|
||||
@@ -140,7 +139,7 @@ describe("add project shared logic", () => {
|
||||
createWorkspaceRootIfMissing: true,
|
||||
defaultModelSelection: {
|
||||
instanceId: "codex",
|
||||
model: DEFAULT_MODEL,
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -96,8 +96,6 @@ const THREAD_SHELL = {
|
||||
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,
|
||||
|
||||
@@ -36,8 +36,6 @@ const stubThread = {
|
||||
createdAt: "2026-04-01T00:00:00.000Z",
|
||||
updatedAt: "2026-04-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
|
||||
@@ -12,11 +12,9 @@ import {
|
||||
type RevertThreadCheckpointInput,
|
||||
type SetThreadInteractionModeInput,
|
||||
type SetThreadRuntimeModeInput,
|
||||
type SettleThreadInput,
|
||||
type StartThreadTurnInput,
|
||||
type StopThreadSessionInput,
|
||||
type UnarchiveThreadInput,
|
||||
type UnsettleThreadInput,
|
||||
type UpdateThreadMetadataInput,
|
||||
archiveThread,
|
||||
createThread,
|
||||
@@ -27,11 +25,9 @@ import {
|
||||
revertThreadCheckpoint,
|
||||
setThreadInteractionMode,
|
||||
setThreadRuntimeMode,
|
||||
settleThread,
|
||||
startThreadTurn,
|
||||
stopThreadSession,
|
||||
unarchiveThread,
|
||||
unsettleThread,
|
||||
updateThreadMetadata,
|
||||
} from "../operations/commands.ts";
|
||||
import type { EnvironmentRegistry } from "../connection/registry.ts";
|
||||
@@ -46,11 +42,9 @@ export type {
|
||||
RevertThreadCheckpointInput,
|
||||
SetThreadInteractionModeInput,
|
||||
SetThreadRuntimeModeInput,
|
||||
SettleThreadInput,
|
||||
StartThreadTurnInput,
|
||||
StopThreadSessionInput,
|
||||
UnarchiveThreadInput,
|
||||
UnsettleThreadInput,
|
||||
UpdateThreadMetadataInput,
|
||||
} from "../operations/commands.ts";
|
||||
|
||||
@@ -88,18 +82,6 @@ export function createThreadEnvironmentAtoms<R, E>(
|
||||
scheduler,
|
||||
concurrency,
|
||||
}),
|
||||
settle: createEnvironmentCommand(runtime, {
|
||||
label: "environment-data:commands:thread:settle",
|
||||
execute: (input: SettleThreadInput) => settleThread(input),
|
||||
scheduler,
|
||||
concurrency,
|
||||
}),
|
||||
unsettle: createEnvironmentCommand(runtime, {
|
||||
label: "environment-data:commands:thread:unsettle",
|
||||
execute: (input: UnsettleThreadInput) => unsettleThread(input),
|
||||
scheduler,
|
||||
concurrency,
|
||||
}),
|
||||
updateMetadata: createEnvironmentCommand(runtime, {
|
||||
label: "environment-data:commands:thread:update-metadata",
|
||||
execute: (input: UpdateThreadMetadataInput) => updateThreadMetadata(input),
|
||||
|
||||
@@ -57,8 +57,6 @@ export function mergeEnvironmentThread(
|
||||
createdAt: shell.createdAt,
|
||||
updatedAt: shell.updatedAt,
|
||||
archivedAt: shell.archivedAt,
|
||||
settledOverride: shell.settledOverride,
|
||||
settledAt: shell.settledAt,
|
||||
session: shell.session,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -34,8 +34,6 @@ const baseThread: OrchestrationThread = {
|
||||
createdAt: "2026-04-01T00:00:00.000Z",
|
||||
updatedAt: "2026-04-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
@@ -166,62 +164,6 @@ describe("applyThreadDetailEvent", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("thread.settled / thread.unsettled", () => {
|
||||
it("sets the settled override and timestamp", () => {
|
||||
const settledAt = "2026-04-01T05:00:00.000Z";
|
||||
const result = applyThreadDetailEvent(baseThread, {
|
||||
...baseEventFields,
|
||||
sequence: 5,
|
||||
occurredAt: settledAt,
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-1"),
|
||||
type: "thread.settled",
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
settledAt,
|
||||
updatedAt: settledAt,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.kind).toBe("updated");
|
||||
if (result.kind === "updated") {
|
||||
expect(result.thread.settledOverride).toBe("settled");
|
||||
expect(result.thread.settledAt).toBe(settledAt);
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
["user", "active"],
|
||||
["activity", null],
|
||||
] as const)("unsettles for %s with override %s", (reason, settledOverride) => {
|
||||
const settledThread: OrchestrationThread = {
|
||||
...baseThread,
|
||||
settledOverride: "settled",
|
||||
settledAt: "2026-04-01T05:00:00.000Z",
|
||||
};
|
||||
const updatedAt = "2026-04-01T06:00:00.000Z";
|
||||
const result = applyThreadDetailEvent(settledThread, {
|
||||
...baseEventFields,
|
||||
sequence: 6,
|
||||
occurredAt: updatedAt,
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-1"),
|
||||
type: "thread.unsettled",
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
reason,
|
||||
updatedAt,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.kind).toBe("updated");
|
||||
if (result.kind === "updated") {
|
||||
expect(result.thread.settledOverride).toBe(settledOverride);
|
||||
expect(result.thread.settledAt).toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("thread.meta-updated", () => {
|
||||
it("patches title and branch", () => {
|
||||
const result = applyThreadDetailEvent(baseThread, {
|
||||
|
||||
@@ -72,8 +72,6 @@ export function applyThreadDetailEvent(
|
||||
createdAt: event.payload.createdAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
@@ -102,28 +100,6 @@ export function applyThreadDetailEvent(
|
||||
thread: { ...thread, archivedAt: null, updatedAt: event.payload.updatedAt },
|
||||
};
|
||||
|
||||
case "thread.settled":
|
||||
return {
|
||||
kind: "updated",
|
||||
thread: {
|
||||
...thread,
|
||||
settledOverride: "settled",
|
||||
settledAt: event.payload.settledAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
},
|
||||
};
|
||||
|
||||
case "thread.unsettled":
|
||||
return {
|
||||
kind: "updated",
|
||||
thread: {
|
||||
...thread,
|
||||
settledOverride: event.payload.reason === "user" ? "active" : null,
|
||||
settledAt: null,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
},
|
||||
};
|
||||
|
||||
// ── Thread metadata ─────────────────────────────────────────────
|
||||
case "thread.meta-updated":
|
||||
return {
|
||||
|
||||
@@ -1,345 +0,0 @@
|
||||
import {
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationThreadShell,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
canSettle,
|
||||
effectiveSettled,
|
||||
hasQueuedTurnStart,
|
||||
threadLastActivityAt,
|
||||
type ChangeRequestStateLike,
|
||||
} from "./threadSettled.ts";
|
||||
|
||||
const NOW = "2026-04-10T00:00:00.000Z";
|
||||
const FRESH = "2026-04-09T00:00:00.000Z";
|
||||
const STALE = "2026-04-06T23:59:59.999Z";
|
||||
|
||||
function makeShell(input: {
|
||||
readonly settledOverride?: "settled" | "active" | null;
|
||||
readonly activityAt: string | null;
|
||||
readonly sessionStatus?: "starting" | "running";
|
||||
readonly pending?: "approval" | "user-input";
|
||||
}): OrchestrationThreadShell {
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
return {
|
||||
id: threadId,
|
||||
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:
|
||||
input.activityAt === null
|
||||
? null
|
||||
: {
|
||||
turnId: TurnId.make("turn-1"),
|
||||
state: "completed",
|
||||
requestedAt: input.activityAt,
|
||||
startedAt: null,
|
||||
completedAt: null,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
createdAt: "2026-04-01T00:00:00.000Z",
|
||||
updatedAt: NOW,
|
||||
archivedAt: null,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledOverride === "settled" ? NOW : null,
|
||||
session:
|
||||
input.sessionStatus === undefined
|
||||
? null
|
||||
: {
|
||||
threadId,
|
||||
status: input.sessionStatus,
|
||||
providerName: "Codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: NOW,
|
||||
},
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: input.pending === "approval",
|
||||
hasPendingUserInput: input.pending === "user-input",
|
||||
hasActionableProposedPlan: false,
|
||||
};
|
||||
}
|
||||
|
||||
describe("threadLastActivityAt", () => {
|
||||
it("returns the latest real user or turn activity and ignores thread/session updates", () => {
|
||||
const shell = makeShell({ activityAt: null, sessionStatus: "running" });
|
||||
const withActivity: OrchestrationThreadShell = {
|
||||
...shell,
|
||||
latestUserMessageAt: "2026-04-04T00:00:00.000Z",
|
||||
latestTurn: {
|
||||
turnId: TurnId.make("turn-1"),
|
||||
state: "completed",
|
||||
requestedAt: "2026-04-03T00:00:00.000Z",
|
||||
startedAt: "2026-04-05T00:00:00.000Z",
|
||||
completedAt: "2026-04-06T00:00:00.000Z",
|
||||
assistantMessageId: null,
|
||||
},
|
||||
};
|
||||
|
||||
expect(threadLastActivityAt(withActivity)).toBe("2026-04-06T00:00:00.000Z");
|
||||
expect(threadLastActivityAt(shell)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("effectiveSettled", () => {
|
||||
const overrideCases = [null, "settled", "active"] as const;
|
||||
const changeRequestStates = [undefined, "open", "merged"] as const;
|
||||
const inactivityCases = [
|
||||
["fresh", FRESH],
|
||||
["stale", STALE],
|
||||
["no-activity", null],
|
||||
] as const;
|
||||
const runningCases = [false, true] as const;
|
||||
const pendingCases = [undefined, "approval", "user-input"] as const;
|
||||
const truthTable = overrideCases.flatMap((settledOverride) =>
|
||||
changeRequestStates.flatMap((changeRequestState) =>
|
||||
inactivityCases.flatMap(([inactivity, activityAt]) =>
|
||||
runningCases.flatMap((running) =>
|
||||
pendingCases.map((pending) => ({
|
||||
settledOverride,
|
||||
changeRequestState,
|
||||
inactivity,
|
||||
activityAt,
|
||||
running,
|
||||
pending,
|
||||
// Settled iff nothing blocks (pending work / live session) AND
|
||||
// the override says settled, or (with no override) a merged PR
|
||||
// or staleness auto-settles. The "active" pin suppresses both
|
||||
// auto signals.
|
||||
expected:
|
||||
pending === undefined &&
|
||||
!running &&
|
||||
(settledOverride === "settled" ||
|
||||
(settledOverride === null &&
|
||||
(changeRequestState === "merged" || inactivity === "stale"))),
|
||||
})),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.each(truthTable)(
|
||||
"override=$settledOverride pr=$changeRequestState inactivity=$inactivity running=$running pending=$pending",
|
||||
({ settledOverride, changeRequestState, activityAt, running, pending, expected }) => {
|
||||
const shell = makeShell({
|
||||
settledOverride,
|
||||
activityAt,
|
||||
...(running ? { sessionStatus: "running" as const } : {}),
|
||||
...(pending === undefined ? {} : { pending }),
|
||||
});
|
||||
const changeRequestOptions =
|
||||
changeRequestState === undefined
|
||||
? {}
|
||||
: { changeRequestState: changeRequestState as ChangeRequestStateLike };
|
||||
|
||||
expect(
|
||||
effectiveSettled(shell, {
|
||||
now: NOW,
|
||||
autoSettleAfterDays: 3,
|
||||
...changeRequestOptions,
|
||||
}),
|
||||
).toBe(expected);
|
||||
},
|
||||
);
|
||||
|
||||
it("treats closed change requests like merged ones", () => {
|
||||
const shell = makeShell({ activityAt: null });
|
||||
expect(
|
||||
effectiveSettled(shell, {
|
||||
now: NOW,
|
||||
autoSettleAfterDays: null,
|
||||
changeRequestState: "closed",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("never settles a starting session, even with a settled override", () => {
|
||||
const shell = makeShell({
|
||||
settledOverride: "settled",
|
||||
activityAt: STALE,
|
||||
sessionStatus: "starting",
|
||||
});
|
||||
expect(
|
||||
effectiveSettled(shell, {
|
||||
now: NOW,
|
||||
autoSettleAfterDays: 3,
|
||||
changeRequestState: "merged",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("uses a strict inactivity boundary and honors a null threshold", () => {
|
||||
const boundary = makeShell({
|
||||
activityAt: "2026-04-07T00:00:00.000Z",
|
||||
});
|
||||
const stale = makeShell({ activityAt: STALE });
|
||||
|
||||
expect(effectiveSettled(boundary, { now: NOW, autoSettleAfterDays: 3 })).toBe(false);
|
||||
expect(effectiveSettled(stale, { now: NOW, autoSettleAfterDays: null })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("hasQueuedTurnStart", () => {
|
||||
const QUEUED_AT = "2026-04-09T12:00:00.000Z";
|
||||
// Within the adoption grace window of the queued message.
|
||||
const JUST_AFTER = { now: "2026-04-09T12:00:30.000Z" };
|
||||
|
||||
it("flags a user message no turn has picked up, within the grace window", () => {
|
||||
const noTurn = { latestUserMessageAt: QUEUED_AT, latestTurn: null, session: null };
|
||||
expect(hasQueuedTurnStart(noTurn, JUST_AFTER)).toBe(true);
|
||||
|
||||
const staleTurn = {
|
||||
...makeShell({ activityAt: FRESH }),
|
||||
latestUserMessageAt: QUEUED_AT,
|
||||
};
|
||||
expect(hasQueuedTurnStart(staleTurn, JUST_AFTER)).toBe(true);
|
||||
});
|
||||
|
||||
it("expires after the grace window: an unadopted message is a failed start, not queued work", () => {
|
||||
const noTurn = { latestUserMessageAt: QUEUED_AT, latestTurn: null, session: null };
|
||||
expect(hasQueuedTurnStart(noTurn, { now: "2026-04-09T12:03:00.000Z" })).toBe(false);
|
||||
// Historical shells (e.g. from servers that never carried latestTurn)
|
||||
// must never read as queued.
|
||||
expect(hasQueuedTurnStart(noTurn, { now: NOW })).toBe(false);
|
||||
});
|
||||
|
||||
it("clears once a turn adopts the message or the start fails", () => {
|
||||
const adopted = {
|
||||
...makeShell({ activityAt: QUEUED_AT }),
|
||||
latestUserMessageAt: QUEUED_AT,
|
||||
};
|
||||
expect(hasQueuedTurnStart(adopted, JUST_AFTER)).toBe(false);
|
||||
|
||||
const failed = makeShell({ activityAt: FRESH });
|
||||
const failedShell = {
|
||||
...failed,
|
||||
latestUserMessageAt: QUEUED_AT,
|
||||
session: {
|
||||
threadId: failed.id,
|
||||
status: "error" as const,
|
||||
providerName: "Codex",
|
||||
runtimeMode: "full-access" as const,
|
||||
activeTurnId: null,
|
||||
lastError: "boom",
|
||||
updatedAt: NOW,
|
||||
},
|
||||
};
|
||||
expect(hasQueuedTurnStart(failedShell, JUST_AFTER)).toBe(false);
|
||||
});
|
||||
|
||||
it("is quiet without user messages", () => {
|
||||
expect(hasQueuedTurnStart(makeShell({ activityAt: FRESH }), JUST_AFTER)).toBe(false);
|
||||
});
|
||||
|
||||
it("bounds the grace window in both directions: a future-stamped message is skew, not queued work", () => {
|
||||
// Message timestamps originate on other devices; a clock an hour ahead
|
||||
// must not hold the queued state for the whole skew.
|
||||
const skewed = {
|
||||
latestUserMessageAt: "2026-04-09T13:00:00.000Z",
|
||||
latestTurn: null,
|
||||
session: null,
|
||||
};
|
||||
expect(hasQueuedTurnStart(skewed, { now: "2026-04-09T12:00:00.000Z" })).toBe(false);
|
||||
// A small negative age (within the grace window) still reads as queued.
|
||||
const slightlyAhead = {
|
||||
latestUserMessageAt: "2026-04-09T12:00:30.000Z",
|
||||
latestTurn: null,
|
||||
session: null,
|
||||
};
|
||||
expect(hasQueuedTurnStart(slightlyAhead, { now: "2026-04-09T12:00:00.000Z" })).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("canSettle", () => {
|
||||
it("blocks every state effectiveSettled refuses to classify as settled", () => {
|
||||
expect(canSettle(makeShell({ activityAt: FRESH }), { now: NOW })).toBe(true);
|
||||
expect(
|
||||
canSettle(makeShell({ activityAt: FRESH, sessionStatus: "starting" }), { now: NOW }),
|
||||
).toBe(false);
|
||||
expect(
|
||||
canSettle(makeShell({ activityAt: FRESH, sessionStatus: "running" }), { now: NOW }),
|
||||
).toBe(false);
|
||||
expect(canSettle(makeShell({ activityAt: FRESH, pending: "approval" }), { now: NOW })).toBe(
|
||||
false,
|
||||
);
|
||||
expect(canSettle(makeShell({ activityAt: FRESH, pending: "user-input" }), { now: NOW })).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("blocks settling a queued turn start, only within the grace window", () => {
|
||||
const queued = {
|
||||
...makeShell({ activityAt: FRESH }),
|
||||
latestUserMessageAt: "2026-04-09T12:00:00.000Z",
|
||||
};
|
||||
const justAfter = "2026-04-09T12:00:30.000Z";
|
||||
expect(canSettle(queued, { now: justAfter })).toBe(false);
|
||||
// effectiveSettled must agree: queued work never auto-settles either,
|
||||
// even with a merged PR.
|
||||
expect(
|
||||
effectiveSettled(queued, {
|
||||
now: justAfter,
|
||||
autoSettleAfterDays: 3,
|
||||
changeRequestState: "merged",
|
||||
}),
|
||||
).toBe(false);
|
||||
// Past the window the message is a failed/stale start: settleable again.
|
||||
expect(canSettle(queued, { now: NOW })).toBe(true);
|
||||
});
|
||||
|
||||
it("lets a server-accepted settle overrule the clock-derived queued blocker", () => {
|
||||
// The settle action ran with wall-clock `now` (past the grace window);
|
||||
// the list partition re-evaluates with a minute-floored `now` that is
|
||||
// still INSIDE the window. settledAt >= message time proves the server
|
||||
// already adjudicated this exact message, so the row must not snap back
|
||||
// to active until the coarser clock catches up.
|
||||
const messageAt = "2026-04-09T12:00:00.000Z";
|
||||
const flooredNow = "2026-04-09T12:01:00.000Z";
|
||||
const base = makeShell({ settledOverride: "settled", activityAt: null });
|
||||
const settledAfterMessage = {
|
||||
...base,
|
||||
latestUserMessageAt: messageAt,
|
||||
settledAt: "2026-04-09T12:02:10.000Z",
|
||||
};
|
||||
expect(hasQueuedTurnStart(settledAfterMessage, { now: flooredNow })).toBe(true);
|
||||
expect(effectiveSettled(settledAfterMessage, { now: flooredNow, autoSettleAfterDays: 3 })).toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
// A message NEWER than settledAt is genuinely new work: still blocked
|
||||
// until the server's auto-unsettle lands.
|
||||
const messageAfterSettle = {
|
||||
...base,
|
||||
latestUserMessageAt: "2026-04-09T12:03:00.000Z",
|
||||
settledAt: "2026-04-09T12:02:10.000Z",
|
||||
};
|
||||
expect(
|
||||
effectiveSettled(messageAfterSettle, {
|
||||
now: "2026-04-09T12:03:30.000Z",
|
||||
autoSettleAfterDays: 3,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("agrees with effectiveSettled's blockers for explicitly settled shells", () => {
|
||||
// Anything canSettle rejects must render as active even when the user
|
||||
// settled it earlier.
|
||||
const blocked = makeShell({
|
||||
settledOverride: "settled",
|
||||
activityAt: FRESH,
|
||||
pending: "user-input",
|
||||
});
|
||||
expect(canSettle(blocked, { now: NOW })).toBe(false);
|
||||
expect(effectiveSettled(blocked, { now: NOW, autoSettleAfterDays: 3 })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,147 +0,0 @@
|
||||
import type { OrchestrationThreadShell } from "@t3tools/contracts";
|
||||
|
||||
export type ChangeRequestStateLike = "open" | "closed" | "merged";
|
||||
|
||||
const DAY_MS = 24 * 60 * 60 * 1_000;
|
||||
|
||||
export function threadLastActivityAt(shell: OrchestrationThreadShell): string | null {
|
||||
const candidates = [
|
||||
shell.latestUserMessageAt,
|
||||
shell.latestTurn?.requestedAt,
|
||||
shell.latestTurn?.startedAt,
|
||||
shell.latestTurn?.completedAt,
|
||||
];
|
||||
let latest: string | null = null;
|
||||
let latestTimestamp = Number.NEGATIVE_INFINITY;
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (candidate === null || candidate === undefined) continue;
|
||||
const timestamp = Date.parse(candidate);
|
||||
if (timestamp > latestTimestamp) {
|
||||
latest = candidate;
|
||||
latestTimestamp = timestamp;
|
||||
}
|
||||
}
|
||||
|
||||
return latest;
|
||||
}
|
||||
|
||||
/**
|
||||
* A queued turn start lives for at most this long: session adoption takes
|
||||
* seconds, so a user message still unadopted after the grace window is a
|
||||
* failed start (or stale data — shells from older servers can carry user
|
||||
* messages with no latestTurn at all), not pending work. Without this bound
|
||||
* such threads would be permanently unsettleable.
|
||||
*/
|
||||
export const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;
|
||||
|
||||
/**
|
||||
* A user message no turn has picked up yet: the turn.start command was
|
||||
* dispatched (message-sent + turn-start-requested) but no session has
|
||||
* adopted it, so `session` is still null and the pending work is invisible
|
||||
* to the session-status checks. Detectable as a user message strictly newer
|
||||
* than every timestamp on the latest turn — on adoption the new turn's
|
||||
* requestedAt equals the message time, clearing the condition — and only
|
||||
* within the adoption grace window.
|
||||
*/
|
||||
export function hasQueuedTurnStart(
|
||||
shell: Pick<OrchestrationThreadShell, "latestUserMessageAt" | "latestTurn" | "session">,
|
||||
options: { readonly now: string },
|
||||
): boolean {
|
||||
if (shell.latestUserMessageAt == null) return false;
|
||||
// A failed session start clears the queued state: the failure is already
|
||||
// visible (status edge / error).
|
||||
if (shell.session?.status === "error") return false;
|
||||
const messageAt = Date.parse(shell.latestUserMessageAt);
|
||||
if (Number.isNaN(messageAt)) return false;
|
||||
const nowMs = Date.parse(options.now);
|
||||
if (Number.isNaN(nowMs)) return false;
|
||||
// Bounded on both sides: message timestamps originate on whichever device
|
||||
// sent the message, so a clock ahead of this one yields a negative age
|
||||
// that would otherwise hold the queued state for the whole skew. Mirrors
|
||||
// the decider's guard.
|
||||
if (Math.abs(nowMs - messageAt) > QUEUED_TURN_START_GRACE_MS) return false;
|
||||
const turn = shell.latestTurn;
|
||||
if (turn === null) return true;
|
||||
return [turn.requestedAt, turn.startedAt, turn.completedAt].every(
|
||||
(candidate) => candidate == null || Date.parse(candidate) < messageAt,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A thread may be settled only when none of effectiveSettled's activity
|
||||
* blockers hold. This is deliberately the same list: anything the partition
|
||||
* refuses to CLASSIFY as settled must also be refused as a settle TARGET.
|
||||
* The server enforces its own invariants; this client-side twin exists so
|
||||
* the UI can disable/reject before a round trip.
|
||||
*/
|
||||
export function canSettle(
|
||||
shell: Pick<
|
||||
OrchestrationThreadShell,
|
||||
"hasPendingApprovals" | "hasPendingUserInput" | "session" | "latestUserMessageAt" | "latestTurn"
|
||||
>,
|
||||
options: { readonly now: string },
|
||||
): boolean {
|
||||
if (shell.hasPendingApprovals || shell.hasPendingUserInput) return false;
|
||||
if (shell.session?.status === "starting" || shell.session?.status === "running") return false;
|
||||
// Queued work is as blocked-on-progress as a live session: settling it
|
||||
// (or auto-settling it on a closed PR) would hide a just-requested turn.
|
||||
if (hasQueuedTurnStart(shell, options)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Settled resolution over the server-backed settled lifecycle. The explicit
|
||||
* user override (thread.settle / thread.unsettle commands, projected into
|
||||
* settledOverride + settledAt) wins in both directions; without one, a
|
||||
* thread auto-settles on a merged/closed PR or inactivity past the window.
|
||||
* The server un-settles on real activity (user message, session start,
|
||||
* approval/user-input request), so an override never goes stale silently.
|
||||
*/
|
||||
export function effectiveSettled(
|
||||
shell: OrchestrationThreadShell,
|
||||
options: {
|
||||
readonly now: string;
|
||||
readonly autoSettleAfterDays: number | null;
|
||||
readonly changeRequestState?: ChangeRequestStateLike | null;
|
||||
},
|
||||
): boolean {
|
||||
// Blocked work must remain visible even when a user explicitly settled it.
|
||||
if (shell.hasPendingApprovals || shell.hasPendingUserInput) return false;
|
||||
if (shell.session?.status === "starting" || shell.session?.status === "running") return false;
|
||||
if (hasQueuedTurnStart(shell, { now: options.now })) {
|
||||
// The queued-turn blocker alone is forgivable: it is clock-derived, and
|
||||
// list callers pass a coarser `now` than the settle action used. When
|
||||
// the server already adjudicated the queued message by accepting a
|
||||
// settle after it (settledAt stamps server accept time), trust that
|
||||
// ruling — otherwise a settle near the grace boundary leaves the row
|
||||
// pinned active until the caller's clock ticks over. A message NEWER
|
||||
// than settledAt is genuinely new work and keeps the block until the
|
||||
// server's auto-unsettle lands.
|
||||
const serverAdjudicated =
|
||||
shell.settledOverride === "settled" &&
|
||||
shell.settledAt !== null &&
|
||||
shell.latestUserMessageAt !== null &&
|
||||
Date.parse(shell.settledAt) >= Date.parse(shell.latestUserMessageAt);
|
||||
if (!serverAdjudicated) return false;
|
||||
}
|
||||
if (shell.settledOverride === "settled") return true;
|
||||
// "active" is the explicit keep-active pin: it suppresses auto-settle
|
||||
// until real activity clears it server-side.
|
||||
if (shell.settledOverride === "active") return false;
|
||||
if (options.changeRequestState === "merged" || options.changeRequestState === "closed") {
|
||||
return true;
|
||||
}
|
||||
if (options.autoSettleAfterDays === null) return false;
|
||||
|
||||
const lastActivityAt = threadLastActivityAt(shell);
|
||||
if (lastActivityAt === null) return false;
|
||||
|
||||
// threadLastActivityAt only returns candidates whose Date.parse beat
|
||||
// -Infinity, so this parse is a real number; a malformed `now` yields NaN,
|
||||
// the comparison is false, and the thread stays active (never a surprise
|
||||
// auto-settle on bad input).
|
||||
return (
|
||||
Date.parse(lastActivityAt) < Date.parse(options.now) - options.autoSettleAfterDays * DAY_MS
|
||||
);
|
||||
}
|
||||
@@ -69,8 +69,6 @@ const BASE_THREAD: OrchestrationThread = {
|
||||
createdAt: "2026-04-01T00:00:00.000Z",
|
||||
updatedAt: "2026-04-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
|
||||
@@ -23,10 +23,6 @@ export type ExecutionEnvironmentPlatform = typeof ExecutionEnvironmentPlatform.T
|
||||
export const ExecutionEnvironmentCapabilities = Schema.Struct({
|
||||
repositoryIdentity: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
|
||||
connectionProbe: Schema.optionalKey(Schema.Boolean),
|
||||
/** Server understands thread.settle / thread.unsettle commands. Absent on
|
||||
pre-settlement servers, so clients treat missing as unsupported and
|
||||
never send the commands under version skew. */
|
||||
threadSettlement: Schema.optionalKey(Schema.Boolean),
|
||||
});
|
||||
export type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type;
|
||||
|
||||
|
||||
@@ -133,18 +133,8 @@ const CURSOR_DRIVER_KIND = ProviderDriverKind.make("cursor");
|
||||
const GROK_DRIVER_KIND = ProviderDriverKind.make("grok");
|
||||
const OPENCODE_DRIVER_KIND = ProviderDriverKind.make("opencode");
|
||||
|
||||
export const DEFAULT_MODEL = "gpt-5.6-sol";
|
||||
|
||||
/**
|
||||
* Codex default-model preference, most preferred first. The provider snapshot
|
||||
* marks the first of these present in the live `model/list` response as
|
||||
* default; when none are available, Codex's own `isDefault` flag wins.
|
||||
*/
|
||||
export const PREFERRED_DEFAULT_CODEX_MODELS: ReadonlyArray<string> = [
|
||||
"gpt-5.6-sol",
|
||||
"gpt-5.6-terra",
|
||||
];
|
||||
export const DEFAULT_GIT_TEXT_GENERATION_MODEL = "gpt-5.6-luna";
|
||||
export const DEFAULT_MODEL = "gpt-5.4";
|
||||
export const DEFAULT_GIT_TEXT_GENERATION_MODEL = "gpt-5.4-mini";
|
||||
|
||||
export const DEFAULT_MODEL_BY_PROVIDER: Partial<Record<ProviderDriverKind, string>> = {
|
||||
[CODEX_DRIVER_KIND]: DEFAULT_MODEL,
|
||||
|
||||
@@ -15,8 +15,6 @@ import {
|
||||
ProjectMetaUpdatedPayload,
|
||||
OrchestrationProposedPlan,
|
||||
OrchestrationSession,
|
||||
OrchestrationThread,
|
||||
OrchestrationThreadShell,
|
||||
ProjectCreateCommand,
|
||||
ThreadMetaUpdatedPayload,
|
||||
ThreadTurnStartCommand,
|
||||
@@ -39,8 +37,6 @@ const decodeThreadTurnStartRequestedPayload = Schema.decodeUnknownEffect(
|
||||
const decodeOrchestrationLatestTurn = Schema.decodeUnknownEffect(OrchestrationLatestTurn);
|
||||
const decodeOrchestrationProposedPlan = Schema.decodeUnknownEffect(OrchestrationProposedPlan);
|
||||
const decodeOrchestrationSession = Schema.decodeUnknownEffect(OrchestrationSession);
|
||||
const decodeOrchestrationThread = Schema.decodeUnknownEffect(OrchestrationThread);
|
||||
const decodeOrchestrationThreadShell = Schema.decodeUnknownEffect(OrchestrationThreadShell);
|
||||
const encodeThreadCreatedPayload = Schema.encodeEffect(ThreadCreatedPayload);
|
||||
|
||||
function getOptionValue(
|
||||
@@ -348,75 +344,6 @@ it.effect("decodes thread archive and unarchive commands", () =>
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes thread settle and unsettle commands", () =>
|
||||
Effect.gen(function* () {
|
||||
const settle = yield* decodeOrchestrationCommand({
|
||||
type: "thread.settle",
|
||||
commandId: "cmd-settle-1",
|
||||
threadId: "thread-1",
|
||||
});
|
||||
const unsettle = yield* decodeOrchestrationCommand({
|
||||
type: "thread.unsettle",
|
||||
commandId: "cmd-unsettle-1",
|
||||
threadId: "thread-1",
|
||||
reason: "user",
|
||||
});
|
||||
|
||||
assert.strictEqual(settle.type, "thread.settle");
|
||||
assert.strictEqual(unsettle.type, "thread.unsettle");
|
||||
|
||||
// "activity" is server-owned: it exists on the event, never on the
|
||||
// command, so a client cannot forge the neutral reset.
|
||||
const forged = yield* decodeOrchestrationCommand({
|
||||
type: "thread.unsettle",
|
||||
commandId: "cmd-unsettle-2",
|
||||
threadId: "thread-1",
|
||||
reason: "activity",
|
||||
}).pipe(Effect.flip);
|
||||
assert.ok(forged);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("defaults settled fields when decoding historical thread data", () =>
|
||||
Effect.gen(function* () {
|
||||
const common = {
|
||||
id: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "Historical thread",
|
||||
modelSelection: { provider: "codex", model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
session: null,
|
||||
};
|
||||
const thread = yield* decodeOrchestrationThread({
|
||||
...common,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
});
|
||||
const shell = yield* decodeOrchestrationThreadShell({
|
||||
...common,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
});
|
||||
|
||||
assert.strictEqual(thread.settledOverride, null);
|
||||
assert.strictEqual(thread.settledAt, null);
|
||||
assert.strictEqual(shell.settledOverride, null);
|
||||
assert.strictEqual(shell.settledAt, null);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes thread archived and unarchived events", () =>
|
||||
Effect.gen(function* () {
|
||||
const archived = yield* decodeOrchestrationEvent({
|
||||
@@ -461,48 +388,6 @@ it.effect("decodes thread archived and unarchived events", () =>
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes thread settled and unsettled events", () =>
|
||||
Effect.gen(function* () {
|
||||
const settled = yield* decodeOrchestrationEvent({
|
||||
sequence: 1,
|
||||
eventId: "event-settle-1",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
type: "thread.settled",
|
||||
occurredAt: "2026-01-01T00:00:00.000Z",
|
||||
commandId: "cmd-settle-1",
|
||||
causationEventId: null,
|
||||
correlationId: "cmd-settle-1",
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
settledAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
},
|
||||
});
|
||||
const unsettled = yield* decodeOrchestrationEvent({
|
||||
sequence: 2,
|
||||
eventId: "event-unsettle-1",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
type: "thread.unsettled",
|
||||
occurredAt: "2026-01-02T00:00:00.000Z",
|
||||
commandId: "cmd-unsettle-1",
|
||||
causationEventId: null,
|
||||
correlationId: "cmd-unsettle-1",
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
reason: "user",
|
||||
updatedAt: "2026-01-02T00:00:00.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
assert.strictEqual(settled.type, "thread.settled");
|
||||
assert.strictEqual(unsettled.type, "thread.unsettled");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("accepts provider-scoped model options in thread.turn.start", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeThreadTurnStartCommand({
|
||||
|
||||
@@ -356,10 +356,6 @@ export const OrchestrationThread = Schema.Struct({
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
archivedAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
|
||||
settledOverride: Schema.NullOr(Schema.Literals(["settled", "active"])).pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(null)),
|
||||
),
|
||||
settledAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
|
||||
deletedAt: Schema.NullOr(IsoDateTime),
|
||||
messages: Schema.Array(OrchestrationMessage),
|
||||
proposedPlans: Schema.Array(OrchestrationProposedPlan).pipe(
|
||||
@@ -406,13 +402,8 @@ export const OrchestrationThreadShell = Schema.Struct({
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
archivedAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
|
||||
settledOverride: Schema.NullOr(Schema.Literals(["settled", "active"])).pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(null)),
|
||||
),
|
||||
settledAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
|
||||
session: Schema.NullOr(OrchestrationSession),
|
||||
latestUserMessageAt: Schema.NullOr(IsoDateTime),
|
||||
hasPendingTurnStart: Schema.optional(Schema.Boolean),
|
||||
hasPendingApprovals: Schema.Boolean,
|
||||
hasPendingUserInput: Schema.Boolean,
|
||||
hasActionableProposedPlan: Schema.Boolean,
|
||||
@@ -567,22 +558,6 @@ const ThreadUnarchiveCommand = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
});
|
||||
|
||||
const ThreadSettleCommand = Schema.Struct({
|
||||
type: Schema.Literal("thread.settle"),
|
||||
commandId: CommandId,
|
||||
threadId: ThreadId,
|
||||
});
|
||||
|
||||
const ThreadUnsettleCommand = Schema.Struct({
|
||||
type: Schema.Literal("thread.unsettle"),
|
||||
commandId: CommandId,
|
||||
threadId: ThreadId,
|
||||
// Commands only carry "user": activity un-settles are decided server-side
|
||||
// (the decider emits thread.unsettled(reason: "activity") events directly,
|
||||
// never through this command), so a client cannot forge the neutral reset.
|
||||
reason: Schema.Literal("user"),
|
||||
});
|
||||
|
||||
const ThreadMetaUpdateCommand = Schema.Struct({
|
||||
type: Schema.Literal("thread.meta.update"),
|
||||
commandId: CommandId,
|
||||
@@ -725,8 +700,6 @@ const DispatchableClientOrchestrationCommand = Schema.Union([
|
||||
ThreadDeleteCommand,
|
||||
ThreadArchiveCommand,
|
||||
ThreadUnarchiveCommand,
|
||||
ThreadSettleCommand,
|
||||
ThreadUnsettleCommand,
|
||||
ThreadMetaUpdateCommand,
|
||||
ThreadRuntimeModeSetCommand,
|
||||
ThreadInteractionModeSetCommand,
|
||||
@@ -748,8 +721,6 @@ export const ClientOrchestrationCommand = Schema.Union([
|
||||
ThreadDeleteCommand,
|
||||
ThreadArchiveCommand,
|
||||
ThreadUnarchiveCommand,
|
||||
ThreadSettleCommand,
|
||||
ThreadUnsettleCommand,
|
||||
ThreadMetaUpdateCommand,
|
||||
ThreadRuntimeModeSetCommand,
|
||||
ThreadInteractionModeSetCommand,
|
||||
@@ -852,8 +823,6 @@ export const OrchestrationEventType = Schema.Literals([
|
||||
"thread.deleted",
|
||||
"thread.archived",
|
||||
"thread.unarchived",
|
||||
"thread.settled",
|
||||
"thread.unsettled",
|
||||
"thread.meta-updated",
|
||||
"thread.runtime-mode-set",
|
||||
"thread.interaction-mode-set",
|
||||
@@ -933,18 +902,6 @@ export const ThreadUnarchivedPayload = Schema.Struct({
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
|
||||
export const ThreadSettledPayload = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
settledAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
|
||||
export const ThreadUnsettledPayload = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
reason: Schema.Literals(["user", "activity"]),
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
|
||||
export const ThreadMetaUpdatedPayload = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
title: Schema.optional(TrimmedNonEmptyString),
|
||||
@@ -1112,16 +1069,6 @@ export const OrchestrationEvent = Schema.Union([
|
||||
type: Schema.Literal("thread.unarchived"),
|
||||
payload: ThreadUnarchivedPayload,
|
||||
}),
|
||||
Schema.Struct({
|
||||
...EventBaseFields,
|
||||
type: Schema.Literal("thread.settled"),
|
||||
payload: ThreadSettledPayload,
|
||||
}),
|
||||
Schema.Struct({
|
||||
...EventBaseFields,
|
||||
type: Schema.Literal("thread.unsettled"),
|
||||
payload: ThreadUnsettledPayload,
|
||||
}),
|
||||
Schema.Struct({
|
||||
...EventBaseFields,
|
||||
type: Schema.Literal("thread.meta-updated"),
|
||||
|
||||
Loaded 100 of 103 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user