feat(web): generate and preserve thread handover drafts #8857
Closedsaphid(GitHub profile, opens in a new tab)wants to merge 3 commits into
main fromrefs/pull/8857/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/web/src/components/ChatView.tsx lines 5025 to 5027OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -4939,0 +5007,21 @@5007+ generateThreadHandover,5008+ handleNewThread,5009+ isGeneratingHandover,5010+ isServerThread,5011+ ]);5012+ const contextLimitBannerItem = useMemo<ComposerBannerStackItem | null>(() => {5013+ if (!activeThreadReachedContextLimit || !activeThread) return null;5014+ const supportsGeneration =5015+ serverConfig?.environment.capabilities.threadHandoverGeneration === true;5016+ return {5017+ id: `context-limit:${activeThread.id}`,5018+ variant: "warning",5019+ urgent: true,5020+ icon: <AlertTriangleIcon />,5021+ title: `This thread has reached ${MAX_CONTEXT_TOKENS_PER_THREAD.toLocaleString("en-US")} tokens`,5022+ description: supportsGeneration5023+ ? "T3 will not start another turn here. Create a compact handover, then review it in a new draft before choosing the next model and reasoning level."5024+ : "T3 will not start another turn here. Update the connected server to create an automatic handover, or start a new thread manually.",5025+ className:5026+ "py-4 text-base [&_[data-slot=alert-title]]:text-lg [&_[data-slot=alert-title]]:leading-6 [&_[data-slot=alert-description]]:text-sm [&_[data-slot=alert-description]]:leading-5",5027+ actionClassName: "self-start",
- apps/web/src/components/usage/usageBudget.ts line 27OutdatedResolvedby saphid(GitHub profile, opens in a new tab)@@ -0,0 +7,21 @@7+8+export type UsageBudgetLevel = "warn" | "approval" | "pause";9+10+export interface UsageBudgetAlert {11+ readonly day: string;12+ readonly level: UsageBudgetLevel;13+ readonly kind: "claude" | "apiEquivalent";14+ readonly valueUsd: number;15+ readonly thresholdUsd: number;16+}17+18+const LEVELS = ["warn", "approval", "pause"] as const;19+const LEVEL_RANK: Record<UsageBudgetLevel, number> = { warn: 0, approval: 1, pause: 2 };20+21+function crossed(22+ valueUsd: number,23+ thresholds: Readonly<Record<UsageBudgetLevel, number>>,24+): { readonly level: UsageBudgetLevel; readonly thresholdUsd: number } | null {25+ let result: { readonly level: UsageBudgetLevel; readonly thresholdUsd: number } | null = null;26+ for (const level of LEVELS) {27+ if (valueUsd >= thresholds[level]) result = { level, thresholdUsd: thresholds[level] };apps/web/src/components/ChatView.tsx line 5955Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -4939,0 +4968,21 @@4968+ toastManager.add(4969+ stackedThreadToast({4970+ type: "error",4971+ title: "Could not create handover",4972+ description: error instanceof Error ? error.message : "Handover generation failed.",4973+ }),4974+ );4975+ }4976+ return;4977+ }4978+4979+ const opened = await handleNewThread(4980+ scopeProjectRef(activeThread.environmentId, activeProject.id),4981+ {4982+ branch: activeThread.branch,4983+ worktreePath: activeThread.worktreePath,4984+ envMode: activeThread.worktreePath ? "worktree" : "local",4985+ startFromOrigin: false,4986+ },4987+ );4988+ if (opened === null) {apps/web/src/components/ChatView.tsx line 5937Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -4939,0 +4957,21 @@4957+ return;4958+ }4959+ setIsGeneratingHandover(true);4960+ try {4961+ const result = await generateThreadHandover({4962+ environmentId: activeThread.environmentId,4963+ input: { threadId: activeThread.id },4964+ });4965+ if (result._tag === "Failure") {4966+ if (!isAtomCommandInterrupted(result)) {4967+ const error = squashAtomCommandFailure(result);4968+ toastManager.add(4969+ stackedThreadToast({4970+ type: "error",4971+ title: "Could not create handover",4972+ description: error instanceof Error ? error.message : "Handover generation failed.",4973+ }),4974+ );4975+ }4976+ return;4977+ }apps/server/src/ws.ts line 1357OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1318,0 +1337,21 @@1337+ ),1338+ onSome: Effect.succeed,1339+ }),1340+ ),1341+ );1342+ const project = yield* projectionSnapshotQuery1343+ .getProjectShellById(thread.projectId)1344+ .pipe(1345+ Effect.flatMap(1346+ Option.match({1347+ onNone: () =>1348+ Effect.fail(1349+ new OrchestrationGenerateHandoverError({1350+ message: `Project '${thread.projectId}' was not found.`,1351+ }),1352+ ),1353+ onSome: Effect.succeed,1354+ }),1355+ ),1356+ );1357+ return yield* providerRegistry.generateHandover({
- apps/server/src/ws.ts lines 1476 to 1479Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1318,0 +1352,21 @@1352+ ),1353+ onSome: Effect.succeed,1354+ }),1355+ ),1356+ );1357+ return yield* providerRegistry.generateHandover({1358+ cwd: thread.worktreePath ?? project.workspaceRoot,1359+ threadContents: formatThreadForHandover(thread),1360+ modelSelection: HANDOVER_MODEL_SELECTION,1361+ });1362+ }).pipe(1363+ Effect.mapError((cause) =>1364+ isOrchestrationGenerateHandoverError(cause)1365+ ? cause1366+ : new OrchestrationGenerateHandoverError({1367+ message:1368+ cause instanceof Error1369+ ? cause.message1370+ : "Failed to generate a thread handover.",1371+ cause,1372+ }),apps/server/src/provider/Services/ProviderRegistry.ts lines 24 to 25OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -16,7 +16,10 @@1616 import type * as Effect from "effect/Effect";1717 import type * as Stream from "effect/Stream";1818 import type { ProviderMaintenanceCapabilities } from "../providerMaintenance.ts";19+import type * as TextGeneration from "../../textGeneration/TextGeneration.ts";19202021 export type ProviderMaintenanceActionKind = "update";21222223 export interface ProviderRegistryShape {24+ /** Run handover text generation through the selected provider instance. */25+ readonly generateHandover: TextGeneration.TextGeneration["Service"]["generateHandover"];
- apps/server/src/orchestration/ThreadHandover.ts line 22OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +2,21 @@2+ DEFAULT_TEXT_GENERATION_MODEL,3+ ProviderInstanceId,4+ type ModelSelection,5+ type OrchestrationThread,6+} from "@t3tools/contracts";7+8+export const HANDOVER_MODEL_SELECTION: ModelSelection = {9+ instanceId: ProviderInstanceId.make("codex"),10+ model: DEFAULT_TEXT_GENERATION_MODEL,11+ options: [{ id: "reasoningEffort", value: "high" }],12+};13+14+export function formatThreadForHandover(thread: OrchestrationThread): string {15+ const metadata = [16+ `Title: ${thread.title}`,17+ `Branch: ${thread.branch ?? "none"}`,18+ `Worktree: ${thread.worktreePath ?? "project checkout"}`,19+ ];20+ const messages = thread.messages.map(21+ (message) => `## ${message.role === "user" ? "User" : "Assistant"}\n\n${message.text}`,22+ );apps/web/src/components/ChatView.tsx line 4991OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -4939,0 +4971,21 @@4971+ title: "Could not create handover",4972+ description: error instanceof Error ? error.message : "Handover generation failed.",4973+ }),4974+ );4975+ }4976+ return;4977+ }4978+4979+ const opened = await handleNewThread(4980+ scopeProjectRef(activeThread.environmentId, activeProject.id),4981+ {4982+ branch: activeThread.branch,4983+ worktreePath: activeThread.worktreePath,4984+ envMode: activeThread.worktreePath ? "worktree" : "local",4985+ startFromOrigin: false,4986+ },4987+ );4988+ if (opened === null) {4989+ throw new Error("The replacement draft could not be opened.");4990+ }4991+ useComposerDraftStore.getState().setPrompt(opened.draftId, result.value.handover);
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/environment/ServerEnvironment.ts lines 83 to 90OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -76,3 +80,11 @@7680 const crypto = yield* Crypto.Crypto;7781 const hostPlatform = yield* HostProcessPlatform;7882 const hostArchitecture = yield* HostProcessArchitecture;83+ const providerInstanceRegistry = yield* Effect.context<never>().pipe(84+ Effect.map((context) =>85+ Context.getOption(86+ context as Context.Context<never>,87+ ProviderInstanceRegistry.ProviderInstanceRegistry,88+ ),89+ ),90+ );apps/server/src/ws.ts lines 518 to 529OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -505,3 +515,15 @@505515 const portDiscovery = yield* PortScanner.PortDiscovery;506516 const providerRegistry = yield* ProviderRegistry.ProviderRegistry;507517 const providerService = yield* ProviderService.ProviderService;518+ const optionalServices = yield* Effect.context<never>().pipe(519+ Effect.map((context) => ({520+ providerInstanceRegistry: Context.getOption(521+ context as Context.Context<never>,522+ ProviderInstanceRegistry.ProviderInstanceRegistry,523+ ),524+ textGeneration: Context.getOption(525+ context as Context.Context<never>,526+ TextGeneration.TextGeneration,527+ ),528+ })),529+ );
- apps/mobile/src/features/threads/ThreadRouteScreen.tsx line 822OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -761,0 +802,21 @@802+ environmentId: selectedThread.environmentId,803+ input: { threadId: selectedThread.id },804+ });805+ if (result._tag === "Failure") {806+ Alert.alert("Could not create handover", "Handover generation failed. Try again.");807+ return;808+ }809+ handover = result.value.handover;810+ pendingMobileHandovers.set(sourceThreadKey, handover);811+ }812+ if (selectedThreadKeyRef.current !== sourceThreadKey) return;813+ navigation.navigate("NewTaskSheet", {814+ screen: "NewTaskDraft",815+ params: {816+ environmentId: String(selectedThread.environmentId),817+ projectId: String(selectedThread.projectId),818+ title: selectedThreadProject.title,819+ initialPrompt: handover,820+ },821+ });822+ pendingMobileHandovers.delete(sourceThreadKey);apps/mobile/src/features/threads/ThreadRouteScreen.tsx line 819OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -761,0 +799,21 @@799+ let handover = pendingMobileHandovers.get(sourceThreadKey);800+ if (handover === undefined) {801+ const result = await generateThreadHandover({802+ environmentId: selectedThread.environmentId,803+ input: { threadId: selectedThread.id },804+ });805+ if (result._tag === "Failure") {806+ Alert.alert("Could not create handover", "Handover generation failed. Try again.");807+ return;808+ }809+ handover = result.value.handover;810+ pendingMobileHandovers.set(sourceThreadKey, handover);811+ }812+ if (selectedThreadKeyRef.current !== sourceThreadKey) return;813+ navigation.navigate("NewTaskSheet", {814+ screen: "NewTaskDraft",815+ params: {816+ environmentId: String(selectedThread.environmentId),817+ projectId: String(selectedThread.projectId),818+ title: selectedThreadProject.title,819+ initialPrompt: handover,apps/mobile/src/features/threads/ThreadDetailScreen.tsx line 150Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -116,3 +116,4 @@116116 readonly threadCwd: string | null;117117 readonly selectedThreadQueueCount: number;118118 readonly serverConfig: T3ServerConfig | null;119+ readonly contextLimitReached: boolean;apps/mobile/src/features/threads/ThreadRouteScreen.tsx line 1022Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -761,0 +820,21 @@820+ },821+ });822+ pendingMobileHandovers.delete(sourceThreadKey);823+ } finally {824+ generatingMobileHandovers.delete(sourceThreadKey);825+ setHandoverStateVersion((version) => version + 1);826+ }827+ }, [828+ currentThreadKey,829+ generateThreadHandover,830+ navigation,831+ selectedThread,832+ selectedThreadDetail,833+ selectedThreadProject,834+ serverConfig?.environment.capabilities.threadHandoverGeneration,835+ ]);836+ const contextLimitReached =837+ selectedThreadDetail !== null &&838+ threadContextReachedLimit(839+ selectedThreadDetail.activities,840+ serverConfig?.settings.threadContextTokenLimit,apps/server/src/orchestration/UsageLimitPolicy.ts line 84OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +64,21 @@64+65+function isRunningSession(session: ProviderSession): boolean {66+ return session.status === "connecting" || session.status === "running";67+}68+69+export function evaluateTurnStartLimits(input: {70+ readonly threadId: ThreadId;71+ readonly contextTokenLimit?: number;72+ readonly activities: ReadonlyArray<OrchestrationThreadActivity>;73+ readonly sessions: ReadonlyArray<ProviderSession>;74+ readonly reservedTurnThreadIds?: ReadonlyArray<ThreadId>;75+}): UsageLimitViolation | undefined {76+ const contextViolation = contextLimitViolation(input);77+ if (contextViolation) return contextViolation;78+79+ const currentThreadIsRunning =80+ input.sessions.some(81+ (session) => session.threadId === input.threadId && isRunningSession(session),82+ ) || input.reservedTurnThreadIds?.includes(input.threadId) === true;83+ const runningTurnCount =84+ input.sessions.filter(isRunningSession).length + (input.reservedTurnThreadIds?.length ?? 0);apps/mobile/src/state/use-thread-composer-state.ts line 305OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -181,3 +199,4 @@181199 if (text.length === 0 && attachments.length === 0) {182200 return null;183201 }202+ if (apps/mobile/src/features/threads/ThreadRouteScreen.tsx line 120Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -83,3 +86,5 @@83868487 type NativeHeaderItems = ReadonlyArray<Record<string, unknown>>;858889+const pendingMobileHandovers = new Map<string, string>();90+const generatingMobileHandovers = new Set<string>();apps/mobile/src/features/threads/ThreadRouteScreen.tsx line 883OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -798,3 +878,6 @@798878 onNativePasteImages={composer.onNativePasteImages}799879 onRemoveDraftImage={composer.onRemoveDraftImage}800880 serverConfig={serverConfig}881+ contextLimitReached={contextLimitReached}882+ isGeneratingHandover={isGeneratingHandover}883+ onGenerateHandover={handleGenerateHandover}
- apps/server/src/orchestration/UsageLimitPolicy.ts line 95OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +75,21 @@75+}): UsageLimitViolation | undefined {76+ const contextViolation = contextLimitViolation(input);77+ if (contextViolation) return contextViolation;78+79+ const currentThreadIsRunning =80+ input.sessions.some(81+ (session) => session.threadId === input.threadId && isRunningSession(session),82+ ) || input.reservedTurnThreadIds?.includes(input.threadId) === true;83+ const runningTurnCount =84+ input.sessions.filter(isRunningSession).length + (input.reservedTurnThreadIds?.length ?? 0);85+ return currentThreadIsRunning ? undefined : concurrentTurnLimitViolation(runningTurnCount);86+}87+88+export function evaluateHandoverStartLimits(input: {89+ readonly contextTokenLimit?: number;90+ readonly activities: ReadonlyArray<OrchestrationThreadActivity>;91+ readonly sessions: ReadonlyArray<ProviderSession>;92+}): UsageLimitViolation | undefined {93+ const contextViolation = contextLimitViolation(input);94+ if (contextViolation) return contextViolation;95+ return concurrentTurnLimitViolation(input.sessions.filter(isRunningSession).length);apps/server/src/orchestration/UsageLimitPolicy.ts line 85OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +65,21 @@65+function isRunningSession(session: ProviderSession): boolean {66+ return session.status === "connecting" || session.status === "running";67+}68+69+export function evaluateTurnStartLimits(input: {70+ readonly threadId: ThreadId;71+ readonly contextTokenLimit?: number;72+ readonly activities: ReadonlyArray<OrchestrationThreadActivity>;73+ readonly sessions: ReadonlyArray<ProviderSession>;74+ readonly reservedTurnThreadIds?: ReadonlyArray<ThreadId>;75+}): UsageLimitViolation | undefined {76+ const contextViolation = contextLimitViolation(input);77+ if (contextViolation) return contextViolation;78+79+ const currentThreadIsRunning =80+ input.sessions.some(81+ (session) => session.threadId === input.threadId && isRunningSession(session),82+ ) || input.reservedTurnThreadIds?.includes(input.threadId) === true;83+ const runningTurnCount =84+ input.sessions.filter(isRunningSession).length + (input.reservedTurnThreadIds?.length ?? 0);85+ return currentThreadIsRunning ? undefined : concurrentTurnLimitViolation(runningTurnCount);
- apps/web/src/components/ChatView.tsx lines 5074 to 5081OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -4939,0 +5061,21 @@5061+ serverConfig?.environment.capabilities.threadHandoverGeneration === true;5062+ return {5063+ id: `context-limit:${activeThread.id}`,5064+ variant: "warning",5065+ priority: "urgent",5066+ icon: <AlertTriangleIcon />,5067+ title: `This thread has reached ${settings.threadContextTokenLimit.toLocaleString("en-US")} tokens`,5068+ description: supportsGeneration5069+ ? "T3 will not start another turn here. Create a compact handover, then review it in a new draft before choosing the next model and reasoning level."5070+ : "T3 will not start another turn here. Update the connected server to create an automatic handover, or start a new thread manually.",5071+ actions: (5072+ <>5073+ <Button5074+ size="icon-xs"5075+ variant="ghost-muted"5076+ aria-label="Change thread token limit"5077+ onClick={() =>5078+ void navigate({5079+ to: "/settings/general",5080+ hash: "thread-context-token-limit",5081+ hashScrollIntoView: false,apps/web/src/components/ChatView.tsx lines 7525 to 7526OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -7345,6 +7522,5 @@73457522 sendDisabledReason={73467523 feedbackUploading73477524 ? "Sending feedback"7348- : threadDetailLoading7349- ? "Messages loading"7350- : null7525+ : activeThreadReachedContextLimit7526+ ? "Thread token limit reached"
- apps/server/src/orchestration/Layers/ProviderCommandReactor.ts line 1195OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1143,3 +1192,4 @@1143119211441193 yield* ensureThreadWorktree(thread);114511941195+ const usageLimitSettings = yield* serverSettingsService.getSettings;apps/mobile/src/features/threads/NewTaskDraftScreen.tsx line 237OutdatedResolvedby saphid(GitHub profile, opens in a new tab)@@ -220,5 +228,10 @@220228 const shareImportMountedRef = useRef(true);221229 const latestDraftKeyRef = useRef(flow.draftKey);222230 const latestIncomingShareIdRef = useRef(props.incomingShareId);231+ const appliedInitialPromptRef = useRef<string | null>(null);232+ const appliedInitialWorkspaceRef = useRef<string | null>(null);223233 latestDraftKeyRef.current = flow.draftKey;224234 latestIncomingShareIdRef.current = props.incomingShareId;235+ useEffect(() => {236+ if (237+ !props.initialPrompt ||apps/mobile/src/features/threads/ThreadRouteScreen.tsx line 839OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -761,0 +819,21 @@819+ const sourceThreadKey = currentThreadKey;820+ if (generatingMobileHandovers.has(sourceThreadKey)) return;821+ generatingMobileHandovers.add(sourceThreadKey);822+ notifyMobileHandoverListeners();823+ try {824+ let handover = pendingMobileHandovers.get(sourceThreadKey);825+ if (handover === undefined) {826+ const result = await generateThreadHandover({827+ environmentId: selectedThread.environmentId,828+ input: { threadId: selectedThread.id },829+ });830+ if (result._tag === "Failure") {831+ Alert.alert("Could not create handover", "Handover generation failed. Try again.");832+ return;833+ }834+ handover = result.value.handover;835+ pendingMobileHandovers.set(sourceThreadKey, handover);836+ notifyMobileHandoverListeners();837+ }838+ if (selectedThreadKeyRef.current !== sourceThreadKey) return;839+ navigation.navigate("NewTaskSheet", {
- apps/web/src/components/ChatView.tsx lines 2379 to 2382OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2368,3 +2376,7 @@23682376 () => deriveLatestContextWindowSnapshot(threadActivities),23692377 [threadActivities],23702378 );2379+ const activeThreadReachedContextLimit = contextWindowReachedThreadLimit(2380+ activeContextWindow,2381+ settings.threadContextTokenLimit,2382+ );
- apps/web/src/components/settings/SettingsPanels.tsx lines 2171 to 2174OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2143,0 +2154,21 @@2154+ onClick={() =>2155+ updateSettings({2156+ threadContextTokenLimit: DEFAULT_UNIFIED_SETTINGS.threadContextTokenLimit,2157+ })2158+ }2159+ />2160+ ) : null2161+ }2162+ control={2163+ <div className="flex items-center gap-2">2164+ <NumberField2165+ value={settings.threadContextTokenLimit / 1_000}2166+ min={MIN_THREAD_CONTEXT_TOKEN_LIMIT / 1_000}2167+ max={MAX_THREAD_CONTEXT_TOKEN_LIMIT / 1_000}2168+ step={10}2169+ size="sm"2170+ className="w-28"2171+ onValueChange={(value) => {2172+ if (value === null) return;2173+ updateSettings({ threadContextTokenLimit: Math.round(value) * 1_000 });2174+ }}
- apps/server/src/orchestration/UsageLimitPolicy.ts line 103OutdatedResolvedby saphid(GitHub profile, opens in a new tab)@@ -0,0 +83,21 @@83+ readonly sessions: ReadonlyArray<ProviderSession>;84+ readonly reservedTurnThreadIds?: ReadonlyArray<ThreadId>;85+}): UsageLimitViolation | undefined {86+ const contextViolation = contextLimitViolation(input);87+ if (contextViolation) return contextViolation;88+89+ const currentThreadIsRunning =90+ input.sessions.some(91+ (session) => session.threadId === input.threadId && isRunningSession(session),92+ ) || input.reservedTurnThreadIds?.includes(input.threadId) === true;93+ const runningTurnCount = runningTurnThreadIds(94+ input.sessions,95+ input.reservedTurnThreadIds ?? [],96+ ).size;97+ return currentThreadIsRunning ? undefined : concurrentTurnLimitViolation(runningTurnCount);98+}99+100+export function evaluateHandoverStartLimits(input: {101+ readonly sessions: ReadonlyArray<ProviderSession>;102+}): UsageLimitViolation | undefined {103+ return concurrentTurnLimitViolation(runningTurnThreadIds(input.sessions, []).size);apps/web/src/components/settings/settingsSearch.ts line 200OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -194,3 +194,7 @@194194 "balanced performance battery saver advanced git fetch provider health refresh host power monitor idle policy",195195 ],196196 },197+ {198+ id: "thread-context-token-limit",199+ title: "Thread token limit",200+ to: "/settings/general",
- apps/server/src/orchestration/Layers/ProviderCommandReactor.ts line 1233OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1230,4 +1302,3 @@1230130212311303 yield* providerService12321304 .sendTurn(sendTurnRequest.value)1233- .pipe(Effect.catchCause(recoverTurnStartFailure), Effect.forkScoped);apps/mobile/src/features/threads/NewTaskDraftScreen.tsx line 300OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -272,5 +280,21 @@272280 const shareImportMountedRef = useRef(true);273281 const latestDraftKeyRef = useRef(flow.draftKey);274282 const latestIncomingShareIdRef = useRef(props.incomingShareId);283+ const appliedInitialPromptRef = useRef<string | null>(null);284+ const appliedInitialWorkspaceRef = useRef<string | null>(null);275285 latestDraftKeyRef.current = flow.draftKey;276286 latestIncomingShareIdRef.current = props.incomingShareId;287+ useEffect(() => {288+ if (289+ !props.initialPrompt ||290+ !flow.draftKey ||291+ appliedInitialPromptRef.current === `${flow.draftKey}:${props.initialPrompt}`292+ ) {293+ return;294+ }295+ // A handover is an explicit replacement for the destination project's296+ // unsent prompt. This keeps the generated continuation from being lost297+ // when that project already has a saved draft.298+ appliedInitialPromptRef.current = `${flow.draftKey}:${props.initialPrompt}`;299+ flow.setPrompt(props.initialPrompt);300+ }, [flow.draftKey, flow.prompt, flow.setPrompt, props.initialPrompt]);
- apps/web/src/components/settings/settingsSearch.ts line 200OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -194,3 +194,7 @@194194 "balanced performance battery saver advanced git fetch provider health refresh host power monitor idle policy",195195 ],196196 },197+ {198+ id: "thread-context-token-limit",199+ title: "Thread token limit",200+ to: "/settings/general",
- apps/mobile/src/features/threads/ThreadRouteScreen.tsx line 794OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -759,3 +791,4 @@759791 connectionState: routeConnectionState,760792 });761793 const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;794+ const selectedThreadKeyRef = useRef(apps/web/src/components/usage/UsagePage.tsx line 79OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -74,3 +76,4 @@7476 () => (isPast24Hours ? merged.hourly : merged.daily).toReversed(),7577 [isPast24Hours, merged.daily, merged.hourly],7678 );79+ const budgetAlert = useMemo(() => evaluateDailyUsageBudget(merged.daily), [merged.daily]);apps/server/src/orchestration/Layers/ProviderCommandReactor.ts line 344OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -321,3 +324,21 @@321324 timeToLive: HANDLED_TURN_START_KEY_TTL,322325 lookup: () => Effect.succeed(true),323326 });327+ const turnReservations = yield* Ref.make(new Map<string, ThreadId>());328+329+ const releaseTurnReservation = (key: string) =>330+ Ref.update(turnReservations, (reservations) => {331+ if (!reservations.has(key)) return reservations;332+ const next = new Map(reservations);333+ next.delete(key);334+ return next;335+ });336+337+ const reserveTurnStart = (input: {338+ readonly key: string;339+ readonly threadId: ThreadId;340+ readonly contextTokenLimit?: number;341+ readonly activities: ReadonlyArray<OrchestrationThreadActivity>;342+ }) =>343+ Effect.gen(function* () {344+ const sessions = yield* providerService.listSessions();apps/web/src/components/ChatView.tsx line 440OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -434,3 +437,4 @@434437 const EMPTY_PROVIDERS: ServerProvider[] = [];435438 const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];436439 const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};440+const pendingThreadHandovers = new Map<string, string>();
- apps/server/src/environment/ServerEnvironment.ts lines 192 to 197OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -185,3 +189,9 @@185189 const identity = yield* ServerEnvironmentIdentity;186190 const hostPlatform = yield* HostProcessPlatform;187191 const hostArchitecture = yield* HostProcessArchitecture;192+ // Connect-only commands intentionally do not boot provider drivers. Use193+ // Effect's typed optional-service lookup so that this degraded capability is194+ // explicit without hiding a required dependency behind an ambient cast.195+ const providerInstanceRegistry = yield* Effect.serviceOption(196+ ProviderInstanceRegistry.ProviderInstanceRegistry,197+ );
- apps/mobile/src/features/threads/ThreadRouteScreen.tsx line 809OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -759,3 +791,19 @@759791 connectionState: routeConnectionState,760792 });761793 const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;794+ const selectedThreadKeyRef = useRef(795+ selectedThread ? scopedThreadKey(selectedThread.environmentId, selectedThread.id) : null,796+ );797+ selectedThreadKeyRef.current = selectedThread798+ ? scopedThreadKey(selectedThread.environmentId, selectedThread.id)799+ : null;800+ const currentThreadKey = selectedThread801+ ? scopedThreadKey(selectedThread.environmentId, selectedThread.id)802+ : null;803+ const handoverState = useSyncExternalStore(804+ subscribeMobileHandoverState,805+ () => mobileHandoverStateSnapshot(currentThreadKey),806+ () => mobileHandoverStateSnapshot(currentThreadKey),807+ );808+ const isGeneratingHandover = handoverState.startsWith("true:");809+ const handleGenerateHandover = useCallback(async () => {
- apps/server/src/orchestration/UsageLimitReservations.ts lines 102 to 111OutdatedResolvedby saphid(GitHub profile, opens in a new tab)@@ -0,0 +91,21 @@91+ });92+ if (violation) return violation;93+94+ reservations.set(input.key, { kind: "handover", threadId: input.threadId });95+ return undefined;96+ });97+ });98+99+ return { reserveTurn, reserveHandover, release };100+}101+102+const storesByProviderService = new WeakMap<ProviderServiceShape, UsageLimitReservations>();103+104+/** One reservation store per server-lifetime provider runtime. */105+export function forProviderService(providerService: ProviderServiceShape): UsageLimitReservations {106+ const existing = storesByProviderService.get(providerService);107+ if (existing) return existing;108+ const created = make(providerService.listSessions);109+ storesByProviderService.set(providerService, created);110+ return created;111+}
- apps/mobile/src/features/threads/ThreadRouteScreen.tsx line 454OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -297,0 +398,21 @@398+ handover = result.value.handover;399+ savePendingMobileHandover(sourceThreadKey, handover);400+ notifyMobileHandoverListeners();401+ }402+ if (403+ !mountedRef.current ||404+ !isFocusedRef.current ||405+ selectedThreadKeyRef.current !== sourceThreadKey406+ ) {407+ return;408+ }409+410+ const destinationDraftKey = `new-task:${selectedThread.environmentId}:${selectedThread.projectId}`;411+ await replaceComposerDraftText(destinationDraftKey, handover);412+ updateComposerDraftSettings(destinationDraftKey, {413+ workspaceSelection: {414+ mode: selectedThread.worktreePath ? "worktree" : "local",415+ branch: selectedThread.branch,416+ worktreePath: selectedThread.worktreePath,417+ startFromOrigin: false,418+ },
- apps/mobile/src/features/threads/ThreadRouteScreen.tsx line 412OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -298,0 +392,21 @@392+ environmentId: selectedThread.environmentId,393+ input: { threadId: selectedThread.id },394+ });395+ if (result._tag === "Failure") {396+ Alert.alert("Could not create handover", "Handover generation failed. Try again.");397+ return;398+ }399+ handover = result.value.handover;400+ savePendingMobileHandover(sourceThreadKey, handover);401+ notifyMobileHandoverListeners();402+ }403+ if (404+ !mountedRef.current ||405+ !isFocusedRef.current ||406+ selectedThreadKeyRef.current !== sourceThreadKey407+ ) {408+ return;409+ }410+411+ const destinationDraftKey = `new-task:${selectedThread.environmentId}:${selectedThread.projectId}`;412+ await replaceComposerDraftText(destinationDraftKey, handover);
- docs/user/usage.md lines 62 to 66OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -45,0 +46,21 @@46+47+## Thread handovers and work limits48+49+Use **Past 24h** for an hourly chart covering the exact rolling 24-hour period. The **7 days**,50+**30 days**, and **90 days** ranges use daily resolution. Cost and token toggles update both the51+headline and chart, and refreshing rescans every connected environment.52+53+The page warns when the latest calendar day's usage crosses the built-in budget levels. Claude54+warnings use its API-rate estimate. API-equivalent warnings include subscription traffic such as55+Codex. The warning level starts at $500 of Claude usage or $1,000 API-equivalent. Approval starts at56+$1,000 or $1,500. The pause level is $2,000 for either measure.57+58+T3 also applies two hard limits before it sends a new turn to any provider:59+60+A thread cannot continue after its latest reported context usage reaches the configured token61+ limit, which defaults to 250,000 tokens and can be changed in General settings. Start a new thread62+ instead of paying to resend the same long conversation. When this happens, the chat shows a63+ warning with a **Handover to new thread** button. The button uses GPT64+ 5.6 Luna with high reasoning to summarize the thread, opens a new draft in the same checkout, and65+ places the handover in its composer. It does not start the new thread, so you can choose its model66+ and reasoning level before sending.
- apps/mobile/src/features/threads/ThreadRouteScreen.tsx line 411OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -298,0 +391,21 @@391+ const result = await generateThreadHandover({392+ environmentId: selectedThread.environmentId,393+ input: { threadId: selectedThread.id },394+ });395+ if (result._tag === "Failure") {396+ Alert.alert("Could not create handover", "Handover generation failed. Try again.");397+ return;398+ }399+ handover = result.value.handover;400+ savePendingMobileHandover(sourceThreadKey, handover);401+ notifyMobileHandoverListeners();402+ }403+ if (404+ !mountedRef.current ||405+ !isFocusedRef.current ||406+ selectedThreadKeyRef.current !== sourceThreadKey407+ ) {408+ return;409+ }410+411+ const destinationDraftKey = `new-task:${selectedThread.environmentId}:${selectedThread.projectId}`;
- apps/mobile/src/features/threads/ThreadRouteScreen.tsx line 438OutdatedResolvedby saphid(GitHub profile, opens in a new tab)@@ -298,0 +418,21 @@418+419+ if (!attempt.draftWritten) {420+ const destinationDraftKey = `new-task:${selectedThread.environmentId}:${selectedThread.projectId}`;421+ await mergeComposerDraftContent(destinationDraftKey, {422+ text: attempt.handover,423+ attachments: [],424+ });425+ updateComposerDraftSettings(destinationDraftKey, {426+ workspaceSelection: {427+ // Local mode continues the selected checkout; worktree mode creates a new one.428+ mode: "local",429+ branch: selectedThread.branch,430+ worktreePath: selectedThread.worktreePath,431+ startFromOrigin: false,432+ },433+ });434+ await flushComposerDrafts();435+ attempt = { ...attempt, draftWritten: true };436+ saveMobileHandoverAttempt(sourceThreadKey, attempt);437+ notifyMobileHandoverListeners();438+ }
- apps/mobile/src/features/threads/ThreadRouteScreen.tsx line 119Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -83,3 +100,10 @@8310084101 type NativeHeaderItems = ReadonlyArray<Record<string, unknown>>;85102103+interface MobileHandoverAttempt {104+ readonly handover: string;105+ readonly draftImportId: string;106+ readonly draftWritten: boolean;107+}108+109+const mobileHandoverAttempts = new Map<string, MobileHandoverAttempt>();
- apps/mobile/src/features/threads/ThreadRouteScreen.tsx line 473Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -298,0 +445,21 @@445+ attempt = { ...attempt, draftWritten: true };446+ saveMobileHandoverAttempt(sourceThreadKey, attempt);447+ notifyMobileHandoverListeners();448+ }449+450+ if (451+ !mountedRef.current ||452+ !isFocusedRef.current ||453+ selectedThreadKeyRef.current !== sourceThreadKey454+ ) {455+ return;456+ }457+ navigation.navigate("NewTaskSheet", {458+ screen: "NewTaskDraft",459+ params: {460+ environmentId: String(selectedThread.environmentId),461+ projectId: String(selectedThread.projectId),462+ title: selectedThreadProject.title,463+ },464+ });465+ mobileHandoverAttempts.delete(sourceThreadKey);
- apps/mobile/src/features/threads/ThreadRouteScreen.tsx line 474Resolvedby saphid(GitHub profile, opens in a new tab)@@ -298,0 +446,21 @@446+ saveMobileHandoverAttempt(sourceThreadKey, attempt);447+ notifyMobileHandoverListeners();448+ }449+450+ if (451+ !mountedRef.current ||452+ !isFocusedRef.current ||453+ selectedThreadKeyRef.current !== sourceThreadKey454+ ) {455+ return;456+ }457+ navigation.navigate("NewTaskSheet", {458+ screen: "NewTaskDraft",459+ params: {460+ environmentId: String(selectedThread.environmentId),461+ projectId: String(selectedThread.projectId),462+ title: selectedThreadProject.title,463+ },464+ });465+ mobileHandoverAttempts.delete(sourceThreadKey);466+ notifyMobileHandoverListeners();@@ -5417,0 +5494,21 @@5494+ await writeTextToClipboard(handover, "thread handover");5495+ toastManager.add(5496+ stackedThreadToast({5497+ type: "info",5498+ title: "Handover saved",5499+ description:5500+ "The draft could not be opened, so the handover was copied to your clipboard. Try again from this thread.",5501+ }),5502+ );5503+ } catch (error) {5504+ throw new Error(5505+ "The replacement draft could not be opened and the handover could not be copied.",5506+ {5507+ cause: error,5508+ },5509+ );5510+ }5511+ return;5512+ }5513+ useComposerDraftStore.getState().setPrompt(opened.draftId, handover);5514+ pendingThreadHandovers.delete(sourceThreadKey);
- apps/mobile/src/features/threads/ThreadRouteScreen.tsx lines 442 to 442OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -298,0 +422,21 @@422+ ) {423+ return;424+ }425+426+ const destinationDraftKey = `new-task:${selectedThread.environmentId}:${selectedThread.projectId}`;427+ const draftAlreadyImported = getComposerDraftSnapshot(428+ destinationDraftKey,429+ ).importedShareIds?.includes(attempt.draftImportId);430+ if (!attempt.draftWritten || !draftAlreadyImported) {431+ if (!draftAlreadyImported) {432+ await mergeComposerDraftContent(destinationDraftKey, {433+ text: attempt.handover,434+ attachments: [],435+ sourceShareId: attempt.draftImportId,436+ });437+ updateComposerDraftSettings(destinationDraftKey, {438+ workspaceSelection: {439+ // Local mode continues the selected checkout; worktree mode creates a new one.440+ mode: "local",441+ branch: selectedThread.branch,442+ worktreePath: selectedThread.worktreePath,
- apps/mobile/src/features/threads/ThreadRouteScreen.tsx line 446OutdatedResolvedby saphid(GitHub profile, opens in a new tab)@@ -298,0 +426,21 @@426+ const destinationDraftKey = `new-task:${selectedThread.environmentId}:${selectedThread.projectId}`;427+ const draftAlreadyImported = getComposerDraftSnapshot(428+ destinationDraftKey,429+ ).importedShareIds?.includes(attempt.draftImportId);430+ if (!attempt.draftWritten || !draftAlreadyImported) {431+ if (!draftAlreadyImported) {432+ await mergeComposerDraftContent(destinationDraftKey, {433+ text: attempt.handover,434+ attachments: [],435+ sourceShareId: attempt.draftImportId,436+ });437+ updateComposerDraftSettings(destinationDraftKey, {438+ workspaceSelection: {439+ // Local mode continues the selected checkout; worktree mode creates a new one.440+ mode: "local",441+ branch: selectedThread.branch,442+ worktreePath: selectedThread.worktreePath,443+ startFromOrigin: false,444+ },445+ });446+ }
- apps/mobile/src/features/threads/ThreadRouteScreen.tsx line 1020Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -759,4 +954,7 @@759954 detailDeleted: selectedThreadDetailState.status === "deleted",760955 connectionState: routeConnectionState,761956 });762- const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;957+ const contextLimitReached =958+ serverConfig !== null &&959+ selectedThreadDetail !== null &&960+ threadContextReachedLimit(
- apps/mobile/src/features/threads/ThreadRouteScreen.tsx line 365OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -296,3 +355,11 @@296355 : null,297356 [composer.interactionMode, composer.modelSelection, composer.runtimeMode, selectedThread],298357 );358+ const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;359+ const selectedThreadKeyRef = useRef(360+ selectedThread ? scopedThreadKey(selectedThread.environmentId, selectedThread.id) : null,361+ );362+ selectedThreadKeyRef.current = selectedThread363+ ? scopedThreadKey(selectedThread.environmentId, selectedThread.id)364+ : null;365+ const currentThreadKey = selectedThreadapps/web/src/components/ChatView.tsx line 5489OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -5425,0 +5469,21 @@5469+ if (result._tag === "Failure") {5470+ if (!isAtomCommandInterrupted(result)) {5471+ const error = squashAtomCommandFailure(result);5472+ toastManager.add(5473+ stackedThreadToast({5474+ type: "error",5475+ title: "Could not create handover",5476+ description: error instanceof Error ? error.message : "Handover generation failed.",5477+ }),5478+ );5479+ }5480+ return;5481+ }5482+ attempt = { handover: result.value.handover };5483+ pendingThreadHandovers.save(sourceThreadKey, attempt);5484+ setHandoverStateVersion((version) => version + 1);5485+ }5486+ const handoverAttempt = attempt;5487+ const handover = handoverAttempt.handover;5488+5489+ if (routeThreadKeyRef.current !== sourceThreadKey) {apps/web/src/hooks/useHandleNewThread.ts lines 442 to 442OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -392,3 +439,4 @@392439 interactionMode: racedDraft.interactionMode,393440 ...pickExplicitWorkspaceOptions(options),394441 });442+ prepareDraft(racedDraft.draftId);apps/web/src/components/ChatView.tsx line 6003Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -5425,0 +5538,21 @@5538+ }),5539+ );5540+ } finally {5541+ generatingThreadHandovers.delete(sourceThreadKey);5542+ setHandoverStateVersion((version) => version + 1);5543+ }5544+ }, [5545+ activeProject,5546+ activeThread,5547+ activeThreadReachedContextLimit,5548+ activeThreadHandoverKey,5549+ generateThreadHandover,5550+ handleNewThread,5551+ isGeneratingHandover,5552+ isServerThread,5553+ ]);5554+ const contextLimitBannerItem = useMemo<ComposerBannerStackItem | null>(() => {5555+ if (!activeThreadReachedContextLimit || !activeThread) return null;5556+ const supportsGeneration =5557+ serverConfig?.environment.capabilities.threadHandoverGeneration === true;5558+ return buildContextLimitBannerItem({
- @@ -89,3 +93,4 @@8993 }9094 return `${(value / 1_000_000).toFixed(1).replace(/\.0$/, "")}m`;9195 }96+apps/web/src/hooks/useHandleNewThread.ts line 442OutdatedResolvedby saphid(GitHub profile, opens in a new tab)@@ -392,3 +439,4 @@392439 interactionMode: racedDraft.interactionMode,393440 ...pickExplicitWorkspaceOptions(options),394441 });442+ prepareDraft(racedDraft.draftId);
- apps/mobile/src/features/threads/ThreadRouteScreen.tsx line 450OutdatedResolvedby saphid(GitHub profile, opens in a new tab)@@ -298,0 +430,21 @@430+ const destinationDraftKey = `new-task:${selectedThread.environmentId}:${selectedThread.projectId}`;431+ const draftAlreadyImported = getComposerDraftSnapshot(432+ destinationDraftKey,433+ ).importedShareIds?.includes(attempt.draftImportId);434+ if (!attempt.draftWritten || !draftAlreadyImported) {435+ if (!draftAlreadyImported) {436+ await mergeComposerDraftContent(destinationDraftKey, {437+ text: attempt.handover,438+ attachments: [],439+ sourceShareId: attempt.draftImportId,440+ });441+ updateComposerDraftSettings(destinationDraftKey, {442+ workspaceSelection: {443+ // Local mode continues the selected checkout; worktree mode creates a new one.444+ mode: "local",445+ branch: selectedThread.branch,446+ worktreePath: selectedThreadWorktreePath,447+ startFromOrigin: false,448+ },449+ });450+ }
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID:
18de1247-11e0-4db2-9fa2-dcbbbf9b44fdYou can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
Warning
Your free Security trial is over. An organization admin can activate Security or dismiss this notice.
Comment `@coderabbitai help` to get the list of available commands.