Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(web-app): define the missing main-view colour tokens, and guard i18n keys
Akarshan Biswasc72d5f55d286
diff --git a/extensions/llamacpp-extension/src/preset.test.ts b/extensions/llamacpp-extension/src/preset.test.tsindex e05ad1e1a..bfc8196b8 100644--- a/extensions/llamacpp-extension/src/preset.test.ts+++ b/extensions/llamacpp-extension/src/preset.test.ts@@ -162,19 +162,19 @@ describe('generatePreset MTP emission', () => {})describe('generatePreset parallel reservation', () => {- it('adds one reserved background slot on top of the global parallel value', async () => {+ it('adds the reserved background slots on top of the global parallel value', async () => {setupModel('llama', {})await generatePreset('/p', '/jan', { parallel: 1 } as any, {})const ini = writtenFiles['/p/router.preset.ini']- expect(ini).toContain('parallel = 2')+ expect(ini).toContain('parallel = 3')})- it('adds one reserved background slot on top of a per-model parallel override', async () => {+ it('adds the reserved background slots on top of a per-model parallel override', async () => {setupModel('llama', { parallel: 3 })await generatePreset('/p', '/jan', {} as any)const ini = writtenFiles['/p/router.preset.ini']- expect(ini).toContain('parallel = 4')+ expect(ini).toContain('parallel = 5')})it('omits parallel when unset, leaving llama.cpp auto-default untouched', async () => {@@ -218,10 +218,10 @@ describe('generatePreset parallel reservation', () => {// slot count rather than rejecting it. So the reservation has to be// unconditional: every emitted `parallel` must be at least 2, or the pin// silently lands back on the chat slot 0.- it('reserves the background slot by default, so slot 1 always exists', async () => {+ it('reserves the background slots by default, so slots 1 and 2 always exist', async () => {setupModel('llama', {})await generatePreset('/p', '/jan', { parallel: 1 } as any)- expect(writtenFiles['/p/router.preset.ini']).toContain('parallel = 2')+ expect(writtenFiles['/p/router.preset.ini']).toContain('parallel = 3')})it('reserves it in the per-model section too, which overrides [*]', async () => {@@ -230,8 +230,8 @@ describe('generatePreset parallel reservation', () => {const ini = writtenFiles['/p/router.preset.ini']// The provider-level value is what the old pin was computed from; the// section's own value is what llama.cpp actually applies.- expect(ini).toContain('parallel = 5')- expect(ini).toContain('parallel = 2')+ expect(ini).toContain('parallel = 6')+ expect(ini).toContain('parallel = 3')})})@@ -241,7 +241,7 @@ describe('generatePreset kv-unified', () => {await generatePreset('/p', '/jan', { parallel: 1 } as any, {})const ini = writtenFiles['/p/router.preset.ini']- expect(ini).toContain('parallel = 2')+ expect(ini).toContain('parallel = 3')expect(ini).toContain('kv-unified = true')})diff --git a/extensions/llamacpp-extension/src/preset.ts b/extensions/llamacpp-extension/src/preset.tsindex 673cf1ed1..d970e75b4 100644--- a/extensions/llamacpp-extension/src/preset.ts+++ b/extensions/llamacpp-extension/src/preset.ts@@ -59,13 +59,13 @@ type ModelYaml = ModelConfig & {// Hidden from the setting's UI value.//// Added unconditionally, and that is load-bearing. The emitted `parallel` is-// therefore always 2 or more, which is what lets the frontend pin background-// work to a fixed BACKGROUND_SLOT_ID (web-app/src/constants/models.ts) instead+// therefore always 3 or more, which is what lets the frontend pin background+// work and Cowork to fixed slot ids (web-app/src/constants/models.ts) instead// of computing an index here that the two sides then have to keep in sync.// Upstream wraps an out-of-range id_slot modulo the slot count rather than// rejecting it, so any such desync is silent: the background request lands back// on the chat slot and overwrites the cache it was meant to protect.-export const RESERVED_BACKGROUND_SLOTS = 1+export const RESERVED_BACKGROUND_SLOTS = 2/*** The ubatch every embedding model's preset section is pinned to.diff --git a/web-app/src/components/TokenCounter.tsx b/web-app/src/components/TokenCounter.tsxindex e4b9e0421..782243dd2 100644--- a/web-app/src/components/TokenCounter.tsx+++ b/web-app/src/components/TokenCounter.tsx@@ -1,6 +1,6 @@import { useMemo, useEffect, useState, useRef, memo } from 'react'import { useTranslation } from '@/i18n/react-i18next-compat'-import { cn } from '@/lib/utils'+import { cn, formatTokenCount } from '@/lib/utils'import {Tooltip,TooltipContent,@@ -32,12 +32,6 @@ interface TokenCounterProps {const WARN_PCT = 85const OVER_PCT = 100-const formatNumber = (num: number) => {- if (num >= 1_000_000) return `${(num / 1_000_000).toFixed(1)}M`- if (num >= 1_000) return `${(num / 1_000).toFixed(1)}K`- return num.toString()-}-const formatExact = (num: number) => num.toLocaleString()export const TokenCounter = memo(function TokenCounter({@@ -238,8 +232,8 @@ export const TokenCounter = memo(function TokenCounter({{pct?.toFixed(1) ?? '0.0'}%</span><span className="text-xs text-muted-foreground tabular-nums font-mono">- {formatNumber(totalTokens)} /{' '}- {formatNumber(tokenData.maxTokens)}+ {formatTokenCount(totalTokens)} /{' '}+ {formatTokenCount(tokenData.maxTokens)}</span></div><div className="w-full h-1.5 bg-muted rounded-full overflow-hidden">@@ -296,7 +290,7 @@ export const TokenCounter = memo(function TokenCounter({title={`Configured ctx_len: ${formatExact(tokenData.configuredCtxLen!)}`}><IconAdjustmentsAlt className="size-3" />- Fitted to {formatNumber(tokenData.maxTokens)}+ Fitted to {formatTokenCount(tokenData.maxTokens)}</span>)}{modelProps?.totalSlots !== undefined &&@@ -353,7 +347,7 @@ function TokenCountOnly({<div className="flex items-center gap-1.5 px-2 py-1 rounded-md bg-background border border-border"><IconSum className="size-3.5 text-muted-foreground shrink-0" /><span className="text-xs font-medium tabular-nums text-foreground">- {formatNumber(totalTokens)}+ {formatTokenCount(totalTokens)}</span></div></div>diff --git a/web-app/src/constants/__tests__/slots.test.ts b/web-app/src/constants/__tests__/slots.test.tsnew file mode 100644index 000000000..481a2f43a--- /dev/null+++ b/web-app/src/constants/__tests__/slots.test.ts@@ -0,0 +1,33 @@+import { describe, it, expect } from 'vitest'+import {+ CHAT_SLOT_ID,+ BACKGROUND_SLOT_ID,+ COWORK_SLOT_ID,+} from '@/constants/models'+import { RESERVED_BACKGROUND_SLOTS } from '../../../../extensions/llamacpp-extension/src/preset'++// llama.cpp wraps an out-of-range id_slot modulo the slot count instead of+// rejecting it, so a pin naming a slot that does not exist silently lands back+// on slot 0 and overwrites the chat cache it was meant to avoid. These two+// files are the only things keeping that from happening, and they live in+// separate packages — so the invariant is asserted rather than commented.+describe('llama.cpp slot allocation', () => {+ it('gives every pinned surface a distinct slot', () => {+ const pins = [CHAT_SLOT_ID, BACKGROUND_SLOT_ID, COWORK_SLOT_ID]+ expect(new Set(pins).size).toBe(pins.length)+ })++ it('reserves enough slots for every non-chat pin to exist', () => {+ const nonChatPins = [BACKGROUND_SLOT_ID, COWORK_SLOT_ID]+ expect(RESERVED_BACKGROUND_SLOTS).toBeGreaterThanOrEqual(+ nonChatPins.length+ )+ // Contiguous from 1: the reservation adds N slots above the user's+ // configured parallel value, so pin ids must fill 1..N with no gap.+ expect([...nonChatPins].sort()).toEqual([1, 2])+ })++ it('keeps chat on slot 0', () => {+ expect(CHAT_SLOT_ID).toBe(0)+ })+})diff --git a/web-app/src/constants/models.ts b/web-app/src/constants/models.tsindex 825ad6633..525b2711e 100644--- a/web-app/src/constants/models.ts+++ b/web-app/src/constants/models.ts@@ -148,8 +148,18 @@ export const providerModels = {/*** llama.cpp slot pins. Jan sends every chat turn to slot 0 so a thread reuses- * its cached KV prefix across turns, and every background task (title- * generation) to slot 1 so it can never overwrite that cache.+ * its cached KV prefix across turns, every background task (title generation,+ * subagents) to slot 1 so it can never overwrite that cache, and every Cowork+ * turn to slot 2.+ *+ * Cowork needs its own slot because one agent turn re-prefills a growing prompt+ * dozens of times; sharing slot 0 would evict the viewed thread's prefix on+ * every step, and vice versa. Subagents deliberately reuse the background slot+ * rather than taking a fourth: their prefixes are worth nothing to preserve+ * (each has a different system prompt, so concurrent subagents evict each other+ * regardless), and all that matters is that a dispatch cannot evict the+ * *parent's* prefix on slot 2. Reserving one slot instead of two keeps the KV+ * cache split three ways rather than four.** Both are fixed indices rather than values derived from the "Parallel* Sequences" setting, because upstream *wraps* an out-of-range `id_slot`@@ -162,3 +172,4 @@ export const providerModels = {*/export const CHAT_SLOT_ID = 0export const BACKGROUND_SLOT_ID = 1+export const COWORK_SLOT_ID = 2diff --git a/web-app/src/constants/routes.ts b/web-app/src/constants/routes.tsindex d1df028cc..6fb5ecefd 100644--- a/web-app/src/constants/routes.ts+++ b/web-app/src/constants/routes.ts@@ -2,6 +2,7 @@ export const route = {// home as new chat or threadhome: '/',code: '/code',+ artifacts: '/artifacts',appLogs: '/logs',project: '/project',projectDetail: '/project/$projectId',@@ -32,3 +33,10 @@ export const route = {systemMonitor: '/system-monitor',threadsDetail: '/threads/$threadId',}++/**+ * Routes belonging to the Cowork surface, so the sidebar keeps the Cowork nav+ * instead of falling back to Home. A new Cowork route only has to be added here.+ */+export const isCoworkRoute = (pathname: string): boolean =>+ pathname === route.code || pathname === route.artifactsdiff --git a/web-app/src/index.css b/web-app/src/index.cssindex 8ca4b80df..c8242dd52 100644--- a/web-app/src/index.css+++ b/web-app/src/index.css@@ -55,6 +55,10 @@--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);--color-sidebar-border: var(--sidebar-border);--color-sidebar-ring: var(--sidebar-ring);+ /* Aliased to the base surface so the alpha modifiers the `bg-main-view` /+ `text-main-view-fg/60` call sites were written against actually resolve. */+ --color-main-view: var(--background);+ --color-main-view-fg: var(--foreground);--animate-hue-rotate: hue-rotate 4s infinite;--font-studio: "StudioFeixenSans";--font-sans: "Inter", sans-serif;diff --git a/web-app/src/lib/utils.ts b/web-app/src/lib/utils.tsindex 453ed20d4..88deca3f9 100644--- a/web-app/src/lib/utils.ts+++ b/web-app/src/lib/utils.ts@@ -352,6 +352,26 @@ export function formatDuration(startTime: number, endTime?: number): string {}}+/** Compact token count for badges and labels, e.g. 24567 -> "24.6K". */+export function formatTokenCount(num: number): string {+ if (num >= 1_000_000) return `${(num / 1_000_000).toFixed(1)}M`+ if (num >= 1_000) return `${(num / 1_000).toFixed(1)}K`+ return num.toString()+}++/**+ * Elide the middle of a path so both ends stay readable. The tail identifies+ * which file or session it is, so truncating from the end (CSS ellipsis) hides+ * the only part worth reading.+ */+export function truncateMiddle(value: string, max: number): string {+ if (value.length <= max) return value+ const keep = max - 1+ const head = Math.ceil(keep / 2)+ const tail = Math.floor(keep / 2)+ return `${value.slice(0, head)}…${value.slice(value.length - tail)}`+}+export function sanitizeModelId(modelId: string): string {return modelId.replace(/[^a-zA-Z0-9/_\-.]/g, '').replace(/\./g, '_')}diff --git a/web-app/src/locales/__tests__/localeKeys.test.ts b/web-app/src/locales/__tests__/localeKeys.test.tsindex 26b181835..4e0963cca 100644--- a/web-app/src/locales/__tests__/localeKeys.test.ts+++ b/web-app/src/locales/__tests__/localeKeys.test.ts@@ -6,7 +6,7 @@ const SRC = resolve(__dirname, '../..')const LOCALE_DIR = resolve(__dirname, '../en')/** Namespaces whose keys are asserted to exist. */-const GUARDED_NAMESPACES = ['setup', 'model-errors']+const GUARDED_NAMESPACES = ['setup', 'model-errors', 'common', 'chat']/*** Keys the code composes at runtime (`t(`setup:${stage.messageKey}`)`), which adiff --git a/web-app/src/test/setup.ts b/web-app/src/test/setup.tsindex d3700645a..3c07d64d3 100644--- a/web-app/src/test/setup.ts+++ b/web-app/src/test/setup.ts@@ -113,6 +113,7 @@ const mockServiceHub = {opener: vi.fn().mockReturnValue({open: vi.fn().mockResolvedValue(undefined),revealItemInDir: vi.fn().mockResolvedValue(undefined),+ openPath: vi.fn().mockResolvedValue(undefined),}),updater: () => ({checkForUpdates: vi.fn().mockResolvedValue(null),@@ -143,10 +144,28 @@ const mockServiceHub = {vi.mock('@/hooks/useServiceHub', () => ({useServiceHub: () => mockServiceHub,getServiceHub: () => mockServiceHub,+ // The transports read the hub off the store in their constructor, so an+ // incomplete mock here makes the class impossible to instantiate in a test.+ useServiceStore: {+ getState: () => ({ serviceHub: mockServiceHub }),+ setState: vi.fn(),+ subscribe: vi.fn(),+ },initializeServiceHubStore: vi.fn(),isServiceHubInitialized: () => true,}))+// Radix's floating primitives (Tooltip, Popover, Select) measure with+// ResizeObserver, which jsdom does not implement. Stubbed globally rather than+// per test file, where it was already copied three times.+if (!('ResizeObserver' in globalThis)) {+ globalThis.ResizeObserver = class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+}+// Mock window.matchMedia for useMediaQuery testsObject.defineProperty(window, 'matchMedia', {writable: true,