Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio library: cache Intl formatters for per-row dates and sizes (#17251)
Daniel Hand72e1dc48d25
diff --git a/studio/frontend/src/features/library/chats/chats-items.tsx b/studio/frontend/src/features/library/chats/chats-items.tsxindex 93493b882f0..31e0c8bc355 100644--- a/studio/frontend/src/features/library/chats/chats-items.tsx+++ b/studio/frontend/src/features/library/chats/chats-items.tsx@@ -1,6 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+import { formatDate as formatCachedDate } from "@/lib/intl-cache";import { useTimeFormat, withTimeFormat } from "@/lib/time-format";import { Checkbox } from "@/components/ui/checkbox";import {@@ -772,15 +773,16 @@ function groupedTime(): string {const date = new Date(ts);if (bucket === "today" || bucket === "yesterday") {- return date.toLocaleTimeString(+ return formatCachedDate(+ date,locale,withTimeFormat({ hour: "numeric", minute: "2-digit" }, locale),);}if (bucket === "week") {- return date.toLocaleDateString(locale, { weekday: "long" });+ return formatCachedDate(date, locale, { weekday: "long" });}- return date.toLocaleDateString(locale, {+ return formatCachedDate(date, locale, {month: "short",day: "numeric",year:diff --git a/studio/frontend/src/features/library/format.ts b/studio/frontend/src/features/library/format.tsindex 1e94b8000d4..a4cf0a96ca3 100644--- a/studio/frontend/src/features/library/format.ts+++ b/studio/frontend/src/features/library/format.ts@@ -3,6 +3,7 @@import type { InterpolationValues, Locale, TranslationKey } from "@/i18n";import { formatRelativeTime } from "../../i18n/relative-time.ts";+import { formatDate, formatNumber } from "../../lib/intl-cache.ts";import { withTimeFormat } from "../../lib/time-format.ts";type Translate = (key: TranslationKey, values?: InterpolationValues) => string;@@ -31,17 +32,14 @@ export function formatCardTime(ts: number, locale: Locale, now: number = Date.no// Rounded: DST days are 23 or 25 hours long.const days = Math.round((startOfDay(today) - startOfDay(then)) / DAY_MS);if (days === 0) {- return then.toLocaleTimeString(- locale,- withTimeFormat({ hour: "numeric", minute: "2-digit" }, locale),- );+ return formatDate(then, locale, withTimeFormat({ hour: "numeric", minute: "2-digit" }, locale));}if (days === 1) {const word = yesterday(locale);return word.charAt(0).toLocaleUpperCase(locale) + word.slice(1);}- if (days > 1 && days < 7) return then.toLocaleDateString(locale, { weekday: "long" });- return then.toLocaleDateString(locale, {+ if (days > 1 && days < 7) return formatDate(then, locale, { weekday: "long" });+ return formatDate(then, locale, {month: "short",day: "numeric",year: then.getFullYear() === today.getFullYear() ? undefined : "numeric",@@ -72,7 +70,7 @@ const SIZE_UNITS = [export function formatSize(bytes: number | null, locale: Locale, t: Translate): string | null {if (bytes === null) return null;if (bytes < 1024) {- return t("library.size.bytes", { value: bytes.toLocaleString(locale, { useGrouping: false }) });+ return t("library.size.bytes", { value: formatNumber(bytes, locale, { useGrouping: false }) });}let value = bytes / 1024;let unit: (typeof SIZE_UNITS)[number] = SIZE_UNITS[0];@@ -82,7 +80,7 @@ export function formatSize(bytes: number | null, locale: Locale, t: Translate):unit = next;}const digits = value >= 10 ? 0 : 1;- const formatted = value.toLocaleString(locale, {+ const formatted = formatNumber(value, locale, {minimumFractionDigits: digits,maximumFractionDigits: digits,});diff --git a/studio/frontend/src/lib/intl-cache.ts b/studio/frontend/src/lib/intl-cache.tsnew file mode 100644index 00000000000..016a589d89e--- /dev/null+++ b/studio/frontend/src/lib/intl-cache.ts@@ -0,0 +1,67 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Building an Intl formatter costs ~20x a format() call, and toLocale*String builds one each time.+const dateFormats = new Map<string, Intl.DateTimeFormat>();+const numberFormats = new Map<string, Intl.NumberFormat>();++// A cached DateTimeFormat keeps its build-time zone; the OS zone can change while the page is open.+// Two UTC offsets per call, plus the zone name at most once a second for same-offset changes.+const JAN = Date.UTC(2026, 0, 1);+const JUL = Date.UTC(2026, 6, 1);+let zoneOffsets = "";+let zoneName: string | undefined;+let zoneCheckedAt = Number.NEGATIVE_INFINITY;++function dropFormatsFromOldZone(): void {+ const offsets = `${new Date(JAN).getTimezoneOffset()}/${new Date(JUL).getTimezoneOffset()}`;+ const now = Date.now();+ if (offsets === zoneOffsets && now - zoneCheckedAt < 1000 && now >= zoneCheckedAt) {+ return;+ }+ zoneOffsets = offsets;+ zoneCheckedAt = now;+ const name = new Intl.DateTimeFormat().resolvedOptions().timeZone;+ if (name !== zoneName) {+ zoneName = name;+ dateFormats.clear();+ }+}++const keyOf = (locale: string | undefined, options: object) =>+ `${locale ?? ""}\u0000${JSON.stringify(options)}`;++/** Same output as date.toLocaleString(locale, options) with explicit fields, from a cached formatter. */+export function formatDate(+ date: Date,+ locale: string | undefined,+ options: Intl.DateTimeFormatOptions,+): string {+ // format() throws on an invalid Date where toLocale*String returns "Invalid Date".+ if (Number.isNaN(date.getTime())) {+ return date.toLocaleString(locale, options);+ }+ dropFormatsFromOldZone();+ const key = keyOf(locale, options);+ let formatter = dateFormats.get(key);+ if (!formatter) {+ formatter = new Intl.DateTimeFormat(locale, options);+ dateFormats.set(key, formatter);+ }+ return formatter.format(date);+}++/** Same output as value.toLocaleString(locale, options), from a cached formatter. */+export function formatNumber(+ value: number,+ locale: string | undefined,+ options: Intl.NumberFormatOptions,+): string {+ const key = keyOf(locale, options);+ let formatter = numberFormats.get(key);+ if (!formatter) {+ formatter = new Intl.NumberFormat(locale, options);+ numberFormats.set(key, formatter);+ }+ return formatter.format(value);+}diff --git a/studio/frontend/src/lib/time-format.ts b/studio/frontend/src/lib/time-format.tsindex 55097f4b718..84abf708c77 100644--- a/studio/frontend/src/lib/time-format.ts+++ b/studio/frontend/src/lib/time-format.ts@@ -62,24 +62,39 @@ type HourCycle = "h12" | "h23";const language = (tag: string) => tag.split("-")[0].toLowerCase();+// Resolved once: the runtime default locale is fixed for the page's lifetime.+let browserClock: { language: string; hourCycle: HourCycle } | null | undefined;++function getBrowserClock(): { language: string; hourCycle: HourCycle } | null {+ if (browserClock === undefined) {+ try {+ const browser = new Intl.DateTimeFormat(undefined, {+ hour: "numeric",+ }).resolvedOptions();+ browserClock = {+ language: language(browser.locale),+ hourCycle:+ browser.hourCycle === "h11" || browser.hourCycle === "h12"+ ? "h12"+ : "h23",+ };+ } catch {+ browserClock = null;+ }+ }+ return browserClock;+}+// The UI locale has no region (en-GB is "en"), so a shared language takes the browser's clock.function systemHourCycle(locale: string | undefined): HourCycle | undefined {if (!locale) {return undefined;}- try {- const browser = new Intl.DateTimeFormat(undefined, {- hour: "numeric",- }).resolvedOptions();- if (language(browser.locale) !== language(locale)) {- return undefined;- }- return browser.hourCycle === "h11" || browser.hourCycle === "h12"- ? "h12"- : "h23";- } catch {+ const browser = getBrowserClock();+ if (!browser || browser.language !== language(locale)) {return undefined;}+ return browser.hourCycle;}export function withTimeFormat(diff --git a/studio/frontend/tests/intl-cache.test.ts b/studio/frontend/tests/intl-cache.test.tsnew file mode 100644index 00000000000..56918bea7fa--- /dev/null+++ b/studio/frontend/tests/intl-cache.test.ts@@ -0,0 +1,187 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";+import { formatCardTime, formatSize } from "../src/features/library/format.ts";+import { formatDate, formatNumber } from "../src/lib/intl-cache.ts";+import {+ type TimeFormat,+ setTimeFormat,+ withTimeFormat,+} from "../src/lib/time-format.ts";++const store = new Map<string, string>();+(globalThis as { localStorage?: unknown }).localStorage = {+ getItem: (key: string) => store.get(key) ?? null,+ setItem: (key: string, value: string) => {+ store.set(key, value);+ },+ removeItem: (key: string) => {+ store.delete(key);+ },+};++test.afterEach(() => store.clear());++const browserLanguage = new Intl.DateTimeFormat(undefined, { hour: "numeric" })+ .resolvedOptions()+ .locale.split("-")[0];+const LOCALES = [+ undefined,+ "en",+ "en-US",+ "en-GB",+ "de-DE",+ "ja-JP",+ "ar-EG",+ "hi-IN",+ browserLanguage,+];+const FORMATS: TimeFormat[] = ["system", "12h", "24h"];+const NOW = new Date(2026, 8, 25, 12, 0).getTime();+const STAMPS = Array.from(+ { length: 400 },+ (_, i) => NOW - i * 3_600_000 * 7.3 + i * 61_000,+);++// The uncached calls format.ts made before the cache.+function referenceCardTime(+ ts: number,+ locale: string | undefined,+ now: number,+): string {+ const then = new Date(ts);+ const today = new Date(now);+ const start = (d: Date) =>+ new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();+ const days = Math.round((start(today) - start(then)) / 86_400_000);+ if (days === 0) {+ return then.toLocaleTimeString(+ locale,+ withTimeFormat({ hour: "numeric", minute: "2-digit" }, locale),+ );+ }+ if (days > 1 && days < 7)+ return then.toLocaleDateString(locale, { weekday: "long" });+ return then.toLocaleDateString(locale, {+ month: "short",+ day: "numeric",+ year: then.getFullYear() === today.getFullYear() ? undefined : "numeric",+ });+}++test("cached card times match the uncached toLocale calls in every locale and clock", () => {+ for (const format of FORMATS) {+ setTimeFormat(format);+ for (const locale of LOCALES) {+ for (const ts of STAMPS) {+ const then = new Date(ts);+ const days = Math.round(+ (new Date(2026, 8, 25).getTime() -+ new Date(+ then.getFullYear(),+ then.getMonth(),+ then.getDate(),+ ).getTime()) /+ 86_400_000,+ );+ if (days === 1) continue; // "Yesterday" comes from RelativeTimeFormat, unchanged.+ assert.equal(+ formatCardTime(ts, locale as never, NOW),+ referenceCardTime(ts, locale, NOW),+ `${format} ${locale} ${ts}`,+ );+ }+ }+ }+});++test("cached sizes match Number.toLocaleString", () => {+ const t = (_key: string, values?: { value?: unknown }) =>+ String(values?.value);+ for (const locale of LOCALES) {+ for (let bytes = 0; bytes < 2 ** 44; bytes = bytes * 3 + 7) {+ const value =+ bytes < 1024+ ? bytes+ : bytes / 1024 ** Math.min(4, Math.floor(Math.log2(bytes) / 10));+ const digits = value >= 10 ? 0 : 1;+ const expected =+ bytes < 1024+ ? bytes.toLocaleString(locale, { useGrouping: false })+ : value.toLocaleString(locale, {+ minimumFractionDigits: digits,+ maximumFractionDigits: digits,+ });+ assert.equal(+ formatSize(bytes, locale as never, t as never),+ expected,+ `${locale} ${bytes}`,+ );+ assert.equal(+ formatNumber(value, locale, { maximumFractionDigits: 1 }),+ value.toLocaleString(locale, { maximumFractionDigits: 1 }),+ );+ }+ }+});++test("an invalid date formats as the toLocale calls do instead of throwing", () => {+ const invalid = new Date(Number.NaN);+ assert.equal(+ formatDate(invalid, "en", { weekday: "long" }),+ invalid.toLocaleDateString("en", { weekday: "long" }),+ );+ assert.equal(+ formatDate(invalid, "de-DE", { hour: "numeric" }),+ invalid.toLocaleTimeString("de-DE", { hour: "numeric" }),+ );+ // Finite but past the Date range: formatCardTime's own isFinite guard does not catch it.+ assert.equal(+ formatCardTime(1e17, "en" as never, NOW),+ new Date(1e17).toLocaleDateString("en", { month: "short", day: "numeric" }),+ );+});++test("the system clock still follows the locale's language on every call", () => {+ setTimeFormat("system");+ const browser = new Intl.DateTimeFormat(undefined, {+ hour: "numeric",+ }).resolvedOptions();+ const expected =+ browser.hourCycle === "h11" || browser.hourCycle === "h12" ? "h12" : "h23";+ for (let i = 0; i < 3; i++) {+ assert.equal(+ withTimeFormat({ hour: "numeric" }, browserLanguage).hourCycle,+ expected,+ );+ assert.equal(+ withTimeFormat(+ { hour: "numeric" },+ browserLanguage === "de" ? "fr" : "de",+ ).hourCycle,+ undefined,+ );+ }+ setTimeFormat("24h");+ assert.equal(+ withTimeFormat({ hour: "numeric" }, browserLanguage).hourCycle,+ "h23",+ );+});++test("a time zone change while the page is open formats in the new zone", () => {+ const previous = process.env.TZ;+ const when = new Date(Date.UTC(2026, 3, 10, 22, 10));+ const options: Intl.DateTimeFormatOptions = { hour: "numeric", minute: "2-digit" };+ try {+ process.env.TZ = "America/New_York";+ assert.equal(formatDate(when, "en-US", options), when.toLocaleString("en-US", options));+ process.env.TZ = "Asia/Tokyo";+ assert.equal(formatDate(when, "en-US", options), when.toLocaleString("en-US", options));+ } finally {+ if (previous === undefined) delete process.env.TZ;+ else process.env.TZ = previous;+ }+});