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.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(create): the prompt rewrite has a time limit and Cancel drops a silent stream
purple1a5be8fe8876
diff --git a/src/lib/render/__tests__/improve-prompt-run.test.ts b/src/lib/render/__tests__/improve-prompt-run.test.tsindex 1ecbed51..f1bd57d7 100644--- a/src/lib/render/__tests__/improve-prompt-run.test.ts+++ b/src/lib/render/__tests__/improve-prompt-run.test.ts@@ -1,4 +1,4 @@-import { describe, it, expect, vi, beforeEach } from 'vitest'+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'const calls = vi.hoisted(() => ({list: [] as { model: string; messages: { role: string; content: string }[]; opts: Record<string, unknown> }[],@@ -7,6 +7,7 @@ const calls = vi.hoisted(() => ({const plan = vi.hoisted(() => ({chunks: [] as string[],throws: null as Error | null,+ hangs: false,provider: 'lu-cloud' as string,lane: 'cloud' as 'cloud' | 'local',queued: false,@@ -21,6 +22,7 @@ vi.mock('../../../api/providers', () => ({async *chatStream(model: string, messages: { role: string; content: string }[], opts: Record<string, unknown>) {calls.list.push({ model, messages, opts })if (plan.throws) throw plan.throws+ if (plan.hangs) await new Promise(() => {})for (const c of plan.chunks) yield { content: c, done: false }yield { content: '', done: true }},@@ -41,12 +43,16 @@ vi.mock('../../run-slot', () => ({import { useModelStore } from '../../../stores/modelStore'import { improveAvailabilityFor, improvePrompt } from '../improve-prompt-run'+import { IMPROVE_TIMEOUT_MS } from '../improve-prompt'++afterEach(() => { vi.useRealTimers() })beforeEach(() => {calls.list.length = 0calls.lanes.length = 0plan.chunks = ['A red fox ', 'in deep snow.']plan.throws = null+ plan.hangs = falseplan.provider = 'lu-cloud'plan.lane = 'cloud'plan.queued = false@@ -55,6 +61,34 @@ beforeEach(() => {})describe('Improve my prompt: Lauf (Desktop)', () => {+ it('ein haengender Aufruf endet nach der Frist als failed, lokal nach der doppelten', async () => {+ for (const [lane, limit] of [['cloud', IMPROVE_TIMEOUT_MS], ['local', IMPROVE_TIMEOUT_MS * 2]] as const) {+ vi.useFakeTimers()+ calls.list.length = 0+ plan.hangs = true+ plan.lane = lane+ const run = improvePrompt('x', { kind: 'image' })+ let settled = false+ void run.then(() => { settled = true })+ await vi.advanceTimersByTimeAsync(limit - 1)+ expect(settled, lane).toBe(false)+ await vi.advanceTimersByTimeAsync(1)+ expect(await run).toEqual({ status: 'failed' })+ expect((calls.list[0].opts.signal as AbortSignal).aborted).toBe(true)+ vi.useRealTimers()+ }+ })++ it('Cancel beendet auch einen Aufruf, der auf den Abbruch nicht hoert', async () => {+ plan.hangs = true+ const ac = new AbortController()+ const run = improvePrompt('x', { kind: 'image' }, ac.signal)+ await new Promise((r) => setTimeout(r, 0))+ ac.abort()+ expect(await run).toEqual({ status: 'failed' })+ expect((calls.list[0].opts.signal as AbortSignal).aborted).toBe(true)+ })+it('schreibt mit dem gewaehlten Chatmodell um und liefert die neue Fassung', async () => {const out = await improvePrompt('fox in snow', { kind: 'image' })expect(out).toEqual({ status: 'improved', prompt: 'A red fox in deep snow.' })diff --git a/src/lib/render/improve-prompt-run.ts b/src/lib/render/improve-prompt-run.tsindex e65a084d..afea1870 100644--- a/src/lib/render/improve-prompt-run.ts+++ b/src/lib/render/improve-prompt-run.ts@@ -16,7 +16,7 @@ import { resolveAgentNumCtx } from '../agent-num-ctx'import { runInLane } from '../run-slot'import { laneOf, currentLaneFacts } from '../run-lane-of-model'import {- IMPROVE_MAX_TOKENS, buildImproveMessages, cleanImproved,+ IMPROVE_MAX_TOKENS, IMPROVE_TIMEOUT_MS, buildImproveMessages, cleanImproved,type ImproveOutcome, type ImproveTarget,} from './improve-prompt'@@ -61,21 +61,31 @@ export async function improvePrompt(const canThink = thinkMode ? thinkMode === 'toggle' : isThinkingCompatible(activeModel)const effortLevels = meta && 'effortLevels' in meta ? meta.effortLevels : undefinedconst effortDefault = meta && 'effortDefault' in meta ? meta.effortDefault : undefined+ const lane = laneOf(activeModel, currentLaneFacts())+ // A local model may have to load first, so it gets twice the time.+ const limit = lane === 'local' ? IMPROVE_TIMEOUT_MS * 2 : IMPROVE_TIMEOUT_MS+ // The call ends on its own, on the user's Cancel, or after the time limit.+ // The last two also drop a stream that does not answer the abort.const own = new AbortController()- const onAbort = () => own.abort()- signal?.addEventListener('abort', onAbort)+ let stop: () => void = () => {}+ const stopped = new Promise<false>((resolve) => { stop = () => { own.abort(); resolve(false) } })+ signal?.addEventListener('abort', stop)+ let timer: ReturnType<typeof setTimeout> | undefinedlet text = ''let ran = false- try {- const outcome = await runInLane(- { conversationId: IMPROVE_TURN, lane: laneOf(activeModel, currentLaneFacts()), abort: () => own.abort() },- async () => {- if (own.signal.aborted) return- // The num_ctx the chat runs with, so a local model is not reloaded- // for this call.- const numCtx = await resolveAgentNumCtx(- modelId, providerId, useSettingsStore.getState().settings.contextWindowOverride, activeModel,- )+ const run = runInLane(+ { conversationId: IMPROVE_TURN, lane, abort: () => stop() },+ async () => {+ if (own.signal.aborted) return+ // The clock starts when the call does, not while it waits behind a+ // chat turn on the local card.+ timer = setTimeout(stop, limit)+ // The num_ctx the chat runs with, so a local model is not reloaded+ // for this call.+ const numCtx = await resolveAgentNumCtx(+ modelId, providerId, useSettingsStore.getState().settings.contextWindowOverride, activeModel,+ )+ const read = (async () => {const stream = provider.chatStream(modelId, buildImproveMessages(target, prompt), {temperature: 0.4,maxTokens: IMPROVE_MAX_TOKENS,@@ -92,13 +102,22 @@ export async function improvePrompt(if (chunk.content) text += chunk.contentif (chunk.done) break}- ran = true- },- )- if (outcome !== 'ran' || !ran) return { status: 'failed' }+ return true as const+ })()+ read.catch(() => {})+ // A stopped call gives the lane back at once, answered or not.+ ran = await Promise.race([read, stopped])+ },+ ).then((outcome) => outcome === 'ran' && ran)+ run.catch(() => {})+ let finished = false+ try {+ finished = await Promise.race([run, stopped])} finally {- signal?.removeEventListener('abort', onAbort)+ clearTimeout(timer)+ signal?.removeEventListener('abort', stop)}+ if (!finished) return { status: 'failed' }const cleaned = cleanImproved(text)if (!cleaned) return { status: 'failed' }if (cleaned === prompt.trim()) return { status: 'unchanged' }diff --git a/src/lib/render/improve-prompt.ts b/src/lib/render/improve-prompt.tsindex 6c866ba2..0d13ad15 100644--- a/src/lib/render/improve-prompt.ts+++ b/src/lib/render/improve-prompt.ts@@ -33,6 +33,10 @@ export const IMPROVE_MAX_CHARS = 3000* reasoning off spends part of it before the first word. */export const IMPROVE_MAX_TOKENS = 1500+/** How long the rewrite may take. A chat call that hangs must not hold the run:+ * after this the call is dropped and the run goes on with the user's own prompt. */+export const IMPROVE_TIMEOUT_MS = 90_000+export interface ImproveTarget {kind: ImproveKind/** The model the prompt is for, as the user sees it. Named to the chat model