Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(remote): agent runs from the phone pause at an hourly token limit (CA)

purplefd750ea32244
diff --git a/mobile-client/agent-core.js b/mobile-client/agent-core.js
index 5374b38c..433f551f 100644
--- a/mobile-client/agent-core.js
+++ b/mobile-client/agent-core.js
@@ -347,10 +347,58 @@ import { stripNonCanonicalTags } from './personas.js'
cleaned = stripNonCanonicalTags(cleaned).trim();
return {content: cleaned, thinking: think};
}
+ // ── Hourly token limit for agent runs from the phone (CA, 14.11.2026) ──
+ // The phone cannot see what the desktop's model costs (a local engine or a
+ // cloud model with the user's own paid key behind the relay), and the relay
+ // reports no token counts. One run is capped at 50 steps; runs one after
+ // another were not capped at all. So both phone loops (this page and the
+ // app, src/mobile/remote/remoteAgent.ts) count an ESTIMATE from the
+ // characters sent and received, for every model, and pause once per hour
+ // above the limit: the desktop's hourly pause in tokens instead of credits.
+ // About 250 full steps an hour, which a local model rarely meets.
+ var AGENT_HOUR_TOKEN_LIMIT = 2000000;
+ // Below the usual 4: an estimate that runs high pauses early, never late.
+ var AGENT_CHARS_PER_TOKEN = 3.5;
+ var AGENT_HOUR_KEY = 'lu-remote-agent-token-hour';
+ var AGENT_HOUR_MS = 60 * 60 * 1000;
+
+ function estimateAgentTokens(chars){
+ return chars > 0 ? Math.ceil(chars / AGENT_CHARS_PER_TOKEN) : 0;
+ }
+
+ // Count one step. True when the hour is over the limit and no pause
+ // happened in this hour yet: the caller stops, and the user's next message
+ // goes on for another hour. A failing store means a fresh hour.
+ function countAgentHourTokens(tokens, now, limit){
+ if(now === undefined) now = Date.now();
+ if(limit === undefined) limit = AGENT_HOUR_TOKEN_LIMIT;
+ var state = {entries: [], pausedAt: null};
+ try {
+ var raw = globalThis.localStorage && globalThis.localStorage.getItem(AGENT_HOUR_KEY);
+ var s = raw ? JSON.parse(raw) : {};
+ if(Array.isArray(s.entries)){
+ state.entries = s.entries.filter(function(e){
+ return e && typeof e.at === 'number' && typeof e.tokens === 'number' && isFinite(e.tokens) && now - e.at < AGENT_HOUR_MS;
+ });
+ }
+ if(typeof s.pausedAt === 'number' && now - s.pausedAt < AGENT_HOUR_MS) state.pausedAt = s.pausedAt;
+ } catch(_e){ /* a fresh hour */ }
+ if(tokens > 0) state.entries.push({at: now, tokens: tokens});
+ var sum = 0;
+ for(var i = 0; i < state.entries.length; i++) sum += state.entries[i].tokens;
+ var pause = limit > 0 && sum >= limit && state.pausedAt === null;
+ if(pause) state.pausedAt = now;
+ try { globalThis.localStorage && globalThis.localStorage.setItem(AGENT_HOUR_KEY, JSON.stringify(state)); } catch(_e){ /* a fresh hour */ }
+ return pause;
+ }
+
/*@@LU_TOOLING_ONLY@@*/
// Cut out by src-tauri/build.rs — see caveman.js.
export {
AGENT_ALL_TOOLS,
+ AGENT_CHARS_PER_TOKEN,
+ AGENT_HOUR_KEY,
+ AGENT_HOUR_TOKEN_LIMIT,
AGENT_TOOLS,
CODEX_TOOLS,
DECAY_AFTER_ITERATIONS,
@@ -362,8 +410,10 @@ export {
buildToolDefs,
capToolResult,
compactApiMessages,
+ countAgentHourTokens,
decayToolResults,
dropOldImages,
+ estimateAgentTokens,
extractToolCallsFromContent,
isDecayedAt,
isSystemPromptEcho,
diff --git a/mobile-client/client.js b/mobile-client/client.js
index 28012b73..ac91366c 100644
--- a/mobile-client/client.js
+++ b/mobile-client/client.js
@@ -24,7 +24,9 @@ import {
buildToolDefs,
capToolResult,
compactApiMessages,
+ countAgentHourTokens,
decayToolResults,
+ estimateAgentTokens,
extractToolCallsFromContent,
isDecayedAt,
isSystemPromptEcho,
@@ -1879,7 +1881,21 @@ import {
// context with room to spare for the model's reply.
apiMessages = compactApiMessages(apiMessages, 24000);
+ var sentChars = JSON.stringify(apiMessages).length + JSON.stringify(tools).length;
nativeToolChat(apiMessages, tools).then(function(res){
+ // Hourly token limit (agent-core.js): estimated from the characters
+ // that went out and came back. Over it, the run ends here, before
+ // any further tool runs, and the next message goes on.
+ var gotChars = (res.content || '').length + (res.thinking || '').length + JSON.stringify(res.toolCalls || []).length;
+ if(countAgentHourTokens(estimateAgentTokens(sentChars + gotChars))){
+ if(thinkingStepIdx >= 0 && target.agentSteps && target.agentSteps[thinkingStepIdx]){
+ target.agentSteps.splice(thinkingStepIdx, 1);
+ thinkingStepIdx = -1;
+ }
+ appendAgentStep('error', 'Paused: agent runs from this phone sent a lot to the model in the last hour. Send a message to go on.');
+ finishToolLoop(null);
+ return;
+ }
// Remove the initial "thinking" placeholder on the first
// successful response (only matters for iter === 1).
if(thinkingStepIdx >= 0 && target.agentSteps && target.agentSteps[thinkingStepIdx]){
diff --git a/src/lib/agent-core/remote-token-hour.ts b/src/lib/agent-core/remote-token-hour.ts
new file mode 100644
index 00000000..7be19f33
--- /dev/null
+++ b/src/lib/agent-core/remote-token-hour.ts
@@ -0,0 +1,27 @@
+/**
+ * The phone's hourly token limit for agent runs (CA, 14.11.2026). One
+ * implementation for both phone loops, the app and the desktop's phone page:
+ * mobile-client/agent-core.js, where the reasons are written down.
+ */
+import {
+ AGENT_HOUR_KEY,
+ AGENT_HOUR_TOKEN_LIMIT,
+ countAgentHourTokens,
+ estimateAgentTokens,
+} from '../../../mobile-client/agent-core.js'
+
+export const REMOTE_HOUR_TOKEN_LIMIT: number = AGENT_HOUR_TOKEN_LIMIT
+
+export function estimateRemoteTokens(chars: number): number {
+ return estimateAgentTokens(chars) as number
+}
+
+/** True when this step takes the hour over the limit and no pause came yet. */
+export function countRemoteStep(tokens: number, now?: number, limit?: number): boolean {
+ return countAgentHourTokens(tokens, now, limit) as boolean
+}
+
+/** Tests only. */
+export function _resetRemoteTokenHour(): void {
+ try { globalThis.localStorage?.removeItem(AGENT_HOUR_KEY as string) } catch { /* nothing */ }
+}
diff --git a/src/mobile/remote/__tests__/phone-agent-runs-pause-at-the-hour-limit.test.ts b/src/mobile/remote/__tests__/phone-agent-runs-pause-at-the-hour-limit.test.ts
new file mode 100644
index 00000000..82dd9c94
--- /dev/null
+++ b/src/mobile/remote/__tests__/phone-agent-runs-pause-at-the-hour-limit.test.ts
@@ -0,0 +1,85 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * CA (14.11.2026): agent runs from the phone drive the desktop's model, which
+ * can be a cloud model with the user's own paid key. One run stopped at 50
+ * steps; runs one after another had no limit. Both phone loops now count an
+ * estimate per hour and pause cleanly above it.
+ */
+import { describe, it, expect, beforeEach } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { runRemoteAgentLoop } from '../remoteAgent'
+import { _resetRemoteTokenHour, countRemoteStep, estimateRemoteTokens, REMOTE_HOUR_TOKEN_LIMIT } from '../../../lib/agent-core/remote-token-hour'
+
+beforeEach(() => _resetRemoteTokenHour())
+
+const T0 = 1_800_000_000_000
+
+describe('the phone hour', () => {
+ it('estimates high rather than low', () => {
+ expect(estimateRemoteTokens(3_500)).toBe(1_000)
+ expect(estimateRemoteTokens(0)).toBe(0)
+ })
+
+ it('pauses once when the hour passes the limit, then goes on for an hour', () => {
+ expect(countRemoteStep(REMOTE_HOUR_TOKEN_LIMIT - 1, T0)).toBe(false)
+ expect(countRemoteStep(10, T0 + 1)).toBe(true)
+ // The next message is the go-ahead: no second pause within the hour.
+ expect(countRemoteStep(500_000, T0 + 2)).toBe(false)
+ // An hour after the pause, the old steps are gone too: counting starts over.
+ expect(countRemoteStep(10, T0 + 61 * 60_000)).toBe(false)
+ })
+
+ it('a store that cannot answer means a fresh hour, never a crash', () => {
+ const original = globalThis.localStorage.getItem
+ globalThis.localStorage.getItem = () => { throw new Error('denied') }
+ try {
+ expect(countRemoteStep(10, T0)).toBe(false)
+ } finally {
+ globalThis.localStorage.getItem = original
+ }
+ })
+})
+
+describe('the app loop stops cleanly at the limit', () => {
+ it('ends as cost-limit before running the tools of that step', async () => {
+ countRemoteStep(REMOTE_HOUR_TOKEN_LIMIT - 5, Date.now())
+ let toolRuns = 0
+ const res = await runRemoteAgentLoop({
+ client: {
+ chatWithTools: async () => ({ content: 'reading', thinking: '', toolCalls: [{ function: { name: 'file_read', arguments: { path: 'a.txt' } } }] }),
+ runAgentTool: async () => { toolRuns++; return { ok: true, result: 'text' } },
+ } as never,
+ model: 'm', chatId: 'c', tools: ['file_read'],
+ messages: [{ role: 'system', content: 'sys' }, { role: 'user', content: 'read a.txt' }] as never,
+ })
+ expect(res.end).toBe('cost-limit')
+ expect(toolRuns).toBe(0)
+ expect(res.content).toMatch(/reading/)
+ })
+
+ it('a run far below the limit is never touched', async () => {
+ const res = await runRemoteAgentLoop({
+ client: {
+ chatWithTools: async () => ({ content: 'done', thinking: '', toolCalls: [] }),
+ runAgentTool: async () => ({ ok: true, result: '' }),
+ } as never,
+ model: 'm', chatId: 'c', tools: ['file_read'],
+ messages: [{ role: 'system', content: 'sys' }, { role: 'user', content: 'hi' }] as never,
+ })
+ expect(res.end).toBe('done')
+ })
+})
+
+describe('the desktop phone page counts the same way', () => {
+ it('imports the shared counter and stops before running tools', () => {
+ const page = readFileSync(join(process.cwd(), 'mobile-client/client.js'), 'utf8')
+ expect(page).toMatch(/countAgentHourTokens,/)
+ const at = page.indexOf('if(countAgentHourTokens(estimateAgentTokens(')
+ expect(at).toBeGreaterThan(0)
+ const block = page.slice(at, at + 700)
+ expect(block).toMatch(/finishToolLoop\(null\);\s*return;/)
+ expect(block).toMatch(/Send a message to go on/)
+ })
+})
diff --git a/src/mobile/remote/remoteAgent.ts b/src/mobile/remote/remoteAgent.ts
index 28522b19..915249b9 100644
--- a/src/mobile/remote/remoteAgent.ts
+++ b/src/mobile/remote/remoteAgent.ts
@@ -32,6 +32,7 @@
* bekommt die Schritte und das Ende als Daten.
*/
import { AgentLoopGuard } from '../../lib/agent-loop-guard'
+import { countRemoteStep, estimateRemoteTokens } from '../../lib/agent-core/remote-token-hour'
import {
AGENT_TOOLS,
buildToolDefs,
@@ -334,6 +335,9 @@ export type RemoteAgentEnd =
/** Der Loop-Guard hat den Lauf beendet: dieselben Aufrufe immer wieder
* (lib/agent-loop-guard.ts, derselbe Waechter wie am Desktop, CA 14.11.). */
| 'looping'
+ /** Die Stundengrenze fuer Agentenlaeufe vom Handy ist erreicht
+ * (lib/agent-core/remote-token-hour.ts, CA 14.11.). */
+ | 'cost-limit'
/** Das Modell kann keine Werkzeuge. */
| 'no-tools'
@@ -448,14 +452,24 @@ export async function runRemoteAgentLoop(run: RemoteAgentRun): Promise<RemoteAge
decayToolResults(messages, iter)
messages = compactApiMessages(messages, HISTORY_CHAR_BUDGET) as LoopMessage[]
+ const sent = messages.map(({ iter: _iter, ...message }) => message)
const answer = await run.client.chatWithTools({
model: run.model,
// `iter` ist Buchhaltung dieser Schleife und geht nicht an den Desktop.
- messages: messages.map(({ iter: _iter, ...message }) => message),
+ messages: sent,
tools,
think: run.think,
signal: run.signal,
})
+ // Kosten: geschaetzt aus den Zeichen, die hin und zurueck gingen. Ueber
+ // der Stundengrenze endet der Lauf hier, bevor weitere Werkzeuge laufen.
+ {
+ const chars = JSON.stringify(sent).length + JSON.stringify(tools).length
+ + (answer.content?.length ?? 0) + (answer.thinking?.length ?? 0) + JSON.stringify(answer.toolCalls ?? []).length
+ if (countRemoteStep(estimateRemoteTokens(chars))) {
+ return finish('cost-limit', [lastContent, answer.content ?? ''].filter((x) => x.trim()).join('\n\n'))
+ }
+ }
if (answer.thinking && run.keepThinking) thinking = thinking ? `${thinking}\n${answer.thinking}` : answer.thinking
let content = answer.content
diff --git a/src/mobile/remote/remoteClientStore.ts b/src/mobile/remote/remoteClientStore.ts
index da37ea50..2f2734c7 100644
--- a/src/mobile/remote/remoteClientStore.ts
+++ b/src/mobile/remote/remoteClientStore.ts
@@ -156,7 +156,7 @@ export interface RemoteMessage {
/** Nur Antworten im Agentenmodus: die Werkzeugschritte auf dem Desktop. */
steps?: RemoteAgentStep[]
/** Nur Antworten im Agentenmodus: warum der Lauf endete, wenn nicht mit einer Antwort. */
- agentEnd?: Extract<RemoteAgentEnd, 'max-iterations' | 'tool-errors' | 'looping'>
+ agentEnd?: Extract<RemoteAgentEnd, 'max-iterations' | 'tool-errors' | 'looping' | 'cost-limit'>
}
export interface RemoteChat {
@@ -487,7 +487,7 @@ function sanitizeChats(raw: unknown, fallbackBaseUrl: string | null = null): Rem
...(m.role === 'user' ? { mirrored: m.mirrored === true } : {}),
...(m.role === 'user' && Array.isArray(m.images) && m.images.length > 0 ? { images: sanitizeImages(m.images) } : {}),
...(m.role === 'assistant' && Array.isArray(m.steps) && m.steps.length > 0 ? { steps: sanitizeSteps(m.steps) } : {}),
- ...(m.role === 'assistant' && (m.agentEnd === 'max-iterations' || m.agentEnd === 'tool-errors' || m.agentEnd === 'looping') ? { agentEnd: m.agentEnd } : {}),
+ ...(m.role === 'assistant' && (m.agentEnd === 'max-iterations' || m.agentEnd === 'tool-errors' || m.agentEnd === 'looping' || m.agentEnd === 'cost-limit') ? { agentEnd: m.agentEnd } : {}),
})
}
out.push({
diff --git a/src/mobile/screens/remote/RemoteChatPage.tsx b/src/mobile/screens/remote/RemoteChatPage.tsx
index 37b9e176..ff8d57e1 100644
--- a/src/mobile/screens/remote/RemoteChatPage.tsx
+++ b/src/mobile/screens/remote/RemoteChatPage.tsx
@@ -115,7 +115,7 @@ function Answer({ chat, message, isLast, status, waiting, foreign }: { chat: Rem
) : null}
{message.agentEnd ? (
<div className="m-remote-msg-foot m-remote-msg-foot--warn" data-testid="m-remote-chat-agent-end">
- <span className="m-grow">{message.agentEnd === 'max-iterations' ? S.chat.endMaxSteps : message.agentEnd === 'looping' ? S.chat.endLooping : S.chat.endToolErrors}</span>
+ <span className="m-grow">{message.agentEnd === 'max-iterations' ? S.chat.endMaxSteps : message.agentEnd === 'looping' ? S.chat.endLooping : message.agentEnd === 'cost-limit' ? S.chat.endCostLimit : S.chat.endToolErrors}</span>
</div>
) : null}
{footer ? (
diff --git a/src/mobile/strings/remote.ts b/src/mobile/strings/remote.ts
index 5ded388c..3252e0a8 100644
--- a/src/mobile/strings/remote.ts
+++ b/src/mobile/strings/remote.ts
@@ -177,6 +177,7 @@ export const REMOTE_STRINGS = {
endMaxSteps: 'The model stopped after the highest number of steps.',
endToolErrors: 'The model stopped because several steps in a row failed.',
endLooping: 'Stopped because the model kept repeating the same steps.',
+ endCostLimit: 'Paused: agent runs from this phone sent a lot to the model in the last hour. Send a message to go on.',
missingTitle: 'This remote chat is not on this phone',
missingText: 'It may have been deleted. Your other remote chats are in the list.',
backToList: 'Back to remote chats',