refactor: isolate runtime contracts and enforce import boundaries (#6166)

* test: enforce Python import ownership boundaries

* test: protect client import boundaries and rehome shared UI contracts

* refactor: remove gateway and client dependency inversions

* fix: detect dynamic imports in conditional expressions

* refactor(tools): keep configuration contracts with their owners

* docs: keep design guidance focused on ownership and checks

* fix: preserve default threaded turn delivery
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-13 13:56:28 +08:00
1 parent cd2a863710
commit 328e933d36
162 files changed
+3449 -1888

No files matched your search

+2 -1
View File
@@ -13,7 +13,8 @@ import { Trans, useTranslation } from "react-i18next";
import { channelUiPresentation } from "@/channel-plugins/registry";
import { StarPrompt } from "@/components/StarPrompt";
import { Sidebar } from "@/components/Sidebar";
import { RemoteInstances, useRemoteConnections } from "@/components/remote/RemoteInstances";
import { RemoteInstances } from "@/components/remote/RemoteInstances";
import { useRemoteConnections } from "@/components/remote/remote-context";
import { RemoteConnectionsPage } from "@/components/remote/RemoteConnectionsPage";
import { LanguageSwitcher } from "@/components/LanguageSwitcher";
import { SidebarResizeHandle, SIDEBAR_MIN_WIDTH, SIDEBAR_MAX_WIDTH } from "@/components/SidebarResizeHandle";
+1 -1
View File
@@ -1,6 +1,6 @@
import type { ComponentType } from "react";
import type { ChannelPresentation } from "@/components/settings/channels/catalog";
import type { ChannelPresentation } from "@/channel-plugins/catalog";
import type {
NanobotFeatureInfo,
NanobotFeaturesPayload,
+2 -1
View File
@@ -51,7 +51,8 @@ import {
SIDEBAR_SELECTION_ITEM_CLASS,
SidebarSelectionHighlight,
} from "@/components/SidebarSelectionHighlight";
import { relativeTime, visibleSessionPreview } from "@/lib/format";
import { visibleSessionPreview } from "@/lib/format";
import { relativeTime } from "@/lib/format-time";
import {
COLLAPSED_CHATS_VISIBLE_COUNT,
displayTitle,
+1 -10
View File
@@ -10,16 +10,7 @@ import { logoFallbackUrls } from "@/lib/provider-brand";
import { sessionHandleColor } from "@/lib/session-handle";
import type { CliAppInfo, McpPresetInfo, SessionMention } from "@/lib/types";
import { cn } from "@/lib/utils";
import { composerMentionLabel } from "@/lib/composer-mention-text";
type CliAppMentionSegment =
| { kind: "text"; text: string }
| { kind: "cli"; text: string; app: CliAppInfo };
export type CapabilityMentionSegment =
| CliAppMentionSegment
| { kind: "mcp"; text: string; preset: McpPresetInfo }
| { kind: "session"; text: string; mention: SessionMention };
import { composerMentionLabel, type CapabilityMentionSegment } from "@/lib/composer-mention-text";
// Paint-only weight keeps the native textarea's regular-width caret and wrapping in sync.
const COMPOSER_BRAND_NAME_CLASS = "[-webkit-text-stroke:0.4px_currentColor]";
+1 -1
View File
@@ -12,7 +12,7 @@ import type { TFunction } from "i18next";
import { Trash2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { currentLocale } from "@/i18n";
import { fmtDateTime } from "@/lib/format";
import { fmtDateTime } from "@/lib/format-time";
import type { SessionAutomationJob } from "@/lib/types";
interface DeleteConfirmProps {
+2 -30
View File
@@ -19,12 +19,13 @@ import { InlineImageProvider, useInlineImages } from "@/components/InlineImageCo
import { MarkdownText } from "@/components/MarkdownText";
import { SlashCommandText } from "@/components/SlashCommandText";
import { ReasoningRow } from "@/components/thread/activity/ReasoningRow";
import { StreamingLabelSheen } from "@/components/ui/streaming-label-sheen";
import { ContextCompactionNotice } from "@/components/thread/ContextCompactionNotice";
import { UserMessageText } from "@/components/UserMessageText";
import { HoverHint } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
import { copyTextToClipboard } from "@/lib/clipboard";
import { formatMessageEndTime } from "@/lib/format";
import { formatMessageEndTime } from "@/lib/format-time";
import { toMediaAttachment } from "@/lib/media";
import { matchingSlashCommand } from "@/lib/slash-command";
import { sessionHandleColor } from "@/lib/session-handle";
@@ -704,35 +705,6 @@ function ThinkingState() {
);
}
/** L→R sheen on the glyphs themselves; inactive labels stay solid muted text. */
export function StreamingLabelSheen({
children,
active,
className,
}: {
children: ReactNode;
active: boolean;
className?: string;
}) {
const sheenText =
typeof children === "string" || typeof children === "number"
? String(children)
: undefined;
return (
<span className={cn("block min-w-0 overflow-hidden py-px", className)}>
<span
data-sheen-text={active ? sheenText : undefined}
className={cn(
"block w-fit max-w-full truncate pr-0.5 font-medium leading-normal",
active ? "streaming-text-sheen after:pr-0.5" : "text-muted-foreground",
)}
>
{children}
</span>
</span>
);
}
interface ReasoningBubbleProps {
text: string;
streaming: boolean;
+1 -1
View File
@@ -4,13 +4,13 @@ import { useTranslation } from "react-i18next";
import {
CapabilityMentionToken,
splitCapabilityMentionSegments,
type CapabilityMentionSegment,
} from "@/components/CliAppMentionText";
import {
INLINE_TOKEN_HIGHLIGHT_COLOR,
InlineTokenHighlight,
} from "@/components/InlineTokenHighlight";
import type { CliAppInfo, McpPresetInfo, SessionMention } from "@/lib/types";
import type { CapabilityMentionSegment } from "@/lib/composer-mention-text";
type SkillReferenceSegment =
| { kind: "text"; text: string }
@@ -2,7 +2,7 @@ import { CircleAlert, Loader2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { cn } from "@/lib/utils";
export type HostConnectionState = "open" | "closed" | "connecting" | "error";
import type { HostConnectionState } from "./remote-context";
/** Connectivity is independent of which host the user is currently viewing. */
export function HostConnectionStatus({ state, compact = false }: {
+2 -1
View File
@@ -9,7 +9,8 @@ import { useClient } from "@/providers/ClientProvider";
import { cn } from "@/lib/utils";
import type { ConnectionStatus } from "@/lib/types";
import type { HostAnchor, EmbeddedHost } from "./host-bridge";
import { HostConnectionStatus, type HostConnectionState } from "./HostConnectionStatus";
import { HostConnectionStatus } from "./HostConnectionStatus";
import type { HostConnectionState } from "./remote-context";
export interface HostPicker {
kind: "shell";
@@ -5,7 +5,7 @@ import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useClient } from "@/providers/ClientProvider";
import { remoteAction } from "@/lib/remote-instances";
import { useRemoteConnections } from "./RemoteInstances";
import { useRemoteConnections } from "./remote-context";
/** An explicit escape hatch for a VPN/bound-interface route, not a new SSH form. */
export function PairRouteSettings({ id, onSaved, showHint = true }: { id: string; onSaved?: () => void; showHint?: boolean }) {
@@ -12,7 +12,7 @@ import { CodeBlock } from "@/components/CodeBlock";
import { remoteAction } from "@/lib/remote-instances";
import { pairingReturnOrigin, type PairReturn } from "@/lib/remote-pair-return";
import type { ConnectionStatus } from "@/lib/types";
import { useRemoteConnections } from "./RemoteInstances";
import { useRemoteConnections } from "./remote-context";
import { PairRouteSettings } from "./PairRouteSettings";
import "./remote-layout.css";
@@ -13,7 +13,7 @@ import { groupRemoteProfiles, isCompatibilityError, remoteAction, type RemoteIns
import { cn } from "@/lib/utils";
import { parseSSHAddress } from "@/lib/ssh-address";
import { clearPairReturn, readPairReturn, subscribePairReturn } from "@/lib/remote-pair-return";
import { useRemoteConnections } from "./RemoteInstances";
import { useRemoteConnections } from "./remote-context";
import { SSHHostPicker } from "./SSHHostPicker";
import { QuickPairSetup } from "./QuickPairSetup";
import { PairRouteSettings } from "./PairRouteSettings";
@@ -1,39 +1,16 @@
import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, type ReactNode } from "react";
import { useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, type ReactNode } from "react";
import { Loader2, PlugZap } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { groupRemoteProfiles, isCompatibilityError, needsRemoteSetup, type RemoteDirectory } from "@/lib/remote-instances";
import { groupRemoteProfiles, isCompatibilityError, needsRemoteSetup } from "@/lib/remote-instances";
import { HostCompatibilityDialog } from "./HostCompatibilityDialog";
import { RemoteConnectionsPage } from "./RemoteConnectionsPage";
import type { HostAnchor } from "./host-bridge";
import { ThemeProvider } from "@/hooks/useTheme";
import { useHostSessions } from "./useHostSessions";
import { HostNavigationContext, HostSwitcher, RemoteHostMenu, type HostPicker } from "./HostSwitcher";
import { useSidebarHostBridge } from "./useSidebarHostBridge";
import { readPairReturn, subscribePairReturn } from "@/lib/remote-pair-return";
import type { HostConnectionState } from "./HostConnectionStatus";
const RemoteContext = createContext<{
available: boolean;
localActive: boolean;
activeHostId: string | null;
hostStates: Record<string, HostConnectionState>;
managing: boolean;
embeddedManagement?: boolean;
reportManagementSurface?: (rect: HostAnchor, theme: "light" | "dark") => void;
closeManagement: () => void;
selectLocal: () => void;
openHostIds: string[];
directory: RemoteDirectory | null;
directoryError: boolean;
refresh: () => Promise<RemoteDirectory>;
rename: (id: string, name: string) => Promise<void>;
connect: (id: string, stillWanted?: () => boolean) => Promise<void>;
disconnect: (id: string) => Promise<void>;
remove: (id: string) => Promise<void>;
cancel: () => void;
} | null>(null);
export function useRemoteConnections() { return useContext(RemoteContext); }
import { RemoteContext, type HostConnectionState } from "./remote-context";
/** Keep host views alive; navigation belongs in each view's sidebar, not a second header. */
export function RemoteInstances({ children }: { children: ReactNode }) {
@@ -0,0 +1,28 @@
import { createContext, useContext } from "react";
import type { RemoteDirectory } from "@/lib/remote-instances";
import type { HostAnchor } from "./host-bridge";
export type HostConnectionState = "open" | "closed" | "connecting" | "error";
export const RemoteContext = createContext<{
available: boolean;
localActive: boolean;
activeHostId: string | null;
hostStates: Record<string, HostConnectionState>;
managing: boolean;
embeddedManagement?: boolean;
reportManagementSurface?: (rect: HostAnchor, theme: "light" | "dark") => void;
closeManagement: () => void;
selectLocal: () => void;
openHostIds: string[];
directory: RemoteDirectory | null;
directoryError: boolean;
refresh: () => Promise<RemoteDirectory>;
rename: (id: string, name: string) => Promise<void>;
connect: (id: string, stillWanted?: () => boolean) => Promise<void>;
disconnect: (id: string) => Promise<void>;
remove: (id: string) => Promise<void>;
cancel: () => void;
} | null>(null);
export function useRemoteConnections() { return useContext(RemoteContext); }
@@ -4,7 +4,7 @@ import type {
ChannelConfigField,
ChannelFieldSection,
ChannelSetupRequirement,
} from "@/components/settings/channels/catalog";
} from "@/channel-plugins/catalog";
import {
CredentialForm,
channelFieldInputId,
@@ -2,7 +2,7 @@ import { channelUiContribution } from "@/channel-plugins/registry";
import { CircleHelp, ExternalLink } from "lucide-react";
import { useTranslation } from "react-i18next";
import { channelSetup } from "@/components/settings/channels/ChannelIdentity";
import { docsUrlWithBase } from "@/components/settings/channels/catalog";
import { docsUrlWithBase } from "@/channel-plugins/catalog";
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { Tooltip, TooltipProvider, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
import type { NanobotFeatureInfo } from "@/lib/types";
@@ -15,7 +15,7 @@ import type {
ChannelConfigField,
ChannelFieldPresentation,
ChannelSetupPresentation,
} from "@/components/settings/channels/catalog";
} from "@/channel-plugins/catalog";
import { channelValidationMessage } from "@/components/settings/channels/validationMessages";
import { useLogoFallback } from "@/hooks/useLogoFallback";
import { normalizeLocale } from "@/i18n/config";
@@ -4,7 +4,7 @@ import { useTranslation } from "react-i18next";
import { channelUiPresentation } from "@/channel-plugins/registry";
import { ToggleButton } from "@/components/settings/ToggleButton";
import type { ChannelConfigField } from "@/components/settings/channels/catalog";
import type { ChannelConfigField } from "@/channel-plugins/catalog";
import {
CredentialForm,
channelValuesForSave,
@@ -29,7 +29,7 @@ import { useAutoSave } from "@/components/settings/shared/useAutoSave";
import {
type ChannelProviderPreset,
type ChannelSetupPresentation,
} from "@/components/settings/channels/catalog";
} from "@/channel-plugins/catalog";
import {
ChannelFieldGroups,
channelRequirementErrors,
@@ -6,7 +6,7 @@ import { Button } from "@/components/ui/button";
import {
type ChannelProviderPreset,
type ChannelSetupPresentation,
} from "@/components/settings/channels/catalog";
} from "@/channel-plugins/catalog";
import { copyTextToClipboard } from "@/lib/clipboard";
import type { NanobotFeatureInfo } from "@/lib/types";
@@ -3,7 +3,7 @@ import { useTranslation } from "react-i18next";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import type { ChannelConfigField } from "@/components/settings/channels/catalog";
import type { ChannelConfigField } from "@/channel-plugins/catalog";
import { cn } from "@/lib/utils";
function channelFieldValue(field: ChannelConfigField, values: Record<string, string>): string {
@@ -41,7 +41,7 @@ import { SegmentedControl } from "@/components/ui/segmented-control";
import { Textarea } from "@/components/ui/textarea";
import { displayTitle } from "@/lib/chat-groups";
import { copyTextToClipboard } from "@/lib/clipboard";
import { fmtDateTime, relativeTime } from "@/lib/format";
import { fmtDateTime, relativeTime } from "@/lib/format-time";
import type { SendAttachment, SendOptions } from "@/hooks/useNanobotStream";
import type {
AutomationsPayload,
@@ -14,7 +14,8 @@ import {
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { formatCompactTokenCount, formatTurnLatency } from "@/lib/format";
import { formatCompactTokenCount } from "@/lib/format";
import { formatTurnLatency } from "@/lib/format-time";
import { cn } from "@/lib/utils";
export interface ComposerContextUsage {
@@ -16,7 +16,7 @@ import {
type PromptAnchor,
userPromptAnchors,
} from "@/components/thread/promptNavigation";
import { fmtDateTime } from "@/lib/format";
import { fmtDateTime } from "@/lib/format-time";
import type { UIMessage } from "@/lib/types";
import { cn } from "@/lib/utils";
@@ -25,7 +25,7 @@ import { useSessionAutomationJobs } from "@/hooks/useSessionAutomationJobs";
import { currentLocale } from "@/i18n";
import { runAutomationAction, updateAutomation } from "@/lib/api";
import type { WebUIMutationTransport } from "@/lib/api";
import { fmtDateTime } from "@/lib/format";
import { fmtDateTime } from "@/lib/format-time";
import type {
AutomationUpdatePayload,
SessionAutomationJob,
@@ -43,8 +43,8 @@ import {
cliAppInitials,
mcpPresetInitials,
splitCapabilityMentionSegments,
type CapabilityMentionSegment,
} from "@/components/CliAppMentionText";
import type { CapabilityMentionSegment } from "@/lib/composer-mention-text";
import { INLINE_TOKEN_HIGHLIGHT_COLOR } from "@/components/InlineTokenHighlight";
import {
ArrowUp,
@@ -15,7 +15,7 @@ import { Dialog, DialogContent, DialogTitle, DialogTrigger } from "@/components/
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { useMediaQuery } from "@/hooks/useMediaQuery";
import { useLocalPreferences } from "@/hooks/useLocalPreferences";
import { fmtDateTime, formatMessageHoverTime } from "@/lib/format";
import { fmtDateTime, formatMessageHoverTime } from "@/lib/format-time";
import { projectActivityTimeline, type TurnUnit } from "@/lib/activity-timeline";
import { cn } from "@/lib/utils";
import type { CliAppInfo, McpPresetInfo, RetryStatus, SlashCommand, UIMessage } from "@/lib/types";
@@ -1,7 +1,7 @@
import { useRef, useState, type CSSProperties, type ReactNode } from "react";
import type { LucideIcon } from "lucide-react";
import { StreamingLabelSheen } from "@/components/MessageBubble";
import { StreamingLabelSheen } from "@/components/ui/streaming-label-sheen";
import { formControlFocusClassName } from "@/components/ui/form-control";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
@@ -0,0 +1,32 @@
import type { ReactNode } from "react";
import { cn } from "@/lib/utils";
/** L→R sheen on the glyphs themselves; inactive labels stay solid muted text. */
export function StreamingLabelSheen({
children,
active,
className,
}: {
children: ReactNode;
active: boolean;
className?: string;
}) {
const sheenText =
typeof children === "string" || typeof children === "number"
? String(children)
: undefined;
return (
<span className={cn("block min-w-0 overflow-hidden py-px", className)}>
<span
data-sheen-text={active ? sheenText : undefined}
className={cn(
"block w-fit max-w-full truncate pr-0.5 font-medium leading-normal",
active ? "streaming-text-sheen after:pr-0.5" : "text-muted-foreground",
)}
>
{children}
</span>
</span>
);
}
+1 -2
View File
@@ -1,8 +1,7 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import type { ChangeEvent, ClipboardEvent, KeyboardEvent, RefObject } from "react";
import type { CapabilityMentionSegment } from "@/components/CliAppMentionText";
import { composerCompositionSegments, composerMentionText, editComposerMentionText, mentionTextOffset } from "@/lib/composer-mention-text";
import { composerCompositionSegments, composerMentionText, editComposerMentionText, mentionTextOffset, type CapabilityMentionSegment } from "@/lib/composer-mention-text";
type Snapshot = { value: string; start: number; end: number };
const HISTORY_LIMIT = 100;
+7 -1
View File
@@ -1,4 +1,10 @@
import type { CapabilityMentionSegment } from "@/components/CliAppMentionText";
import type { CliAppInfo, McpPresetInfo, SessionMention } from "@/lib/types";
export type CapabilityMentionSegment =
| { kind: "text"; text: string }
| { kind: "cli"; text: string; app: CliAppInfo }
| { kind: "mcp"; text: string; preset: McpPresetInfo }
| { kind: "session"; text: string; mention: SessionMention };
export function composerMentionLabel(segment: CapabilityMentionSegment): string {
const app = segment.kind === "cli" ? segment.app : segment.kind === "mcp" ? segment.preset : null;
+159
View File
@@ -0,0 +1,159 @@
import i18n from "i18next";
import { normalizeLocale } from "@/i18n/config";
/** Loose ISO-or-epoch parser; returns ``null`` for missing/invalid input. */
function parseDate(value: string | number | null | undefined): Date | null {
if (value === null || value === undefined || value === "") return null;
const d = new Date(value);
return Number.isNaN(d.getTime()) ? null : d;
}
const RELATIVE_THRESHOLDS: [number, Intl.RelativeTimeFormatUnit][] = [
[60, "second"],
[60, "minute"],
[24, "hour"],
[7, "day"],
[4.345, "week"],
[12, "month"],
[Number.POSITIVE_INFINITY, "year"],
];
const relativeTimeFormatters = new Map<string, Intl.RelativeTimeFormat>();
const dateTimeFormatters = new Map<string, Intl.DateTimeFormat>();
const clockTimeFormatters = new Map<string, Intl.DateTimeFormat>();
const hoverTimeFormatters = new Map<string, Intl.DateTimeFormat>();
function activeLocale(locale?: string): string {
return locale || i18n.resolvedLanguage || i18n.language || normalizeLocale(i18n.resolvedLanguage ?? i18n.language);
}
function relativeTimeFormatter(locale: string): Intl.RelativeTimeFormat {
const existing = relativeTimeFormatters.get(locale);
if (existing) return existing;
const formatter = new Intl.RelativeTimeFormat(locale, { numeric: "auto" });
relativeTimeFormatters.set(locale, formatter);
return formatter;
}
function dateTimeFormatter(locale: string): Intl.DateTimeFormat {
const existing = dateTimeFormatters.get(locale);
if (existing) return existing;
const formatter = new Intl.DateTimeFormat(locale, {
dateStyle: "medium",
timeStyle: "short",
});
dateTimeFormatters.set(locale, formatter);
return formatter;
}
function clockTimeFormatter(locale: string): Intl.DateTimeFormat {
const existing = clockTimeFormatters.get(locale);
if (existing) return existing;
const formatter = new Intl.DateTimeFormat(locale, {
hour: "2-digit",
minute: "2-digit",
});
clockTimeFormatters.set(locale, formatter);
return formatter;
}
function isSameLocalCalendarDay(left: Date, right: Date): boolean {
return (
left.getFullYear() === right.getFullYear()
&& left.getMonth() === right.getMonth()
&& left.getDate() === right.getDate()
);
}
export function relativeTime(
value: string | number | null | undefined,
locale?: string,
): string {
const date = parseDate(value);
if (!date) return "";
let delta = (date.getTime() - Date.now()) / 1000;
const formatter = relativeTimeFormatter(activeLocale(locale));
for (const [step, unit] of RELATIVE_THRESHOLDS) {
if (Math.abs(delta) < step) {
return formatter.format(Math.round(delta), unit);
}
delta /= step;
}
return formatter.format(Math.round(delta), "year");
}
export function fmtDateTime(
value: string | number | null | undefined,
locale?: string,
): string {
const date = parseDate(value);
return date ? dateTimeFormatter(activeLocale(locale)).format(date) : "";
}
/**
* Format a completion timestamp in the browser's local timezone.
* Today's messages stay compact; older messages include their date for orientation.
*/
export function formatMessageEndTime(
value: number | null | undefined,
locale?: string,
): string {
const date = parseDate(value);
if (!date) return "";
const loc = activeLocale(locale);
return isSameLocalCalendarDay(date, new Date())
? clockTimeFormatter(loc).format(date)
: dateTimeFormatter(loc).format(date);
}
/** One-line gutter label; the full local date/time belongs in its tooltip. */
export function formatMessageHoverTime(
value: number | null | undefined,
locale?: string,
now = new Date(),
): string {
const date = parseDate(value);
if (!date) return "";
const loc = activeLocale(locale);
const today = isSameLocalCalendarDay(date, now);
const key = `${loc}:${today ? "clock" : "date"}`;
let formatter = hoverTimeFormatters.get(key);
if (!formatter) {
formatter = new Intl.DateTimeFormat(loc, today
? { hour: "2-digit", minute: "2-digit", hourCycle: "h23" }
: { month: "numeric", day: "numeric" });
hoverTimeFormatters.set(key, formatter);
}
return formatter.format(date);
}
/** Human-readable turn duration (wall-clock), locale-aware via ``Intl`` (seconds/minutes). */
export function formatTurnLatency(ms: number, locale?: string): string {
const loc = activeLocale(locale);
const msClamped = Math.max(0, ms);
const secTotal = msClamped / 1000;
if (secTotal < 60) {
return new Intl.NumberFormat(loc, {
style: "unit",
unit: "second",
unitDisplay: "narrow",
maximumFractionDigits: secTotal < 10 ? 1 : 0,
minimumFractionDigits: 0,
}).format(secTotal);
}
const wholeMin = Math.floor(secTotal / 60);
const remSec = Math.max(0, Math.round(secTotal - wholeMin * 60));
const minStr = new Intl.NumberFormat(loc, {
style: "unit",
unit: "minute",
unitDisplay: "narrow",
}).format(wholeMin);
const secStr = new Intl.NumberFormat(loc, {
style: "unit",
unit: "second",
unitDisplay: "narrow",
maximumFractionDigits: 0,
}).format(remSec);
return `${minStr}\u00a0${secStr}`;
}
-158
View File
@@ -1,5 +1,3 @@
import i18n, { currentLocale } from "@/i18n";
/** Compact token counts for dense runtime metadata (for example, 74.9K). */
export function formatCompactTokenCount(value: number): string {
if (value < 1_000) return Math.round(value).toLocaleString();
@@ -62,159 +60,3 @@ export function deriveTitle(preview: string | undefined, fallback: string): stri
if (isLowInformationTitlePreview(oneLine)) return fallback;
return oneLine.length > 60 ? `${oneLine.slice(0, 57)}…` : oneLine;
}
/** Loose ISO-or-epoch parser; returns ``null`` for missing/invalid input. */
function parseDate(value: string | number | null | undefined): Date | null {
if (value === null || value === undefined || value === "") return null;
const d = new Date(value);
return Number.isNaN(d.getTime()) ? null : d;
}
const RELATIVE_THRESHOLDS: [number, Intl.RelativeTimeFormatUnit][] = [
[60, "second"],
[60, "minute"],
[24, "hour"],
[7, "day"],
[4.345, "week"],
[12, "month"],
[Number.POSITIVE_INFINITY, "year"],
];
const relativeTimeFormatters = new Map<string, Intl.RelativeTimeFormat>();
const dateTimeFormatters = new Map<string, Intl.DateTimeFormat>();
const clockTimeFormatters = new Map<string, Intl.DateTimeFormat>();
const hoverTimeFormatters = new Map<string, Intl.DateTimeFormat>();
function activeLocale(locale?: string): string {
return locale || i18n.resolvedLanguage || i18n.language || currentLocale();
}
function relativeTimeFormatter(locale: string): Intl.RelativeTimeFormat {
const existing = relativeTimeFormatters.get(locale);
if (existing) return existing;
const formatter = new Intl.RelativeTimeFormat(locale, { numeric: "auto" });
relativeTimeFormatters.set(locale, formatter);
return formatter;
}
function dateTimeFormatter(locale: string): Intl.DateTimeFormat {
const existing = dateTimeFormatters.get(locale);
if (existing) return existing;
const formatter = new Intl.DateTimeFormat(locale, {
dateStyle: "medium",
timeStyle: "short",
});
dateTimeFormatters.set(locale, formatter);
return formatter;
}
function clockTimeFormatter(locale: string): Intl.DateTimeFormat {
const existing = clockTimeFormatters.get(locale);
if (existing) return existing;
const formatter = new Intl.DateTimeFormat(locale, {
hour: "2-digit",
minute: "2-digit",
});
clockTimeFormatters.set(locale, formatter);
return formatter;
}
function isSameLocalCalendarDay(left: Date, right: Date): boolean {
return (
left.getFullYear() === right.getFullYear()
&& left.getMonth() === right.getMonth()
&& left.getDate() === right.getDate()
);
}
export function relativeTime(
value: string | number | null | undefined,
locale?: string,
): string {
const date = parseDate(value);
if (!date) return "";
let delta = (date.getTime() - Date.now()) / 1000;
const formatter = relativeTimeFormatter(activeLocale(locale));
for (const [step, unit] of RELATIVE_THRESHOLDS) {
if (Math.abs(delta) < step) {
return formatter.format(Math.round(delta), unit);
}
delta /= step;
}
return formatter.format(Math.round(delta), "year");
}
export function fmtDateTime(
value: string | number | null | undefined,
locale?: string,
): string {
const date = parseDate(value);
return date ? dateTimeFormatter(activeLocale(locale)).format(date) : "";
}
/**
* Format a completion timestamp in the browser's local timezone.
* Today's messages stay compact; older messages include their date for orientation.
*/
export function formatMessageEndTime(
value: number | null | undefined,
locale?: string,
): string {
const date = parseDate(value);
if (!date) return "";
const loc = activeLocale(locale);
return isSameLocalCalendarDay(date, new Date())
? clockTimeFormatter(loc).format(date)
: dateTimeFormatter(loc).format(date);
}
/** One-line gutter label; the full local date/time belongs in its tooltip. */
export function formatMessageHoverTime(
value: number | null | undefined,
locale?: string,
now = new Date(),
): string {
const date = parseDate(value);
if (!date) return "";
const loc = activeLocale(locale);
const today = isSameLocalCalendarDay(date, now);
const key = `${loc}:${today ? "clock" : "date"}`;
let formatter = hoverTimeFormatters.get(key);
if (!formatter) {
formatter = new Intl.DateTimeFormat(loc, today
? { hour: "2-digit", minute: "2-digit", hourCycle: "h23" }
: { month: "numeric", day: "numeric" });
hoverTimeFormatters.set(key, formatter);
}
return formatter.format(date);
}
/** Human-readable turn duration (wall-clock), locale-aware via ``Intl`` (seconds/minutes). */
export function formatTurnLatency(ms: number, locale?: string): string {
const loc = activeLocale(locale);
const msClamped = Math.max(0, ms);
const secTotal = msClamped / 1000;
if (secTotal < 60) {
return new Intl.NumberFormat(loc, {
style: "unit",
unit: "second",
unitDisplay: "narrow",
maximumFractionDigits: secTotal < 10 ? 1 : 0,
minimumFractionDigits: 0,
}).format(secTotal);
}
const wholeMin = Math.floor(secTotal / 60);
const remSec = Math.max(0, Math.round(secTotal - wholeMin * 60));
const minStr = new Intl.NumberFormat(loc, {
style: "unit",
unit: "minute",
unitDisplay: "narrow",
}).format(wholeMin);
const secStr = new Intl.NumberFormat(loc, {
style: "unit",
unit: "second",
unitDisplay: "narrow",
maximumFractionDigits: 0,
}).format(remSec);
return `${minStr}\u00a0${secStr}`;
}
@@ -7,7 +7,7 @@ import {
defaultChannelFieldValues,
} from "@/components/settings/channels/CredentialForm";
import { channelSetup } from "@/components/settings/channels/ChannelIdentity";
import type { ChannelConfigField } from "@/components/settings/channels/catalog";
import type { ChannelConfigField } from "@/channel-plugins/catalog";
const fields: ChannelConfigField[] = [
{
+1 -1
View File
@@ -7,7 +7,7 @@ import {
formatMessageHoverTime,
formatTurnLatency,
relativeTime,
} from "@/lib/format";
} from "@/lib/format-time";
describe("localized format helpers", () => {
beforeEach(() => {
@@ -2,7 +2,7 @@ import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-li
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { LinearResetConnection } from "../../../nanobot/channels/linear/webui/LinearResetConnection";
import type { ChannelConfigField } from "@/components/settings/channels/catalog";
import type { ChannelConfigField } from "@/channel-plugins/catalog";
const { requestMutation } = vi.hoisted(() => ({ requestMutation: vi.fn() }));
vi.mock("@/providers/ClientProvider", () => ({
+1 -1
View File
@@ -5,7 +5,7 @@ import { MessageBlockMenuActions, MessageBubble } from "@/components/MessageBubb
import { ThreadMessages } from "@/components/thread/ThreadMessages";
import { setAppLanguage } from "@/i18n";
import * as clipboard from "@/lib/clipboard";
import { formatMessageEndTime } from "@/lib/format";
import { formatMessageEndTime } from "@/lib/format-time";
import type {
CliAppInfo,
McpPresetInfo,
+1 -1
View File
@@ -1,7 +1,7 @@
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { ThreadMessages } from "@/components/thread/ThreadMessages";
import { fmtDateTime } from "@/lib/format";
import { fmtDateTime } from "@/lib/format-time";
vi.mock("@/components/MarkdownText", () => ({ MarkdownText: ({ content }: { content: string }) => <p>{content}</p> }));
afterEach(() => { cleanup(); vi.useRealTimers(); });
+1 -1
View File
@@ -6,7 +6,7 @@ import i18n from "@/i18n";
const mocks = vi.hoisted(() => ({ action: vi.fn(), refresh: vi.fn(), config: "" }));
vi.mock("@/providers/ClientProvider", () => ({ useClient: () => ({ client: { requestMutation: mocks.action } }) }));
vi.mock("@/components/remote/RemoteInstances", () => ({ useRemoteConnections: () => ({ refresh: mocks.refresh, directory: { profiles: [{ id: "paired", paired: true, ssh_config: mocks.config }, { id: "ssh", name: "Team SSH", paired: false }] } }) }));
vi.mock("@/components/remote/remote-context", () => ({ useRemoteConnections: () => ({ refresh: mocks.refresh, directory: { profiles: [{ id: "paired", paired: true, ssh_config: mocks.config }, { id: "ssh", name: "Team SSH", paired: false }] } }) }));
beforeEach(async () => { await i18n.changeLanguage("en"); mocks.action.mockReset().mockResolvedValue({}); mocks.refresh.mockReset().mockResolvedValue(undefined); mocks.config = ""; });
afterEach(cleanup);
+1 -1
View File
@@ -21,7 +21,7 @@ const mocks = vi.hoisted(() => {
return { action, client, listeners, transportClient: null as NanobotClient | null, connect: vi.fn(), refresh: vi.fn(), cancel: vi.fn(), copy: vi.fn() };
});
vi.mock("@/providers/ClientProvider", () => ({ useClient: () => ({ client: mocks.transportClient ?? mocks.client }) }));
vi.mock("@/components/remote/RemoteInstances", () => ({ useRemoteConnections: () => ({ connect: mocks.connect, refresh: mocks.refresh, cancel: mocks.cancel, directory: { profiles: [] } }) }));
vi.mock("@/components/remote/remote-context", () => ({ useRemoteConnections: () => ({ connect: mocks.connect, refresh: mocks.refresh, cancel: mocks.cancel, directory: { profiles: [] } }) }));
vi.mock("@/lib/clipboard", () => ({ copyTextToClipboard: mocks.copy }));
const request = () => ({ id: "request-1", command: "nanobot remote pair nbpr1.public", expires: Date.now() / 1000 + 600 });
const preview = { id: "request-1", host: "ubuntu@server", hostname: "team", fingerprint: "SHA256:trusted-server", authorized_until: Date.now() / 1000 + 86400, revoke_command: "nanobot remote revoke request-1" };
+2 -1
View File
@@ -1,7 +1,8 @@
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { useEffect, useState } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { RemoteInstances, useRemoteConnections } from "@/components/remote/RemoteInstances";
import { RemoteInstances } from "@/components/remote/RemoteInstances";
import { useRemoteConnections } from "@/components/remote/remote-context";
import { RemoteConnectionsPage } from "@/components/remote/RemoteConnectionsPage";
import { Sidebar } from "@/components/Sidebar";
import { HOST_BRIDGE } from "@/components/remote/host-bridge";