Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(cowork-ui): refetch the context meter when the model window grows
thinhlpgd901192a152e
diff --git a/web-app/src/hooks/__tests__/useTokensCount.test.ts b/web-app/src/hooks/__tests__/useTokensCount.test.tsindex 2bd9cbe54..78f715f8b 100644--- a/web-app/src/hooks/__tests__/useTokensCount.test.ts+++ b/web-app/src/hooks/__tests__/useTokensCount.test.ts@@ -231,6 +231,61 @@ describe('useTokensCount', () => {)expect(result.current.tokenCount).toBe(4242)})++ // "Increase context" (Cowork's recovery chip, the model rail's settings+ // form) writes the new size and reloads the router with it. The meter+ // divides by the launched window, so it has to refetch or it keeps+ // reporting the previous one for the rest of the session.+ it('refetches the launched window when the configured context size grows', async () => {+ modelProviderState.selectedModel = {+ id: 'model-1',+ name: 'Model One',+ capabilities: [],+ settings: { ctx_len: { controller_props: { value: 8192 } } },+ }+ mockGetModelProps.mockResolvedValue({ nCtx: 8192 })+ const { result, rerender } = renderHook(() =>+ useTokensCount([], {+ threadId: 'session-1',+ usage: { totalTokens: 500 },+ })+ )+ await waitFor(() => expect(result.current.maxTokens).toBe(8192))++ modelProviderState.selectedModel = {+ id: 'model-1',+ name: 'Model One',+ capabilities: [],+ settings: { ctx_len: { controller_props: { value: 16384 } } },+ }+ mockGetModelProps.mockResolvedValue({ nCtx: 16384 })+ rerender()++ await waitFor(() => expect(result.current.maxTokens).toBe(16384))+ expect(result.current.percentage).toBeCloseTo((500 / 16384) * 100, 3)+ })++ // Cowork mirrors loads onto useCoworkRun under the session id, so the+ // thread-keyed slots the hook reads itself never move for a session. The+ // surface has to be able to report its own mirror.+ it('refetches when the surface reports its own model load', async () => {+ mockGetModelProps.mockResolvedValue({ nCtx: 8192 })+ const { result, rerender } = renderHook(+ ({ loading }: { loading: boolean }) =>+ useTokensCount([], {+ threadId: 'session-1',+ usage: { totalTokens: 500 },+ loadingModel: loading,+ }),+ { initialProps: { loading: true } }+ )+ await waitFor(() => expect(result.current.maxTokens).toBe(8192))++ mockGetModelProps.mockResolvedValue({ nCtx: 16384 })+ rerender({ loading: false })++ await waitFor(() => expect(result.current.maxTokens).toBe(16384))+ })})it('context overflow still works when there are no live stats at all', async () => {diff --git a/web-app/src/hooks/useTokensCount.ts b/web-app/src/hooks/useTokensCount.tsindex f121546be..1d61e20a6 100644--- a/web-app/src/hooks/useTokensCount.ts+++ b/web-app/src/hooks/useTokensCount.ts@@ -43,6 +43,15 @@ export interface UsageMeta {export interface TokenUsageSource {threadId?: stringusage?: UsageMeta+ /**+ * Whether the model is loading for this surface's own thread.+ *+ * A surface that keeps its load state outside `useAppState` reports it here:+ * Cowork mirrors loads in `useCoworkRun` under the session id, so the+ * thread-keyed slots the hook reads on its own never see them. Without it the+ * launched context window is never refetched for a Cowork session.+ */+ loadingModel?: boolean}// The token-usage popup normally reflects the last *successful* turn. When a@@ -104,9 +113,24 @@ export const useTokensCount = (// normally doesn't happen until the first turn is sent. Refetch as soon as that// load finishes so the counter can appear mid-turn instead of waiting for the// full response (and the resulting messages.length bump) to land.- const loadingModel = useAppState((s) =>+ //+ // Cowork mirrors its load state onto `useCoworkRun` under the session id, so+ // these thread-keyed slots never see it; such a surface reports its own mirror+ // through `source.loadingModel`.+ const appLoadingModel = useAppState((s) =>threadId ? s.loadingModels[threadId] : s.loadingModel)+ const loadingModel = source?.loadingModel || appLoadingModel+ // The window the meter divides by is the one the engine actually launched,+ // and it moves without a model switch: "Increase context" recovery, the model+ // settings form, or a re-fit. A local settings write publishes the new value+ // only after the router has reloaded with it (`updateModelSettings` awaits+ // `refreshEnginePreset`), so depending on it here refetches the launched window+ // in the same tick the UI learns of the edit. Chat also refetched on its next+ // message; Cowork has no message-length trigger at all.+ const configuredCtxLen = readSettingNumber(+ selectedModel?.settings?.ctx_len?.controller_props?.value+ )useEffect(() => {if (!modelId) {@@ -135,7 +159,13 @@ export const useTokensCount = (if (id !== reqId.current) returnsetLoading(false)})- }, [modelId, selectedProvider, messages.length, loadingModel])+ }, [+ modelId,+ selectedProvider,+ messages.length,+ loadingModel,+ configuredCtxLen,+ ])const tokenData: TokenCountData = useMemo(() => {if (!isLocalProvider) {@@ -183,9 +213,6 @@ export const useTokensCount = (const fitEnabled =provider?.settings?.find((s) => s.key === 'fit')?.controller_props?.value === true- const configuredCtxLen = readSettingNumber(- selectedModel?.settings?.ctx_len?.controller_props?.value- )const modelDisplayName =modelProps?.modelAlias || selectedModel?.name || modelIdconst caps = selectedModel?.capabilities ?? []@@ -220,6 +247,7 @@ export const useTokensCount = (liveStats,getProviderByName,selectedModel,+ configuredCtxLen,])return {diff --git a/web-app/src/routes/cowork.tsx b/web-app/src/routes/cowork.tsxindex 5b6a94886..b288ae5de 100644--- a/web-app/src/routes/cowork.tsx+++ b/web-app/src/routes/cowork.tsx@@ -366,6 +366,12 @@ function CoworkPage() {)const usage = liveUsage ?? session?.lastUsage ?? null+ // Cowork writes model loads to `useCoworkRun`, keyed by session id, so the+ // meter cannot see them on its own; hand it the mirror so the launched window+ // is refetched when the engine reloads.+ const sessionLoadingModel = useCoworkRun((s) =>+ currentId ? !!s.loadingModels[currentId] : false+ )const tokenSource = useMemo(() => ({threadId: session?.id,@@ -376,8 +382,9 @@ function CoworkPage() {totalTokens: usage.total_tokens,}: undefined,+ loadingModel: sessionLoadingModel,}),- [session?.id, usage]+ [session?.id, usage, sessionLoadingModel])// Live runs write into the run store; a committed session carries its own.