Skip to content
Closed
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
51 changes: 51 additions & 0 deletions apps/mobile/src/components/ComposerContextRing.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import Svg, { Circle } from "react-native-svg";
import { withUniwind } from "uniwind";

const ThemedCircle = withUniwind(Circle);

/**
* How full the thread's context window is, drawn as a ring inside a round composer button.
* `percent` is 0-100. The ring takes the colour of `colorClassName`; past 90 the arc turns danger.
*/
export function ComposerContextRing(props: {
readonly size: number;
readonly percent: number;
readonly colorClassName: string;
}) {
const used = Math.max(0, Math.min(100, props.percent));
const strokeWidth = Math.max(2, props.size * 0.075);
const radius = props.size / 2 - strokeWidth * 1.1;
const circumference = 2 * Math.PI * radius;
const center = props.size / 2;
return (
<Svg
width={props.size}
height={props.size}
style={{ position: "absolute", transform: [{ rotate: "-90deg" }] }}
pointerEvents="none"
>
<ThemedCircle
cx={center}
cy={center}
r={radius}
fill="none"
colorClassName={props.colorClassName}
stroke="currentColor"
strokeOpacity={0.28}
strokeWidth={strokeWidth}
/>
<ThemedCircle
cx={center}
cy={center}
r={radius}
fill="none"
colorClassName={used > 90 ? "accent-danger-foreground" : props.colorClassName}
stroke="currentColor"
strokeWidth={strokeWidth}
strokeLinecap="round"
strokeDasharray={`${circumference} ${circumference}`}
strokeDashoffset={circumference * (1 - used / 100)}
/>
</Svg>
);
}
16 changes: 16 additions & 0 deletions apps/mobile/src/components/ComposerToolbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import Animated, { FadeIn, useReducedMotion } from "react-native-reanimated";
import { cn } from "../lib/cn";
import { AppText as Text } from "./ui/AppText";
import { SymbolView } from "./ui/AppSymbol";
import { ComposerContextRing } from "./ComposerContextRing";
import { useAndroidControlSizing } from "./ui/useAndroidControlSizing";

const COMPOSER_TOOLBAR_GAP = 8;
Expand Down Expand Up @@ -290,6 +291,8 @@ export function ComposerActionButton(props: {
readonly icon: ComponentProps<typeof SymbolView>["name"];
readonly onPress: () => void;
readonly variant?: "primary" | "danger";
/** Context window used, 0-100, drawn as a ring inside the button; null draws none. */
readonly contextPercent?: number | null;
// Menu injects onLongPress on Android and onTouchStart/onPress on iOS.
readonly onLongPress?: PressableProps["onLongPress"];
readonly onTouchStart?: PressableProps["onTouchStart"];
Expand Down Expand Up @@ -320,6 +323,19 @@ export function ComposerActionButton(props: {
: "bg-primary",
)}
>
{props.contextPercent != null ? (
<ComposerContextRing
size={circleSize}
percent={props.contextPercent}
colorClassName={
props.variant === "danger"
? "accent-danger-foreground"
: props.disabled
? "accent-foreground"
: "accent-primary-foreground"
}
/>
) : null}
{/* Fade the icon as one layer: a translucent tint, or opacity on a Tabler icon (which
copies it onto every path), stacks where the SVG strokes overlap. */}
<View
Expand Down
10 changes: 10 additions & 0 deletions apps/mobile/src/features/threads/ThreadComposer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ import {
import { useVoiceInputController } from "../voice-input/useVoiceInputController";
import { resolveVoiceComposerPresentation } from "../voice-input/voiceInputPresentation";
import type { ExistingThreadSettingsRouteParams } from "./ThreadSettingsSheet";
import type { ContextWindowSnapshot } from "@t3tools/client-runtime/state/context-window";
import {
useThreadSettingsSheetPresentation,
type NavigationWithFinishTransitioning,
Expand All @@ -134,6 +135,8 @@ export const THREAD_COMPOSER_BOTTOM_GUTTER = COMPOSER_BOTTOM_GUTTER;
const NO_MACHINES: ReadonlyArray<ComposerEnvironmentCandidate> = [];

export interface ThreadComposerProps {
/** The thread's context window use, drawn as a ring in the send and stop buttons. */
readonly contextWindow?: ContextWindowSnapshot | null;
readonly isDraft?: boolean;
readonly canOperateThread: boolean;
readonly placeholder: string;
Expand Down Expand Up @@ -216,6 +219,7 @@ function SendActionButton(props: {
readonly accessibilityLabel: string;
readonly presentation: ComposerSendPresentation;
readonly disabled: boolean;
readonly contextPercent?: number | null;
readonly onSend: (followUp?: ActiveTurnComposerAction) => void;
}) {
const { presentation } = props;
Expand All @@ -228,6 +232,7 @@ function SendActionButton(props: {
icon={presentation.icon}
variant="primary"
disabled={props.disabled}
contextPercent={props.contextPercent}
onPress={() => props.onSend()}
/>
);
Expand Down Expand Up @@ -258,6 +263,7 @@ function SendActionButton(props: {

export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps) {
const gt = useGT();
const contextPercent = props.contextWindow?.usedPercentage ?? null;
const messages = useMessages();
const project = useProject(scopeProjectRef(props.environmentId, props.selectedThread.projectId));
const { themeVariables: materialTheme } = useAppearancePreferences();
Expand Down Expand Up @@ -1056,6 +1062,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
icon="stop.fill"
variant="danger"
disabled={!props.canOperateThread}
contextPercent={contextPercent}
onPress={props.onStopThread}
/>
) : showResumeAction ? (
Expand All @@ -1072,6 +1079,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
accessibilityLabel={sendBlockedReason ?? sendLabel}
presentation={sendPresentation}
disabled={!canSend}
contextPercent={contextPercent}
onSend={handleSend}
/>
)}
Expand Down Expand Up @@ -1124,6 +1132,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
icon="stop.fill"
variant="danger"
disabled={!props.canOperateThread}
contextPercent={contextPercent}
onPress={props.onStopThread}
/>
) : showResumeAction && voicePresentation.showsSend ? (
Expand All @@ -1140,6 +1149,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
accessibilityLabel={sendBlockedReason ?? sendLabel}
presentation={sendPresentation}
disabled={!canSend}
contextPercent={contextPercent}
onSend={handleSend}
/>
) : null}
Expand Down
3 changes: 3 additions & 0 deletions apps/mobile/src/features/threads/ThreadDetailScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { mobilePreferencesAtom } from "../../state/preferences";
import { parseThreadKey, threadKey } from "@t3tools/client-runtime/state/entities";
import { createThreadVisitTracker } from "@t3tools/client-runtime/state/thread-visits";
import { useChildThreadInputs, useThreadReportedModelSelection } from "../../state/entities";
import { useThreadContextWindow } from "../../state/use-thread-detail";
import { UsageLimitRecoveryCard } from "./UsageLimitRecoveryCard";
import { useFocusEffect, useNavigation } from "@react-navigation/native";
import {
Expand Down Expand Up @@ -434,6 +435,7 @@ function ThreadDetailBody(
const openInspector = useOpenThreadInspector();
const { session: voiceInputSession } = useGlobalVoiceInput();
const reportedModelSelection = useThreadReportedModelSelection(props.selectedThreadDetailRef);
const contextWindow = useThreadContextWindow(props.selectedThreadDetailRef);
const deviceState = useEnvironmentQuery(
deviceEnvironment.state({ environmentId: props.environmentId, input: {} }),
);
Expand Down Expand Up @@ -1919,6 +1921,7 @@ function ThreadDetailBody(
) : (
<>
<ThreadComposer
contextWindow={contextWindow}
isDraft={Boolean(props.draftMode)}
canOperateThread={props.canOperateThread}
reportedModelSelection={reportedModelSelection}
Expand Down
23 changes: 23 additions & 0 deletions apps/mobile/src/state/use-thread-detail.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { useAtomValue } from "@effect/atom-react";
import type { PendingThreadRequests } from "@t3tools/client-runtime/state/thread-requests";
import {
deriveLatestContextWindowSnapshot,
latestProviderTurnTokenUsage,
type ContextWindowSnapshot,
} from "@t3tools/client-runtime/state/context-window";
import type { EnvironmentThreadStructure } from "@t3tools/client-runtime/state/models";
import type { EnvironmentThread } from "@t3tools/client-runtime/state/shell";
import type {
Expand All @@ -9,6 +14,7 @@ import type {
ThreadId,
} from "@t3tools/contracts";
import { Atom } from "effect/reactivity";
import { useMemo } from "react";

import { environmentThreadDetails, useEnvironmentThread } from "./threads";
import { useThreadSelection } from "./use-thread-selection";
Expand Down Expand Up @@ -56,6 +62,23 @@ export function useQuietThreadStructure(
);
}

/** The thread's context window use, derived the same way as the web composer's. */
export function useThreadContextWindow(ref: ScopedThreadRef | null): ContextWindowSnapshot | null {
const structure = useQuietThreadStructure(ref);
return useMemo(() => {
if (structure === null) return null;
const { projection } = structure;
const providerThread = projection.providerThreads.find(
(thread) => thread.id === projection.thread.activeProviderThreadId,
);
return deriveLatestContextWindowSnapshot(
projection.visibleTurnItems,
latestProviderTurnTokenUsage(projection.providerTurns, projection, providerThread),
providerThread,
);
}, [structure]);
}

export function useSelectedThreadProjection(): EnvironmentThread | null {
const { selectedThreadDetailRef } = useThreadSelection();
return useThreadProjection({
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/components/ChatView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3821,6 +3821,7 @@ export default function ChatView(props: ChatViewProps) {
) : null}
{!composerMounted ? null : (
<ChatComposer
activeContextWindow={activeContextWindow}
canOperateThread={canOperateThread}
reportedModelSelection={reportedModelSelection}
multipleModelSelections={multipleModelSelections}
Expand Down
11 changes: 10 additions & 1 deletion apps/web/src/components/chat/ChatComposer.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { copySnapshot } from "./copySnapshot";
import type { ContextWindowSnapshot } from "@t3tools/client-runtime/state/context-window";
import { VoiceInputSetup } from "./VoiceInputSetup";
import { useComposerTypingGuard } from "./useComposerTypingGuard";
import { insertAttachmentReferencesForDraft } from "./composerAttachmentReferences";
Expand Down Expand Up @@ -224,6 +225,7 @@ import {
ComposerRestingImagePreviews,
} from "./ComposerAttachmentStrip";
import { CollapsedComposerStopAction, ComposerPrimaryActions } from "./ComposerPrimaryActions";
import { ComposerContextRing } from "./ComposerContextRing";
import { ComposerFooterPrimaryActions } from "./ComposerFooterControls";
import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";
import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight";
Expand Down Expand Up @@ -369,6 +371,8 @@ export interface ChatComposerHandle {
}

export interface ChatComposerProps {
/** The thread's context window use, drawn as a ring in the send and stop buttons. */
activeContextWindow?: ContextWindowSnapshot | null;
composerDraftTarget: ScopedThreadRef | DraftId;
environmentId: EnvironmentId;
canOperateThread: boolean;
Expand Down Expand Up @@ -3777,11 +3781,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
hasSendableContent={hasMessageToSend}
isEditingQueuedMessage={isEditingQueuedMessage}
onInterrupt={handleInterruptPrimaryActionStable}
contextWindow={props.activeContextWindow ?? null}
>
<button
type="button"
data-chat-composer-transition-actions="true"
className="flex size-8 shrink-0 items-center justify-center rounded-full bg-message-action text-message-action-foreground hover:bg-message-action-hover disabled:opacity-64"
className="relative flex size-8 shrink-0 items-center justify-center rounded-full bg-message-action text-message-action-foreground hover:bg-message-action-hover disabled:opacity-64"
disabled={collapsedComposerPrimaryActionDisabled}
aria-label={collapsedComposerPrimaryActionLabel}
aria-busy={composerSendHeld || isSendBusy || undefined}
Expand All @@ -3794,6 +3799,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
else submitComposer();
}}
>
{props.activeContextWindow ? (
<ComposerContextRing usage={props.activeContextWindow} />
) : null}
{composerSendHeld || isSendBusy ? (
<Spinner size="sm" aria-hidden="true" />
) : showResumeAction ? (
Expand Down Expand Up @@ -4073,6 +4081,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
key={`${environmentId}:${activeThreadId ?? "new"}`}
compact={isComposerPrimaryActionsCompact}
canOperateThread={canOperateThread}
activeContextWindow={props.activeContextWindow ?? null}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
pendingAction={pendingPrimaryAction}
isRunning={(phase === "running" || phase === "connecting") && !draftRunsLocally}
canInterrupt={canInterrupt}
Expand Down
43 changes: 43 additions & 0 deletions apps/web/src/components/chat/ComposerContextRing.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import type { ContextWindowSnapshot } from "@t3tools/client-runtime/state/context-window";

const RING_RADIUS = 12;
const RING_CIRCUMFERENCE = 2 * Math.PI * RING_RADIUS;

/**
* How full the thread's context window is, drawn as a ring inside the round send and stop buttons.
* It takes the button's text colour and turns to the error colour past 90%.
*/
export function ComposerContextRing(props: { usage: ContextWindowSnapshot }) {
if (props.usage.usedPercentage === null) return null;
const used = Math.max(0, Math.min(100, props.usage.usedPercentage));
return (
<svg
viewBox="0 0 32 32"
className="pointer-events-none absolute inset-0 size-full -rotate-90"
aria-hidden="true"
data-composer-context-ring={Math.round(used)}
>
<circle
cx="16"
cy="16"
r={RING_RADIUS}
fill="none"
stroke="currentColor"
strokeOpacity={0.26}
strokeWidth="2.5"
/>
<circle
cx="16"
cy="16"
r={RING_RADIUS}
fill="none"
stroke={used > 90 ? "var(--color-error)" : "currentColor"}
strokeWidth="2.5"
strokeLinecap="round"
strokeDasharray={RING_CIRCUMFERENCE}
strokeDashoffset={RING_CIRCUMFERENCE * (1 - used / 100)}
className="transition-[stroke-dashoffset,stroke] duration-500 ease-out motion-reduce:transition-none"
/>
</svg>
);
}
3 changes: 3 additions & 0 deletions apps/web/src/components/chat/ComposerFooterControls.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { ContextWindowSnapshot } from "@t3tools/client-runtime/state/context-window";
import type { ModelSelection, ProviderInstanceId, RuntimeMode } from "@t3tools/contracts";
import { createModelSelection } from "@t3tools/shared/model";
import { T, useGT, useMessages } from "gt-react";
Expand Down Expand Up @@ -195,6 +196,7 @@ export const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryA
children?: React.ReactNode;
compact: boolean;
canOperateThread: boolean;
activeContextWindow?: ContextWindowSnapshot | null;
isPreparingWorktree: boolean;
pendingAction: {
questionIndex: number;
Expand Down Expand Up @@ -257,6 +259,7 @@ export const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryA
hideCompactToggle={props.hideCompactToggle}
keepFullHistory={props.keepFullHistory}
onToggleKeepFullHistory={props.onToggleKeepFullHistory}
contextWindow={props.activeContextWindow ?? null}
>
{props.children}
</ComposerPrimaryActions>
Expand Down
Loading
Loading