feat: display native app and browser icons in work logs (#9093)
Co-authored-by: maria-rcks <[email protected]>
This commit is contained in:
1 parent
0bc59bbae3
commit
6cf0c6ea55
32 files changed
+2165
-32
No files matched your search
@@ -185,6 +185,7 @@ const ANDROID_ICON_BY_MATERIAL_NAME: Record<string, Icon> = {
|
||||
close: IconX,
|
||||
construction: IconHammer,
|
||||
content_copy: IconCopy,
|
||||
desktop_windows: IconDeviceDesktop,
|
||||
edit: IconEdit,
|
||||
error: IconAlertCircle,
|
||||
folder: IconFolder,
|
||||
|
||||
@@ -1501,6 +1501,7 @@ function renderFeedEntry(
|
||||
readonly markdownStyles: MarkdownStyleSets;
|
||||
readonly reviewCommentColors: ReviewCommentColors;
|
||||
readonly reviewCommentBubbleWidth: number;
|
||||
readonly themeAppearance: "light" | "dark";
|
||||
readonly userBubbleMaxWidth: number;
|
||||
},
|
||||
) {
|
||||
@@ -1538,12 +1539,16 @@ function renderFeedEntry(
|
||||
if (entry.type === "work-toggle") {
|
||||
return (
|
||||
<ThreadWorkGroupToggle
|
||||
environmentId={props.environmentId}
|
||||
rowSizing={props.workRowSizing}
|
||||
expanded={entry.expanded}
|
||||
hiddenCount={entry.hiddenCount}
|
||||
iconSubtleColor={iconSubtleColor}
|
||||
summary={entry.summary}
|
||||
summaryKind={entry.summaryKind}
|
||||
themeAppearance={props.themeAppearance}
|
||||
toolSurface={entry.toolSurface}
|
||||
toolIcon={entry.toolIcon}
|
||||
summaryToolIcon={entry.summaryToolIcon}
|
||||
hasFailure={entry.hasFailure}
|
||||
shimmer={entry.shimmer}
|
||||
@@ -1716,12 +1721,14 @@ function renderFeedEntry(
|
||||
// Anchors/details live in ThreadFeed and survive this group-only remount.
|
||||
key={`${entry.id}:${props.workRowSizing.textSizeKey}`}
|
||||
activities={entry.activities}
|
||||
environmentId={props.environmentId}
|
||||
anchorKey={entry.id}
|
||||
copiedRowId={props.copiedRowId}
|
||||
expandedRows={props.expandedWorkRows}
|
||||
rowSizing={props.workRowSizing}
|
||||
scrollPositions={props.workGroupScrollPositions}
|
||||
iconSubtleColor={iconSubtleColor}
|
||||
themeAppearance={props.themeAppearance}
|
||||
onCopyRow={props.onCopyWorkRow}
|
||||
onToggleRow={props.onToggleWorkRow}
|
||||
renderImage={props.renderViewedImage}
|
||||
@@ -2001,6 +2008,7 @@ function ThreadFeedPlaceholder(props: {
|
||||
|
||||
export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const navigation = useNavigation();
|
||||
const { themeAppearance } = useAppearancePreferences();
|
||||
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const disclosureSettleFrameRef = useRef<number | null>(null);
|
||||
const disclosureSettleSecondFrameRef = useRef<number | null>(null);
|
||||
@@ -2319,6 +2327,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
iconSubtleColor,
|
||||
markdownStyles,
|
||||
reviewCommentColors,
|
||||
themeAppearance,
|
||||
userBubbleColor,
|
||||
viewportWidth,
|
||||
}),
|
||||
@@ -2329,6 +2338,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
iconSubtleColor,
|
||||
markdownStyles,
|
||||
reviewCommentColors,
|
||||
themeAppearance,
|
||||
userBubbleColor,
|
||||
viewportWidth,
|
||||
],
|
||||
@@ -2754,6 +2764,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
markdownStyles,
|
||||
reviewCommentColors,
|
||||
reviewCommentBubbleWidth,
|
||||
themeAppearance,
|
||||
userBubbleMaxWidth,
|
||||
skills: props.skills,
|
||||
onUseArtifactTemplate: props.onUseArtifactTemplate,
|
||||
@@ -2774,6 +2785,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
markdownStyles,
|
||||
reviewCommentColors,
|
||||
reviewCommentBubbleWidth,
|
||||
themeAppearance,
|
||||
userBubbleMaxWidth,
|
||||
onCopyWorkRow,
|
||||
markdownLinkHandlers,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { Image } from "expo-image";
|
||||
import { type AppSymbolName, SymbolView } from "../../components/AppSymbol";
|
||||
import { MaskedView } from "@expo/ui/community/masked-view";
|
||||
import type { LegendListRef } from "@legendapp/list/react-native";
|
||||
@@ -26,6 +27,8 @@ import {
|
||||
View,
|
||||
} from "react-native";
|
||||
import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
|
||||
import type { EnvironmentId, ToolActivityIcon } from "@t3tools/contracts";
|
||||
import { toolActivityFaviconUrl } from "@t3tools/shared/favicon";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { T3Wordmark } from "../../components/T3Wordmark";
|
||||
@@ -58,6 +61,7 @@ import Animated, {
|
||||
withSequence,
|
||||
withTiming,
|
||||
} from "react-native-reanimated";
|
||||
import { useAssetUrl } from "../../state/assets";
|
||||
|
||||
const SHIMMER_WIDTH = 72;
|
||||
const SHIMMER_SWEEP_MS = 1_350;
|
||||
@@ -134,17 +138,28 @@ export function ThreadDisclosureChevron(props: {
|
||||
}
|
||||
|
||||
function ShimmerWorkContent(props: {
|
||||
readonly environmentId?: EnvironmentId;
|
||||
readonly highlighted: boolean;
|
||||
readonly icon: WorkContentIcon;
|
||||
readonly iconSubtleColor: ColorValue;
|
||||
readonly label: string;
|
||||
readonly onTextLayout?: ComponentProps<typeof Text>["onTextLayout"];
|
||||
readonly showIcon: boolean;
|
||||
readonly themeAppearance?: "light" | "dark";
|
||||
readonly toolIcon?: ToolActivityIcon;
|
||||
}) {
|
||||
return (
|
||||
<View className="flex-row items-center gap-1.5">
|
||||
<View className="h-6 w-6 shrink-0 items-center justify-center">
|
||||
{props.showIcon ? (
|
||||
{props.showIcon && props.toolIcon && props.environmentId ? (
|
||||
<ToolActivityIconView
|
||||
environmentId={props.environmentId}
|
||||
icon={props.toolIcon}
|
||||
fallback={props.icon}
|
||||
fallbackColor={props.iconSubtleColor}
|
||||
themeAppearance={props.themeAppearance ?? "light"}
|
||||
/>
|
||||
) : props.showIcon ? (
|
||||
<WorkLogIcon
|
||||
icon={props.icon}
|
||||
color={props.iconSubtleColor}
|
||||
@@ -167,10 +182,13 @@ function ShimmerWorkContent(props: {
|
||||
}
|
||||
|
||||
export function ShimmeringWorkContent(props: {
|
||||
readonly environmentId?: EnvironmentId;
|
||||
readonly icon: WorkContentIcon;
|
||||
readonly iconSubtleColor: ColorValue;
|
||||
readonly label: string;
|
||||
readonly showIcon: boolean;
|
||||
readonly themeAppearance?: "light" | "dark";
|
||||
readonly toolIcon?: ToolActivityIcon;
|
||||
}) {
|
||||
const [availableWidth, setAvailableWidth] = useState(0);
|
||||
const [textWidth, setTextWidth] = useState(0);
|
||||
@@ -235,11 +253,14 @@ export function ShimmeringWorkContent(props: {
|
||||
onLayout={(event) => setAvailableWidth(event.nativeEvent.layout.width)}
|
||||
>
|
||||
<ShimmerWorkContent
|
||||
environmentId={props.environmentId}
|
||||
highlighted={false}
|
||||
icon={props.icon}
|
||||
iconSubtleColor={props.iconSubtleColor}
|
||||
label={props.label}
|
||||
showIcon={props.showIcon}
|
||||
themeAppearance={props.themeAppearance}
|
||||
toolIcon={props.toolIcon}
|
||||
onTextLayout={(event) => setTextWidth(event.nativeEvent.lines[0]?.width ?? 0)}
|
||||
/>
|
||||
{!reducedMotion && appIsActive && screenIsFocused && contentWidth > 0 ? (
|
||||
@@ -272,11 +293,14 @@ export function ShimmeringWorkContent(props: {
|
||||
>
|
||||
<Animated.View style={[{ width: availableWidth }, counterSweepStyle]}>
|
||||
<ShimmerWorkContent
|
||||
environmentId={props.environmentId}
|
||||
highlighted
|
||||
icon={props.icon}
|
||||
iconSubtleColor={props.iconSubtleColor}
|
||||
label={props.label}
|
||||
showIcon={props.showIcon}
|
||||
themeAppearance={props.themeAppearance}
|
||||
toolIcon={props.toolIcon}
|
||||
/>
|
||||
</Animated.View>
|
||||
</MaskedView>
|
||||
@@ -307,10 +331,14 @@ function workRowSymbolName(icon: ThreadFeedActivity["icon"]): AppSymbolName {
|
||||
return { ios: "sparkles", android: "auto_awesome" };
|
||||
case "alert":
|
||||
return { ios: "exclamationmark.triangle", android: "error" };
|
||||
case "browser":
|
||||
return { ios: "safari", android: "public" };
|
||||
case "check":
|
||||
return { ios: "checkmark", android: "check" };
|
||||
case "command":
|
||||
return { ios: "terminal", android: "terminal" };
|
||||
case "computer":
|
||||
return { ios: "desktopcomputer", android: "desktop_windows" };
|
||||
case "edit":
|
||||
return { ios: "square.and.pencil", android: "edit" };
|
||||
case "eye":
|
||||
@@ -369,11 +397,13 @@ export function collapsedWorkLogHeight(activities: ReadonlyArray<ThreadFeedActiv
|
||||
interface ThreadWorkLogProps {
|
||||
readonly activities: ReadonlyArray<ThreadFeedActivity>;
|
||||
readonly anchorKey: string;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedRows: Readonly<Record<string, boolean>>;
|
||||
readonly rowSizing: ReturnType<typeof deriveThreadWorkLogSizing>;
|
||||
readonly scrollPositions: Map<string, ThreadWorkGroupScrollPosition>;
|
||||
readonly iconSubtleColor: ColorValue;
|
||||
readonly themeAppearance: "light" | "dark";
|
||||
readonly onCopyRow: (rowId: string, value: string) => void;
|
||||
readonly onToggleRow: (rowId: string, anchorKey: string) => void;
|
||||
readonly renderImage: MarkdownImageRenderer;
|
||||
@@ -388,20 +418,24 @@ export function ThreadWorkLog(props: ThreadWorkLogProps) {
|
||||
anchorKey={props.anchorKey}
|
||||
copied={props.copiedRowId === row.id}
|
||||
expanded={props.expandedRows[row.id] ?? false}
|
||||
environmentId={props.environmentId}
|
||||
iconSubtleColor={props.iconSubtleColor}
|
||||
onCopyRow={props.onCopyRow}
|
||||
onToggleRow={props.onToggleRow}
|
||||
renderImage={props.renderImage}
|
||||
themeAppearance={props.themeAppearance}
|
||||
/>
|
||||
),
|
||||
[
|
||||
props.anchorKey,
|
||||
props.copiedRowId,
|
||||
props.expandedRows,
|
||||
props.environmentId,
|
||||
props.iconSubtleColor,
|
||||
props.onCopyRow,
|
||||
props.onToggleRow,
|
||||
props.renderImage,
|
||||
props.themeAppearance,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -669,7 +703,12 @@ const ThreadWorkLogRow = memo(function ThreadWorkLogRow(
|
||||
!toolPresentation && expanded && row.workEntry.command?.trim() ? "Command" : previewText;
|
||||
const iconIsDestructive = row.icon === "alert" || row.icon === "warning";
|
||||
const failed = row.status === "failure";
|
||||
const icon = toolPresentation?.icon ?? (failed ? "xmark" : workRowSymbolName(row.icon));
|
||||
const toolIcon = row.workEntry.toolIcon ?? row.workEntry.toolSource?.icon;
|
||||
const hasSpecialToolIcon =
|
||||
toolPresentation !== null || row.workEntry.toolSurface !== undefined || toolIcon !== undefined;
|
||||
const icon =
|
||||
toolPresentation?.icon ??
|
||||
(failed && !hasSpecialToolIcon ? "xmark" : workRowSymbolName(row.icon));
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
@@ -697,18 +736,31 @@ const ThreadWorkLogRow = memo(function ThreadWorkLogRow(
|
||||
<View className="min-h-8 flex-row items-center gap-1.5">
|
||||
{row.live ? (
|
||||
<ShimmeringWorkContent
|
||||
environmentId={props.environmentId}
|
||||
icon={icon}
|
||||
iconSubtleColor={props.iconSubtleColor}
|
||||
label={displayText}
|
||||
showIcon
|
||||
themeAppearance={props.themeAppearance}
|
||||
toolIcon={toolIcon}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<View className="h-6 w-6 shrink-0 items-center justify-center">
|
||||
<WorkLogIcon
|
||||
icon={icon}
|
||||
color={iconIsDestructive ? "#e11d48" : props.iconSubtleColor}
|
||||
/>
|
||||
{failed && !hasSpecialToolIcon ? (
|
||||
<WorkLogIcon
|
||||
icon={icon}
|
||||
color={iconIsDestructive ? "#e11d48" : props.iconSubtleColor}
|
||||
/>
|
||||
) : (
|
||||
<ToolActivityIconView
|
||||
environmentId={props.environmentId}
|
||||
icon={toolIcon}
|
||||
fallback={icon}
|
||||
fallbackColor={props.iconSubtleColor}
|
||||
themeAppearance={props.themeAppearance}
|
||||
/>
|
||||
)}
|
||||
</View>
|
||||
<Text
|
||||
className={cn(
|
||||
@@ -728,7 +780,7 @@ const ThreadWorkLogRow = memo(function ThreadWorkLogRow(
|
||||
Copied
|
||||
</Text>
|
||||
) : null}
|
||||
{failed && toolPresentation ? (
|
||||
{failed && hasSpecialToolIcon ? (
|
||||
<View
|
||||
className="h-4 w-4 items-center justify-center"
|
||||
accessibilityElementsHidden
|
||||
@@ -786,6 +838,7 @@ const ThreadWorkLogRow = memo(function ThreadWorkLogRow(
|
||||
});
|
||||
|
||||
export function ThreadWorkGroupToggle(props: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly rowSizing: ReturnType<typeof deriveThreadWorkLogSizing>;
|
||||
readonly expanded: boolean;
|
||||
readonly hiddenCount: number;
|
||||
@@ -793,6 +846,9 @@ export function ThreadWorkGroupToggle(props: {
|
||||
readonly summary: string;
|
||||
readonly summaryKind: ToolGroupSummaryKind;
|
||||
readonly summaryToolIcon?: "browser" | "t3-code";
|
||||
readonly themeAppearance: "light" | "dark";
|
||||
readonly toolSurface?: import("@t3tools/contracts").ToolActivitySurface;
|
||||
readonly toolIcon?: ToolActivityIcon;
|
||||
readonly hasFailure: boolean;
|
||||
readonly shimmer: boolean;
|
||||
readonly onToggle: () => void;
|
||||
@@ -800,7 +856,11 @@ export function ThreadWorkGroupToggle(props: {
|
||||
const accessibilityLabel = props.hasFailure
|
||||
? `${props.summary}, tool call failed`
|
||||
: props.summary;
|
||||
const icon = props.summaryToolIcon ?? toolGroupSummarySymbolName(props.summaryKind);
|
||||
const icon =
|
||||
props.summaryToolIcon ??
|
||||
(props.toolSurface
|
||||
? workRowSymbolName(props.toolSurface)
|
||||
: toolGroupSummarySymbolName(props.summaryKind));
|
||||
|
||||
return (
|
||||
<View className="-mx-1 px-1 py-0">
|
||||
@@ -820,15 +880,24 @@ export function ThreadWorkGroupToggle(props: {
|
||||
{props.shimmer ? (
|
||||
<ShimmeringWorkContent
|
||||
key={props.rowSizing.textSizeKey}
|
||||
environmentId={props.environmentId}
|
||||
icon={icon}
|
||||
iconSubtleColor={props.iconSubtleColor}
|
||||
label={props.summary}
|
||||
showIcon
|
||||
themeAppearance={props.themeAppearance}
|
||||
toolIcon={props.toolIcon}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<View className="h-6 w-6 items-center justify-center">
|
||||
<WorkLogIcon icon={icon} color={props.iconSubtleColor} />
|
||||
<ToolActivityIconView
|
||||
environmentId={props.environmentId}
|
||||
icon={props.toolIcon}
|
||||
fallback={icon}
|
||||
fallbackColor={props.iconSubtleColor}
|
||||
themeAppearance={props.themeAppearance}
|
||||
/>
|
||||
</View>
|
||||
<Text
|
||||
key={props.rowSizing.textSizeKey}
|
||||
@@ -850,6 +919,112 @@ export function ThreadWorkGroupToggle(props: {
|
||||
);
|
||||
}
|
||||
|
||||
function ToolActivityIconView(props: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly icon?: ToolActivityIcon;
|
||||
readonly fallback: WorkContentIcon;
|
||||
readonly fallbackColor: ColorValue;
|
||||
readonly themeAppearance: "light" | "dark";
|
||||
}) {
|
||||
if (!props.icon) {
|
||||
return <WorkLogIcon icon={props.fallback} color={props.fallbackColor} />;
|
||||
}
|
||||
if (props.icon._tag === "website") {
|
||||
const source = toolActivityFaviconUrl(props.icon, props.themeAppearance, 32);
|
||||
return source ? (
|
||||
<ToolActivityImage
|
||||
key={source}
|
||||
source={source}
|
||||
fallback={props.fallback}
|
||||
color={props.fallbackColor}
|
||||
themeAppearance={props.themeAppearance}
|
||||
/>
|
||||
) : (
|
||||
<WorkLogIcon icon={props.fallback} color={props.fallbackColor} />
|
||||
);
|
||||
}
|
||||
if (props.icon._tag === "themed-logo") {
|
||||
const source =
|
||||
props.themeAppearance === "dark"
|
||||
? (props.icon.logoUrlDark ?? props.icon.logoUrl)
|
||||
: props.icon.logoUrl;
|
||||
return (
|
||||
<ToolActivityImage
|
||||
key={source}
|
||||
source={source}
|
||||
fallback={props.fallback}
|
||||
color={props.fallbackColor}
|
||||
themeAppearance={props.themeAppearance}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<NativeAppToolActivityIcon
|
||||
environmentId={props.environmentId}
|
||||
app={props.icon.app}
|
||||
fallback={props.fallback}
|
||||
color={props.fallbackColor}
|
||||
themeAppearance={props.themeAppearance}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function NativeAppToolActivityIcon(props: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly app: Extract<ToolActivityIcon, { readonly _tag: "native-app" }>["app"];
|
||||
readonly fallback: WorkContentIcon;
|
||||
readonly color: ColorValue;
|
||||
readonly themeAppearance: "light" | "dark";
|
||||
}) {
|
||||
const source = useAssetUrl(props.environmentId, {
|
||||
_tag: "native-app-icon",
|
||||
app: props.app,
|
||||
});
|
||||
return source ? (
|
||||
<ToolActivityImage
|
||||
key={source}
|
||||
source={source}
|
||||
fallback={props.fallback}
|
||||
color={props.color}
|
||||
themeAppearance={props.themeAppearance}
|
||||
/>
|
||||
) : (
|
||||
<WorkLogIcon icon={props.fallback} color={props.color} />
|
||||
);
|
||||
}
|
||||
|
||||
function ToolActivityImage(props: {
|
||||
readonly source: string;
|
||||
readonly fallback: WorkContentIcon;
|
||||
readonly color: ColorValue;
|
||||
readonly themeAppearance: "light" | "dark";
|
||||
}) {
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const [failed, setFailed] = useState(false);
|
||||
return (
|
||||
<View className="h-4 w-4 items-center justify-center overflow-hidden rounded-[3px] bg-background">
|
||||
{!loaded || failed ? <WorkLogIcon icon={props.fallback} color={props.color} /> : null}
|
||||
{!failed ? (
|
||||
<View
|
||||
style={[
|
||||
StyleSheet.absoluteFill,
|
||||
props.themeAppearance === "light" ? { filter: [{ brightness: 0.6 }] } : undefined,
|
||||
]}
|
||||
>
|
||||
<Image
|
||||
source={props.source}
|
||||
cachePolicy="memory-disk"
|
||||
contentFit="contain"
|
||||
style={[StyleSheet.absoluteFill, { opacity: loaded ? 0.7 : 0 }]}
|
||||
onLoad={() => setLoaded(true)}
|
||||
onError={() => setFailed(true)}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function toolGroupSummarySymbolName(kind: ToolGroupSummaryKind): AppSymbolName {
|
||||
switch (kind) {
|
||||
case "read":
|
||||
|
||||
@@ -800,6 +800,20 @@ describe("buildThreadFeed", () => {
|
||||
payload: {
|
||||
title: "Call repository tool",
|
||||
itemType: "mcp_tool_call",
|
||||
toolSurface: "computer",
|
||||
toolIcon: {
|
||||
_tag: "native-app",
|
||||
app: { _tag: "app-id", appId: "com.example.Editor" },
|
||||
},
|
||||
toolSource: {
|
||||
key: "native-app:com.example.editor",
|
||||
name: "Computer Use",
|
||||
kind: "computer",
|
||||
icon: {
|
||||
_tag: "native-app",
|
||||
app: { _tag: "app-id", appId: "com.example.Editor" },
|
||||
},
|
||||
},
|
||||
detail: "repository.search",
|
||||
status: "completed",
|
||||
data: {
|
||||
@@ -820,7 +834,21 @@ describe("buildThreadFeed", () => {
|
||||
return;
|
||||
}
|
||||
|
||||
expect(group.activities[0]?.icon).toBe("wrench");
|
||||
expect(group.activities[0]?.icon).toBe("computer");
|
||||
expect(group.activities[0]?.workEntry.toolSurface).toBe("computer");
|
||||
expect(group.activities[0]?.workEntry.toolIcon).toEqual({
|
||||
_tag: "native-app",
|
||||
app: { _tag: "app-id", appId: "com.example.Editor" },
|
||||
});
|
||||
expect(group.activities[0]?.workEntry.toolSource).toEqual({
|
||||
key: "native-app:com.example.editor",
|
||||
name: "Computer Use",
|
||||
kind: "computer",
|
||||
icon: {
|
||||
_tag: "native-app",
|
||||
app: { _tag: "app-id", appId: "com.example.Editor" },
|
||||
},
|
||||
});
|
||||
expect(group.activities[0]?.getFullDetail()).toContain('"query": "work log"');
|
||||
expect(group.activities[0]?.getFullDetail()).toContain("repository.search");
|
||||
});
|
||||
@@ -1600,6 +1628,8 @@ describe("buildThreadFeed", () => {
|
||||
id: string,
|
||||
createdAt: string,
|
||||
status: ThreadFeedActivity["status"] = "success",
|
||||
toolSurface?: "browser" | "computer",
|
||||
toolIcon?: import("@t3tools/contracts").ToolActivityIcon,
|
||||
): ThreadFeedActivity => ({
|
||||
id,
|
||||
createdAt,
|
||||
@@ -1619,6 +1649,8 @@ describe("buildThreadFeed", () => {
|
||||
label: `Tool ${id}`,
|
||||
command: `command ${id}`,
|
||||
tone: "tool",
|
||||
...(toolSurface ? { toolSurface } : {}),
|
||||
...(toolIcon ? { toolIcon } : {}),
|
||||
},
|
||||
});
|
||||
const feed: ThreadFeedEntry[] = [
|
||||
@@ -1630,8 +1662,11 @@ describe("buildThreadFeed", () => {
|
||||
activities: [
|
||||
activity("activity-1", "2026-04-01T00:00:01.000Z"),
|
||||
activity("activity-neutral", "2026-04-01T00:00:02.000Z", "neutral"),
|
||||
activity("activity-2", "2026-04-01T00:00:03.000Z"),
|
||||
activity("activity-3", "2026-04-01T00:00:04.000Z"),
|
||||
activity("activity-2", "2026-04-01T00:00:03.000Z", "success", "browser"),
|
||||
activity("activity-3", "2026-04-01T00:00:04.000Z", "success", "computer", {
|
||||
_tag: "native-app",
|
||||
app: { _tag: "app-id", appId: "com.example.Editor" },
|
||||
}),
|
||||
],
|
||||
},
|
||||
];
|
||||
@@ -1644,6 +1679,11 @@ describe("buildThreadFeed", () => {
|
||||
hiddenCount: 3,
|
||||
expanded: false,
|
||||
summary: "Ran 3 commands",
|
||||
toolSurface: "computer",
|
||||
toolIcon: {
|
||||
_tag: "native-app",
|
||||
app: { _tag: "app-id", appId: "com.example.Editor" },
|
||||
},
|
||||
});
|
||||
|
||||
const expanded = deriveThreadFeedPresentation(
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
toolGroupSummaryKind,
|
||||
type ToolGroupSummaryKind,
|
||||
} from "@t3tools/client-runtime/work-log/presentation";
|
||||
import { extractToolActivityPresentation } from "@t3tools/client-runtime/work-log/tool-presentation";
|
||||
import { commandProgramName } from "@t3tools/client-runtime/work-log/command-label";
|
||||
|
||||
import * as Arr from "effect/Array";
|
||||
@@ -67,8 +68,10 @@ export interface ThreadFeedActivity {
|
||||
readonly icon:
|
||||
| "agent"
|
||||
| "alert"
|
||||
| "browser"
|
||||
| "check"
|
||||
| "command"
|
||||
| "computer"
|
||||
| "edit"
|
||||
| "eye"
|
||||
| "globe"
|
||||
@@ -99,6 +102,9 @@ export interface WorkLogEntry {
|
||||
changedFiles?: ReadonlyArray<string>;
|
||||
tone: "thinking" | "tool" | "info" | "error";
|
||||
toolTitle?: string;
|
||||
toolSurface?: import("@t3tools/contracts").ToolActivitySurface;
|
||||
toolIcon?: import("@t3tools/contracts").ToolActivityIcon;
|
||||
toolSource?: import("@t3tools/contracts").ToolActivitySource;
|
||||
itemType?: ToolLifecycleItemType;
|
||||
requestKind?: PendingApproval["requestKind"];
|
||||
toolLifecycleStatus?: WorkLogToolLifecycleStatus;
|
||||
@@ -149,6 +155,8 @@ export type ThreadFeedEntry =
|
||||
readonly expanded: boolean;
|
||||
readonly summary: string;
|
||||
readonly summaryKind: ToolGroupSummaryKind;
|
||||
readonly toolSurface?: WorkLogEntry["toolSurface"];
|
||||
readonly toolIcon?: WorkLogEntry["toolIcon"];
|
||||
readonly summaryToolIcon?: "browser" | "t3-code";
|
||||
readonly hasFailure: boolean;
|
||||
readonly live: boolean;
|
||||
@@ -398,6 +406,7 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
|
||||
const commandPreview = extractToolCommand(payload);
|
||||
const changedFiles = extractChangedFiles(payload);
|
||||
const title = extractToolTitle(payload);
|
||||
const toolPresentation = extractToolActivityPresentation(payload);
|
||||
// task.updated included: terminal bypassed updates (Codex children's only
|
||||
// terminal signal) must carry task identity so they collapse per child
|
||||
// instead of stacking anonymous "Task idle" rows.
|
||||
@@ -479,6 +488,15 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
|
||||
if (title) {
|
||||
entry.toolTitle = title;
|
||||
}
|
||||
if (toolPresentation.toolSurface) {
|
||||
entry.toolSurface = toolPresentation.toolSurface;
|
||||
}
|
||||
if (toolPresentation.toolIcon) {
|
||||
entry.toolIcon = toolPresentation.toolIcon;
|
||||
}
|
||||
if (toolPresentation.toolSource) {
|
||||
entry.toolSource = toolPresentation.toolSource;
|
||||
}
|
||||
if (itemType === "mcp_tool_call") {
|
||||
const data = asRecord(payload?.data);
|
||||
const toolData = typeof data?.toolName === "string" ? (data.item ?? data) : data?.item;
|
||||
@@ -614,6 +632,9 @@ function mergeDerivedWorkLogEntries(
|
||||
const command = next.command ?? previous.command;
|
||||
const rawCommand = next.rawCommand ?? previous.rawCommand;
|
||||
const toolTitle = next.toolTitle ?? previous.toolTitle;
|
||||
const toolSurface = next.toolSurface ?? previous.toolSurface;
|
||||
const toolIcon = next.toolIcon ?? previous.toolIcon;
|
||||
const toolSource = next.toolSource ?? previous.toolSource;
|
||||
const itemType = next.itemType ?? previous.itemType;
|
||||
const requestKind = next.requestKind ?? previous.requestKind;
|
||||
const collapseKey = next.collapseKey ?? previous.collapseKey;
|
||||
@@ -631,6 +652,9 @@ function mergeDerivedWorkLogEntries(
|
||||
...(rawCommand ? { rawCommand } : {}),
|
||||
...(changedFiles.length > 0 ? { changedFiles } : {}),
|
||||
...(toolTitle ? { toolTitle } : {}),
|
||||
...(toolSurface ? { toolSurface } : {}),
|
||||
...(toolIcon ? { toolIcon } : {}),
|
||||
...(toolSource ? { toolSource } : {}),
|
||||
...(itemType ? { itemType } : {}),
|
||||
...(requestKind ? { requestKind } : {}),
|
||||
...(collapseKey ? { collapseKey } : {}),
|
||||
@@ -752,6 +776,7 @@ function workEntryIcon(entry: DerivedWorkLogEntry): ThreadFeedActivity["icon"] {
|
||||
return "message";
|
||||
}
|
||||
if (entry.sourceActivityKind === "runtime.warning") return "warning";
|
||||
if (entry.toolSurface) return entry.toolSurface;
|
||||
if (entry.requestKind === "command") return "command";
|
||||
if (entry.requestKind === "file-read") return "eye";
|
||||
if (entry.requestKind === "file-change") return "edit";
|
||||
@@ -1537,6 +1562,27 @@ function appendToolGroupRows(
|
||||
: singleActivity !== null && !singleActivity.toolLike
|
||||
? singleActivity.workEntry.label
|
||||
: summarizeToolGroup(activities.map((activity) => activity.workEntry));
|
||||
const primarySourceActivity = activities.find(
|
||||
(activity) => activity.workEntry.toolSource !== undefined,
|
||||
);
|
||||
const primarySourceKey = primarySourceActivity?.workEntry.toolSource?.key;
|
||||
const primarySourceIcon = primarySourceKey
|
||||
? (activities.find(
|
||||
(activity) =>
|
||||
activity.workEntry.toolSource?.key === primarySourceKey &&
|
||||
activity.workEntry.toolIcon !== undefined,
|
||||
)?.workEntry.toolIcon ?? primarySourceActivity?.workEntry.toolSource?.icon)
|
||||
: undefined;
|
||||
const groupToolSurface =
|
||||
primarySourceActivity?.workEntry.toolSurface ??
|
||||
latestActivity.workEntry.toolSurface ??
|
||||
activities.findLast((activity) => activity.workEntry.toolSurface !== undefined)?.workEntry
|
||||
.toolSurface;
|
||||
const groupToolIcon =
|
||||
primarySourceIcon ??
|
||||
latestActivity.workEntry.toolIcon ??
|
||||
activities.findLast((activity) => activity.workEntry.toolIcon !== undefined)?.workEntry
|
||||
.toolIcon;
|
||||
const summaryToolIcon = live
|
||||
? resolveWorkEntryToolPresentation(latestActivity.workEntry)?.icon
|
||||
: singleActivity !== null &&
|
||||
@@ -1556,6 +1602,8 @@ function appendToolGroupRows(
|
||||
summaryKind: toolGroupSummaryKind(
|
||||
(live ? [latestActivity] : activities).map((activity) => activity.workEntry),
|
||||
),
|
||||
...(groupToolSurface ? { toolSurface: groupToolSurface } : {}),
|
||||
...(groupToolIcon ? { toolIcon: groupToolIcon } : {}),
|
||||
...(summaryToolIcon ? { summaryToolIcon } : {}),
|
||||
hasFailure: activities.findLast((activity) => activity.toolLike)?.status === "failure",
|
||||
live,
|
||||
|
||||
@@ -22,6 +22,7 @@ import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
|
||||
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
|
||||
import { assetFileResponse } from "../http.ts";
|
||||
import { ASSET_ROUTE_PREFIX, issueAssetUrl, resolveAsset } from "./AssetAccess.ts";
|
||||
import * as NativeAppIconResolver from "./NativeAppIconResolver.ts";
|
||||
import { openMediaFile } from "./MediaFile.ts";
|
||||
|
||||
vi.mock("node:fs/promises", async (importOriginal) => {
|
||||
@@ -40,6 +41,7 @@ const testLayer = Layer.mergeAll(
|
||||
Layer.provide(WorkspacePaths.layer),
|
||||
Layer.provide(T3ProjectFileLoader.layer),
|
||||
),
|
||||
NativeAppIconResolver.layer.pipe(Layer.provide(configLayer)),
|
||||
ServerSecretStore.layer.pipe(Layer.provide(configLayer)),
|
||||
).pipe(Layer.provideMerge(NodeServices.layer));
|
||||
|
||||
@@ -576,6 +578,21 @@ describe("AssetAccess", () => {
|
||||
});
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
it.effect("issues signed native application icon capabilities", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* issueAssetUrl({
|
||||
resource: {
|
||||
_tag: "native-app-icon",
|
||||
app: { _tag: "app-id", appId: "com.example.Editor" },
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.relativeUrl).toMatch(
|
||||
new RegExp(`^${ASSET_ROUTE_PREFIX}/[^/]+/native-app-icon\\.png$`, "u"),
|
||||
);
|
||||
expect(result.expiresAt).toBeGreaterThan(0);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("serves document attachments inline when a viewer requests it", () =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
AssetWorkspacePathValidationError,
|
||||
AssetWorkspaceResolutionError,
|
||||
AssetWorkspaceRootNormalizationError,
|
||||
ToolActivityNativeAppReference,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
hostPreviewMimeTypeFromExtension,
|
||||
@@ -42,6 +43,7 @@ import { parseAttachmentFileExtension, resolveAttachmentPathById } from "../atta
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
|
||||
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
|
||||
import * as NativeAppIconResolver from "./NativeAppIconResolver.ts";
|
||||
import { openMediaFile, type OpenMediaFile } from "./MediaFile.ts";
|
||||
|
||||
export const ASSET_ROUTE_PREFIX = "/api/assets";
|
||||
@@ -120,6 +122,12 @@ const AssetClaimsSchema = Schema.Union([
|
||||
filePath: Schema.String,
|
||||
expiresAt: Schema.Number,
|
||||
}),
|
||||
Schema.Struct({
|
||||
version: Schema.Literal(1),
|
||||
kind: Schema.Literal("native-app-icon"),
|
||||
app: ToolActivityNativeAppReference,
|
||||
expiresAt: Schema.Number,
|
||||
}),
|
||||
]);
|
||||
type AssetClaims = typeof AssetClaimsSchema.Type;
|
||||
|
||||
@@ -504,6 +512,16 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "native-app-icon": {
|
||||
claims = {
|
||||
version: 1,
|
||||
kind: "native-app-icon",
|
||||
app: input.resource.app,
|
||||
expiresAt,
|
||||
};
|
||||
fileName = "native-app-icon.png";
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const secretStore = yield* ServerSecretStore.ServerSecretStore;
|
||||
@@ -603,6 +621,12 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
|
||||
: null;
|
||||
}
|
||||
|
||||
if (claims.kind === "native-app-icon") {
|
||||
const nativeAppIconResolver = yield* NativeAppIconResolver.NativeAppIconResolver;
|
||||
const iconPath = yield* nativeAppIconResolver.resolve(claims.app);
|
||||
return iconPath ? ({ kind: "file", path: iconPath } satisfies ResolvedAsset) : null;
|
||||
}
|
||||
|
||||
const decodedPath = decodeRelativePath(relativePath);
|
||||
if (decodedPath === null) return null;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as NativeAppIconResolver from "./NativeAppIconResolver.ts";
|
||||
|
||||
function emptyProcessHandle() {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.empty,
|
||||
stderr: Stream.empty,
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
});
|
||||
}
|
||||
|
||||
describe("resolveNativeAppIcon", () => {
|
||||
it.effect("escapes Spotlight wildcards and caches misses", () => {
|
||||
const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> = [];
|
||||
const spawner = ChildProcessSpawner.make((command) =>
|
||||
Effect.sync(() => {
|
||||
const input = command as unknown as {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
};
|
||||
commands.push(input);
|
||||
return emptyProcessHandle();
|
||||
}),
|
||||
);
|
||||
const configLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-native-app-icon-test-",
|
||||
});
|
||||
const dependencies = Layer.mergeAll(
|
||||
configLayer,
|
||||
Layer.succeed(HostProcessPlatform, "darwin"),
|
||||
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
).pipe(Layer.provideMerge(NodeServices.layer));
|
||||
const testLayer = NativeAppIconResolver.layer.pipe(Layer.provide(dependencies));
|
||||
const app = { _tag: "display-name", displayName: "Review * App" } as const;
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const resolver = yield* NativeAppIconResolver.NativeAppIconResolver;
|
||||
expect(yield* resolver.resolve(app)).toBeNull();
|
||||
expect(yield* resolver.resolve(app)).toBeNull();
|
||||
|
||||
expect(commands).toHaveLength(1);
|
||||
expect(commands[0]).toMatchObject({ command: "/usr/bin/mdfind" });
|
||||
expect(commands[0]?.args[0]).toContain("Review \\* App");
|
||||
|
||||
for (let index = 0; index < 256; index += 1) {
|
||||
expect(
|
||||
yield* resolver.resolve({
|
||||
_tag: "display-name",
|
||||
displayName: `Missing Review App ${index}`,
|
||||
}),
|
||||
).toBeNull();
|
||||
}
|
||||
expect(commands).toHaveLength(257);
|
||||
expect(yield* resolver.resolve(app)).toBeNull();
|
||||
expect(commands).toHaveLength(258);
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,268 @@
|
||||
import * as NodeCrypto from "node:crypto";
|
||||
import type { ToolActivityNativeAppReference } from "@t3tools/contracts";
|
||||
import * as Cache from "effect/Cache";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
|
||||
const ICON_SIZE = 64;
|
||||
const COMMAND_TIMEOUT = "5 seconds";
|
||||
const RESOLUTION_CACHE_TTL = Duration.hours(1);
|
||||
const RESOLUTION_CACHE_MAX_ENTRIES = 256;
|
||||
|
||||
/** Resolves and caches macOS application icons without exposing host paths to clients. */
|
||||
export class NativeAppIconResolver extends Context.Service<
|
||||
NativeAppIconResolver,
|
||||
{
|
||||
/** Returns a cached PNG path for the application, or `null` when no icon is available. */
|
||||
readonly resolve: (app: ToolActivityNativeAppReference) => Effect.Effect<string | null>;
|
||||
}
|
||||
>()("t3/assets/NativeAppIconResolver") {}
|
||||
|
||||
function appCacheKey(app: ToolActivityNativeAppReference): string {
|
||||
return JSON.stringify(app);
|
||||
}
|
||||
|
||||
function appFromCacheKey(key: string): ToolActivityNativeAppReference {
|
||||
return JSON.parse(key) as ToolActivityNativeAppReference;
|
||||
}
|
||||
|
||||
const existingFile = Effect.fn("NativeAppIconResolver.existingFile")(function* (filePath: string) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const info = yield* fileSystem.stat(filePath).pipe(
|
||||
Effect.map(Option.some),
|
||||
Effect.catchTags({
|
||||
PlatformError: (error) =>
|
||||
error.reason._tag === "NotFound" ? Effect.succeed(Option.none()) : Effect.fail(error),
|
||||
}),
|
||||
);
|
||||
return Option.isSome(info) && info.value.type === "File" ? filePath : null;
|
||||
});
|
||||
|
||||
const commandOutput = Effect.fn("NativeAppIconResolver.commandOutput")(function* (
|
||||
command: string,
|
||||
args: ReadonlyArray<string>,
|
||||
) {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
return yield* spawner
|
||||
.string(ChildProcess.make(command, args, { stdin: "ignore", stderr: "ignore" }))
|
||||
.pipe(Effect.timeout(COMMAND_TIMEOUT));
|
||||
});
|
||||
|
||||
const plistValue = Effect.fn("NativeAppIconResolver.plistValue")(function* (
|
||||
infoPlistPath: string,
|
||||
key: string,
|
||||
) {
|
||||
return yield* commandOutput("/usr/bin/plutil", [
|
||||
"-extract",
|
||||
key,
|
||||
"raw",
|
||||
"-o",
|
||||
"-",
|
||||
infoPlistPath,
|
||||
]).pipe(
|
||||
Effect.map((value) => value.trim()),
|
||||
Effect.orElseSucceed(() => ""),
|
||||
);
|
||||
});
|
||||
|
||||
function escapeSpotlightString(value: string): string {
|
||||
return value.replace(/([\\'*?])/gu, "\\$1");
|
||||
}
|
||||
|
||||
function containsControlCharacter(value: string): boolean {
|
||||
return [...value].some((character) => {
|
||||
const codePoint = character.codePointAt(0) ?? 0;
|
||||
return codePoint <= 31 || codePoint === 127;
|
||||
});
|
||||
}
|
||||
|
||||
const resolveApplicationPath = Effect.fn("NativeAppIconResolver.resolveApplicationPath")(function* (
|
||||
app: ToolActivityNativeAppReference,
|
||||
) {
|
||||
const path = yield* Path.Path;
|
||||
const query =
|
||||
app._tag === "app-id"
|
||||
? `kMDItemCFBundleIdentifier == '${app.appId}'`
|
||||
: `kMDItemContentType == 'com.apple.application-bundle' && kMDItemDisplayName == '${escapeSpotlightString(app.displayName)}'`;
|
||||
const spotlightOutput = yield* commandOutput("/usr/bin/mdfind", [query]);
|
||||
const candidates = spotlightOutput
|
||||
.split(/\r?\n/u)
|
||||
.map((value) => value.trim())
|
||||
.filter((value) => value.endsWith(".app"));
|
||||
const matchingCandidates =
|
||||
app._tag === "app-id"
|
||||
? candidates
|
||||
: candidates.filter(
|
||||
(value) =>
|
||||
path.basename(value, ".app").toLocaleLowerCase() ===
|
||||
app.displayName.toLocaleLowerCase(),
|
||||
);
|
||||
const rankedCandidates = matchingCandidates.length > 0 ? matchingCandidates : candidates;
|
||||
let mostRecentlyUsed: { readonly path: string; readonly lastUsed: string } | null = null;
|
||||
for (const candidate of rankedCandidates) {
|
||||
const lastUsed = yield* commandOutput("/usr/bin/mdls", [
|
||||
"-raw",
|
||||
"-name",
|
||||
"kMDItemLastUsedDate",
|
||||
candidate,
|
||||
]).pipe(
|
||||
Effect.map((value) => value.trim()),
|
||||
Effect.orElseSucceed(() => ""),
|
||||
);
|
||||
if (!mostRecentlyUsed || lastUsed > mostRecentlyUsed.lastUsed) {
|
||||
mostRecentlyUsed = { path: candidate, lastUsed };
|
||||
}
|
||||
}
|
||||
return mostRecentlyUsed?.path ?? null;
|
||||
});
|
||||
|
||||
const resolveNativeAppIconUncached = Effect.fn("NativeAppIconResolver.resolveUncached")(function* (
|
||||
app: ToolActivityNativeAppReference,
|
||||
) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const appPath = yield* resolveApplicationPath(app);
|
||||
if (!appPath) return null;
|
||||
|
||||
const canonicalAppPath = yield* fileSystem.realPath(appPath);
|
||||
const infoPlistPath = path.join(canonicalAppPath, "Contents", "Info.plist");
|
||||
const resourcesDirectory = path.join(canonicalAppPath, "Contents", "Resources");
|
||||
const iconName =
|
||||
(yield* plistValue(infoPlistPath, "CFBundleIconFile")) ||
|
||||
(yield* plistValue(infoPlistPath, "CFBundleIconName"));
|
||||
if (iconName && path.basename(iconName) !== iconName) return null;
|
||||
const iconFileName = iconName ? (path.extname(iconName) ? iconName : `${iconName}.icns`) : null;
|
||||
const resourceEntries = yield* fileSystem
|
||||
.readDirectory(resourcesDirectory)
|
||||
.pipe(Effect.orElseSucceed(() => []));
|
||||
const sourceIconCandidate =
|
||||
(iconFileName ? yield* existingFile(path.join(resourcesDirectory, iconFileName)) : null) ??
|
||||
(yield* existingFile(path.join(resourcesDirectory, "AppIcon.icns"))) ??
|
||||
(resourceEntries.find((entry) => entry.toLowerCase().endsWith(".icns"))
|
||||
? yield* existingFile(
|
||||
path.join(
|
||||
resourcesDirectory,
|
||||
resourceEntries.find((entry) => entry.toLowerCase().endsWith(".icns"))!,
|
||||
),
|
||||
)
|
||||
: null);
|
||||
if (!sourceIconCandidate) return null;
|
||||
const sourceIconPath = yield* fileSystem.realPath(sourceIconCandidate);
|
||||
const relativeSource = path.relative(resourcesDirectory, sourceIconPath);
|
||||
if (
|
||||
relativeSource === ".." ||
|
||||
relativeSource.startsWith(`..${path.sep}`) ||
|
||||
path.isAbsolute(relativeSource)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const appVersion =
|
||||
(yield* plistValue(infoPlistPath, "CFBundleVersion")) ||
|
||||
(yield* plistValue(infoPlistPath, "CFBundleShortVersionString"));
|
||||
const cacheKey = NodeCrypto.createHash("sha256")
|
||||
.update(`${canonicalAppPath}\0${appVersion}\0${sourceIconPath}`)
|
||||
.digest("hex");
|
||||
const cacheDirectory = path.join(config.providerStatusCacheDir, "native-app-icons");
|
||||
const cachePath = path.join(cacheDirectory, `${cacheKey}.png`);
|
||||
if (yield* existingFile(cachePath)) return cachePath;
|
||||
|
||||
yield* fileSystem.makeDirectory(cacheDirectory, { recursive: true });
|
||||
const temporaryPath = path.join(
|
||||
cacheDirectory,
|
||||
`.${cacheKey}-${process.pid}-${(yield* Clock.currentTimeMillis).toString(36)}-${NodeCrypto.randomUUID()}.png`,
|
||||
);
|
||||
yield* commandOutput("/usr/bin/sips", [
|
||||
"-z",
|
||||
String(ICON_SIZE),
|
||||
String(ICON_SIZE),
|
||||
"-s",
|
||||
"format",
|
||||
"png",
|
||||
sourceIconPath,
|
||||
"--out",
|
||||
temporaryPath,
|
||||
]).pipe(
|
||||
Effect.tap(() => fileSystem.rename(temporaryPath, cachePath)),
|
||||
Effect.ensuring(
|
||||
fileSystem.remove(temporaryPath).pipe(Effect.catchTags({ PlatformError: () => Effect.void })),
|
||||
),
|
||||
);
|
||||
return yield* existingFile(cachePath);
|
||||
});
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const hostPlatform = yield* HostProcessPlatform;
|
||||
const resolutionSemaphore = yield* Semaphore.make(2);
|
||||
const resolutionCache: Cache.Cache<
|
||||
string,
|
||||
string | null,
|
||||
PlatformError.PlatformError | Cause.TimeoutError
|
||||
> = yield* Cache.makeWith(
|
||||
(key: string) =>
|
||||
resolutionSemaphore.withPermits(1)(resolveNativeAppIconUncached(appFromCacheKey(key))),
|
||||
{
|
||||
capacity: RESOLUTION_CACHE_MAX_ENTRIES,
|
||||
timeToLive: Exit.match({
|
||||
onSuccess: () => RESOLUTION_CACHE_TTL,
|
||||
onFailure: () => Duration.zero,
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
const cachedFileExists = (filePath: string) =>
|
||||
fileSystem.stat(filePath).pipe(
|
||||
Effect.map((info) => info.type === "File"),
|
||||
Effect.catchTags({
|
||||
PlatformError: (error) =>
|
||||
error.reason._tag === "NotFound" ? Effect.succeed(false) : Effect.fail(error),
|
||||
}),
|
||||
);
|
||||
|
||||
const resolveAttempt = Effect.fn("NativeAppIconResolver.resolve")(function* (
|
||||
app: ToolActivityNativeAppReference,
|
||||
) {
|
||||
if (
|
||||
hostPlatform !== "darwin" ||
|
||||
(app._tag === "display-name" && containsControlCharacter(app.displayName))
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const key = appCacheKey(app);
|
||||
const cached = yield* Cache.get(resolutionCache, key);
|
||||
if (cached === null) return null;
|
||||
if (yield* cachedFileExists(cached)) return cached;
|
||||
|
||||
yield* Cache.invalidate(resolutionCache, key);
|
||||
return yield* Cache.get(resolutionCache, key);
|
||||
});
|
||||
|
||||
const resolve: NativeAppIconResolver["Service"]["resolve"] = (app) =>
|
||||
resolveAttempt(app).pipe(
|
||||
Effect.tapError((cause) =>
|
||||
Effect.logDebug("Failed to resolve native application icon.", { app, cause }),
|
||||
),
|
||||
Effect.orElseSucceed(() => null),
|
||||
);
|
||||
|
||||
return NativeAppIconResolver.of({ resolve });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(NativeAppIconResolver, make);
|
||||
@@ -2844,6 +2844,16 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
itemType: "command_execution",
|
||||
status: "inProgress",
|
||||
title: "Command run",
|
||||
toolSurface: "computer",
|
||||
toolIcon: {
|
||||
_tag: "native-app",
|
||||
app: { _tag: "app-id", appId: "com.apple.Terminal" },
|
||||
},
|
||||
toolSource: {
|
||||
key: "native-app:com.apple.terminal",
|
||||
name: "Terminal",
|
||||
kind: "computer",
|
||||
},
|
||||
detail: "Bash: vp test run",
|
||||
data: {
|
||||
toolName: "Bash",
|
||||
@@ -2871,6 +2881,17 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
itemType: "command_execution",
|
||||
toolCallId: "tool-call-9",
|
||||
status: "inProgress",
|
||||
title: "Command run",
|
||||
toolSurface: "computer",
|
||||
toolIcon: {
|
||||
_tag: "native-app",
|
||||
app: { _tag: "app-id", appId: "com.apple.Terminal" },
|
||||
},
|
||||
toolSource: {
|
||||
key: "native-app:com.apple.terminal",
|
||||
name: "Terminal",
|
||||
kind: "computer",
|
||||
},
|
||||
detail: "Bash: vp test run",
|
||||
data: {
|
||||
toolName: "Bash",
|
||||
|
||||
@@ -812,7 +812,11 @@ export function runtimeEventToActivities(
|
||||
itemType: event.payload.itemType,
|
||||
...(event.itemId !== undefined ? { toolCallId: event.itemId } : {}),
|
||||
...(event.payload.status ? { status: event.payload.status } : {}),
|
||||
...(event.payload.title ? { title: event.payload.title } : {}),
|
||||
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
|
||||
...(event.payload.toolSurface ? { toolSurface: event.payload.toolSurface } : {}),
|
||||
...(event.payload.toolIcon ? { toolIcon: event.payload.toolIcon } : {}),
|
||||
...(event.payload.toolSource ? { toolSource: event.payload.toolSource } : {}),
|
||||
...(event.payload.data !== undefined ? { data: event.payload.data } : {}),
|
||||
...(event.payload.agentId ? { agentId: event.payload.agentId } : {}),
|
||||
...(event.payload.parentToolUseId
|
||||
@@ -840,7 +844,11 @@ export function runtimeEventToActivities(
|
||||
itemType: event.payload.itemType,
|
||||
...(event.itemId !== undefined ? { toolCallId: event.itemId } : {}),
|
||||
...(event.payload.status ? { status: event.payload.status } : {}),
|
||||
...(event.payload.title ? { title: event.payload.title } : {}),
|
||||
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
|
||||
...(event.payload.toolSurface ? { toolSurface: event.payload.toolSurface } : {}),
|
||||
...(event.payload.toolIcon ? { toolIcon: event.payload.toolIcon } : {}),
|
||||
...(event.payload.toolSource ? { toolSource: event.payload.toolSource } : {}),
|
||||
...(event.payload.data !== undefined ? { data: event.payload.data } : {}),
|
||||
...(event.payload.agentId ? { agentId: event.payload.agentId } : {}),
|
||||
...(event.payload.parentToolUseId
|
||||
@@ -868,7 +876,11 @@ export function runtimeEventToActivities(
|
||||
itemType: event.payload.itemType,
|
||||
...(event.itemId !== undefined ? { toolCallId: event.itemId } : {}),
|
||||
...(event.payload.status ? { status: event.payload.status } : {}),
|
||||
...(event.payload.title ? { title: event.payload.title } : {}),
|
||||
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
|
||||
...(event.payload.toolSurface ? { toolSurface: event.payload.toolSurface } : {}),
|
||||
...(event.payload.toolIcon ? { toolIcon: event.payload.toolIcon } : {}),
|
||||
...(event.payload.toolSource ? { toolSource: event.payload.toolSource } : {}),
|
||||
...(event.payload.data !== undefined ? { data: event.payload.data } : {}),
|
||||
...(event.payload.agentId ? { agentId: event.payload.agentId } : {}),
|
||||
...(event.payload.parentToolUseId
|
||||
|
||||
@@ -800,9 +800,207 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("presents browser and computer-use calls with Codex-style titles and sources", () =>
|
||||
Effect.gen(function* () {
|
||||
const { adapter, runtime } = yield* startLifecycleRuntime();
|
||||
const eventsFiber = yield* Stream.runCollect(Stream.take(adapter.streamEvents, 3)).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
const longIntentTitle = ` ${"a".repeat(39)} ${"a".repeat(38)}😀bc `;
|
||||
const serializedOverContractUrl = `https://example.com/?query=${"😀".repeat(400)}`;
|
||||
|
||||
yield* runtime.emit({
|
||||
id: asEventId("evt-computer-start"),
|
||||
kind: "notification",
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
method: "item/started",
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
itemId: asItemId("computer_1"),
|
||||
payload: {
|
||||
startedAtMs: 1_778_000_000_000,
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
item: {
|
||||
type: "mcpToolCall",
|
||||
id: "computer_1",
|
||||
server: "node_repl",
|
||||
tool: "js",
|
||||
arguments: {
|
||||
code: 'await sky.click({ app: "Finder", x: 10, y: 20 })',
|
||||
title: longIntentTitle,
|
||||
},
|
||||
durationMs: null,
|
||||
error: null,
|
||||
result: {
|
||||
_meta: {
|
||||
"codex/toolSurface": {
|
||||
kind: "computerUse",
|
||||
app: { kind: "appId", appId: "com.apple.finder" },
|
||||
},
|
||||
},
|
||||
content: [],
|
||||
},
|
||||
status: "inProgress",
|
||||
},
|
||||
},
|
||||
});
|
||||
yield* runtime.emit({
|
||||
id: asEventId("evt-browser-complete"),
|
||||
kind: "notification",
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
method: "item/completed",
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
itemId: asItemId("browser_1"),
|
||||
payload: {
|
||||
completedAtMs: 1_778_000_001_000,
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
item: {
|
||||
type: "mcpToolCall",
|
||||
id: "browser_1",
|
||||
server: "node_repl",
|
||||
tool: "js",
|
||||
arguments: { code: "await tab.playwright.domSnapshot()", title: "Inspect checkout" },
|
||||
durationMs: 12,
|
||||
error: null,
|
||||
result: {
|
||||
_meta: {
|
||||
"codex/toolSurface": {
|
||||
kind: "browserUse",
|
||||
backend: "chrome",
|
||||
openTabs: [
|
||||
{
|
||||
pageUrl: "https://www.mathworks.com/help/matlab/",
|
||||
faviconUrl: "https://www.mathworks.com/favicon.ico",
|
||||
faviconUrlDark: "https://www.mathworks.com/favicon-dark.ico",
|
||||
url: "https://www.mathworks.com/help/matlab/",
|
||||
},
|
||||
],
|
||||
},
|
||||
browser_use: { url: serializedOverContractUrl },
|
||||
},
|
||||
content: [],
|
||||
},
|
||||
status: "completed",
|
||||
},
|
||||
},
|
||||
});
|
||||
yield* runtime.emit({
|
||||
id: asEventId("evt-computer-use-complete"),
|
||||
kind: "notification",
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:02.000Z",
|
||||
method: "item/completed",
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
itemId: asItemId("computer_2"),
|
||||
payload: {
|
||||
completedAtMs: 1_778_000_002_000,
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
item: {
|
||||
type: "mcpToolCall",
|
||||
id: "computer_2",
|
||||
server: "computer-use",
|
||||
tool: "type_text",
|
||||
arguments: { text: "Hello world", app: "TextEdit" },
|
||||
durationMs: 12,
|
||||
error: null,
|
||||
result: {
|
||||
_meta: {
|
||||
"codex/toolSurface": {
|
||||
kind: "computerUse",
|
||||
app: { kind: "displayName", displayName: "TextEdit" },
|
||||
},
|
||||
},
|
||||
content: [],
|
||||
},
|
||||
status: "completed",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const events = Array.from(yield* Fiber.join(eventsFiber));
|
||||
NodeAssert.deepStrictEqual(
|
||||
events.map((event) => ({
|
||||
type: event.type,
|
||||
title: "title" in event.payload ? event.payload.title : undefined,
|
||||
toolSurface: "toolSurface" in event.payload ? event.payload.toolSurface : undefined,
|
||||
toolIcon: "toolIcon" in event.payload ? event.payload.toolIcon : undefined,
|
||||
toolSource: "toolSource" in event.payload ? event.payload.toolSource : undefined,
|
||||
})),
|
||||
[
|
||||
{
|
||||
type: "item.started",
|
||||
title: `${"a".repeat(39)} ${"a".repeat(38)}😀…`,
|
||||
toolSurface: "computer",
|
||||
toolIcon: {
|
||||
_tag: "native-app",
|
||||
app: { _tag: "app-id", appId: "com.apple.finder" },
|
||||
},
|
||||
toolSource: {
|
||||
key: "native-app:com.apple.finder",
|
||||
name: "Finder",
|
||||
kind: "computer",
|
||||
icon: {
|
||||
_tag: "native-app",
|
||||
app: { _tag: "app-id", appId: "com.apple.finder" },
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "item.completed",
|
||||
title: "Inspect checkout",
|
||||
toolSurface: "browser",
|
||||
toolIcon: {
|
||||
_tag: "website",
|
||||
pageUrl: "https://www.mathworks.com/help/matlab/",
|
||||
faviconUrl: "https://www.mathworks.com/favicon.ico",
|
||||
faviconUrlDark: "https://www.mathworks.com/favicon-dark.ico",
|
||||
},
|
||||
toolSource: {
|
||||
key: "browser-use:chrome",
|
||||
name: "Chrome",
|
||||
kind: "integration",
|
||||
icon: {
|
||||
_tag: "native-app",
|
||||
app: { _tag: "display-name", displayName: "Google Chrome" },
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "item.completed",
|
||||
title: "Typed text in TextEdit",
|
||||
toolSurface: "computer",
|
||||
toolIcon: {
|
||||
_tag: "native-app",
|
||||
app: { _tag: "display-name", displayName: "TextEdit" },
|
||||
},
|
||||
toolSource: {
|
||||
key: "native-app-name:textedit",
|
||||
name: "TextEdit",
|
||||
kind: "computer",
|
||||
icon: {
|
||||
_tag: "native-app",
|
||||
app: { _tag: "display-name", displayName: "TextEdit" },
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves failed and declined outcomes on completed tool items", () =>
|
||||
Effect.gen(function* () {
|
||||
const { adapter, runtime } = yield* startLifecycleRuntime();
|
||||
const maxLengthAppId = `com.${"a".repeat(508)}`;
|
||||
const collidingMaxLengthAppId = `com.${"a".repeat(507)}b`;
|
||||
const longAppSourceKeys: string[] = [];
|
||||
const items = [
|
||||
{
|
||||
type: "commandExecution",
|
||||
@@ -822,6 +1020,42 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
|
||||
error: { message: "Build failed" },
|
||||
status: "failed",
|
||||
},
|
||||
{
|
||||
type: "mcpToolCall",
|
||||
id: "failed-computer",
|
||||
server: "computer-use",
|
||||
tool: "click",
|
||||
arguments: { app: "Finder" },
|
||||
error: { message: "Click failed" },
|
||||
result: {
|
||||
_meta: {
|
||||
"codex/toolSurface": {
|
||||
kind: "computerUse",
|
||||
app: { kind: "appId", appId: maxLengthAppId },
|
||||
},
|
||||
},
|
||||
content: [],
|
||||
},
|
||||
status: "failed",
|
||||
},
|
||||
{
|
||||
type: "mcpToolCall",
|
||||
id: "failed-computer-collision",
|
||||
server: "computer-use",
|
||||
tool: "click",
|
||||
arguments: { app: "Other" },
|
||||
error: { message: "Click failed" },
|
||||
result: {
|
||||
_meta: {
|
||||
"codex/toolSurface": {
|
||||
kind: "computerUse",
|
||||
app: { kind: "appId", appId: collidingMaxLengthAppId },
|
||||
},
|
||||
},
|
||||
content: [],
|
||||
},
|
||||
status: "failed",
|
||||
},
|
||||
{
|
||||
type: "fileChange",
|
||||
id: "declined-change",
|
||||
@@ -856,7 +1090,14 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
|
||||
return;
|
||||
}
|
||||
NodeAssert.equal(firstEvent.value.payload.status, item.status);
|
||||
if (item.id.startsWith("failed-computer")) {
|
||||
NodeAssert.equal(firstEvent.value.payload.title, "computer-use · click");
|
||||
const sourceKey = firstEvent.value.payload.toolSource?.key;
|
||||
NodeAssert.equal(sourceKey?.length, 512);
|
||||
if (sourceKey) longAppSourceKeys.push(sourceKey);
|
||||
}
|
||||
}
|
||||
NodeAssert.equal(new Set(longAppSourceKeys).size, 2);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -17,6 +17,9 @@ import {
|
||||
type ProviderRuntimeEvent,
|
||||
type ProviderRequestKind,
|
||||
type ThreadTokenUsageSnapshot,
|
||||
type ToolActivityIcon,
|
||||
type ToolActivityNativeAppReference,
|
||||
type ToolActivitySource,
|
||||
type ProviderUserInputAnswers,
|
||||
RuntimeItemId,
|
||||
RuntimeRequestId,
|
||||
@@ -27,6 +30,7 @@ import {
|
||||
ProviderSendTurnInput,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as NodeCrypto from "node:crypto";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
@@ -150,6 +154,236 @@ function trimText(value: string | undefined | null): string | undefined {
|
||||
return trimmed && trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function asUnknownRecord(value: unknown): Record<string, unknown> | undefined {
|
||||
return value && typeof value === "object" ? (value as Record<string, unknown>) : undefined;
|
||||
}
|
||||
|
||||
function normalizeMcpIntentTitle(value: unknown): string | undefined {
|
||||
if (typeof value !== "string") return undefined;
|
||||
const normalized = value.trim().replace(/\s+/gu, " ");
|
||||
if (!normalized) return undefined;
|
||||
const characters = Array.from(normalized);
|
||||
return characters.length <= 80 ? normalized : `${characters.slice(0, 79).join("")}…`;
|
||||
}
|
||||
|
||||
function normalizedHttpUrl(value: unknown): string | undefined {
|
||||
if (typeof value !== "string" || value.length > 4096) return undefined;
|
||||
try {
|
||||
const url = new URL(value);
|
||||
const href = url.href;
|
||||
return (url.protocol === "http:" || url.protocol === "https:") && href.length <= 4096
|
||||
? href
|
||||
: undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizedImageUrl(value: unknown): string | undefined {
|
||||
if (typeof value !== "string" || value.length > 4096) return undefined;
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return url.protocol === "http:" || url.protocol === "https:" || url.protocol === "data:"
|
||||
? url.href
|
||||
: undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizedAppId(value: unknown): string | undefined {
|
||||
if (typeof value !== "string") return undefined;
|
||||
const appId = value.trim();
|
||||
return appId.length > 0 && appId.length <= 512 && /^[A-Za-z0-9._-]+$/u.test(appId)
|
||||
? appId
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function normalizedDisplayName(value: unknown): string | undefined {
|
||||
if (typeof value !== "string") return undefined;
|
||||
const displayName = value.trim().replace(/\s+/gu, " ");
|
||||
return displayName && displayName.length <= 160 ? displayName : undefined;
|
||||
}
|
||||
|
||||
function normalizedSourceKeyPart(value: string): string {
|
||||
return value.trim().toLowerCase();
|
||||
}
|
||||
|
||||
function nativeAppSourceKey(appId: string): string {
|
||||
const key = `native-app:${appId.toLowerCase()}`;
|
||||
if (key.length <= 512) return key;
|
||||
const digest = NodeCrypto.createHash("sha256").update(key).digest("hex");
|
||||
return `${key.slice(0, 512 - digest.length - 1)}:${digest}`;
|
||||
}
|
||||
|
||||
function browserDisplayName(value: unknown): string | undefined {
|
||||
const normalized = normalizedDisplayName(value)?.toLowerCase();
|
||||
if (!normalized) return undefined;
|
||||
if (normalized.includes("chrome") || normalized === "chromium") return "Chrome";
|
||||
if (normalized.includes("edge")) return "Microsoft Edge";
|
||||
if (normalized.includes("firefox")) return "Firefox";
|
||||
if (normalized.includes("safari")) return "Safari";
|
||||
if (normalized.includes("arc")) return "Arc";
|
||||
if (normalized === "iab" || normalized.includes("in-app")) return "Browser";
|
||||
return normalizedDisplayName(value);
|
||||
}
|
||||
|
||||
function browserNativeAppReference(name: string): ToolActivityNativeAppReference | undefined {
|
||||
switch (name) {
|
||||
case "Chrome":
|
||||
return { _tag: "display-name", displayName: "Google Chrome" };
|
||||
case "Microsoft Edge":
|
||||
case "Firefox":
|
||||
case "Safari":
|
||||
case "Arc":
|
||||
return { _tag: "display-name", displayName: name };
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function appDisplayNameFromId(appId: string): string | undefined {
|
||||
const knownNames: Readonly<Record<string, string>> = {
|
||||
"com.apple.finder": "Finder",
|
||||
"com.apple.safari": "Safari",
|
||||
"com.google.chrome": "Chrome",
|
||||
"com.microsoft.edgemac": "Microsoft Edge",
|
||||
"org.mozilla.firefox": "Firefox",
|
||||
"company.thebrowser.browser": "Arc",
|
||||
};
|
||||
return knownNames[appId.toLowerCase()];
|
||||
}
|
||||
|
||||
function nativeAppReference(value: unknown): ToolActivityNativeAppReference | undefined {
|
||||
const app = asUnknownRecord(value);
|
||||
if (app?.kind === "appId") {
|
||||
const appId = normalizedAppId(app.appId);
|
||||
return appId ? { _tag: "app-id", appId } : undefined;
|
||||
}
|
||||
if (app?.kind === "displayName") {
|
||||
const displayName = normalizedDisplayName(app.displayName);
|
||||
return displayName ? { _tag: "display-name", displayName } : undefined;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function themedLogoIcon(
|
||||
...records: ReadonlyArray<Record<string, unknown> | undefined>
|
||||
): ToolActivityIcon | undefined {
|
||||
for (const record of records) {
|
||||
const logoUrl = normalizedImageUrl(record?.logoUrl);
|
||||
if (!logoUrl) continue;
|
||||
const logoUrlDark = normalizedImageUrl(record?.logoUrlDark ?? record?.logoDarkUrl);
|
||||
return {
|
||||
_tag: "themed-logo",
|
||||
logoUrl,
|
||||
...(logoUrlDark ? { logoUrlDark } : {}),
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
interface McpToolPresentation {
|
||||
readonly toolSurface?: "browser" | "computer";
|
||||
readonly toolIcon?: ToolActivityIcon;
|
||||
readonly toolSource?: ToolActivitySource;
|
||||
}
|
||||
|
||||
function mcpToolPresentation(
|
||||
item: Extract<CodexLifecycleItem, { readonly type: "mcpToolCall" }>,
|
||||
): McpToolPresentation {
|
||||
const result = asUnknownRecord(item.result);
|
||||
const metadata = asUnknownRecord(result?._meta);
|
||||
const surface = asUnknownRecord(metadata?.["codex/toolSurface"]);
|
||||
const sourceMetadata = asUnknownRecord(metadata?.source);
|
||||
const appContext = asUnknownRecord(item.appContext);
|
||||
const sourceLogo = themedLogoIcon(surface, sourceMetadata, appContext);
|
||||
if (surface?.kind === "browserUse") {
|
||||
const screenshot = asUnknownRecord(surface.screenshot);
|
||||
const browserUse = asUnknownRecord(metadata?.browser_use);
|
||||
const openTabs = Array.isArray(surface.openTabs) ? surface.openTabs : [];
|
||||
const latestOpenTab = openTabs
|
||||
.toReversed()
|
||||
.map(asUnknownRecord)
|
||||
.find((tab) => normalizedHttpUrl(tab?.url) !== undefined);
|
||||
const selectedPage = [
|
||||
{ record: screenshot, url: screenshot?.pageUrl },
|
||||
{ record: browserUse, url: browserUse?.url },
|
||||
{ record: latestOpenTab, url: latestOpenTab?.url },
|
||||
]
|
||||
.map((candidate) => ({ ...candidate, pageUrl: normalizedHttpUrl(candidate.url) }))
|
||||
.find((candidate) => candidate.pageUrl !== undefined);
|
||||
const pageUrl = selectedPage?.pageUrl;
|
||||
const faviconUrl = normalizedImageUrl(
|
||||
selectedPage?.record?.faviconUrl ?? selectedPage?.record?.favIconUrl,
|
||||
);
|
||||
const faviconUrlDark = normalizedImageUrl(
|
||||
selectedPage?.record?.faviconUrlDark ?? selectedPage?.record?.favIconUrlDark,
|
||||
);
|
||||
const name =
|
||||
browserDisplayName(appContext?.appName) ??
|
||||
browserDisplayName(surface.browserFamily) ??
|
||||
browserDisplayName(surface.backend) ??
|
||||
"Browser";
|
||||
const nativeBrowserIcon = browserNativeAppReference(name);
|
||||
const sourceIcon =
|
||||
sourceLogo ??
|
||||
(nativeBrowserIcon ? ({ _tag: "native-app", app: nativeBrowserIcon } as const) : undefined);
|
||||
const sourceKeyPart = normalizedSourceKeyPart(name) || "browser";
|
||||
return {
|
||||
toolSurface: "browser",
|
||||
...(pageUrl
|
||||
? {
|
||||
toolIcon: {
|
||||
_tag: "website",
|
||||
pageUrl,
|
||||
...(faviconUrl ? { faviconUrl } : {}),
|
||||
...(faviconUrlDark ? { faviconUrlDark } : {}),
|
||||
} as const,
|
||||
}
|
||||
: {}),
|
||||
toolSource: {
|
||||
key: `browser-use:${sourceKeyPart}`,
|
||||
name,
|
||||
kind: name === "Browser" ? "browser" : "integration",
|
||||
...(sourceIcon ? { icon: sourceIcon } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
if (surface?.kind === "computerUse") {
|
||||
const app = nativeAppReference(surface.app);
|
||||
const args = asUnknownRecord(item.arguments);
|
||||
const argumentAppName =
|
||||
normalizedDisplayName(args?.appName) ??
|
||||
normalizedDisplayName(args?.application) ??
|
||||
normalizedDisplayName(typeof args?.app === "string" ? args.app : undefined);
|
||||
const name =
|
||||
normalizedDisplayName(appContext?.appName) ??
|
||||
argumentAppName ??
|
||||
(app?._tag === "display-name" ? app.displayName : undefined) ??
|
||||
(app?._tag === "app-id" ? appDisplayNameFromId(app.appId) : undefined) ??
|
||||
"Computer Use";
|
||||
const sourceIcon = sourceLogo ?? (app ? ({ _tag: "native-app", app } as const) : undefined);
|
||||
const sourceKey = app
|
||||
? app._tag === "app-id"
|
||||
? nativeAppSourceKey(app.appId)
|
||||
: `native-app-name:${normalizedSourceKeyPart(app.displayName)}`
|
||||
: "computer-use";
|
||||
return {
|
||||
toolSurface: "computer",
|
||||
...(app ? { toolIcon: { _tag: "native-app", app } as const } : {}),
|
||||
toolSource: {
|
||||
key: sourceKey,
|
||||
name,
|
||||
kind: "computer",
|
||||
...(sourceIcon ? { icon: sourceIcon } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
const FATAL_CODEX_STDERR_SNIPPETS = ["failed to connect to websocket"];
|
||||
|
||||
function isFatalCodexProcessStderrMessage(message: string): boolean {
|
||||
@@ -239,8 +473,82 @@ function toCanonicalItemType(raw: string | undefined | null): CanonicalItemType
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function itemTitle(itemType: CanonicalItemType, item?: CodexLifecycleItem): string | undefined {
|
||||
function boundedToolArgument(value: unknown): string | undefined {
|
||||
const normalized = typeof value === "string" ? value.trim().replace(/\s+/gu, " ") : "";
|
||||
if (!normalized) return undefined;
|
||||
return normalized.length <= 48 ? normalized : `${normalized.slice(0, 47)}…`;
|
||||
}
|
||||
|
||||
function normalizedMcpToolName(value: string): string {
|
||||
return (
|
||||
value
|
||||
.split(/__|[./:]/u)
|
||||
.at(-1)
|
||||
?.trim() ?? value.trim()
|
||||
);
|
||||
}
|
||||
|
||||
function computerUseToolTitle(
|
||||
item: Extract<CodexLifecycleItem, { readonly type: "mcpToolCall" }>,
|
||||
presentation: McpToolPresentation,
|
||||
): string | undefined {
|
||||
if (normalizeItemType(item.server) !== "computer use") return undefined;
|
||||
if (item.status === "failed") return undefined;
|
||||
const tool = normalizeItemType(normalizedMcpToolName(item.tool)).replace(/ /gu, "_");
|
||||
const inProgress = item.status === "inProgress";
|
||||
const args = asUnknownRecord(item.arguments);
|
||||
const appName =
|
||||
(presentation.toolSource?.kind === "computer" && presentation.toolSource.name !== "Computer Use"
|
||||
? presentation.toolSource.name
|
||||
: undefined) ??
|
||||
normalizedDisplayName(args?.appName) ??
|
||||
normalizedDisplayName(args?.application) ??
|
||||
normalizedDisplayName(typeof args?.app === "string" ? args.app : undefined);
|
||||
const withApp = (label: string) => (appName ? `${label} in ${appName}` : label);
|
||||
switch (tool) {
|
||||
case "list_apps":
|
||||
return inProgress ? "Listing apps" : "Listed apps";
|
||||
case "click":
|
||||
return withApp(inProgress ? "Clicking" : "Clicked");
|
||||
case "drag":
|
||||
return withApp(inProgress ? "Dragging" : "Dragged");
|
||||
case "get_app_state":
|
||||
case "get_state":
|
||||
return appName
|
||||
? `${inProgress ? "Looking at" : "Looked at"} ${appName}`
|
||||
: inProgress
|
||||
? "Looking at the screen"
|
||||
: "Looked at the screen";
|
||||
case "perform_accessibility_action":
|
||||
case "perform_secondary_action":
|
||||
return inProgress ? "Performing accessibility action" : "Performed accessibility action";
|
||||
case "press_key":
|
||||
return withApp(inProgress ? "Pressing key" : "Pressed key");
|
||||
case "scroll": {
|
||||
const direction = boundedToolArgument(args?.direction)?.toLowerCase();
|
||||
return withApp(`${inProgress ? "Scrolling" : "Scrolled"}${direction ? ` ${direction}` : ""}`);
|
||||
}
|
||||
case "set_value":
|
||||
return withApp(inProgress ? "Setting value" : "Set value");
|
||||
case "type_text":
|
||||
return withApp(inProgress ? "Typing text" : "Typed text");
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function itemTitle(
|
||||
itemType: CanonicalItemType,
|
||||
item?: CodexLifecycleItem,
|
||||
presentation: McpToolPresentation = {},
|
||||
): string | undefined {
|
||||
if (itemType === "mcp_tool_call" && item?.type === "mcpToolCall") {
|
||||
if (normalizedMcpToolName(item.tool) === "js") {
|
||||
const intentTitle = normalizeMcpIntentTitle(asUnknownRecord(item.arguments)?.title);
|
||||
if (intentTitle) return intentTitle;
|
||||
}
|
||||
const computerUseTitle = computerUseToolTitle(item, presentation);
|
||||
if (computerUseTitle) return computerUseTitle;
|
||||
return `${item.server} · ${item.tool}`;
|
||||
}
|
||||
switch (itemType) {
|
||||
@@ -481,6 +789,8 @@ function mapItemLifecycle(
|
||||
}
|
||||
|
||||
const detail = itemDetail(itemType, item);
|
||||
const toolPresentation = item.type === "mcpToolCall" ? mcpToolPresentation(item) : {};
|
||||
const title = itemTitle(itemType, item, toolPresentation);
|
||||
const status =
|
||||
lifecycle === "item.started"
|
||||
? "inProgress"
|
||||
@@ -496,8 +806,9 @@ function mapItemLifecycle(
|
||||
payload: {
|
||||
itemType,
|
||||
...(status ? { status } : {}),
|
||||
...(itemTitle(itemType, item) ? { title: itemTitle(itemType, item) } : {}),
|
||||
...(title ? { title } : {}),
|
||||
...(detail ? { detail } : {}),
|
||||
...toolPresentation,
|
||||
...(event.payload !== undefined ? { data: event.payload } : {}),
|
||||
},
|
||||
};
|
||||
|
||||
@@ -122,6 +122,7 @@ import * as TerminalManager from "./terminal/Manager.ts";
|
||||
import * as PreviewManager from "./preview/Manager.ts";
|
||||
import * as PortScanner from "./preview/PortScanner.ts";
|
||||
import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
|
||||
import * as NativeAppIconResolver from "./assets/NativeAppIconResolver.ts";
|
||||
import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts";
|
||||
import * as T3ProjectFileLoader from "./project/T3ProjectFileLoader.ts";
|
||||
import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts";
|
||||
@@ -626,6 +627,7 @@ const buildAppUnderTest = (options?: {
|
||||
Layer.provide(WorkspacePaths.layer),
|
||||
Layer.provide(T3ProjectFileLoader.layer),
|
||||
),
|
||||
NativeAppIconResolver.layer,
|
||||
);
|
||||
const gitWorkflowLayer = GitWorkflowService.layer.pipe(
|
||||
Layer.provideMerge(vcsDriverRegistryLayer),
|
||||
|
||||
@@ -67,6 +67,7 @@ import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";
|
||||
import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
|
||||
import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry.ts";
|
||||
import * as ServerSettings from "./serverSettings.ts";
|
||||
import * as NativeAppIconResolver from "./assets/NativeAppIconResolver.ts";
|
||||
import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts";
|
||||
import * as T3ProjectFileLoader from "./project/T3ProjectFileLoader.ts";
|
||||
import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts";
|
||||
@@ -443,7 +444,7 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
|
||||
// keeps a single Live for all opencode consumers.
|
||||
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
|
||||
Layer.provideMerge(WorkspaceLayerLive),
|
||||
Layer.provideMerge(ProjectFaviconResolverLayerLive),
|
||||
Layer.provideMerge(Layer.mergeAll(NativeAppIconResolver.layer, ProjectFaviconResolverLayerLive)),
|
||||
Layer.provideMerge(RepositoryIdentityResolver.layer),
|
||||
Layer.provideMerge(ServerEnvironmentLayerLive),
|
||||
Layer.provideMerge(AuthLayerLive),
|
||||
|
||||
@@ -2125,7 +2125,10 @@ const makeWsRpcLayer = (
|
||||
observeRpcEffect(
|
||||
WS_METHODS.assetsCreateUrl,
|
||||
Effect.gen(function* () {
|
||||
if (input.resource._tag === "attachment") {
|
||||
if (
|
||||
input.resource._tag === "attachment" ||
|
||||
input.resource._tag === "native-app-icon"
|
||||
) {
|
||||
return yield* issueAssetUrl({ resource: input.resource });
|
||||
}
|
||||
if (input.resource._tag === "project-favicon") {
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
resolveWorkGroupScrollIndex,
|
||||
shouldFollowWorkGroupAppend,
|
||||
shouldPreserveAssistantLineBreaks,
|
||||
type MessagesTimelineRow,
|
||||
workEntryDisplayLabel,
|
||||
} from "./MessagesTimeline.logic";
|
||||
|
||||
@@ -1660,6 +1661,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
label: "Status updated",
|
||||
detail: "Editing MessagesTimeline.tsx",
|
||||
tone: middleTone,
|
||||
toolSurface: "computer" as const,
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -1672,6 +1674,8 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
label: "test",
|
||||
detail: "Running tests",
|
||||
tone: "tool" as const,
|
||||
toolSurface: "browser" as const,
|
||||
toolIcon: { _tag: "website" as const, pageUrl: "https://example.com/checkout" },
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -1695,6 +1699,8 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
hiddenCount: 3,
|
||||
expanded: false,
|
||||
summary,
|
||||
toolSurface: "browser",
|
||||
toolIcon: { _tag: "website", pageUrl: "https://example.com/checkout" },
|
||||
});
|
||||
expect(expandedRows.map((row) => row.id)).toEqual([
|
||||
"work-toggle:work-entry-1",
|
||||
@@ -1709,6 +1715,84 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("deduplicates integration sources and uses the first source icon for the group", () => {
|
||||
const chromeSource = {
|
||||
key: "browser-use:chrome",
|
||||
name: "Chrome",
|
||||
kind: "integration" as const,
|
||||
icon: {
|
||||
_tag: "native-app" as const,
|
||||
app: { _tag: "display-name" as const, displayName: "Google Chrome" },
|
||||
},
|
||||
};
|
||||
const timelineEntries = [
|
||||
{
|
||||
id: "browser-1",
|
||||
kind: "work" as const,
|
||||
createdAt: "2026-01-01T00:00:01Z",
|
||||
entry: {
|
||||
id: "browser-1",
|
||||
createdAt: "2026-01-01T00:00:01Z",
|
||||
label: "Open MATLAB",
|
||||
tone: "tool" as const,
|
||||
toolSurface: "browser" as const,
|
||||
toolSource: chromeSource,
|
||||
toolIcon: {
|
||||
_tag: "website" as const,
|
||||
pageUrl: "https://www.mathworks.com/help/matlab/",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "browser-2",
|
||||
kind: "work" as const,
|
||||
createdAt: "2026-01-01T00:00:02Z",
|
||||
entry: {
|
||||
id: "browser-2",
|
||||
createdAt: "2026-01-01T00:00:02Z",
|
||||
label: "Show summary",
|
||||
tone: "tool" as const,
|
||||
toolSurface: "browser" as const,
|
||||
toolSource: chromeSource,
|
||||
toolIcon: {
|
||||
_tag: "website" as const,
|
||||
pageUrl: "https://www.mathworks.com/help/matlab/summary.html",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "command-1",
|
||||
kind: "work" as const,
|
||||
createdAt: "2026-01-01T00:00:03Z",
|
||||
entry: {
|
||||
id: "command-1",
|
||||
createdAt: "2026-01-01T00:00:03Z",
|
||||
label: "Ran command",
|
||||
command: "git status",
|
||||
itemType: "command_execution" as const,
|
||||
tone: "tool" as const,
|
||||
},
|
||||
},
|
||||
];
|
||||
const [row] = deriveMessagesTimelineRows({
|
||||
timelineEntries,
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
});
|
||||
|
||||
expect(row).toMatchObject({
|
||||
kind: "work-toggle",
|
||||
summary: "Used Chrome integration and ran 1 command",
|
||||
toolSurface: "browser",
|
||||
toolIcon: {
|
||||
_tag: "website",
|
||||
pageUrl: "https://www.mathworks.com/help/matlab/",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.each([true, false])(
|
||||
"keeps a large expanded tool run inside one timeline item, live=%s",
|
||||
(isWorking) => {
|
||||
@@ -1845,6 +1929,34 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
});
|
||||
|
||||
describe("computeStableMessagesTimelineRows", () => {
|
||||
it("replaces a cached work toggle when its icon presentation changes", () => {
|
||||
const initialRow: MessagesTimelineRow = {
|
||||
kind: "work-toggle",
|
||||
id: "work-toggle:1",
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
groupId: "work-group:1",
|
||||
hiddenCount: 1,
|
||||
expanded: false,
|
||||
summary: "Used Browser",
|
||||
summaryKind: "other",
|
||||
toolSurface: "browser",
|
||||
hasFailure: false,
|
||||
};
|
||||
const initial = computeStableMessagesTimelineRows([initialRow], {
|
||||
byId: new Map(),
|
||||
result: [],
|
||||
});
|
||||
const enrichedRow: MessagesTimelineRow = {
|
||||
...initialRow,
|
||||
toolIcon: { _tag: "website", pageUrl: "https://example.com" },
|
||||
};
|
||||
|
||||
const updated = computeStableMessagesTimelineRows([enrichedRow], initial);
|
||||
|
||||
expect(updated).not.toBe(initial);
|
||||
expect(updated.result[0]).toBe(enrichedRow);
|
||||
});
|
||||
|
||||
it.each(["", " \n"])("keeps Thinking after assistant content grows from %j", (text) => {
|
||||
const startedAt = "2026-01-01T00:00:00Z";
|
||||
const turnId = TurnId.make("turn-1");
|
||||
|
||||
@@ -304,6 +304,8 @@ export type MessagesTimelineRow =
|
||||
expanded: boolean;
|
||||
summary: string;
|
||||
summaryKind: ToolGroupSummaryKind;
|
||||
toolSurface?: WorkLogEntry["toolSurface"];
|
||||
toolIcon?: WorkLogEntry["toolIcon"];
|
||||
summaryToolIcon?: "browser" | "t3-code";
|
||||
hasFailure: boolean;
|
||||
}
|
||||
@@ -849,6 +851,22 @@ export function deriveMessagesTimelineRows(input: {
|
||||
const groupId = workGroupId(timelineEntry.id, timelineEntry.entry);
|
||||
const expanded = input.expandedWorkGroupIds?.has(groupId) ?? false;
|
||||
const summaryKind = toolGroupSummaryKind(visibleGroupedEntries);
|
||||
const primarySourceEntry = visibleGroupedEntries.find(
|
||||
(entry) => entry.toolSource !== undefined,
|
||||
);
|
||||
const primarySourceKey = primarySourceEntry?.toolSource?.key;
|
||||
const primarySourceIcon = primarySourceKey
|
||||
? (visibleGroupedEntries.find(
|
||||
(entry) =>
|
||||
entry.toolSource?.key === primarySourceKey && entry.toolIcon !== undefined,
|
||||
)?.toolIcon ?? primarySourceEntry?.toolSource?.icon)
|
||||
: undefined;
|
||||
const groupToolSurface =
|
||||
primarySourceEntry?.toolSurface ??
|
||||
visibleGroupedEntries.findLast((entry) => entry.toolSurface !== undefined)?.toolSurface;
|
||||
const groupToolIcon =
|
||||
primarySourceIcon ??
|
||||
visibleGroupedEntries.findLast((entry) => entry.toolIcon !== undefined)?.toolIcon;
|
||||
const latestToolEntry = visibleGroupedEntries.findLast(workLogEntryIsToolLike);
|
||||
const singleEntry =
|
||||
visibleGroupedEntries.length === 1 ? (visibleGroupedEntries[0] ?? null) : null;
|
||||
@@ -872,6 +890,8 @@ export function deriveMessagesTimelineRows(input: {
|
||||
? singleEntry.label
|
||||
: summarizeToolGroup(visibleGroupedEntries),
|
||||
summaryKind,
|
||||
...(groupToolSurface ? { toolSurface: groupToolSurface } : {}),
|
||||
...(groupToolIcon ? { toolIcon: groupToolIcon } : {}),
|
||||
...(summaryToolIcon ? { summaryToolIcon } : {}),
|
||||
hasFailure:
|
||||
latestToolEntry !== undefined &&
|
||||
@@ -1014,6 +1034,8 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
|
||||
a.expanded === bw.expanded &&
|
||||
a.summary === bw.summary &&
|
||||
a.summaryKind === bw.summaryKind &&
|
||||
a.toolSurface === bw.toolSurface &&
|
||||
Equal.equals(a.toolIcon, bw.toolIcon) &&
|
||||
a.hasFailure === bw.hasFailure
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
type MessageId,
|
||||
type ScopedThreadRef,
|
||||
type ServerProviderSkill,
|
||||
type ToolActivityIcon,
|
||||
type TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
|
||||
@@ -25,6 +26,8 @@ const NOOP_OPEN_AGENTS = () => {};
|
||||
const NOOP_USE_ARTIFACT_TEMPLATE = () => {};
|
||||
const NOOP_OPEN_ATTACHMENT = (_attachment: ChatFileAttachment) => {};
|
||||
import { resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
|
||||
import { toolActivityFaviconUrl } from "@t3tools/shared/favicon";
|
||||
import { getProjectFaviconCacheKey } from "@t3tools/shared/projectFavicon";
|
||||
import {
|
||||
createContext,
|
||||
Fragment,
|
||||
@@ -32,6 +35,7 @@ import {
|
||||
use,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useId,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
@@ -155,7 +159,6 @@ import { cn } from "~/lib/utils";
|
||||
import { useUiStateStore } from "~/uiStateStore";
|
||||
import { type TimestampFormat } from "@t3tools/contracts/settings";
|
||||
import { formatChatTimestampTooltip, formatDayAwareTimestamp } from "../../timestampFormat";
|
||||
|
||||
import {
|
||||
buildInlineTerminalContextText,
|
||||
formatInlineTerminalContextLabel,
|
||||
@@ -1768,10 +1771,12 @@ function ActivityShimmerOverlay({ children }: { children: ReactNode }) {
|
||||
function LiveActivityRow({
|
||||
label,
|
||||
iconName,
|
||||
toolIcon,
|
||||
failed = false,
|
||||
}: {
|
||||
label: string;
|
||||
iconName?: WorkEntryIconName;
|
||||
toolIcon?: ToolActivityIcon | undefined;
|
||||
failed?: boolean;
|
||||
}) {
|
||||
return (
|
||||
@@ -1779,11 +1784,18 @@ function LiveActivityRow({
|
||||
<LiveActivityContent
|
||||
label={label}
|
||||
iconName={iconName}
|
||||
toolIcon={toolIcon}
|
||||
failed={failed}
|
||||
announceFailure={failed}
|
||||
/>
|
||||
<ActivityShimmerOverlay>
|
||||
<LiveActivityContent label={label} iconName={iconName} failed={failed} highlighted />
|
||||
<LiveActivityContent
|
||||
label={label}
|
||||
iconName={iconName}
|
||||
toolIcon={toolIcon}
|
||||
failed={failed}
|
||||
highlighted
|
||||
/>
|
||||
</ActivityShimmerOverlay>
|
||||
</div>
|
||||
);
|
||||
@@ -1792,17 +1804,20 @@ function LiveActivityRow({
|
||||
function LiveActivityContent({
|
||||
label,
|
||||
iconName,
|
||||
toolIcon,
|
||||
failed = false,
|
||||
announceFailure = false,
|
||||
highlighted = false,
|
||||
}: {
|
||||
label: string;
|
||||
iconName: WorkEntryIconName | undefined;
|
||||
toolIcon?: ToolActivityIcon | undefined;
|
||||
failed?: boolean;
|
||||
announceFailure?: boolean;
|
||||
highlighted?: boolean;
|
||||
}) {
|
||||
const isSpecialToolIcon = iconName === "browser" || iconName === "t3-code";
|
||||
const isSpecialToolIcon =
|
||||
iconName === "browser" || iconName === "computer" || iconName === "t3-code";
|
||||
const resolvedIconName = failed && !isSpecialToolIcon ? "circle-alert" : iconName;
|
||||
|
||||
return (
|
||||
@@ -1822,9 +1837,11 @@ function LiveActivityContent({
|
||||
role={announceFailure ? "img" : undefined}
|
||||
aria-label={announceFailure ? "Tool call failed" : undefined}
|
||||
>
|
||||
<WorkEntryIcon
|
||||
name={resolvedIconName}
|
||||
className={cn("block size-4 shrink-0 stroke-[1.8]", !highlighted && "opacity-70")}
|
||||
<ToolActivityIconView
|
||||
icon={failed && !isSpecialToolIcon ? undefined : toolIcon}
|
||||
fallbackName={resolvedIconName}
|
||||
className="block size-4 shrink-0 stroke-[1.8]"
|
||||
muted={!highlighted}
|
||||
/>
|
||||
</span>
|
||||
) : null}
|
||||
@@ -1848,12 +1865,18 @@ function LiveWorkEntryTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "
|
||||
onClick={() => ctx.onToggleWorkGroup(row.groupId, row.id)}
|
||||
>
|
||||
{row.active ? (
|
||||
<LiveActivityRow label={label} iconName={workEntryIconName(row.entry)} failed={failed} />
|
||||
<LiveActivityRow
|
||||
label={label}
|
||||
iconName={workEntryIconName(row.entry)}
|
||||
toolIcon={row.entry.toolIcon ?? row.entry.toolSource?.icon}
|
||||
failed={failed}
|
||||
/>
|
||||
) : (
|
||||
<div className="min-h-6 w-fit max-w-full min-w-0 overflow-hidden rounded-md text-sm leading-relaxed">
|
||||
<LiveActivityContent
|
||||
label={label}
|
||||
iconName={workEntryIconName(row.entry)}
|
||||
toolIcon={row.entry.toolIcon ?? row.entry.toolSource?.icon}
|
||||
failed={failed}
|
||||
announceFailure={failed}
|
||||
/>
|
||||
@@ -1908,9 +1931,13 @@ function WorkGroupToggleTimelineRow({
|
||||
onClick={() => ctx.onToggleWorkGroup(row.groupId, row.id)}
|
||||
>
|
||||
<span className="flex size-6 shrink-0 items-center justify-center text-icon-muted">
|
||||
<WorkEntryIcon
|
||||
name={row.summaryToolIcon ?? toolGroupSummaryIconName(row.summaryKind)}
|
||||
className="size-4 shrink-0 stroke-[1.8] opacity-70"
|
||||
<ToolActivityIconView
|
||||
icon={row.toolIcon}
|
||||
fallbackName={
|
||||
row.summaryToolIcon ?? row.toolSurface ?? toolGroupSummaryIconName(row.summaryKind)
|
||||
}
|
||||
className="size-4 shrink-0 stroke-[1.8]"
|
||||
muted
|
||||
/>
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate text-secondary-label">{row.summary}</span>
|
||||
@@ -2445,6 +2472,7 @@ type WorkEntryIconName =
|
||||
| "browser"
|
||||
| "check"
|
||||
| "circle-alert"
|
||||
| "computer"
|
||||
| "eye"
|
||||
| "globe"
|
||||
| "hammer"
|
||||
@@ -2457,6 +2485,203 @@ type WorkEntryIconName =
|
||||
| "x"
|
||||
| "zap";
|
||||
|
||||
function BrowserAppIcon({ className }: { className: string }) {
|
||||
return (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.9"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className={className}
|
||||
aria-hidden
|
||||
>
|
||||
<path d="M8.5 19H7.2C4.4 19 3 17.5 3 14.6V7.4C3 4.5 4.5 3 7.4 3h8.2C18.5 3 20 4.5 20 7.4v2.4" />
|
||||
<circle cx="7.4" cy="7.2" r="0.75" fill="currentColor" stroke="none" />
|
||||
<path d="M11.2 7.2h4.3" />
|
||||
<path d="m12.4 11.4 7.5 2.6-3.4 1.6-1.5 3.6z" fill="currentColor" stroke="none" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function ComputerUseAppIcon({ className }: { className: string }) {
|
||||
const gradientId = `${useId().replaceAll(":", "")}-computer-use-app-gradient`;
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" className={className} aria-hidden>
|
||||
<defs>
|
||||
<linearGradient id={gradientId} x1="2" y1="2" x2="22" y2="22">
|
||||
<stop offset="0" stopColor="#00dff0" />
|
||||
<stop offset="0.42" stopColor="#3b9cff" />
|
||||
<stop offset="0.72" stopColor="#b044f5" />
|
||||
<stop offset="1" stopColor="#ff78b6" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect x="1" y="1" width="22" height="22" rx="5" fill={`url(#${gradientId})`} />
|
||||
<path
|
||||
d="m7.2 6.2 10.5 4.1-4.2 2.1-2 4.7z"
|
||||
fill="white"
|
||||
stroke="#315cff"
|
||||
strokeWidth="1.1"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function ToolActivityIconView(props: {
|
||||
icon: ToolActivityIcon | undefined;
|
||||
fallbackName: WorkEntryIconName;
|
||||
className: string;
|
||||
muted: boolean;
|
||||
}) {
|
||||
const { resolvedTheme } = use(TimelineRowCtx);
|
||||
const fallbackClassName = cn(props.className, props.muted && "opacity-70 light:brightness-[.6]");
|
||||
if (!props.icon) {
|
||||
return <WorkEntryIcon name={props.fallbackName} className={fallbackClassName} />;
|
||||
}
|
||||
if (props.icon._tag === "website") {
|
||||
const src = toolActivityFaviconUrl(props.icon, resolvedTheme, 32);
|
||||
return src ? (
|
||||
<ToolActivityImageIcon
|
||||
key={src}
|
||||
cacheKey={src}
|
||||
src={src}
|
||||
fallbackName={props.fallbackName}
|
||||
className={props.className}
|
||||
muted={props.muted}
|
||||
/>
|
||||
) : (
|
||||
<WorkEntryIcon name={props.fallbackName} className={fallbackClassName} />
|
||||
);
|
||||
}
|
||||
if (props.icon._tag === "themed-logo") {
|
||||
const src =
|
||||
resolvedTheme === "dark"
|
||||
? (props.icon.logoUrlDark ?? props.icon.logoUrl)
|
||||
: props.icon.logoUrl;
|
||||
return (
|
||||
<ToolActivityImageIcon
|
||||
key={src}
|
||||
cacheKey={src}
|
||||
src={src}
|
||||
fallbackName={props.fallbackName}
|
||||
className={props.className}
|
||||
muted={props.muted}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<NativeAppToolActivityIcon
|
||||
app={props.icon.app}
|
||||
fallbackName={props.fallbackName}
|
||||
className={props.className}
|
||||
muted={props.muted}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function NativeAppToolActivityIcon(props: {
|
||||
app: Extract<ToolActivityIcon, { readonly _tag: "native-app" }>["app"];
|
||||
fallbackName: WorkEntryIconName;
|
||||
className: string;
|
||||
muted: boolean;
|
||||
}) {
|
||||
const { activeThreadEnvironmentId } = use(TimelineRowCtx);
|
||||
const asset = useAssetUrlState(activeThreadEnvironmentId, {
|
||||
_tag: "native-app-icon",
|
||||
app: props.app,
|
||||
});
|
||||
if (asset._tag !== "Success") {
|
||||
return (
|
||||
<WorkEntryIcon
|
||||
name={props.fallbackName}
|
||||
className={cn(props.className, props.muted && "opacity-70 light:brightness-[.6]")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
const cacheKey = getProjectFaviconCacheKey(
|
||||
activeThreadEnvironmentId,
|
||||
JSON.stringify(props.app),
|
||||
asset.url,
|
||||
);
|
||||
return (
|
||||
<ToolActivityImageIcon
|
||||
key={cacheKey}
|
||||
cacheKey={cacheKey}
|
||||
src={asset.url}
|
||||
fallbackName={props.fallbackName}
|
||||
className={props.className}
|
||||
muted={props.muted}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const loadedToolActivityIconSrcs = new Map<string, string>();
|
||||
|
||||
function ToolActivityImageIcon(props: {
|
||||
cacheKey: string;
|
||||
src: string;
|
||||
fallbackName: WorkEntryIconName;
|
||||
className: string;
|
||||
muted: boolean;
|
||||
}) {
|
||||
const [displayedSrc, setDisplayedSrc] = useState<string | null>(
|
||||
() => loadedToolActivityIconSrcs.get(props.cacheKey) ?? null,
|
||||
);
|
||||
const isLoading = displayedSrc !== props.src;
|
||||
const handleLoadError = (failedSrc: string) => {
|
||||
if (loadedToolActivityIconSrcs.get(props.cacheKey) === failedSrc) {
|
||||
loadedToolActivityIconSrcs.delete(props.cacheKey);
|
||||
}
|
||||
setDisplayedSrc((currentSrc) => (currentSrc === failedSrc ? null : currentSrc));
|
||||
};
|
||||
return (
|
||||
<>
|
||||
{displayedSrc === null ? (
|
||||
<WorkEntryIcon
|
||||
name={props.fallbackName}
|
||||
className={cn(props.className, props.muted && "opacity-70 light:brightness-[.6]")}
|
||||
/>
|
||||
) : null}
|
||||
{displayedSrc ? (
|
||||
<span
|
||||
className={cn(
|
||||
props.className,
|
||||
"inline-block overflow-hidden rounded-[3px] bg-background",
|
||||
props.muted && "opacity-70",
|
||||
)}
|
||||
>
|
||||
<img
|
||||
src={displayedSrc}
|
||||
alt=""
|
||||
aria-hidden
|
||||
decoding="async"
|
||||
referrerPolicy="no-referrer"
|
||||
className={cn("block size-full object-contain", props.muted && "light:brightness-[.6]")}
|
||||
onError={() => handleLoadError(displayedSrc)}
|
||||
/>
|
||||
</span>
|
||||
) : null}
|
||||
{isLoading ? (
|
||||
<img
|
||||
src={props.src}
|
||||
alt=""
|
||||
aria-hidden
|
||||
decoding="async"
|
||||
referrerPolicy="no-referrer"
|
||||
className="hidden"
|
||||
onLoad={() => {
|
||||
loadedToolActivityIconSrcs.set(props.cacheKey, props.src);
|
||||
setDisplayedSrc(props.src);
|
||||
}}
|
||||
onError={() => handleLoadError(props.src)}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function WorkEntryIcon({ name, className }: { name: WorkEntryIconName; className: string }) {
|
||||
switch (name) {
|
||||
case "bot":
|
||||
@@ -2464,7 +2689,9 @@ function WorkEntryIcon({ name, className }: { name: WorkEntryIconName; className
|
||||
case "brain":
|
||||
return <BrainIcon className={className} aria-hidden />;
|
||||
case "browser":
|
||||
return <GlobeIcon className={className} aria-hidden />;
|
||||
return <BrowserAppIcon className={className} />;
|
||||
case "computer":
|
||||
return <ComputerUseAppIcon className={className} />;
|
||||
case "t3-code":
|
||||
return <T3Wordmark className={className} aria-hidden />;
|
||||
case "check":
|
||||
@@ -2570,6 +2797,7 @@ function workEntryIconName(workEntry: TimelineWorkEntry): WorkEntryIconName {
|
||||
) {
|
||||
return "message-circle";
|
||||
}
|
||||
if (workEntry.toolSurface) return workEntry.toolSurface;
|
||||
const toolPresentation = resolveWorkEntryToolPresentation(workEntry);
|
||||
if (toolPresentation) return toolPresentation.icon;
|
||||
const action = toolGroupAction(workEntry);
|
||||
@@ -2731,8 +2959,9 @@ const PlainWorkEntryRow = memo(function PlainWorkEntryRow(props: {
|
||||
const showWarningIndicator = workEntry.sourceActivityKind === "runtime.warning";
|
||||
const showFailedIndicator = workEntryDisplayIndicatesToolFailure(workEntry);
|
||||
const toolPresentation = resolveWorkEntryToolPresentation(workEntry);
|
||||
const hasSpecialToolIcon = toolPresentation !== null || workEntry.toolSurface !== undefined;
|
||||
const entryIconName =
|
||||
showWarningIndicator || (showFailedIndicator && !toolPresentation)
|
||||
showWarningIndicator || (showFailedIndicator && !hasSpecialToolIcon)
|
||||
? "circle-alert"
|
||||
: workEntryIconName(workEntry);
|
||||
const previewText = workEntryDisplayLabel(workEntry, workspaceRoot);
|
||||
@@ -2812,9 +3041,15 @@ const PlainWorkEntryRow = memo(function PlainWorkEntryRow(props: {
|
||||
role={showFailedIndicator ? "img" : undefined}
|
||||
aria-label={showFailedIndicator ? "Tool call failed" : undefined}
|
||||
>
|
||||
<WorkEntryIcon
|
||||
name={entryIconName}
|
||||
className="block size-4 shrink-0 stroke-[1.8] opacity-70"
|
||||
<ToolActivityIconView
|
||||
icon={
|
||||
showWarningIndicator || (showFailedIndicator && !hasSpecialToolIcon)
|
||||
? undefined
|
||||
: (workEntry.toolIcon ?? workEntry.toolSource?.icon)
|
||||
}
|
||||
fallbackName={entryIconName}
|
||||
className="block size-4 shrink-0 stroke-[1.8]"
|
||||
muted
|
||||
/>
|
||||
</span>
|
||||
<div className="flex min-w-0 flex-1 items-center gap-1.5">
|
||||
@@ -2823,7 +3058,7 @@ const PlainWorkEntryRow = memo(function PlainWorkEntryRow(props: {
|
||||
<span className={cn("min-w-0 flex-1 truncate", headingClass)}>{displayText}</span>
|
||||
</p>
|
||||
</div>
|
||||
{showFailedIndicator && toolPresentation ? (
|
||||
{showFailedIndicator && hasSpecialToolIcon ? (
|
||||
<XIcon aria-hidden className="size-3 shrink-0 text-icon-muted" />
|
||||
) : null}
|
||||
<span
|
||||
|
||||
@@ -1240,6 +1240,13 @@ describe("deriveWorkLogEntries", () => {
|
||||
payload: {
|
||||
itemType: "mcp_tool_call",
|
||||
title: "t3-code · preview_status",
|
||||
toolSurface: "browser",
|
||||
toolIcon: { _tag: "website", pageUrl: "https://example.com/checkout" },
|
||||
toolSource: {
|
||||
key: "browser-use:browser",
|
||||
name: "Browser",
|
||||
kind: "browser",
|
||||
},
|
||||
data: { item },
|
||||
},
|
||||
}),
|
||||
@@ -1247,6 +1254,16 @@ describe("deriveWorkLogEntries", () => {
|
||||
|
||||
const [entry] = deriveWorkLogEntries(activities);
|
||||
expect(entry?.toolTitle).toBe("t3-code · preview_status");
|
||||
expect(entry?.toolSurface).toBe("browser");
|
||||
expect(entry?.toolIcon).toEqual({
|
||||
_tag: "website",
|
||||
pageUrl: "https://example.com/checkout",
|
||||
});
|
||||
expect(entry?.toolSource).toEqual({
|
||||
key: "browser-use:browser",
|
||||
name: "Browser",
|
||||
kind: "browser",
|
||||
});
|
||||
expect(entry?.toolData).toEqual(item);
|
||||
});
|
||||
|
||||
@@ -1296,6 +1313,7 @@ describe("deriveWorkLogEntries", () => {
|
||||
payload: {
|
||||
itemType: "mcp_tool_call",
|
||||
toolCallId: "call-1",
|
||||
toolSurface: "browser",
|
||||
data: { item },
|
||||
},
|
||||
}),
|
||||
@@ -1306,6 +1324,7 @@ describe("deriveWorkLogEntries", () => {
|
||||
payload: {
|
||||
itemType: "mcp_tool_call",
|
||||
toolCallId: "call-1",
|
||||
toolIcon: { _tag: "website", pageUrl: "https://example.com/result" },
|
||||
},
|
||||
}),
|
||||
];
|
||||
@@ -1313,6 +1332,11 @@ describe("deriveWorkLogEntries", () => {
|
||||
const [entry] = deriveWorkLogEntries(activities);
|
||||
expect(entry?.toolData).toEqual(item);
|
||||
expect(entry?.toolCallId).toBe("call-1");
|
||||
expect(entry?.toolSurface).toBe("browser");
|
||||
expect(entry?.toolIcon).toEqual({
|
||||
_tag: "website",
|
||||
pageUrl: "https://example.com/result",
|
||||
});
|
||||
expect(resolveWorkEntryToolPresentation(entry!)?.displayName).toBe(
|
||||
"Took a snapshot of the preview page",
|
||||
);
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
extractCommandOutputText,
|
||||
isWorktreeSetupActivity,
|
||||
} from "@t3tools/client-runtime/work-log/presentation";
|
||||
import { extractToolActivityPresentation } from "@t3tools/client-runtime/work-log/tool-presentation";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
isToolLifecycleItemType,
|
||||
@@ -83,6 +84,9 @@ export interface WorkLogEntry {
|
||||
changedFiles?: ReadonlyArray<string>;
|
||||
tone: "thinking" | "tool" | "info" | "error";
|
||||
toolTitle?: string;
|
||||
toolSurface?: import("@t3tools/contracts").ToolActivitySurface;
|
||||
toolIcon?: import("@t3tools/contracts").ToolActivityIcon;
|
||||
toolSource?: import("@t3tools/contracts").ToolActivitySource;
|
||||
toolData?: unknown;
|
||||
itemType?: ToolLifecycleItemType;
|
||||
requestKind?: PendingApproval["requestKind"];
|
||||
@@ -889,6 +893,7 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
|
||||
const commandPreview = extractToolCommand(payload);
|
||||
const changedFiles = extractChangedFiles(payload);
|
||||
const title = extractToolTitle(payload);
|
||||
const toolPresentation = extractToolActivityPresentation(payload);
|
||||
const isTaskActivity =
|
||||
activity.kind === "task.started" ||
|
||||
activity.kind === "task.progress" ||
|
||||
@@ -948,6 +953,15 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
|
||||
if (title) {
|
||||
entry.toolTitle = title;
|
||||
}
|
||||
if (toolPresentation.toolSurface) {
|
||||
entry.toolSurface = toolPresentation.toolSurface;
|
||||
}
|
||||
if (toolPresentation.toolIcon) {
|
||||
entry.toolIcon = toolPresentation.toolIcon;
|
||||
}
|
||||
if (toolPresentation.toolSource) {
|
||||
entry.toolSource = toolPresentation.toolSource;
|
||||
}
|
||||
if (itemType === "mcp_tool_call") {
|
||||
const data = asRecord(payload?.data);
|
||||
const toolData = typeof data?.toolName === "string" ? (data.item ?? data) : data?.item;
|
||||
@@ -1170,6 +1184,9 @@ function mergeDerivedWorkLogEntries(
|
||||
const command = next.command ?? previous.command;
|
||||
const rawCommand = next.rawCommand ?? previous.rawCommand;
|
||||
const toolTitle = next.toolTitle ?? previous.toolTitle;
|
||||
const toolSurface = next.toolSurface ?? previous.toolSurface;
|
||||
const toolIcon = next.toolIcon ?? previous.toolIcon;
|
||||
const toolSource = next.toolSource ?? previous.toolSource;
|
||||
const itemType = next.itemType ?? previous.itemType;
|
||||
const requestKind = next.requestKind ?? previous.requestKind;
|
||||
const collapseKey = next[workLogCollapseKey] ?? previous[workLogCollapseKey];
|
||||
@@ -1185,6 +1202,9 @@ function mergeDerivedWorkLogEntries(
|
||||
...(rawCommand ? { rawCommand } : {}),
|
||||
...(changedFiles.length > 0 ? { changedFiles } : {}),
|
||||
...(toolTitle ? { toolTitle } : {}),
|
||||
...(toolSurface ? { toolSurface } : {}),
|
||||
...(toolIcon ? { toolIcon } : {}),
|
||||
...(toolSource ? { toolSource } : {}),
|
||||
...(itemType ? { itemType } : {}),
|
||||
...(requestKind ? { requestKind } : {}),
|
||||
...(collapseKey ? { [workLogCollapseKey]: collapseKey } : {}),
|
||||
|
||||
@@ -40,6 +40,17 @@ The web and desktop Agents panel shows each sub-agent's model and reasoning effo
|
||||
reports them. If Codex does not report either value, T3 Code leaves it out instead of using the
|
||||
parent agent's settings.
|
||||
|
||||
## Browser and computer activity
|
||||
|
||||
Browser and Computer Use calls show their user-facing task title when Codex provides one. Expanded
|
||||
activity groups show an icon for every call. Website calls use the active page's favicon when it is
|
||||
available, and desktop app calls use the app's native icon on macOS when available. Other hosts use
|
||||
a generic fallback glyph.
|
||||
|
||||
Collapsed activity groups are summarized by source, such as `Used Chrome integration`, instead of
|
||||
showing the underlying tool name. Website favicons and native app icons keep their original colors;
|
||||
integrations that provide separate light and dark logos use the logo for the current appearance.
|
||||
|
||||
## Approve access to other apps
|
||||
|
||||
When a Codex tool needs access to an app such as Safari, T3 Code shows the app name and asks for
|
||||
|
||||
@@ -199,6 +199,10 @@
|
||||
"types": "./src/work-log/presentation.ts",
|
||||
"default": "./src/work-log/presentation.ts"
|
||||
},
|
||||
"./work-log/tool-presentation": {
|
||||
"types": "./src/work-log/toolPresentation.ts",
|
||||
"default": "./src/work-log/toolPresentation.ts"
|
||||
},
|
||||
"./work-log/command-label": {
|
||||
"types": "./src/work-log/commandLabel.ts",
|
||||
"default": "./src/work-log/commandLabel.ts"
|
||||
|
||||
@@ -14,6 +14,41 @@ import {
|
||||
workEntryViewedImagePath,
|
||||
} from "./presentation.js";
|
||||
|
||||
describe("summarizeToolGroup", () => {
|
||||
it("deduplicates named sources ahead of ordinary actions", () => {
|
||||
const source = { key: "browser-use:chrome", name: "Chrome", kind: "integration" as const };
|
||||
expect(
|
||||
summarizeToolGroup([
|
||||
{ label: "Open page", tone: "tool", toolSource: source },
|
||||
{ label: "Inspect page", tone: "tool", toolSource: source },
|
||||
{
|
||||
label: "Ran command",
|
||||
tone: "tool",
|
||||
itemType: "command_execution",
|
||||
command: "git status",
|
||||
},
|
||||
]),
|
||||
).toBe("Used Chrome integration and ran 1 command");
|
||||
});
|
||||
|
||||
it("omits the integration suffix for special browser and computer sources", () => {
|
||||
expect(
|
||||
summarizeToolGroup([
|
||||
{
|
||||
label: "Inspect page",
|
||||
tone: "tool",
|
||||
toolSource: { key: "browser-use", name: "Browser", kind: "browser" },
|
||||
},
|
||||
{
|
||||
label: "Click",
|
||||
tone: "tool",
|
||||
toolSource: { key: "computer-use", name: "Computer Use", kind: "computer" },
|
||||
},
|
||||
]),
|
||||
).toBe("Used Browser and Computer Use");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveWorkEntryToolPresentation", () => {
|
||||
it.each([
|
||||
"mcp__t3-code__preview_click",
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
isToolLifecycleItemType,
|
||||
type AssetResource,
|
||||
type ThreadId,
|
||||
type ToolActivitySource,
|
||||
type ToolLifecycleItemType,
|
||||
} from "@t3tools/contracts";
|
||||
import { classifyMarkdownImageSource } from "@t3tools/client-runtime/markdown-images";
|
||||
@@ -28,6 +29,7 @@ export interface WorkLogPresentationEntry {
|
||||
readonly toolLifecycleStatus?: string;
|
||||
readonly sourceActivityKind?: string;
|
||||
readonly taskId?: string;
|
||||
readonly toolSource?: ToolActivitySource;
|
||||
}
|
||||
|
||||
export type ToolGroupAction =
|
||||
@@ -426,8 +428,13 @@ function toolGroupActionLabel(action: ToolGroupAction, count: number): string {
|
||||
|
||||
export function summarizeToolGroup(entries: ReadonlyArray<WorkLogPresentationEntry>): string {
|
||||
const summaryEntries = omitSupersededLifecycleMarkers(entries, (entry) => entry);
|
||||
const sources = new Map<string, ToolActivitySource>();
|
||||
const groupedEntries = new Map<ToolGroupAction, WorkLogPresentationEntry[]>();
|
||||
for (const entry of summaryEntries) {
|
||||
if (entry.toolSource) {
|
||||
sources.set(entry.toolSource.key, entry.toolSource);
|
||||
continue;
|
||||
}
|
||||
const action = toolGroupAction(entry);
|
||||
const group = groupedEntries.get(action);
|
||||
if (group) group.push(entry);
|
||||
@@ -436,6 +443,20 @@ export function summarizeToolGroup(entries: ReadonlyArray<WorkLogPresentationEnt
|
||||
const labels = [...groupedEntries].map(([action, actionEntries]) =>
|
||||
toolGroupActionLabel(action, toolGroupActionCount(action, actionEntries)),
|
||||
);
|
||||
if (sources.size > 0) {
|
||||
const sourceValues = [...sources.values()];
|
||||
const sourceNames = sourceValues.map((source) => source.name);
|
||||
const formattedNames =
|
||||
sourceNames.length < 2
|
||||
? sourceNames[0]!
|
||||
: sourceNames.length === 2
|
||||
? sourceNames.join(" and ")
|
||||
: `${sourceNames.slice(0, -1).join(", ")}, and ${sourceNames.at(-1)}`;
|
||||
const allIntegrations = sourceValues.every((source) => source.kind === "integration");
|
||||
labels.unshift(
|
||||
`Used ${formattedNames}${allIntegrations ? ` ${sources.size === 1 ? "integration" : "integrations"}` : ""}`,
|
||||
);
|
||||
}
|
||||
const sentenceLabels = labels.map((label, index) =>
|
||||
index === 0 ? label : label.charAt(0).toLowerCase() + label.slice(1),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
|
||||
import { extractToolActivityPresentation } from "./toolPresentation.ts";
|
||||
|
||||
describe("extractToolActivityPresentation", () => {
|
||||
it("reads provider-neutral presentation fields", () => {
|
||||
expect(
|
||||
extractToolActivityPresentation({
|
||||
toolSurface: "browser",
|
||||
toolIcon: {
|
||||
_tag: "website",
|
||||
pageUrl: "https://example.com/docs",
|
||||
faviconUrl: "https://example.com/favicon.png",
|
||||
faviconUrlDark: "https://example.com/favicon-dark.png",
|
||||
},
|
||||
toolSource: {
|
||||
key: "integration:example",
|
||||
name: "Example",
|
||||
kind: "integration",
|
||||
icon: {
|
||||
_tag: "themed-logo",
|
||||
logoUrl: "https://example.com/logo-light.png",
|
||||
logoUrlDark: "https://example.com/logo-dark.png",
|
||||
},
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
toolSurface: "browser",
|
||||
toolIcon: {
|
||||
_tag: "website",
|
||||
pageUrl: "https://example.com/docs",
|
||||
faviconUrl: "https://example.com/favicon.png",
|
||||
faviconUrlDark: "https://example.com/favicon-dark.png",
|
||||
},
|
||||
toolSource: {
|
||||
key: "integration:example",
|
||||
name: "Example",
|
||||
kind: "integration",
|
||||
icon: {
|
||||
_tag: "themed-logo",
|
||||
logoUrl: "https://example.com/logo-light.png",
|
||||
logoUrlDark: "https://example.com/logo-dark.png",
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("reads provider-neutral native app icons", () => {
|
||||
expect(
|
||||
extractToolActivityPresentation({
|
||||
toolSurface: "computer",
|
||||
toolIcon: {
|
||||
_tag: "native-app",
|
||||
app: { _tag: "app-id", appId: "com.example.Editor" },
|
||||
},
|
||||
toolSource: {
|
||||
key: "native-app:com.example.editor",
|
||||
name: "Editor",
|
||||
kind: "computer",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
toolSurface: "computer",
|
||||
toolIcon: {
|
||||
_tag: "native-app",
|
||||
app: { _tag: "app-id", appId: "com.example.Editor" },
|
||||
},
|
||||
toolSource: {
|
||||
key: "native-app:com.example.editor",
|
||||
name: "Editor",
|
||||
kind: "computer",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("does not infer presentation from provider-specific payload data", () => {
|
||||
expect(
|
||||
extractToolActivityPresentation({
|
||||
data: {
|
||||
item: {
|
||||
arguments: { code: 'await sky.click({ app: "Finder" })' },
|
||||
result: {
|
||||
_meta: {
|
||||
"codex/toolSurface": {
|
||||
kind: "computerUse",
|
||||
app: { kind: "displayName", displayName: "Finder" },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
).toEqual({});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
import type {
|
||||
ToolActivityIcon,
|
||||
ToolActivityNativeAppReference,
|
||||
ToolActivitySource,
|
||||
ToolActivitySurface,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
export interface ExtractedToolActivityPresentation {
|
||||
readonly toolSurface?: ToolActivitySurface;
|
||||
readonly toolIcon?: ToolActivityIcon;
|
||||
readonly toolSource?: ToolActivitySource;
|
||||
}
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> | undefined {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function trimmedString(value: unknown, maxLength: number): string | undefined {
|
||||
if (typeof value !== "string") return undefined;
|
||||
const trimmed = value.trim();
|
||||
return trimmed && trimmed.length <= maxLength ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function imageUrl(value: unknown): string | undefined {
|
||||
const raw = trimmedString(value, 4096);
|
||||
if (!raw) return undefined;
|
||||
try {
|
||||
const url = new URL(raw);
|
||||
return url.protocol === "http:" || url.protocol === "https:" || url.protocol === "data:"
|
||||
? url.href
|
||||
: undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function pageUrl(value: unknown): string | undefined {
|
||||
const raw = trimmedString(value, 4096);
|
||||
if (!raw) return undefined;
|
||||
try {
|
||||
const url = new URL(raw);
|
||||
return url.protocol === "http:" || url.protocol === "https:" ? url.href : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function nativeAppReference(value: unknown): ToolActivityNativeAppReference | undefined {
|
||||
const app = asRecord(value);
|
||||
const appId = trimmedString(app?.appId, 512);
|
||||
if (app?._tag === "app-id" && appId && /^[A-Za-z0-9._-]+$/u.test(appId)) {
|
||||
return { _tag: "app-id", appId };
|
||||
}
|
||||
const displayName = trimmedString(app?.displayName, 160);
|
||||
if (app?._tag === "display-name" && displayName) {
|
||||
return { _tag: "display-name", displayName };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function activityIcon(value: unknown): ToolActivityIcon | undefined {
|
||||
const icon = asRecord(value);
|
||||
if (icon?._tag === "website") {
|
||||
const resolvedPageUrl = pageUrl(icon.pageUrl);
|
||||
const faviconUrl = imageUrl(icon.faviconUrl);
|
||||
const faviconUrlDark = imageUrl(icon.faviconUrlDark);
|
||||
if (resolvedPageUrl) {
|
||||
return {
|
||||
_tag: "website",
|
||||
pageUrl: resolvedPageUrl,
|
||||
...(faviconUrl ? { faviconUrl } : {}),
|
||||
...(faviconUrlDark ? { faviconUrlDark } : {}),
|
||||
};
|
||||
}
|
||||
}
|
||||
if (icon?._tag === "native-app") {
|
||||
const app = nativeAppReference(icon.app);
|
||||
if (app) return { _tag: "native-app", app };
|
||||
}
|
||||
if (icon?._tag === "themed-logo") {
|
||||
const logoUrl = imageUrl(icon.logoUrl);
|
||||
const logoUrlDark = imageUrl(icon.logoUrlDark);
|
||||
if (logoUrl) {
|
||||
return {
|
||||
_tag: "themed-logo",
|
||||
logoUrl,
|
||||
...(logoUrlDark ? { logoUrlDark } : {}),
|
||||
};
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function activitySource(value: unknown): ToolActivitySource | undefined {
|
||||
const source = asRecord(value);
|
||||
const key = trimmedString(source?.key, 512);
|
||||
const name = trimmedString(source?.name, 160);
|
||||
const kind = source?.kind;
|
||||
if (!key || !name || (kind !== "browser" && kind !== "computer" && kind !== "integration")) {
|
||||
return undefined;
|
||||
}
|
||||
const icon = activityIcon(source?.icon);
|
||||
return { key, name, kind, ...(icon ? { icon } : {}) };
|
||||
}
|
||||
|
||||
export function extractToolActivityPresentation(
|
||||
payloadValue: unknown,
|
||||
): ExtractedToolActivityPresentation {
|
||||
const payload = asRecord(payloadValue);
|
||||
const toolSurface =
|
||||
payload?.toolSurface === "browser" || payload?.toolSurface === "computer"
|
||||
? payload.toolSurface
|
||||
: undefined;
|
||||
const toolIcon = activityIcon(payload?.toolIcon);
|
||||
const toolSource = activitySource(payload?.toolSource);
|
||||
return {
|
||||
...(toolSurface ? { toolSurface } : {}),
|
||||
...(toolIcon ? { toolIcon } : {}),
|
||||
...(toolSource ? { toolSource } : {}),
|
||||
};
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES,
|
||||
ProjectFaviconPath,
|
||||
} from "./orchestration.ts";
|
||||
import { ToolActivityNativeAppReference } from "./providerRuntime.ts";
|
||||
|
||||
const ASSET_PATH_MAX_LENGTH = 1024;
|
||||
|
||||
@@ -40,6 +41,9 @@ export const AssetResource = Schema.Union([
|
||||
// project projection before it issues the signed URL.
|
||||
path: Schema.optional(ProjectFaviconPath),
|
||||
}),
|
||||
Schema.TaggedStruct("native-app-icon", {
|
||||
app: ToolActivityNativeAppReference,
|
||||
}),
|
||||
]);
|
||||
export type AssetResource = typeof AssetResource.Type;
|
||||
|
||||
|
||||
@@ -406,11 +406,54 @@ const TurnDiffUpdatedPayload = Schema.Struct({
|
||||
});
|
||||
export type TurnDiffUpdatedPayload = typeof TurnDiffUpdatedPayload.Type;
|
||||
|
||||
export const ToolActivitySurface = Schema.Literals(["browser", "computer"]);
|
||||
export type ToolActivitySurface = typeof ToolActivitySurface.Type;
|
||||
|
||||
export const ToolActivityNativeAppReference = Schema.Union([
|
||||
Schema.TaggedStruct("app-id", {
|
||||
appId: TrimmedNonEmptyStringSchema.check(
|
||||
Schema.isMaxLength(512),
|
||||
Schema.isPattern(/^[A-Za-z0-9._-]+$/u),
|
||||
),
|
||||
}),
|
||||
Schema.TaggedStruct("display-name", {
|
||||
displayName: TrimmedNonEmptyStringSchema.check(Schema.isMaxLength(160)),
|
||||
}),
|
||||
]);
|
||||
export type ToolActivityNativeAppReference = typeof ToolActivityNativeAppReference.Type;
|
||||
|
||||
export const ToolActivityIcon = Schema.Union([
|
||||
Schema.TaggedStruct("website", {
|
||||
pageUrl: TrimmedNonEmptyStringSchema.check(Schema.isMaxLength(4096)),
|
||||
faviconUrl: Schema.optional(TrimmedNonEmptyStringSchema.check(Schema.isMaxLength(4096))),
|
||||
faviconUrlDark: Schema.optional(TrimmedNonEmptyStringSchema.check(Schema.isMaxLength(4096))),
|
||||
}),
|
||||
Schema.TaggedStruct("native-app", {
|
||||
app: ToolActivityNativeAppReference,
|
||||
}),
|
||||
Schema.TaggedStruct("themed-logo", {
|
||||
logoUrl: TrimmedNonEmptyStringSchema.check(Schema.isMaxLength(4096)),
|
||||
logoUrlDark: Schema.optional(TrimmedNonEmptyStringSchema.check(Schema.isMaxLength(4096))),
|
||||
}),
|
||||
]);
|
||||
export type ToolActivityIcon = typeof ToolActivityIcon.Type;
|
||||
|
||||
export const ToolActivitySource = Schema.Struct({
|
||||
key: TrimmedNonEmptyStringSchema.check(Schema.isMaxLength(512)),
|
||||
name: TrimmedNonEmptyStringSchema.check(Schema.isMaxLength(160)),
|
||||
kind: Schema.Literals(["browser", "computer", "integration"]),
|
||||
icon: Schema.optional(ToolActivityIcon),
|
||||
});
|
||||
export type ToolActivitySource = typeof ToolActivitySource.Type;
|
||||
|
||||
export const ItemLifecyclePayload = Schema.Struct({
|
||||
itemType: CanonicalItemType,
|
||||
status: Schema.optional(RuntimeItemStatus),
|
||||
title: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
detail: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
toolSurface: Schema.optional(ToolActivitySurface),
|
||||
toolIcon: Schema.optional(ToolActivityIcon),
|
||||
toolSource: Schema.optional(ToolActivitySource),
|
||||
data: Schema.optional(Schema.Unknown),
|
||||
/**
|
||||
* Owning agent when this item ran inside a subagent (resolved from the
|
||||
|
||||
@@ -79,6 +79,10 @@
|
||||
"types": "./src/toolActivity.ts",
|
||||
"import": "./src/toolActivity.ts"
|
||||
},
|
||||
"./favicon": {
|
||||
"types": "./src/favicon.ts",
|
||||
"import": "./src/favicon.ts"
|
||||
},
|
||||
"./Struct": {
|
||||
"types": "./src/Struct.ts",
|
||||
"import": "./src/Struct.ts"
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
|
||||
import { explicitFaviconUrl, faviconUrlForPage, toolActivityFaviconUrl } from "./favicon.ts";
|
||||
|
||||
describe("faviconUrlForPage", () => {
|
||||
it("uses the page origin instead of a third-party favicon service", () => {
|
||||
expect(faviconUrlForPage("https://example.com/docs/page?q=1")).toBe(
|
||||
"https://example.com/favicon.ico",
|
||||
);
|
||||
expect(faviconUrlForPage("http://localhost:5173/app")).toBe(
|
||||
"http://localhost:5173/favicon.ico",
|
||||
);
|
||||
});
|
||||
|
||||
it("selects site-owned light and dark variants without filtering full-color icons", () => {
|
||||
expect(toolActivityFaviconUrl({ pageUrl: "https://github.com/openai/codex" }, "light")).toBe(
|
||||
"https://github.githubassets.com/favicons/favicon.svg",
|
||||
);
|
||||
expect(toolActivityFaviconUrl({ pageUrl: "https://github.com/openai/codex" }, "dark")).toBe(
|
||||
"https://github.githubassets.com/favicons/favicon-dark.svg",
|
||||
);
|
||||
|
||||
const fullColorIcon = {
|
||||
pageUrl: "https://example.com/docs",
|
||||
faviconUrl: "https://cdn.example.com/full-color.png",
|
||||
};
|
||||
expect(toolActivityFaviconUrl(fullColorIcon, "light")).toBe(fullColorIcon.faviconUrl);
|
||||
expect(toolActivityFaviconUrl(fullColorIcon, "dark")).toBe(fullColorIcon.faviconUrl);
|
||||
});
|
||||
|
||||
it("prefers a provider-supplied dark favicon", () => {
|
||||
expect(
|
||||
toolActivityFaviconUrl(
|
||||
{
|
||||
pageUrl: "https://example.com/docs",
|
||||
faviconUrl: "https://example.com/light.svg",
|
||||
faviconUrlDark: "https://example.com/dark.svg",
|
||||
},
|
||||
"dark",
|
||||
),
|
||||
).toBe("https://example.com/dark.svg");
|
||||
});
|
||||
|
||||
it("accepts provider-supplied image URLs but rejects extension URLs", () => {
|
||||
expect(explicitFaviconUrl("https://example.com/icon.png")).toBe("https://example.com/icon.png");
|
||||
expect(explicitFaviconUrl("chrome-extension://example/_favicon/")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* Mirrors Codex's generic Browser Use fallback: ask the page origin for its
|
||||
* conventional favicon and let the image element fall back to a browser glyph.
|
||||
* Chrome-backed tools can pass their tab's explicit favicon URL separately.
|
||||
*/
|
||||
export function faviconUrlForPage(rawUrl: string | null | undefined, _size = 32): string | null {
|
||||
if (!rawUrl || rawUrl.length > 4096) return null;
|
||||
try {
|
||||
const pageUrl = new URL(rawUrl);
|
||||
if (pageUrl.protocol !== "http:" && pageUrl.protocol !== "https:") return null;
|
||||
return new URL("/favicon.ico", pageUrl.origin).href;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const THEMED_FAVICON_BY_HOSTNAME: Readonly<
|
||||
Record<string, Readonly<{ light: string; dark: string }>>
|
||||
> = {
|
||||
"github.com": {
|
||||
light: "https://github.githubassets.com/favicons/favicon.svg",
|
||||
dark: "https://github.githubassets.com/favicons/favicon-dark.svg",
|
||||
},
|
||||
};
|
||||
|
||||
function themedFaviconUrlForPage(
|
||||
rawUrl: string | null | undefined,
|
||||
appearance: "light" | "dark",
|
||||
): string | null {
|
||||
if (!rawUrl || rawUrl.length > 4096) return null;
|
||||
try {
|
||||
const pageUrl = new URL(rawUrl);
|
||||
if (pageUrl.protocol !== "http:" && pageUrl.protocol !== "https:") return null;
|
||||
return THEMED_FAVICON_BY_HOSTNAME[pageUrl.hostname.toLowerCase()]?.[appearance] ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Accepts image URLs supplied by a trusted provider event. */
|
||||
export function explicitFaviconUrl(rawUrl: string | null | undefined): string | null {
|
||||
if (!rawUrl || rawUrl.length > 4096) return null;
|
||||
try {
|
||||
const url = new URL(rawUrl);
|
||||
return url.protocol === "http:" || url.protocol === "https:" || url.protocol === "data:"
|
||||
? url.href
|
||||
: null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Chooses a website icon for the app's resolved theme. Provider-supplied
|
||||
* variants mirror Codex's Chrome-selected favicon path. A small site-owned
|
||||
* fallback table covers websites whose conventional favicon is illegible in
|
||||
* one appearance without recoloring full-color icons.
|
||||
*/
|
||||
export function toolActivityFaviconUrl(
|
||||
icon: {
|
||||
readonly pageUrl: string;
|
||||
readonly faviconUrl?: string | undefined;
|
||||
readonly faviconUrlDark?: string | undefined;
|
||||
},
|
||||
appearance: "light" | "dark",
|
||||
size = 32,
|
||||
): string | null {
|
||||
if (appearance === "dark") {
|
||||
return (
|
||||
explicitFaviconUrl(icon.faviconUrlDark) ??
|
||||
themedFaviconUrlForPage(icon.pageUrl, "dark") ??
|
||||
explicitFaviconUrl(icon.faviconUrl) ??
|
||||
faviconUrlForPage(icon.pageUrl, size)
|
||||
);
|
||||
}
|
||||
return (
|
||||
explicitFaviconUrl(icon.faviconUrl) ??
|
||||
themedFaviconUrlForPage(icon.pageUrl, "light") ??
|
||||
faviconUrlForPage(icon.pageUrl, size)
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user