feat(providers): add context compaction command #9293
Mergedmaria-rcksmerged 30 commits into
main fromrefs/pull/9293/headmerged by maria-rcks 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
- @@ -856,0 +990,21 @@990+ if (pendingCompactions.get(threadId) === pending) {991+ pendingCompactions.delete(threadId);992+ }993+ });994+ const awaitNativeCompaction = Deferred.await(completion).pipe(995+ Effect.timeout("30 seconds"),996+ Effect.mapError(997+ (cause) =>998+ new ProviderAdapterRequestError({999+ provider: routed.adapter.provider,1000+ method: "thread/compact",1001+ detail: "Provider did not report completed context compaction within 30 seconds.",1002+ cause,1003+ }),1004+ ),1005+ );1006+ const terminal = yield* (1007+ nativeCompaction1008+ ? nativeCompaction(routed.threadId, modelSelection).pipe(1009+ Effect.andThen(awaitNativeCompaction),1010+ )apps/mobile/src/features/threads/ThreadComposer.tsx line 359OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -355,4 +356,4 @@355356 environmentId: props.environmentId,356357 projectCwd: props.projectCwd,357358 selectedProviderStatus,358- hasThread: true,359+ hasThread: props.hasCompactableConversation,
- apps/server/src/provider/Layers/ProviderService.ts lines 1024 to 1024OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -856,0 +1004,21 @@1004+ cause,1005+ }),1006+ ),1007+ );1008+ const terminal = yield* (1009+ nativeCompaction1010+ ? nativeCompaction(routed.threadId, modelSelection).pipe(1011+ Effect.andThen(awaitNativeCompaction),1012+ )1013+ : Effect.gen(function* () {1014+ const turn = yield* sendTurn({1015+ threadId,1016+ input: routed.adapter.provider === "cursor" ? "/compress" : "/compact",1017+ ...(modelSelection !== undefined ? { modelSelection } : {}),1018+ });1019+ pending.expectedTurnId = turn.turnId;1020+ const earlyEvents = pending.earlyEvents.splice(0);1021+ for (const earlyEvent of earlyEvents) {1022+ yield* processFallbackCompactionEvent(pending, earlyEvent);1023+ }1024+ return yield* Deferred.await(completion);apps/server/src/orchestration/Layers/ProviderCommandReactor.ts lines 467 to 467Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -429,3 +439,12 @@429439 });430440 });431441442+ const setThreadSessionReadyAfterCompaction = Effect.fnUntraced(function* (threadId: ThreadId) {443+ const thread = yield* resolveThread(threadId);444+ if (!thread?.session) return;445+ const completedAt = DateTime.formatIso(yield* DateTime.now);446+ yield* setThreadSession({447+ threadId,448+ session: {449+ ...thread.session,450+ status: "ready",apps/server/src/provider/Layers/ProviderService.ts lines 988 to 988OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -856,0 +968,21 @@968+ threadId,969+ operation: "ProviderService.compactThread",970+ allowRecovery: true,971+ });972+ yield* Effect.annotateCurrentSpan({973+ "provider.operation": "compact-thread",974+ "provider.kind": routed.adapter.provider,975+ "provider.thread_id": threadId,976+ });977+ yield* McpSessionRegistry.touchActiveMcpThread(threadId);978+ const nativeCompaction = routed.adapter.compactThread;979+ const completion = yield* Deferred.make<string>();980+ const pending: PendingCompaction = {981+ completion,982+ native: nativeCompaction !== undefined,983+ requestId,984+ earlyEvents: [],985+ compactedEventObserved: false,986+ expectedTurnId: undefined,987+ };988+ pendingCompactions.set(threadId, pending);apps/mobile/src/features/threads/ThreadDetailScreen.tsx line 326OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -323,3 +323,4 @@323323 props.activePendingUserInput === null;324324 const floatingWorkingStartedAt = showWorkingControl ? props.activeWorkStartedAt : null;325325 const selectedThreadFeed = props.selectedThreadFeed;326+ const hasCompactableConversation = selectedThreadFeed.some(apps/server/src/provider/Layers/ProviderService.ts line 449OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -355 +430,20 @@355- );430+ Effect.gen(function* () {431+ const canonicalEvent = yield* Effect.sync(() =>432+ correlateRuntimeEventWithInstance(source, event),433+ );434+ yield* increment(providerRuntimeEventsTotal, {435+ provider: canonicalEvent.provider,436+ eventType: canonicalEvent.type,437+ });438+ const pendingCompaction = pendingCompactions.get(canonicalEvent.threadId);439+ if (!pendingCompaction) {440+ yield* publishRuntimeEvent(canonicalEvent);441+ return;442+ }443+ if (pendingCompaction.native) {444+ yield* publishRuntimeEvent(445+ isCompactedEvent(canonicalEvent)446+ ? withCompactionRequestId(canonicalEvent, pendingCompaction)447+ : canonicalEvent,448+ );449+ if (isCompactedEvent(canonicalEvent)) {docs/user/composer.md lines 199 to 199OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -196,3 +196,4 @@196196 On mobile, these menus are available on the **New task** screen before you start a thread. They197197 use the skills and commands from the selected environment and provider.198198199+In an existing thread, send `/compact` to reduce context usage. Web and desktop also offer this action from the context meter, and the work log records token counts when the provider reports them.apps/web/src/components/ChatView.tsx line 655OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -643,3 +643,13 @@643643 (message) => message.role === "user",644644 );645645 const latestUserMessageId = latestUserMessage?.id ?? null;646+ const latestTurnStartFailed =647+ localDispatch !== null &&648+ latestUserMessageId !== null &&649+ input.activeThread?.activities.findLast((activity) => {650+ if (activity.kind !== "provider.turn.start.failed") return false;651+ const payload =652+ typeof activity.payload === "object" && activity.payload !== null653+ ? (activity.payload as { readonly requestId?: unknown })654+ : null;655+ return payload?.requestId === latestUserMessageId;apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts line 289Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -257,3 +259,14 @@257259 return event.payload.usage;258260 }259261262+function compactedTokenCountsFromActivities(263+ activities: ReadonlyArray<OrchestrationThreadActivity> | undefined,264+): { readonly beforeTokens: number; readonly afterTokens: number } | undefined {265+ const usedTokens = (activities ?? []).flatMap((activity) => {266+ if (activity.kind !== "context-window.updated") return [];267+ const payload = Predicate.isObject(activity.payload) ? activity.payload : undefined;268+ return Predicate.isNumber(payload?.usedTokens) && payload.usedTokens > 0269+ ? [payload.usedTokens]270+ : [];271+ });272+ const beforeTokens = usedTokens.at(-2);
- apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts lines 272 to 274OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -257,3 +259,16 @@257259 return event.payload.usage;258260 }259261262+function compactedTokenCountsFromActivities(263+ activities: ReadonlyArray<OrchestrationThreadActivity> | undefined,264+): { readonly beforeTokens: number; readonly afterTokens: number } | undefined {265+ const lastCompactionIndex = activities?.findLastIndex(266+ (activity) => activity.kind === "context-compaction",267+ );268+ const activitiesSinceLastCompaction = activities?.slice((lastCompactionIndex ?? -1) + 1) ?? [];269+ const usedTokens = activitiesSinceLastCompaction.flatMap((activity) => {270+ if (activity.kind !== "context-window.updated") return [];271+ const payload = Predicate.isObject(activity.payload) ? activity.payload : undefined;272+ return Predicate.isNumber(payload?.usedTokens) && payload.usedTokens > 0273+ ? [payload.usedTokens]274+ : [];apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts lines 281 to 286OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -259,0 +266,21 @@266+ (activity) => activity.kind === "context-compaction",267+ );268+ const activitiesSinceLastCompaction = activities?.slice((lastCompactionIndex ?? -1) + 1) ?? [];269+ const usedTokens = activitiesSinceLastCompaction.flatMap((activity) => {270+ if (activity.kind !== "context-window.updated") return [];271+ const payload = Predicate.isObject(activity.payload) ? activity.payload : undefined;272+ return Predicate.isNumber(payload?.usedTokens) && payload.usedTokens > 0273+ ? [payload.usedTokens]274+ : [];275+ });276+ const beforeTokens = usedTokens.at(-2);277+ const afterTokens = usedTokens.at(-1);278+ if (beforeTokens === undefined || afterTokens === undefined || afterTokens >= beforeTokens) {279+ return undefined;280+ }281+ const alreadyUsed = (activities ?? []).some((activity) => {282+ if (activity.kind !== "context-compaction") return false;283+ const payload = Predicate.isObject(activity.payload) ? activity.payload : undefined;284+ return payload?.beforeTokens === beforeTokens && payload.afterTokens === afterTokens;285+ });286+ return alreadyUsed ? undefined : { beforeTokens, afterTokens };
- apps/server/src/provider/Layers/ProviderService.ts line 1075OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -856,0 +1055,21 @@1055+ ? nativeCompaction(routed.threadId, modelSelection).pipe(1056+ Effect.andThen(awaitNativeCompaction),1057+ )1058+ : Effect.gen(function* () {1059+ const turn = yield* sendTurn({1060+ threadId,1061+ input: routed.adapter.provider === "cursor" ? "/compress" : "/compact",1062+ ...(modelSelection !== undefined ? { modelSelection } : {}),1063+ });1064+ pending.expectedTurnId = turn.turnId;1065+ const earlyEvents = pending.earlyEvents.splice(0);1066+ for (const earlyEvent of earlyEvents) {1067+ yield* processFallbackCompactionEvent(pending, earlyEvent);1068+ }1069+ return yield* awaitFallbackCompaction;1070+ })1071+ ).pipe(Effect.ensuring(clearPending));1072+ if (terminal !== "completed") {1073+ return yield* new ProviderAdapterRequestError({1074+ provider: routed.adapter.provider,1075+ method: "turn/start",
- apps/server/src/provider/Layers/ProviderService.ts line 831Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -688,3 +804,4 @@688804 typeof input.modelSelection?.model === "string" &&689805 input.modelSelection.model.trim().length > 0,690806 });807+ timedOutNativeCompactions.delete(threadId);apps/server/src/provider/Layers/ProviderService.ts line 1104Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -856,0 +1049,21 @@1049+ cause,1050+ }),1051+ ),1052+ );1053+ const terminal = yield* (1054+ nativeCompaction1055+ ? nativeCompaction(routed.threadId, modelSelection).pipe(1056+ Effect.andThen(awaitNativeCompaction),1057+ )1058+ : Effect.gen(function* () {1059+ const turn = yield* sendTurn({1060+ threadId,1061+ input: routed.adapter.provider === "cursor" ? "/compress" : "/compact",1062+ ...(modelSelection !== undefined ? { modelSelection } : {}),1063+ });1064+ pending.expectedTurnId = turn.turnId;1065+ const earlyEvents = pending.earlyEvents.splice(0);1066+ for (const earlyEvent of earlyEvents) {1067+ yield* processFallbackCompactionEvent(pending, earlyEvent);1068+ }1069+ return yield* awaitFallbackCompaction;
- apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts lines 270 to 283Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -259 +261,21 @@259261262+function compactedTokenCountsFromActivities(263+ activities: ReadonlyArray<OrchestrationThreadActivity> | undefined,264+): { readonly beforeTokens: number; readonly afterTokens: number } | undefined {265+ const lastCompactionIndex = activities?.findLastIndex(266+ (activity) => activity.kind === "context-compaction",267+ );268+ const lastCompaction =269+ lastCompactionIndex !== undefined && lastCompactionIndex >= 0270+ ? activities?.[lastCompactionIndex]271+ : undefined;272+ const activitiesSinceLastCompaction = activities?.slice((lastCompactionIndex ?? -1) + 1) ?? [];273+ const usedTokens = activitiesSinceLastCompaction.flatMap((activity) => {274+ if (activity.kind !== "context-window.updated") return [];275+ if (lastCompaction !== undefined) {276+ const isAfterLastCompaction =277+ activity.sequence !== undefined && lastCompaction.sequence !== undefined278+ ? activity.sequence > lastCompaction.sequence279+ : activity.createdAt > lastCompaction.createdAt;280+ if (!isAfterLastCompaction) return [];281+ }apps/server/src/provider/Layers/ProviderService.ts lines 1023 to 1023OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -856,0 +1003,21 @@1003+ });1004+ }1005+ const claimed = yield* Effect.sync(() => {1006+ if (pendingCompactions.has(threadId)) return false;1007+ pendingCompactions.set(threadId, pending);1008+ return true;1009+ });1010+ if (!claimed) {1011+ return yield* new ProviderAdapterRequestError({1012+ provider: routed.adapter.provider,1013+ method: "thread/compact",1014+ detail: "Context compaction is already in progress.",1015+ });1016+ }1017+ const clearPending = Effect.sync(() => {1018+ if (pendingCompactions.get(threadId) === pending) {1019+ pendingCompactions.delete(threadId);1020+ }1021+ });1022+ const nativeCompletionTimeout =1023+ routed.adapter.provider === "codex" ? "10 minutes" : "30 seconds";
- @@ -355,0 +448,21 @@448+ yield* publishRuntimeEvent(canonicalEvent);449+ return;450+ }451+ if (pendingCompaction.native) {452+ yield* publishRuntimeEvent(453+ isCompactedEvent(canonicalEvent)454+ ? withCompactionRequestId(canonicalEvent, pendingCompaction)455+ : canonicalEvent,456+ );457+ if (isCompactedEvent(canonicalEvent)) {458+ yield* settleCompaction(canonicalEvent.threadId, pendingCompaction, "completed");459+ }460+ return;461+ }462+ if (463+ pendingCompaction.expectedTurnId === undefined &&464+ canonicalEvent.turnId !== undefined &&465+ (isCompactedEvent(canonicalEvent) || compactionTerminal(canonicalEvent) !== null)466+ ) {467+ pendingCompaction.earlyEvents.push(canonicalEvent);468+ return;
- apps/server/src/provider/Layers/ProviderService.ts line 456Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -355,0 +431,21 @@431+ Effect.gen(function* () {432+ const canonicalEvent = yield* Effect.sync(() =>433+ correlateRuntimeEventWithInstance(source, event),434+ );435+ yield* increment(providerRuntimeEventsTotal, {436+ provider: canonicalEvent.provider,437+ eventType: canonicalEvent.type,438+ });439+ if (440+ isCompactedEvent(canonicalEvent) &&441+ timedOutNativeCompactions.delete(canonicalEvent.threadId)442+ ) {443+ yield* publishRuntimeEvent(canonicalEvent);444+ return;445+ }446+ const pendingCompaction = pendingCompactions.get(canonicalEvent.threadId);447+ if (!pendingCompaction) {448+ yield* publishRuntimeEvent(canonicalEvent);449+ return;450+ }451+ if (pendingCompaction.native) {apps/server/src/provider/Layers/CodexSessionRuntime.ts line 2299Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2293,3 +2294,6 @@22932294 return {22942295 start,22952296 getSession: Ref.get(sessionRef),2297+ compactThread: Effect.gen(function* () {2298+ const providerThreadId = yield* readProviderThreadId;2299+ yield* client.request("thread/compact/start", { threadId: providerThreadId });
- apps/server/src/provider/Layers/ProviderService.ts lines 1036 to 1049OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -856,0 +1029,21 @@1029+ routed.adapter.provider === "codex" || routed.adapter.provider === "opencode"1030+ ? "10 minutes"1031+ : "30 seconds";1032+ const awaitNativeCompaction = (start: Effect.Effect<void, ProviderAdapterError>) =>1033+ start.pipe(1034+ Effect.andThen(Deferred.await(completion)),1035+ Effect.timeout(nativeCompletionTimeout),1036+ Effect.tapError(() =>1037+ Effect.sync(() => {1038+ timedOutNativeCompactions.add(threadId);1039+ }),1040+ ),1041+ Effect.mapError(1042+ (cause) =>1043+ new ProviderAdapterRequestError({1044+ provider: routed.adapter.provider,1045+ method: "thread/compact",1046+ detail: `Provider did not report completed context compaction within ${nativeCompletionTimeout}.`,1047+ cause,1048+ }),1049+ ),
- @@ -856,0 +1030,21 @@1030+ ? "10 minutes"1031+ : "30 seconds";1032+ const awaitNativeCompaction = (start: Effect.Effect<void, ProviderAdapterError>) =>1033+ start.pipe(1034+ Effect.andThen(Deferred.await(completion)),1035+ Effect.timeout(nativeCompletionTimeout),1036+ Effect.tapError(() =>1037+ Effect.sync(() => {1038+ timedOutNativeCompactions.add(threadId);1039+ }),1040+ ),1041+ Effect.mapError(1042+ (cause) =>1043+ new ProviderAdapterRequestError({1044+ provider: routed.adapter.provider,1045+ method: "thread/compact",1046+ detail: `Provider did not report completed context compaction within ${nativeCompletionTimeout}.`,1047+ cause,1048+ }),1049+ ),1050+ );
- @@ -2924,8 +2931,17 @@29242931 activeThread?.modelSelection.instanceId ??29252932 activeProject?.defaultModelSelection?.instanceId ??29262933 null;2927- const compactionProviderAvailable = useMemo(2934+ const activeProviderStatus = useMemo(() => {2935+ if (activeProviderInstanceId) {2936+ return (2937+ providerStatuses.find((status) => status.instanceId === activeProviderInstanceId) ?? null2938+ );2939+ }2940+ const defaultInstanceId = defaultInstanceIdForDriver(selectedProvider);2941+ return providerStatuses.find((status) => status.instanceId === defaultInstanceId) ?? null;2942+ }, [activeProviderInstanceId, providerStatuses, selectedProvider]);2943+ const manualCompactionProviderAvailable = useMemo(29282944 () =>2929- hasAvailableClaudeCompactionProvider({2945+ hasAvailableCompactionProvider({29302946 providers: applyProviderInstanceSettings(29312947 deriveProviderInstanceEntries(providerStatuses),apps/server/src/provider/Layers/ClaudeAdapter.ts line 3227Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3212,12 +3207,15 @@3212- context.lastKnownTotalProcessedTokens,3213- ),3214- {3215- rawMethod: "claude/system/compact_boundary",3216- rawPayload: message,3217- },3207+ const compactedUsage = compactBoundaryTokenUsageSnapshot(3208+ message as unknown as Record<string, unknown>,3209+ context.lastKnownContextWindow,3210+ context.lastKnownTotalProcessedTokens,32183211 );3212+ yield* emitThreadTokenUsage(context, compactedUsage, {3213+ rawMethod: "claude/system/compact_boundary",3214+ rawPayload: message,3215+ });32193216 yield* offerRuntimeEvent({32203217 ...base,32213218 type: "thread.state.changed",32223219 payload: {32233220 state: "compacted",3221+ ...(compactedUsage?.lastUsedTokens !== undefined
- apps/server/src/provider/Layers/ProviderService.ts lines 1055 to 1070Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -856,0 +1031,21 @@1031+ : "30 seconds";1032+ const awaitNativeCompaction = (start: Effect.Effect<void, ProviderAdapterError>) =>1033+ start.pipe(1034+ Effect.andThen(Deferred.await(completion)),1035+ Effect.timeout(nativeCompletionTimeout),1036+ Effect.catchTag("TimeoutError", (cause) =>1037+ Effect.sync(() => {1038+ timedOutNativeCompactions.add(threadId);1039+ }).pipe(1040+ Effect.andThen(1041+ Effect.fail(1042+ new ProviderAdapterRequestError({1043+ provider: routed.adapter.provider,1044+ method: "thread/compact",1045+ detail: `Provider did not report completed context compaction within ${nativeCompletionTimeout}.`,1046+ cause,1047+ }),1048+ ),1049+ ),1050+ ),1051+ ),
- @@ -1222,0 +1292,21 @@1292+ yield* ensureSessionForThread(1293+ event.payload.threadId,1294+ event.payload.createdAt,1295+ event.payload.modelSelection !== undefined1296+ ? { modelSelection: event.payload.modelSelection }1297+ : undefined,1298+ );1299+ if (event.payload.modelSelection !== undefined) {1300+ threadModelSelections.set(event.payload.threadId, event.payload.modelSelection);1301+ }1302+ yield* providerService.compactThread(1303+ event.payload.threadId,1304+ event.payload.modelSelection,1305+ event.payload.messageId,1306+ );1307+ yield* setThreadSessionReadyAfterCompaction(event.payload.threadId);1308+ }).pipe(1309+ Effect.catchCause(recoverCompactionFailure),1310+ Effect.ensuring(Effect.sync(() => void compactingThreadIds.delete(event.payload.threadId))),1311+ Effect.forkScoped,1312+ );@@ -349,7 +432,14 @@349- Effect.flatMap((canonicalEvent) =>350- increment(providerRuntimeEventsTotal, {351- provider: canonicalEvent.provider,352- eventType: canonicalEvent.type,353- }).pipe(Effect.andThen(publishRuntimeEvent(canonicalEvent))),354- ),355- );432+ Effect.gen(function* () {433+ const canonicalEvent = yield* Effect.sync(() =>434+ correlateRuntimeEventWithInstance(source, event),435+ );436+ yield* increment(providerRuntimeEventsTotal, {437+ provider: canonicalEvent.provider,438+ eventType: canonicalEvent.type,439+ });440+ if (441+ isCompactedEvent(canonicalEvent) &&442+ timedOutNativeCompactions.delete(canonicalEvent.threadId)443+ ) {444+ yield* publishRuntimeEvent(canonicalEvent);445+ return;
- @@ -1220,3 +1250,19 @@12201250 ),12211251 );122212521253+ const handleCompactionFailure = (cause: Cause.Cause<unknown>) => {1254+ if (Cause.hasInterruptsOnly(cause)) {1255+ return Effect.void;1256+ }1257+ const detail = formatFailureDetail(cause);1258+ return appendTurnStartFailure("Context compaction failed", detail).pipe(1259+ Effect.ensuring(1260+ setThreadSessionReadyAfterCompaction(event.payload.threadId).pipe(1261+ Effect.catchCause((restoreCause) =>1262+ Effect.logWarning("failed to restore provider session after compaction failure", {1263+ threadId: event.payload.threadId,1264+ cause: Cause.pretty(restoreCause),1265+ }),1266+ ),1267+ ),1268+ ),@@ -2045,2 +2093,20 @@204520932046- const activities = runtimeEventToActivities(event, taskTitle);2094+ let activityEvent = event;2095+ if (2096+ isCompactedThreadState &&2097+ event.requestId === undefined &&2098+ Option.isSome(pendingTurnStart)2099+ ) {2100+ const pendingMessage = (yield* getLoadedThreadDetail())?.messages.find(2101+ (message) => message.id === pendingTurnStart.value.messageId,2102+ );2103+ if (2104+ pendingMessage?.role === "user" &&2105+ (pendingMessage.attachments?.length ?? 0) === 0 &&2106+ pendingMessage.text.trim().toLowerCase() === "/compact"2107+ ) {2108+ activityEvent = {2109+ ...event,2110+ requestId: RuntimeRequestId.make(String(pendingTurnStart.value.messageId)),2111+ };2112+ }
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/orchestration/Layers/ProviderCommandReactor.ts line 1268OutdatedResolvedby maria-rcks@@ -1220,3 +1258,11 @@12201258 ),12211259 );122212601261+ let compactionSessionEnsured = false;1262+ const handleCompactionFailure = (cause: Cause.Cause<unknown>) => {1263+ if (Cause.hasInterruptsOnly(cause)) {1264+ return Effect.void;1265+ }1266+ const detail = formatFailureDetail(cause);1267+ if (stoppingThreadIds.has(event.payload.threadId)) {1268+ return appendTurnStartFailure("Context compaction failed", detail).pipe(Effect.asVoid);
- @@ -1222,0 +1325,21 @@1325+ yield* Effect.gen(function* () {1326+ yield* ensureSessionForThread(1327+ event.payload.threadId,1328+ event.payload.createdAt,1329+ event.payload.modelSelection !== undefined1330+ ? { modelSelection: event.payload.modelSelection, pendingTurnStart: true }1331+ : { pendingTurnStart: true },1332+ );1333+ compactionSessionEnsured = true;1334+ if (event.payload.modelSelection !== undefined) {1335+ threadModelSelections.set(event.payload.threadId, event.payload.modelSelection);1336+ }1337+ yield* providerService.compactThread(1338+ event.payload.threadId,1339+ event.payload.modelSelection,1340+ event.payload.messageId,1341+ );1342+ }).pipe(1343+ Effect.ensuring(Effect.sync(() => void compactingThreadIds.delete(event.payload.threadId))),1344+ Effect.andThen(setThreadSessionReadyAfterCompaction(event.payload.threadId)),1345+ Effect.catchCause(recoverCompactionFailure),
- apps/mobile/src/features/threads/ThreadDetailScreen.tsx lines 762 to 762OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -749,3 +759,4 @@749759 <FloatingWorkingControl750760 colorScheme={isDarkMode ? "dark" : "light"}751761 startedAt={floatingWorkingStartedAt}762+ isCompacting={props.isCompacting}
- @@ -1281,0 +1289,21 @@1289+ String(pendingTurnStart.value.messageId) !==1290+ extractActivityRequestId(event.payload.activity.payload)1291+ ) {1292+ return;1293+ }1294+ yield* projectionTurnRepository.deletePendingTurnStartByThreadId(event.payload);1295+ return;1296+ }1297+ if (event.payload.activity.kind !== "provider.turn.start.failed") return;1298+ const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId(1299+ event.payload,1300+ );1301+ if (1302+ Option.isNone(pendingTurnStart) ||1303+ String(pendingTurnStart.value.messageId) !==1304+ extractActivityRequestId(event.payload.activity.payload)1305+ ) {1306+ return;1307+ }1308+ yield* projectionTurnRepository.deletePendingTurnStartByThreadId(event.payload);1309+ return;
- apps/mobile/src/state/use-thread-composer-state.ts lines 181 to 203OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -172,0 +183,21 @@183+ );184+ const latestMessageIsCompactCommand =185+ latestUserMessage?.text.trim().toLowerCase() === "/compact" &&186+ (latestUserMessage.attachments?.length ?? 0) === 0;187+ const sessionStatus =188+ selectedThreadDetail?.session?.status ?? selectedThreadShell?.session?.status;189+ const compactionSettled =190+ latestMessageIsCompactCommand &&191+ selectedThreadDetail?.activities.some((activity) => {192+ if (193+ activity.kind !== "context-compaction" &&194+ activity.kind !== "provider.turn.start.failed"195+ ) {196+ return false;197+ }198+ const payload =199+ typeof activity.payload === "object" && activity.payload !== null200+ ? (activity.payload as { readonly requestId?: unknown })201+ : null;202+ return payload?.requestId === latestUserMessage.id;203+ });
- apps/server/src/orchestration/Layers/ProjectionPipeline.ts line 1286Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1269,3 +1269,18 @@12691269 return;1270127012711271 case "thread.turn-start-requested": {1272+ const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({1273+ threadId: event.payload.threadId,1274+ });1275+ if (Option.isSome(pendingTurnStart)) {1276+ const pendingMessage = yield* projectionThreadMessageRepository.getByMessageId({1277+ messageId: pendingTurnStart.value.messageId,1278+ });1279+ if (1280+ Option.isSome(pendingMessage) &&1281+ pendingMessage.value.role === "user" &&1282+ (pendingMessage.value.attachments?.length ?? 0) === 0 &&1283+ pendingMessage.value.text.trim().toLowerCase() === "/compact"1284+ ) {1285+ return;1286+ }
- @@ -172,0 +189,21 @@189+ const compactionSettled =190+ latestCompactMessage !== undefined &&191+ selectedThreadDetail?.activities.some((activity) => {192+ if (193+ activity.kind !== "context-compaction" &&194+ activity.kind !== "provider.turn.start.failed"195+ ) {196+ return false;197+ }198+ const payload =199+ typeof activity.payload === "object" && activity.payload !== null200+ ? (activity.payload as { readonly requestId?: unknown })201+ : null;202+ return payload?.requestId === latestCompactMessage.id;203+ });204+ return (205+ queuedMessage !== undefined ||206+ ((sessionStatus === "starting" || sessionStatus === "running") &&207+ latestCompactMessage !== undefined &&208+ !compactionSettled)209+ );@@ -1282,4 +1312,21 @@1312+ }1313+ if (event.payload.activity.kind !== "provider.turn.start.failed") return;1314+ const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId(1315+ event.payload,1316+ );1317+ if (1318+ Option.isNone(pendingTurnStart) ||1319+ String(pendingTurnStart.value.messageId) !==1320+ extractActivityRequestId(event.payload.activity.payload)1321+ ) {1322+ return;1323+ }1324+ yield* projectionTurnRepository.deletePendingTurnStartByThreadId(event.payload);1325+ return;1326+ }1327+12821328 case "thread.session-set": {12831329 const turnId = event.payload.session.activeTurnId;12841330 if (turnId === null || event.payload.session.status !== "running") {12851331 if (1332+ event.payload.session.status === "ready" ||
Sign in to join this conversation.



cursor[bot](GitHub profile, opens in a new tab) reviewed