Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions apps/mobile/src/components/AppSymbol.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import IconArrowUpCircle from "@tabler/icons-react-native/IconArrowUpCircle";
import IconArrowUpRight from "@tabler/icons-react-native/IconArrowUpRight";
import IconArrowUpRightCircle from "@tabler/icons-react-native/IconArrowUpRightCircle";
import IconArrowsMaximize from "@tabler/icons-react-native/IconArrowsMaximize";
import IconArrowsMinimize from "@tabler/icons-react-native/IconArrowsMinimize";
import IconBellRinging from "@tabler/icons-react-native/IconBellRinging";
import IconBolt from "@tabler/icons-react-native/IconBolt";
import IconBox from "@tabler/icons-react-native/IconBox";
Expand Down Expand Up @@ -97,6 +98,7 @@ const ANDROID_ICON_BY_SF_SYMBOL: Partial<Record<SFSymbol, Icon>> = {
"arrow.up": IconArrowUp,
"arrow.up.circle": IconArrowUpCircle,
"arrow.up.left.and.arrow.down.right": IconArrowsMaximize,
"arrow.down.right.and.arrow.up.left": IconArrowsMinimize,
"arrow.up.right": IconArrowUpRight,
"arrow.up.right.circle": IconArrowUpRightCircle,
"arrow.uturn.backward": IconArrowBackUp,
Expand Down
1 change: 1 addition & 0 deletions apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,7 @@ export function NewTaskDraftScreen(props: {
sessionResources: null,
showInteractionModeToggle: flow.showInteractionModeToggle,
hasThread: false,
hasCompactableConversation: false,
enabled: isComposerFocused && !isComposerInteractionLocked,
onChangeDraftMessage: flow.setPrompt,
onUpdateInteractionMode: flow.setInteractionMode,
Expand Down
2 changes: 2 additions & 0 deletions apps/mobile/src/features/threads/ThreadComposer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,7 @@ export interface ThreadComposerProps {
readonly connectionState: RemoteClientConnectionState;
readonly environmentLabel: string | null;
readonly selectedThread: OrchestrationThreadShell;
readonly hasCompactableConversation: boolean;
readonly serverConfig: T3ServerConfig | null;
readonly localOutboxCount: number;
readonly onManagePendingSends: () => void;
Expand Down Expand Up @@ -1243,6 +1244,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
sessionResources: props.sessionResources,
showInteractionModeToggle,
hasThread: true,
hasCompactableConversation: props.hasCompactableConversation,
enabled: !props.sessionInputBlocked,
onChangeDraftMessage: props.onChangeDraftMessage,
onUpdateInteractionMode: props.onUpdateInteractionMode,
Expand Down
15 changes: 14 additions & 1 deletion apps/mobile/src/features/threads/ThreadDetailScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ export interface ThreadDetailScreenProps {
readonly sessionCompactionScopeKey: string | null;
readonly sessionCompactionPendingAction: SessionCompactionMenuAction | null;
readonly activeWorkStartedAt: string | null;
readonly isCompacting: boolean;
readonly activePendingApproval: PendingApproval | null;
readonly respondingApprovalId: ApprovalRequestId | null;
readonly activePendingUserInput: PendingUserInput | null;
Expand Down Expand Up @@ -468,8 +469,10 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
if (threadSyncLabel !== null) {
return { kind: "syncing", label: threadSyncLabel };
}
// Prime reports compaction through its own control snapshot; every other
// provider reports it as a compacting turn.
if (
isSessionCompactionInProgress(props.sessionCompaction) &&
(isSessionCompactionInProgress(props.sessionCompaction) || props.isCompacting) &&
contentPresentationKind === "ready"
) {
return { kind: "compacting" };
Expand All @@ -481,6 +484,15 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
})();
const showWorkingControl = floatingStatus !== null;
const selectedThreadFeed = props.selectedThreadFeed;
const hasCompactableConversation =
selectedThreadFeed.some(
(entry) =>
entry.type === "message" &&
entry.message.role === "user" &&
((entry.message.attachments?.length ?? 0) > 0 ||
entry.message.text.trim().toLowerCase() !== "/compact"),
) ||
(Boolean(props.loadEarlier) && props.selectedThread.latestUserMessageAt !== null);
const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
const composerOverlapHeight = composerChrome + composerBottomInset;
// While a user-input request is pending, the questionnaire owns the
Expand Down Expand Up @@ -1052,6 +1064,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
connectionState={props.connectionStateLabel}
environmentLabel={props.environmentLabel}
selectedThread={props.selectedThread}
hasCompactableConversation={hasCompactableConversation && !props.isCompacting}
serverConfig={props.serverConfig}
localOutboxCount={props.localOutboxCount}
onManagePendingSends={props.onManagePendingSends}
Expand Down
27 changes: 27 additions & 0 deletions apps/mobile/src/features/threads/ThreadFeed.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ import {
} from "@t3tools/mobile-markdown-text/links";
import {
deriveThreadFeedPresentation,
isContextCompactionActivityGroup,
type ThreadFeedEntry,
type ThreadFeedLatestTurn,
} from "../../lib/threadActivity";
Expand Down Expand Up @@ -1417,6 +1418,29 @@ function renderFeedEntry(
);
}

if (entry.type === "activity-group" && isContextCompactionActivityGroup(entry)) {
const label = entry.activities[0]!.summary;
return (
<View
accessible
accessibilityLabel={label}
className="mb-3 flex-row items-center gap-3 px-1 py-1"
>
<View className="h-px flex-1 bg-adaptive-neutral-200-a80-white-a8" />
<View className="shrink-0 flex-row items-center gap-1.5">
<SymbolView
name="arrow.down.right.and.arrow.up.left"
size={12}
tintColor={iconSubtleColor}
type="monochrome"
/>
<Text className="font-t3-medium text-xs text-foreground-muted">{label}</Text>
</View>
<View className="h-px flex-1 bg-adaptive-neutral-200-a80-white-a8" />
</View>
);
}

if (entry.type === "message") {
const { message } = entry;
const isUser = message.role === "user";
Expand Down Expand Up @@ -2615,6 +2639,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
case "thinking":
return WORK_GROUP_TOGGLE_HEIGHT;
case "activity-group":
if (isContextCompactionActivityGroup(entry)) {
return undefined;
}
// Expanded rows append a variable detail block — fall back to
// measurement for those groups.
return entry.activities.some((activity) => expandedWorkRows[activity.id])
Expand Down
1 change: 1 addition & 0 deletions apps/mobile/src/features/threads/ThreadRouteScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -982,6 +982,7 @@ function ThreadRouteContent(
sessionCompactionScopeKey={composer.sessionCompactionScopeKey}
sessionCompactionPendingAction={composer.sessionCompactionPendingAction}
activeWorkStartedAt={composer.activeWorkStartedAt}
isCompacting={composer.isCompacting}
activePendingApproval={requests.activePendingApproval}
respondingApprovalId={requests.respondingApprovalId}
activePendingUserInput={requests.activePendingUserInput}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ const baseInput = {
providerSlashCommands: [],
showInteractionModeToggle: false,
hasThread: true,
hasCompactableConversation: true,
pathEntries: [],
} as const;

Expand Down
8 changes: 8 additions & 0 deletions apps/mobile/src/features/threads/use-composer-command-menu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,13 +84,15 @@ export function buildComposerCommandItems({
providerSlashCommands,
showInteractionModeToggle,
hasThread,
hasCompactableConversation,
pathEntries,
}: {
readonly trigger: ComposerTrigger | null;
readonly selectedProviderStatus: ComposerCommandMenuProvider | null;
readonly providerSlashCommands: ReadonlyArray<ServerProviderSlashCommand>;
readonly showInteractionModeToggle: boolean;
readonly hasThread: boolean;
readonly hasCompactableConversation: boolean;
readonly pathEntries: ReadonlyArray<ComposerPathSearchEntry>;
}): ComposerCommandItem[] {
if (!trigger) return [];
Expand Down Expand Up @@ -146,6 +148,8 @@ export function buildComposerCommandItems({
for (const cmd of expandableCommands) {
if (!cmd.name.toLowerCase().includes(q)) continue;
if (!hasThread && cmd.localAction === "usage-limits") continue;
// Nothing to summarize before the thread has a compactable exchange.
if (cmd.name === "compact" && !hasCompactableConversation) continue;
// Codex `/feedback` uploads an existing thread's session and logs, so it
// has nothing to send before the thread exists.
if (!hasThread && selectedProviderStatus?.driver === "codex" && cmd.name === "feedback") {
Expand Down Expand Up @@ -307,6 +311,7 @@ export function useComposerCommandMenu({
sessionResources,
showInteractionModeToggle,
hasThread,
hasCompactableConversation,
enabled = true,
onChangeDraftMessage,
onUpdateInteractionMode,
Expand All @@ -319,6 +324,7 @@ export function useComposerCommandMenu({
readonly sessionResources: SessionResourcesSnapshot | null;
readonly showInteractionModeToggle: boolean;
readonly hasThread: boolean;
readonly hasCompactableConversation: boolean;
readonly enabled?: boolean;
readonly onChangeDraftMessage: (value: string) => void;
readonly onUpdateInteractionMode?: (mode: ProviderInteractionMode) => void;
Expand Down Expand Up @@ -441,10 +447,12 @@ export function useComposerCommandMenu({
showInteractionModeToggle:
showInteractionModeToggle && onUpdateInteractionMode !== undefined,
hasThread,
hasCompactableConversation,
pathEntries: pathSearch.entries,
}),
[
hasThread,
hasCompactableConversation,
onUpdateInteractionMode,
pathSearch.entries,
providerSlashCommands,
Expand Down
27 changes: 27 additions & 0 deletions apps/mobile/src/lib/threadActivity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,33 @@ describe("buildThreadFeed", () => {
expect(prepended.at(-1)).toBe(page.at(-1));
});

it("keeps context compaction as a standalone timeline row", () => {
const thread = makeThread({
id: ThreadId.make("thread-context-compaction"),
projectId: ProjectId.make("project-1"),
title: "Context compaction",
activities: [
makeActivity({
id: EventId.make("context-compaction"),
kind: "context-compaction",
tone: "info",
summary: "Compacted context 899K → 19K tokens",
createdAt: "2026-09-01T00:00:00.000Z",
turnId: TurnId.make("turn-context-compaction"),
}),
],
});

const presented = deriveThreadFeedPresentation(buildThreadFeed(thread), null, new Set());
expect(presented).toMatchObject([
{
type: "activity-group",
id: "context-compaction",
activities: [{ summary: "Compacted context 899K → 19K tokens" }],
},
]);
});

it("keeps long Claude commands expandable without repeating them in full detail", () => {
const command = `printf 'first line\nsecond line'\n&& printf done`;
const thread = makeThread({
Expand Down
29 changes: 28 additions & 1 deletion apps/mobile/src/lib/threadActivity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,15 @@ export type ThreadFeedLatestTurn = Pick<
"turnId" | "state" | "startedAt" | "completedAt"
>;

export function isContextCompactionActivityGroup(
entry: Extract<ThreadFeedEntry, { readonly type: "activity-group" }>,
): boolean {
return (
entry.activities.length === 1 &&
entry.activities[0]?.workEntry.sourceActivityKind === "context-compaction"
);
}

type ThreadFeedActivityGroup = Extract<ThreadFeedEntry, { readonly type: "activity-group" }>;

// These keys are immutable inputs. Weak caches release old histories with their source data.
Expand Down Expand Up @@ -1528,7 +1537,11 @@ function groupAdjacentActivities(entries: ReadonlyArray<RawThreadFeedEntry>): Th
continue;
}

const isStandalone = entry.activity.terminalResponseNotice === true;
// Terminal response notices and context compaction each own their card, so
// neither joins the surrounding tool group.
const isStandalone =
entry.activity.terminalResponseNotice === true ||
entry.activity.workEntry.sourceActivityKind === "context-compaction";
if (isStandalone || firstActivityEntry?.turnId !== entry.turnId) {
flushGroup();
}
Expand Down Expand Up @@ -1652,6 +1665,16 @@ function deriveThreadFeedTurnFolds(
if (hiddenEntryIds.size === 0) {
continue;
}
// A lone compaction row stays visible on its own; it only folds away as
// part of a turn that already folds other work.
const hidesNonCompactionWork = entries.some(
(entry) =>
hiddenEntryIds.has(entry.id) &&
!(entry.type === "activity-group" && isContextCompactionActivityGroup(entry)),
);
if (!hidesNonCompactionWork) {
continue;
}

const firstEntry = entries[0];
const firstHiddenEntry = entries.find((entry) => hiddenEntryIds.has(entry.id));
Expand Down Expand Up @@ -1816,6 +1839,10 @@ function appendPresentedFeedEntry(
result.push(entry);
return;
}
if (isContextCompactionActivityGroup(entry)) {
result.push(entry);
return;
}

let cached = presentedActivityGroupsCache.get(entry);
if (
Expand Down
46 changes: 45 additions & 1 deletion apps/mobile/src/state/use-thread-composer-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ import {
} from "./thread-outbox";
import { removeThreadOutboxMessageIfCurrent } from "./thread-outbox-removal";
import { recoverPendingSendToComposer } from "./thread-outbox-recovery";
import { useThreadOutboxMessages } from "./use-thread-outbox";
import { dispatchingQueuedMessageIdAtom, useThreadOutboxMessages } from "./use-thread-outbox";
import { useAtomCommand } from "./use-atom-command";
import {
composerAttachmentUploadBlockReason,
Expand Down Expand Up @@ -171,6 +171,7 @@ export function useThreadComposerState() {
) ?? null);
const composerDrafts = useAtomValue(composerDraftsAtom);
const queuedMessagesByThreadKey = useThreadOutboxMessages();
const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
const [feedbackSubmissionsByThreadKey, setFeedbackSubmissionsByThreadKey] = useState<
Record<string, ReadonlyArray<CodexFeedbackSubmission>>
>({});
Expand Down Expand Up @@ -549,6 +550,48 @@ export function useThreadComposerState() {
};
}, [selectedThreadDetail, selectedThreadShell]);

const isCompacting = useMemo(() => {
const queuedMessage = selectedThreadQueuedMessages.findLast(
(message) =>
message.messageId === dispatchingQueuedMessageId &&
message.text.trim().toLowerCase() === "/compact" &&
message.attachments.length === 0,
);
const latestCompactMessage = selectedThreadDetail?.messages.findLast(
(message) =>
message.role === "user" &&
message.text.trim().toLowerCase() === "/compact" &&
!message.attachments?.length,
);
const compactRequestIsActive =
latestCompactMessage !== undefined &&
(latestCompactMessage.createdAt >
(selectedThread?.latestTurn?.requestedAt ?? latestCompactMessage.createdAt) ||
(selectedThread?.latestTurn?.state === "running" &&
latestCompactMessage.createdAt === selectedThread.latestTurn.requestedAt));
const compactionSettled = selectedThreadDetail?.activities.some((activity) => {
if (!["context-compaction", "provider.turn.start.failed"].includes(activity.kind))
return false;
const payload =
typeof activity.payload === "object" && activity.payload !== null
? (activity.payload as { readonly requestId?: unknown })
: null;
return payload?.requestId === latestCompactMessage?.id;
});
return (
queuedMessage !== undefined ||
((selectedThread?.session?.status === "starting" ||
selectedThread?.session?.status === "running") &&
compactRequestIsActive &&
!compactionSettled)
);
}, [
dispatchingQueuedMessageId,
selectedThread,
selectedThreadDetail,
selectedThreadQueuedMessages,
]);

const activeWorkStartedAt = useMemo(() => {
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
if (!selectedThread) {
Expand Down Expand Up @@ -1551,6 +1594,7 @@ export function useThreadComposerState() {
selectedThreadQueueCount,
selectedThreadQueueHold: selectedThreadQueuedMessages[0]?.deliveryHold ?? null,
activeWorkStartedAt,
isCompacting,
draftMessage,
draftAttachments,
modelSelection,
Expand Down
8 changes: 2 additions & 6 deletions apps/mobile/src/state/use-thread-outbox-drain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
} from "@t3tools/contracts";
import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
import * as Cause from "effect/Cause";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { AsyncResult } from "effect/unstable/reactivity";
import { useCallback, useEffect, useRef, useState } from "react";

import { scopedProjectKey, scopedThreadKey } from "../lib/scopedEntities";
Expand Down Expand Up @@ -64,6 +64,7 @@ import {
} from "./use-composer-drafts";
import { useAtomCommand } from "./use-atom-command";
import {
dispatchingQueuedMessageIdAtom,
editingQueuedMessageIdsAtom,
useThreadOutboxMessages,
useThreadOutboxShellStatuses,
Expand All @@ -73,11 +74,6 @@ import {
useRemoteConnectionStatus,
} from "./use-remote-environment-registry";

export const dispatchingQueuedMessageIdAtom = Atom.make<MessageId | null>(null).pipe(
Atom.keepAlive,
Atom.withLabel("mobile:thread-outbox:dispatching-message-id"),
);

function beginDispatchingQueuedMessage(queuedMessageId: MessageId): void {
appAtomRegistry.set(dispatchingQueuedMessageIdAtom, queuedMessageId);
}
Expand Down
Loading
Loading